Reformat catalog-be 34/119534/2
authorvasraz <vasyl.razinkov@est.tech>
Fri, 19 Mar 2021 11:25:07 +0000 (11:25 +0000)
committerChristophe Closset <christophe.closset@intl.att.com>
Fri, 19 Mar 2021 17:00:24 +0000 (17:00 +0000)
Signed-off-by: Vasyl Razinkov <vasyl.razinkov@est.tech>
Issue-ID: SDC-3449
Change-Id: I45ae9fef826bcd5e3aa65c81d232d349faf02f91

552 files changed:
catalog-be/src/main/java/org/openecomp/sdc/be/auditing/api/AuditEventFactory.java
catalog-be/src/main/java/org/openecomp/sdc/be/auditing/impl/AuditAuthRequestEventFactory.java
catalog-be/src/main/java/org/openecomp/sdc/be/auditing/impl/AuditBaseEventFactory.java
catalog-be/src/main/java/org/openecomp/sdc/be/auditing/impl/AuditConsumerEventFactory.java
catalog-be/src/main/java/org/openecomp/sdc/be/auditing/impl/AuditEcompOpEnvEventFactory.java
catalog-be/src/main/java/org/openecomp/sdc/be/auditing/impl/AuditGetUebClusterEventFactory.java
catalog-be/src/main/java/org/openecomp/sdc/be/auditing/impl/AuditingManager.java
catalog-be/src/main/java/org/openecomp/sdc/be/auditing/impl/category/AuditCategoryEventFactory.java
catalog-be/src/main/java/org/openecomp/sdc/be/auditing/impl/category/AuditGetCategoryHierarchyEventFactory.java
catalog-be/src/main/java/org/openecomp/sdc/be/auditing/impl/distribution/AuditAddRemoveKeyDistributionEngineEventFactory.java
catalog-be/src/main/java/org/openecomp/sdc/be/auditing/impl/distribution/AuditCreateTopicDistributionEngineEventFactory.java
catalog-be/src/main/java/org/openecomp/sdc/be/auditing/impl/distribution/AuditDistributionDeployEventFactory.java
catalog-be/src/main/java/org/openecomp/sdc/be/auditing/impl/distribution/AuditDistributionDownloadEventFactory.java
catalog-be/src/main/java/org/openecomp/sdc/be/auditing/impl/distribution/AuditDistributionEngineEventFactory.java
catalog-be/src/main/java/org/openecomp/sdc/be/auditing/impl/distribution/AuditDistributionEngineEventFactoryManager.java
catalog-be/src/main/java/org/openecomp/sdc/be/auditing/impl/distribution/AuditDistributionEngineEventMigrationFactory.java
catalog-be/src/main/java/org/openecomp/sdc/be/auditing/impl/distribution/AuditDistributionNotificationEventFactory.java
catalog-be/src/main/java/org/openecomp/sdc/be/auditing/impl/distribution/AuditDistributionStatusEventFactory.java
catalog-be/src/main/java/org/openecomp/sdc/be/auditing/impl/distribution/AuditRegUnregDistributionEngineEventFactory.java
catalog-be/src/main/java/org/openecomp/sdc/be/auditing/impl/externalapi/AuditActivateServiceExternalApiEventFactory.java
catalog-be/src/main/java/org/openecomp/sdc/be/auditing/impl/externalapi/AuditAssetExternalApiEventFactory.java
catalog-be/src/main/java/org/openecomp/sdc/be/auditing/impl/externalapi/AuditAssetListExternalApiEventFactory.java
catalog-be/src/main/java/org/openecomp/sdc/be/auditing/impl/externalapi/AuditChangeLifecycleExternalApiEventFactory.java
catalog-be/src/main/java/org/openecomp/sdc/be/auditing/impl/externalapi/AuditCreateResourceExternalApiEventFactory.java
catalog-be/src/main/java/org/openecomp/sdc/be/auditing/impl/externalapi/AuditCreateServiceExternalApiEventFactory.java
catalog-be/src/main/java/org/openecomp/sdc/be/auditing/impl/externalapi/AuditCrudExternalApiArtifactEventFactory.java
catalog-be/src/main/java/org/openecomp/sdc/be/auditing/impl/externalapi/AuditDownloadArtifactExternalApiEventFactory.java
catalog-be/src/main/java/org/openecomp/sdc/be/auditing/impl/externalapi/AuditExternalApiEventFactory.java
catalog-be/src/main/java/org/openecomp/sdc/be/auditing/impl/resourceadmin/AuditArtifactResourceAdminEventFactory.java
catalog-be/src/main/java/org/openecomp/sdc/be/auditing/impl/resourceadmin/AuditCertificationResourceAdminEventFactory.java
catalog-be/src/main/java/org/openecomp/sdc/be/auditing/impl/resourceadmin/AuditCreateUpdateResourceAdminEventFactory.java
catalog-be/src/main/java/org/openecomp/sdc/be/auditing/impl/resourceadmin/AuditDistStateChangeRequestResourceAdminEventFactory.java
catalog-be/src/main/java/org/openecomp/sdc/be/auditing/impl/resourceadmin/AuditDistStateChangeResourceAdminEventFactory.java
catalog-be/src/main/java/org/openecomp/sdc/be/auditing/impl/resourceadmin/AuditImportResourceAdminEventFactory.java
catalog-be/src/main/java/org/openecomp/sdc/be/auditing/impl/resourceadmin/AuditResourceAdminEventFactory.java
catalog-be/src/main/java/org/openecomp/sdc/be/auditing/impl/resourceadmin/AuditResourceAdminEventMigrationFactory.java
catalog-be/src/main/java/org/openecomp/sdc/be/auditing/impl/resourceadmin/AuditResourceEventFactoryManager.java
catalog-be/src/main/java/org/openecomp/sdc/be/auditing/impl/usersadmin/AuditGetUsersListEventFactory.java
catalog-be/src/main/java/org/openecomp/sdc/be/auditing/impl/usersadmin/AuditUserAccessEventFactory.java
catalog-be/src/main/java/org/openecomp/sdc/be/auditing/impl/usersadmin/AuditUserAdminEventFactory.java
catalog-be/src/main/java/org/openecomp/sdc/be/catalog/api/IComponentMessage.java
catalog-be/src/main/java/org/openecomp/sdc/be/catalog/api/IMessageQueueHandlerProducer.java
catalog-be/src/main/java/org/openecomp/sdc/be/catalog/api/IStatus.java
catalog-be/src/main/java/org/openecomp/sdc/be/catalog/api/ITypeMessage.java
catalog-be/src/main/java/org/openecomp/sdc/be/catalog/enums/ChangeTypeEnum.java
catalog-be/src/main/java/org/openecomp/sdc/be/catalog/enums/ResultStatusEnum.java
catalog-be/src/main/java/org/openecomp/sdc/be/catalog/impl/ComponentMessage.java
catalog-be/src/main/java/org/openecomp/sdc/be/catalog/impl/DmaapProducer.java
catalog-be/src/main/java/org/openecomp/sdc/be/catalog/impl/DmaapProducerHealth.java
catalog-be/src/main/java/org/openecomp/sdc/be/components/ArtifactsResolver.java
catalog-be/src/main/java/org/openecomp/sdc/be/components/attribute/AttributeDeclarationOrchestrator.java
catalog-be/src/main/java/org/openecomp/sdc/be/components/attribute/AttributeDeclarator.java
catalog-be/src/main/java/org/openecomp/sdc/be/components/attribute/ComponentAttributeDeclarator.java
catalog-be/src/main/java/org/openecomp/sdc/be/components/attribute/ComponentInstanceAttributeDeclarator.java
catalog-be/src/main/java/org/openecomp/sdc/be/components/attribute/ComponentInstanceOutputAttributeDeclarator.java
catalog-be/src/main/java/org/openecomp/sdc/be/components/attribute/DefaultAttributeDeclarator.java
catalog-be/src/main/java/org/openecomp/sdc/be/components/attribute/GetOutputUtils.java
catalog-be/src/main/java/org/openecomp/sdc/be/components/csar/CsarArtifactsAndGroupsBusinessLogic.java
catalog-be/src/main/java/org/openecomp/sdc/be/components/csar/CsarBusinessLogic.java
catalog-be/src/main/java/org/openecomp/sdc/be/components/csar/CsarInfo.java
catalog-be/src/main/java/org/openecomp/sdc/be/components/csar/YamlTemplateParsingHandler.java
catalog-be/src/main/java/org/openecomp/sdc/be/components/distribution/engine/AaiRequestHandler.java
catalog-be/src/main/java/org/openecomp/sdc/be/components/distribution/engine/ArtifactInfoImpl.java
catalog-be/src/main/java/org/openecomp/sdc/be/components/distribution/engine/CambriaErrorResponse.java
catalog-be/src/main/java/org/openecomp/sdc/be/components/distribution/engine/CambriaHandler.java
catalog-be/src/main/java/org/openecomp/sdc/be/components/distribution/engine/DME2EndpointIteratorCreator.java
catalog-be/src/main/java/org/openecomp/sdc/be/components/distribution/engine/DistributionEngine.java
catalog-be/src/main/java/org/openecomp/sdc/be/components/distribution/engine/DistributionEngineClusterHealth.java
catalog-be/src/main/java/org/openecomp/sdc/be/components/distribution/engine/DistributionEngineInitTask.java
catalog-be/src/main/java/org/openecomp/sdc/be/components/distribution/engine/DistributionEnginePollingTask.java
catalog-be/src/main/java/org/openecomp/sdc/be/components/distribution/engine/DistributionNotificationSender.java
catalog-be/src/main/java/org/openecomp/sdc/be/components/distribution/engine/DistributionStatusNotification.java
catalog-be/src/main/java/org/openecomp/sdc/be/components/distribution/engine/DistributionStatusNotificationEnum.java
catalog-be/src/main/java/org/openecomp/sdc/be/components/distribution/engine/DmaapClientFactory.java
catalog-be/src/main/java/org/openecomp/sdc/be/components/distribution/engine/DmaapConsumer.java
catalog-be/src/main/java/org/openecomp/sdc/be/components/distribution/engine/DmaapHealth.java
catalog-be/src/main/java/org/openecomp/sdc/be/components/distribution/engine/DmaapNotificationDataImpl.java
catalog-be/src/main/java/org/openecomp/sdc/be/components/distribution/engine/EnvironmentMessageBusData.java
catalog-be/src/main/java/org/openecomp/sdc/be/components/distribution/engine/EnvironmentsEngine.java
catalog-be/src/main/java/org/openecomp/sdc/be/components/distribution/engine/ExecutorFactory.java
catalog-be/src/main/java/org/openecomp/sdc/be/components/distribution/engine/IArtifactInfo.java
catalog-be/src/main/java/org/openecomp/sdc/be/components/distribution/engine/ICambriaHandler.java
catalog-be/src/main/java/org/openecomp/sdc/be/components/distribution/engine/IDistributionEngine.java
catalog-be/src/main/java/org/openecomp/sdc/be/components/distribution/engine/IDmaapAuditNotificationData.java
catalog-be/src/main/java/org/openecomp/sdc/be/components/distribution/engine/IDmaapNotificationData.java
catalog-be/src/main/java/org/openecomp/sdc/be/components/distribution/engine/INotificationData.java
catalog-be/src/main/java/org/openecomp/sdc/be/components/distribution/engine/INotificationHandler.java
catalog-be/src/main/java/org/openecomp/sdc/be/components/distribution/engine/IResourceArtifactInfo.java
catalog-be/src/main/java/org/openecomp/sdc/be/components/distribution/engine/IServiceArtifactInfo.java
catalog-be/src/main/java/org/openecomp/sdc/be/components/distribution/engine/JsonContainerResourceInstance.java
catalog-be/src/main/java/org/openecomp/sdc/be/components/distribution/engine/NotificationDataImpl.java
catalog-be/src/main/java/org/openecomp/sdc/be/components/distribution/engine/NotificationExecutorService.java
catalog-be/src/main/java/org/openecomp/sdc/be/components/distribution/engine/ResourceArtifactInfoImpl.java
catalog-be/src/main/java/org/openecomp/sdc/be/components/distribution/engine/ServiceArtifactInfoImpl.java
catalog-be/src/main/java/org/openecomp/sdc/be/components/distribution/engine/ServiceDistributionArtifactsBuilder.java
catalog-be/src/main/java/org/openecomp/sdc/be/components/distribution/engine/SubscriberTypeEnum.java
catalog-be/src/main/java/org/openecomp/sdc/be/components/distribution/engine/UebHealthCheckCall.java
catalog-be/src/main/java/org/openecomp/sdc/be/components/distribution/engine/VfModuleArtifactPayload.java
catalog-be/src/main/java/org/openecomp/sdc/be/components/distribution/engine/config/DistributionEngineSpringConfig.java
catalog-be/src/main/java/org/openecomp/sdc/be/components/distribution/engine/report/DistributionCompleteReporter.java
catalog-be/src/main/java/org/openecomp/sdc/be/components/distribution/engine/report/MsoDistributionCompleteReporter.java
catalog-be/src/main/java/org/openecomp/sdc/be/components/distribution/engine/rest/DistributionStatusRequest.java
catalog-be/src/main/java/org/openecomp/sdc/be/components/distribution/engine/rest/MSORestClient.java
catalog-be/src/main/java/org/openecomp/sdc/be/components/health/HealthCheckBusinessLogic.java
catalog-be/src/main/java/org/openecomp/sdc/be/components/health/PortalHealthCheckBuilder.java
catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/AbstractTemplateBusinessLogic.java
catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/ActivationRequestInformation.java
catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/AdditionalInformationBusinessLogic.java
catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/AnnotationBusinessLogic.java
catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/ArchiveBusinessLogic.java
catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/ArtifactResolverImpl.java
catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/ArtifactsBusinessLogic.java
catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/AttributeBusinessLogic.java
catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/BaseBusinessLogic.java
catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/CADIHealthCheck.java
catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/CapabilitiesBusinessLogic.java
catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/CapabilityTypeImportManager.java
catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/CassandraHealthCheck.java
catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/CategoriesImportManager.java
catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/CommonImportManager.java
catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/ComponentBusinessLogic.java
catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/ComponentBusinessLogicProvider.java
catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/ComponentInstanceBusinessLogic.java
catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/ComponentInterfaceOperationBusinessLogic.java
catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/ComponentLocker.java
catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/ComponentNodeFilterBusinessLogic.java
catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/ComponentSubstitutionFilterBusinessLogic.java
catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/CompositionBusinessLogic.java
catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/ConsumerBusinessLogic.java
catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/CsarValidationUtils.java
catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/DataTypeBusinessLogic.java
catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/DataTypeImportManager.java
catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/DataTypesService.java
catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/DistributionMonitoringBusinessLogic.java
catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/ElementBusinessLogic.java
catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/ExternalRefsBusinessLogic.java
catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/GenericArtifactBrowserBusinessLogic.java
catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/GroupBusinessLogic.java
catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/GroupBusinessLogicNew.java
catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/GroupTypeBusinessLogic.java
catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/GroupTypeImportManager.java
catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/HealthCheckInformer.java
catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/IDeploymentArtifactTypeConfigGetter.java
catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/ImportUtils.java
catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/InputsBusinessLogic.java
catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/InterfaceDefinitionHandler.java
catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/InterfaceLifecycleTypeImportManager.java
catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/InterfaceOperationBusinessLogic.java
catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/NodeFilterUploadCreator.java
catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/OnDeleteEntityOperation.java
catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/OutputsBusinessLogic.java
catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/PolicyBusinessLogic.java
catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/PolicyTypeBusinessLogic.java
catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/PolicyTypeImportManager.java
catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/ProductBusinessLogic.java
catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/PropertyBusinessLogic.java
catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/RelationshipTypeBusinessLogic.java
catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/RelationshipTypeImportManager.java
catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/RequirementBusinessLogic.java
catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/RequirementsBusinessLogic.java
catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/ResourceBusinessLogic.java
catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/ResourceImportManager.java
catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/ResponseFormatManager.java
catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/ServiceBusinessLogic.java
catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/ServiceImportBusinessLogic.java
catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/ServiceImportManager.java
catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/ServiceImportParseLogic.java
catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/SoftwareInformationBusinessLogic.java
catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/TogglingBusinessLogic.java
catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/aaf/AafPermission.java
catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/aaf/AafRoles.java
catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/aaf/PermissionAllowed.java
catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/aaf/RoleAuthorizationHandler.java
catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/artifact/ArtifactOperationInfo.java
catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/artifact/ArtifactTypeToPayloadTypeSelector.java
catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/artifact/PayloadTypeEnum.java
catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/exceptions/BusinessLogicException.java
catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/exceptions/ByActionStatusComponentException.java
catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/exceptions/ByResponseFormatComponentException.java
catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/exceptions/ComponentException.java
catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/exceptions/SdcResourceNotFoundException.java
catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/generic/GenericTypeBusinessLogic.java
catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/group/GroupMembersUpdater.java
catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/group/GroupVersionUpdater.java
catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/instance/ComponentInstanceChangeOperationOrchestrator.java
catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/instance/GroupMembersUpdateOperation.java
catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/instance/OnChangeVersionOperation.java
catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/instance/OnComponentInstanceChangeOperation.java
catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/instance/PolicyTargetsUpdateOperation.java
catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/lock/ComponentLockAspect.java
catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/lock/LockingTransactional.java
catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/model/ToscaTypeImportData.java
catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/policy/PolicyTargetsUpdateHandler.java
catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/policy/PolicyTargetsUpdater.java
catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/policy/PolicyVersionUpdater.java
catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/utils/CINodeFilterUtils.java
catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/utils/CapabilityTypeImportUtils.java
catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/utils/ComponentUtils.java
catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/utils/CreateServiceFromYamlParameter.java
catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/utils/DirectivesUtil.java
catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/utils/ExceptionUtils.java
catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/utils/PolicyTypeImportUtils.java
catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/validation/PMDictionaryValidator.java
catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/version/OnChangeVersionCommand.java
catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/version/VesionUpdateHandler.java
catalog-be/src/main/java/org/openecomp/sdc/be/components/lifecycle/CertificationChangeTransition.java
catalog-be/src/main/java/org/openecomp/sdc/be/components/lifecycle/CheckinTransition.java
catalog-be/src/main/java/org/openecomp/sdc/be/components/lifecycle/CheckoutTransition.java
catalog-be/src/main/java/org/openecomp/sdc/be/components/lifecycle/LifeCycleTransition.java
catalog-be/src/main/java/org/openecomp/sdc/be/components/lifecycle/LifecycleBusinessLogic.java
catalog-be/src/main/java/org/openecomp/sdc/be/components/lifecycle/LifecycleChangeInfoBase.java
catalog-be/src/main/java/org/openecomp/sdc/be/components/lifecycle/LifecycleChangeInfoWithAction.java
catalog-be/src/main/java/org/openecomp/sdc/be/components/lifecycle/UndoCheckoutTransition.java
catalog-be/src/main/java/org/openecomp/sdc/be/components/merge/ComponentsGlobalMergeCommand.java
catalog-be/src/main/java/org/openecomp/sdc/be/components/merge/ComponentsMergeCommand.java
catalog-be/src/main/java/org/openecomp/sdc/be/components/merge/GlobalInputsFilteringBusinessLogic.java
catalog-be/src/main/java/org/openecomp/sdc/be/components/merge/RelationsComparator.java
catalog-be/src/main/java/org/openecomp/sdc/be/components/merge/TopologyComparator.java
catalog-be/src/main/java/org/openecomp/sdc/be/components/merge/VspComponentsMergeCommand.java
catalog-be/src/main/java/org/openecomp/sdc/be/components/merge/capability/CapabilityResolver.java
catalog-be/src/main/java/org/openecomp/sdc/be/components/merge/capability/SimpleCapabilityResolver.java
catalog-be/src/main/java/org/openecomp/sdc/be/components/merge/group/ComponentGroupMergeCommand.java
catalog-be/src/main/java/org/openecomp/sdc/be/components/merge/group/GroupPropertiesMergeCommand.java
catalog-be/src/main/java/org/openecomp/sdc/be/components/merge/heat/HeatEnvArtifactsMergeBusinessLogic.java
catalog-be/src/main/java/org/openecomp/sdc/be/components/merge/input/ComponentInputsMergeBL.java
catalog-be/src/main/java/org/openecomp/sdc/be/components/merge/input/DeclaredInputsResolver.java
catalog-be/src/main/java/org/openecomp/sdc/be/components/merge/input/GlobalInputsMergeCommand.java
catalog-be/src/main/java/org/openecomp/sdc/be/components/merge/input/InputsMergeCommand.java
catalog-be/src/main/java/org/openecomp/sdc/be/components/merge/input/InputsValuesMergingBusinessLogic.java
catalog-be/src/main/java/org/openecomp/sdc/be/components/merge/instance/ComponentCapabilitiesPropertiesMergeBL.java
catalog-be/src/main/java/org/openecomp/sdc/be/components/merge/instance/ComponentInstanceArtifactsMerge.java
catalog-be/src/main/java/org/openecomp/sdc/be/components/merge/instance/ComponentInstanceCapabilitiesPropertiesMerge.java
catalog-be/src/main/java/org/openecomp/sdc/be/components/merge/instance/ComponentInstanceForwardingPathMerge.java
catalog-be/src/main/java/org/openecomp/sdc/be/components/merge/instance/ComponentInstanceHeatEnvMerge.java
catalog-be/src/main/java/org/openecomp/sdc/be/components/merge/instance/ComponentInstanceInputsMergeBL.java
catalog-be/src/main/java/org/openecomp/sdc/be/components/merge/instance/ComponentInstanceInputsRedeclareHandler.java
catalog-be/src/main/java/org/openecomp/sdc/be/components/merge/instance/ComponentInstanceInterfacesMerge.java
catalog-be/src/main/java/org/openecomp/sdc/be/components/merge/instance/ComponentInstanceMergeDataBusinessLogic.java
catalog-be/src/main/java/org/openecomp/sdc/be/components/merge/instance/ComponentInstanceMergeInterface.java
catalog-be/src/main/java/org/openecomp/sdc/be/components/merge/instance/ComponentInstancePropertiesMergeBL.java
catalog-be/src/main/java/org/openecomp/sdc/be/components/merge/instance/ComponentInstancePropsAndInputsMerge.java
catalog-be/src/main/java/org/openecomp/sdc/be/components/merge/instance/ComponentInstanceRelationMerge.java
catalog-be/src/main/java/org/openecomp/sdc/be/components/merge/instance/ComponentInstanceRelationMergeCommand.java
catalog-be/src/main/java/org/openecomp/sdc/be/components/merge/instance/ContainerRelationsMergeInfo.java
catalog-be/src/main/java/org/openecomp/sdc/be/components/merge/instance/DataForMergeHolder.java
catalog-be/src/main/java/org/openecomp/sdc/be/components/merge/instance/ExternalRefsMergeBL.java
catalog-be/src/main/java/org/openecomp/sdc/be/components/merge/instance/RelationMergeInfo.java
catalog-be/src/main/java/org/openecomp/sdc/be/components/merge/policy/PoliciesMergeCommand.java
catalog-be/src/main/java/org/openecomp/sdc/be/components/merge/property/DataDefinitionsValuesMergingBusinessLogic.java
catalog-be/src/main/java/org/openecomp/sdc/be/components/merge/property/MergePropertyData.java
catalog-be/src/main/java/org/openecomp/sdc/be/components/merge/property/PropertyDataValueMergeBusinessLogic.java
catalog-be/src/main/java/org/openecomp/sdc/be/components/merge/property/PropertyInstanceMergeDataBuilder.java
catalog-be/src/main/java/org/openecomp/sdc/be/components/merge/property/PropertyValueMerger.java
catalog-be/src/main/java/org/openecomp/sdc/be/components/merge/resource/MergeCommandsFactory.java
catalog-be/src/main/java/org/openecomp/sdc/be/components/merge/resource/MergeResourceBusinessLogic.java
catalog-be/src/main/java/org/openecomp/sdc/be/components/merge/resource/ResourceDataMergeBusinessLogic.java
catalog-be/src/main/java/org/openecomp/sdc/be/components/merge/utils/CapabilityOwner.java
catalog-be/src/main/java/org/openecomp/sdc/be/components/merge/utils/ComponentInstanceBuildingBlocks.java
catalog-be/src/main/java/org/openecomp/sdc/be/components/merge/utils/MergeInstanceUtils.java
catalog-be/src/main/java/org/openecomp/sdc/be/components/path/ForwardingPathValidator.java
catalog-be/src/main/java/org/openecomp/sdc/be/components/property/ComponentInstanceInputPropertyDeclarator.java
catalog-be/src/main/java/org/openecomp/sdc/be/components/property/ComponentInstancePropertyDeclarator.java
catalog-be/src/main/java/org/openecomp/sdc/be/components/property/ComponentPropertyDeclarator.java
catalog-be/src/main/java/org/openecomp/sdc/be/components/property/DefaultPropertyDeclarator.java
catalog-be/src/main/java/org/openecomp/sdc/be/components/property/GetInputUtils.java
catalog-be/src/main/java/org/openecomp/sdc/be/components/property/GroupPropertyDeclarator.java
catalog-be/src/main/java/org/openecomp/sdc/be/components/property/PolicyPropertyDeclarator.java
catalog-be/src/main/java/org/openecomp/sdc/be/components/property/PropertyConstraintsUtils.java
catalog-be/src/main/java/org/openecomp/sdc/be/components/property/PropertyDeclarationOrchestrator.java
catalog-be/src/main/java/org/openecomp/sdc/be/components/property/PropertyDeclarator.java
catalog-be/src/main/java/org/openecomp/sdc/be/components/property/propertytopolicydeclarators/ComponentInstancePropertyToPolicyDeclarator.java
catalog-be/src/main/java/org/openecomp/sdc/be/components/property/propertytopolicydeclarators/ComponentPropertyToPolicyDeclarator.java
catalog-be/src/main/java/org/openecomp/sdc/be/components/scheduledtasks/AbstractScheduleTaskRunner.java
catalog-be/src/main/java/org/openecomp/sdc/be/components/scheduledtasks/AsdcComponentsCleanerTask.java
catalog-be/src/main/java/org/openecomp/sdc/be/components/scheduledtasks/ComponentsCleanBusinessLogic.java
catalog-be/src/main/java/org/openecomp/sdc/be/components/scheduledtasks/RecoveryThreadManager.java
catalog-be/src/main/java/org/openecomp/sdc/be/components/upgrade/ServiceInfo.java
catalog-be/src/main/java/org/openecomp/sdc/be/components/upgrade/UpgradeBusinessLogic.java
catalog-be/src/main/java/org/openecomp/sdc/be/components/upgrade/UpgradeRequest.java
catalog-be/src/main/java/org/openecomp/sdc/be/components/upgrade/UpgradeStatus.java
catalog-be/src/main/java/org/openecomp/sdc/be/components/utils/ArtifactUtils.java
catalog-be/src/main/java/org/openecomp/sdc/be/components/utils/ConsumptionUtils.java
catalog-be/src/main/java/org/openecomp/sdc/be/components/utils/InterfaceOperationUtils.java
catalog-be/src/main/java/org/openecomp/sdc/be/components/utils/MapUtils.java
catalog-be/src/main/java/org/openecomp/sdc/be/components/utils/PropertiesUtils.java
catalog-be/src/main/java/org/openecomp/sdc/be/components/utils/Utils.java
catalog-be/src/main/java/org/openecomp/sdc/be/components/validation/AccessValidations.java
catalog-be/src/main/java/org/openecomp/sdc/be/components/validation/AnnotationValidator.java
catalog-be/src/main/java/org/openecomp/sdc/be/components/validation/ApiResourceEnum.java
catalog-be/src/main/java/org/openecomp/sdc/be/components/validation/CapabilitiesValidation.java
catalog-be/src/main/java/org/openecomp/sdc/be/components/validation/ComponentValidations.java
catalog-be/src/main/java/org/openecomp/sdc/be/components/validation/InterfaceOperationValidation.java
catalog-be/src/main/java/org/openecomp/sdc/be/components/validation/NodeFilterValidator.java
catalog-be/src/main/java/org/openecomp/sdc/be/components/validation/PolicyUtils.java
catalog-be/src/main/java/org/openecomp/sdc/be/components/validation/PropertyValidator.java
catalog-be/src/main/java/org/openecomp/sdc/be/components/validation/RequirementValidation.java
catalog-be/src/main/java/org/openecomp/sdc/be/components/validation/ServiceDistributionValidation.java
catalog-be/src/main/java/org/openecomp/sdc/be/components/validation/UserValidations.java
catalog-be/src/main/java/org/openecomp/sdc/be/components/validation/ValidationException.java
catalog-be/src/main/java/org/openecomp/sdc/be/components/validation/ValidationUtils.java
catalog-be/src/main/java/org/openecomp/sdc/be/components/validation/component/ComponentContactIdValidator.java
catalog-be/src/main/java/org/openecomp/sdc/be/components/validation/component/ComponentDescriptionValidator.java
catalog-be/src/main/java/org/openecomp/sdc/be/components/validation/component/ComponentFieldValidator.java
catalog-be/src/main/java/org/openecomp/sdc/be/components/validation/component/ComponentIconValidator.java
catalog-be/src/main/java/org/openecomp/sdc/be/components/validation/component/ComponentNameValidator.java
catalog-be/src/main/java/org/openecomp/sdc/be/components/validation/component/ComponentProjectCodeValidator.java
catalog-be/src/main/java/org/openecomp/sdc/be/components/validation/component/ComponentTagsValidator.java
catalog-be/src/main/java/org/openecomp/sdc/be/components/validation/component/ComponentValidator.java
catalog-be/src/main/java/org/openecomp/sdc/be/components/validation/service/ServiceCategoryValidator.java
catalog-be/src/main/java/org/openecomp/sdc/be/components/validation/service/ServiceEnvironmentContextValidator.java
catalog-be/src/main/java/org/openecomp/sdc/be/components/validation/service/ServiceFieldValidator.java
catalog-be/src/main/java/org/openecomp/sdc/be/components/validation/service/ServiceFunctionValidator.java
catalog-be/src/main/java/org/openecomp/sdc/be/components/validation/service/ServiceInstantiationTypeValidator.java
catalog-be/src/main/java/org/openecomp/sdc/be/components/validation/service/ServiceNamingPolicyValidator.java
catalog-be/src/main/java/org/openecomp/sdc/be/components/validation/service/ServiceRoleValidator.java
catalog-be/src/main/java/org/openecomp/sdc/be/components/validation/service/ServiceTypeValidator.java
catalog-be/src/main/java/org/openecomp/sdc/be/components/validation/service/ServiceValidator.java
catalog-be/src/main/java/org/openecomp/sdc/be/datamodel/ForwardingPaths.java
catalog-be/src/main/java/org/openecomp/sdc/be/datamodel/NameIdPair.java
catalog-be/src/main/java/org/openecomp/sdc/be/datamodel/NameIdPairWrapper.java
catalog-be/src/main/java/org/openecomp/sdc/be/datamodel/ServiceRelations.java
catalog-be/src/main/java/org/openecomp/sdc/be/datamodel/api/CategoryTypeEnum.java
catalog-be/src/main/java/org/openecomp/sdc/be/datamodel/api/HighestFilterEnum.java
catalog-be/src/main/java/org/openecomp/sdc/be/datamodel/utils/ArtifactUtils.java
catalog-be/src/main/java/org/openecomp/sdc/be/datamodel/utils/ConstraintConvertor.java
catalog-be/src/main/java/org/openecomp/sdc/be/datamodel/utils/NodeTypeConvertUtils.java
catalog-be/src/main/java/org/openecomp/sdc/be/datamodel/utils/PropertyValueConstraintValidationUtil.java
catalog-be/src/main/java/org/openecomp/sdc/be/datamodel/utils/UiComponentDataConverter.java
catalog-be/src/main/java/org/openecomp/sdc/be/distribution/AuditHandler.java
catalog-be/src/main/java/org/openecomp/sdc/be/distribution/DistributionBusinessLogic.java
catalog-be/src/main/java/org/openecomp/sdc/be/distribution/api/client/CambriaOperationStatus.java
catalog-be/src/main/java/org/openecomp/sdc/be/distribution/api/client/RegistrationRequest.java
catalog-be/src/main/java/org/openecomp/sdc/be/distribution/api/client/ServerListResponse.java
catalog-be/src/main/java/org/openecomp/sdc/be/distribution/api/client/TopicRegistrationResponse.java
catalog-be/src/main/java/org/openecomp/sdc/be/distribution/api/client/TopicUnregistrationResponse.java
catalog-be/src/main/java/org/openecomp/sdc/be/distribution/servlet/DistributionCatalogServlet.java
catalog-be/src/main/java/org/openecomp/sdc/be/distribution/servlet/DistributionServlet.java
catalog-be/src/main/java/org/openecomp/sdc/be/dto/ExternalRefDTO.java
catalog-be/src/main/java/org/openecomp/sdc/be/ecomp/EcompIntImpl.java
catalog-be/src/main/java/org/openecomp/sdc/be/ecomp/PortalPropertiesEnum.java
catalog-be/src/main/java/org/openecomp/sdc/be/ecomp/PortalRestApiCentralServiceImpl.java
catalog-be/src/main/java/org/openecomp/sdc/be/ecomp/converters/AssetMetadataConverter.java
catalog-be/src/main/java/org/openecomp/sdc/be/ecomp/converters/EcompRoleConverter.java
catalog-be/src/main/java/org/openecomp/sdc/be/ecomp/converters/EcompUserConverter.java
catalog-be/src/main/java/org/openecomp/sdc/be/exception/RestrictionAccessFilterException.java
catalog-be/src/main/java/org/openecomp/sdc/be/exception/SdcActionException.java
catalog-be/src/main/java/org/openecomp/sdc/be/exception/ToscaExportException.java
catalog-be/src/main/java/org/openecomp/sdc/be/externalapi/servlet/AbstractTemplateServlet.java
catalog-be/src/main/java/org/openecomp/sdc/be/externalapi/servlet/ArtifactExternalServlet.java
catalog-be/src/main/java/org/openecomp/sdc/be/externalapi/servlet/AssetsDataServlet.java
catalog-be/src/main/java/org/openecomp/sdc/be/externalapi/servlet/CrudExternalServlet.java
catalog-be/src/main/java/org/openecomp/sdc/be/externalapi/servlet/ExternalRefsServlet.java
catalog-be/src/main/java/org/openecomp/sdc/be/externalapi/servlet/ServiceActivationServlet.java
catalog-be/src/main/java/org/openecomp/sdc/be/externalapi/servlet/representation/AbstractResourceInfo.java
catalog-be/src/main/java/org/openecomp/sdc/be/externalapi/servlet/representation/ArtifactMetadata.java
catalog-be/src/main/java/org/openecomp/sdc/be/externalapi/servlet/representation/AssetMetadata.java
catalog-be/src/main/java/org/openecomp/sdc/be/externalapi/servlet/representation/CopyServiceInfo.java
catalog-be/src/main/java/org/openecomp/sdc/be/externalapi/servlet/representation/IAssetMetadata.java
catalog-be/src/main/java/org/openecomp/sdc/be/externalapi/servlet/representation/ProductAssetMetadata.java
catalog-be/src/main/java/org/openecomp/sdc/be/externalapi/servlet/representation/ProductCategoryGroupMetadata.java
catalog-be/src/main/java/org/openecomp/sdc/be/externalapi/servlet/representation/ReplaceVNFInfo.java
catalog-be/src/main/java/org/openecomp/sdc/be/externalapi/servlet/representation/ResourceAssetDetailedMetadata.java
catalog-be/src/main/java/org/openecomp/sdc/be/externalapi/servlet/representation/ResourceAssetMetadata.java
catalog-be/src/main/java/org/openecomp/sdc/be/externalapi/servlet/representation/ResourceInstanceMetadata.java
catalog-be/src/main/java/org/openecomp/sdc/be/externalapi/servlet/representation/ServiceAssetDetailedMetadata.java
catalog-be/src/main/java/org/openecomp/sdc/be/externalapi/servlet/representation/ServiceAssetMetadata.java
catalog-be/src/main/java/org/openecomp/sdc/be/externalapi/servlet/representation/ServiceDistributionReqInfo.java
catalog-be/src/main/java/org/openecomp/sdc/be/externalapi/servlet/representation/ServiceDistributionRespInfo.java
catalog-be/src/main/java/org/openecomp/sdc/be/facade/operations/CatalogOperation.java
catalog-be/src/main/java/org/openecomp/sdc/be/facade/operations/FacadeOperationUtils.java
catalog-be/src/main/java/org/openecomp/sdc/be/facade/operations/UserOperation.java
catalog-be/src/main/java/org/openecomp/sdc/be/filters/BasicAuthenticationFilter.java
catalog-be/src/main/java/org/openecomp/sdc/be/filters/BeCadiServletFilter.java
catalog-be/src/main/java/org/openecomp/sdc/be/filters/BeRestrictionAccessFilter.java
catalog-be/src/main/java/org/openecomp/sdc/be/filters/BeServletFilter.java
catalog-be/src/main/java/org/openecomp/sdc/be/filters/ComponentsAvailabilityFilter.java
catalog-be/src/main/java/org/openecomp/sdc/be/filters/FilterConfiguration.java
catalog-be/src/main/java/org/openecomp/sdc/be/filters/GatewayFilter.java
catalog-be/src/main/java/org/openecomp/sdc/be/filters/PortalConfiguration.java
catalog-be/src/main/java/org/openecomp/sdc/be/filters/ReqValidationFilter.java
catalog-be/src/main/java/org/openecomp/sdc/be/filters/ThreadLocalUtils.java
catalog-be/src/main/java/org/openecomp/sdc/be/impl/ComponentsUtils.java
catalog-be/src/main/java/org/openecomp/sdc/be/impl/ForwardingPathUtils.java
catalog-be/src/main/java/org/openecomp/sdc/be/impl/ServiceFilterUtils.java
catalog-be/src/main/java/org/openecomp/sdc/be/impl/ServletUtils.java
catalog-be/src/main/java/org/openecomp/sdc/be/impl/WebAppContextWrapper.java
catalog-be/src/main/java/org/openecomp/sdc/be/info/ArtifactDefinitionInfo.java
catalog-be/src/main/java/org/openecomp/sdc/be/info/ArtifactTemplateInfo.java
catalog-be/src/main/java/org/openecomp/sdc/be/info/ArtifactTypesInfo.java
catalog-be/src/main/java/org/openecomp/sdc/be/info/CreateAndAssotiateInfo.java
catalog-be/src/main/java/org/openecomp/sdc/be/info/DistributionStatus.java
catalog-be/src/main/java/org/openecomp/sdc/be/info/DistributionStatusInfo.java
catalog-be/src/main/java/org/openecomp/sdc/be/info/DistributionStatusListResponse.java
catalog-be/src/main/java/org/openecomp/sdc/be/info/DistributionStatusOfServiceInfo.java
catalog-be/src/main/java/org/openecomp/sdc/be/info/DistributionStatusOfServiceListResponce.java
catalog-be/src/main/java/org/openecomp/sdc/be/info/GenericArtifactQueryInfo.java
catalog-be/src/main/java/org/openecomp/sdc/be/info/GroupDefinitionInfo.java
catalog-be/src/main/java/org/openecomp/sdc/be/info/GroupTemplateInfo.java
catalog-be/src/main/java/org/openecomp/sdc/be/info/MergedArtifactInfo.java
catalog-be/src/main/java/org/openecomp/sdc/be/info/NodeTypeInfoToUpdateArtifacts.java
catalog-be/src/main/java/org/openecomp/sdc/be/info/OperationalEnvInfo.java
catalog-be/src/main/java/org/openecomp/sdc/be/info/RelatedToProperty.java
catalog-be/src/main/java/org/openecomp/sdc/be/info/Relationship.java
catalog-be/src/main/java/org/openecomp/sdc/be/info/RelationshipData.java
catalog-be/src/main/java/org/openecomp/sdc/be/info/RelationshipList.java
catalog-be/src/main/java/org/openecomp/sdc/be/info/ServiceInfo.java
catalog-be/src/main/java/org/openecomp/sdc/be/info/ServiceVersionInfo.java
catalog-be/src/main/java/org/openecomp/sdc/be/info/ServicesWrapper.java
catalog-be/src/main/java/org/openecomp/sdc/be/info/ServletJsonResponse.java
catalog-be/src/main/java/org/openecomp/sdc/be/info/ToscaNodeTypeInfo.java
catalog-be/src/main/java/org/openecomp/sdc/be/info/ToscaNodeTypeInterface.java
catalog-be/src/main/java/org/openecomp/sdc/be/listen/BEAppContextListener.java
catalog-be/src/main/java/org/openecomp/sdc/be/mixin/ComponentInstanceInputMixin.java
catalog-be/src/main/java/org/openecomp/sdc/be/mixin/ComponentInstancePropertyMixin.java
catalog-be/src/main/java/org/openecomp/sdc/be/mixin/GroupCompositionMixin.java
catalog-be/src/main/java/org/openecomp/sdc/be/mixin/GroupTypeMixin.java
catalog-be/src/main/java/org/openecomp/sdc/be/mixin/InputDefinitionMixin.java
catalog-be/src/main/java/org/openecomp/sdc/be/mixin/PolicyCompositionMixin.java
catalog-be/src/main/java/org/openecomp/sdc/be/mixin/PolicyTypeMixin.java
catalog-be/src/main/java/org/openecomp/sdc/be/mixin/PropertyDefinitionMixin.java
catalog-be/src/main/java/org/openecomp/sdc/be/plugins/CsarEntryGenerator.java
catalog-be/src/main/java/org/openecomp/sdc/be/plugins/ServiceCreationPlugin.java
catalog-be/src/main/java/org/openecomp/sdc/be/servlets/AbstractValidationsServlet.java
catalog-be/src/main/java/org/openecomp/sdc/be/servlets/AdditionalInformationServlet.java
catalog-be/src/main/java/org/openecomp/sdc/be/servlets/ArchiveEndpoint.java
catalog-be/src/main/java/org/openecomp/sdc/be/servlets/ArtifactServlet.java
catalog-be/src/main/java/org/openecomp/sdc/be/servlets/AttributeServlet.java
catalog-be/src/main/java/org/openecomp/sdc/be/servlets/AutomatedUpgradeEndpoint.java
catalog-be/src/main/java/org/openecomp/sdc/be/servlets/BeGenericServlet.java
catalog-be/src/main/java/org/openecomp/sdc/be/servlets/BeMonitoringServlet.java
catalog-be/src/main/java/org/openecomp/sdc/be/servlets/CapabilityServlet.java
catalog-be/src/main/java/org/openecomp/sdc/be/servlets/ComponentAttributeServlet.java
catalog-be/src/main/java/org/openecomp/sdc/be/servlets/ComponentInstanceServlet.java
catalog-be/src/main/java/org/openecomp/sdc/be/servlets/ComponentInterfaceOperationServlet.java
catalog-be/src/main/java/org/openecomp/sdc/be/servlets/ComponentNodeFilterServlet.java
catalog-be/src/main/java/org/openecomp/sdc/be/servlets/ComponentPropertyServlet.java
catalog-be/src/main/java/org/openecomp/sdc/be/servlets/ComponentServlet.java
catalog-be/src/main/java/org/openecomp/sdc/be/servlets/ComponentSubstitutionFilterServlet.java
catalog-be/src/main/java/org/openecomp/sdc/be/servlets/ConfigMgrServlet.java
catalog-be/src/main/java/org/openecomp/sdc/be/servlets/ConfigServlet.java
catalog-be/src/main/java/org/openecomp/sdc/be/servlets/ConsumerServlet.java
catalog-be/src/main/java/org/openecomp/sdc/be/servlets/DirectiveServlet.java
catalog-be/src/main/java/org/openecomp/sdc/be/servlets/DistributionServiceServlet.java
catalog-be/src/main/java/org/openecomp/sdc/be/servlets/ElementServlet.java
catalog-be/src/main/java/org/openecomp/sdc/be/servlets/ExceptionHandlerEndpoint.java
catalog-be/src/main/java/org/openecomp/sdc/be/servlets/GenericArtifactBrowserServlet.java
catalog-be/src/main/java/org/openecomp/sdc/be/servlets/GroupEndpoint.java
catalog-be/src/main/java/org/openecomp/sdc/be/servlets/GroupServlet.java
catalog-be/src/main/java/org/openecomp/sdc/be/servlets/GroupTypesEndpoint.java
catalog-be/src/main/java/org/openecomp/sdc/be/servlets/InputsServlet.java
catalog-be/src/main/java/org/openecomp/sdc/be/servlets/InterfaceOperationServlet.java
catalog-be/src/main/java/org/openecomp/sdc/be/servlets/LifecycleServlet.java
catalog-be/src/main/java/org/openecomp/sdc/be/servlets/OutputsServlet.java
catalog-be/src/main/java/org/openecomp/sdc/be/servlets/PolicyServlet.java
catalog-be/src/main/java/org/openecomp/sdc/be/servlets/PolicyTypesEndpoint.java
catalog-be/src/main/java/org/openecomp/sdc/be/servlets/RepresentationUtils.java
catalog-be/src/main/java/org/openecomp/sdc/be/servlets/RequirementServlet.java
catalog-be/src/main/java/org/openecomp/sdc/be/servlets/ResourceUploadServlet.java
catalog-be/src/main/java/org/openecomp/sdc/be/servlets/ResourcesServlet.java
catalog-be/src/main/java/org/openecomp/sdc/be/servlets/ServiceConsumptionServlet.java
catalog-be/src/main/java/org/openecomp/sdc/be/servlets/ServiceForwardingPathServlet.java
catalog-be/src/main/java/org/openecomp/sdc/be/servlets/ServiceServlet.java
catalog-be/src/main/java/org/openecomp/sdc/be/servlets/ServiceUploadServlet.java
catalog-be/src/main/java/org/openecomp/sdc/be/servlets/TogglingServlet.java
catalog-be/src/main/java/org/openecomp/sdc/be/servlets/TypesFetchServlet.java
catalog-be/src/main/java/org/openecomp/sdc/be/servlets/TypesUploadEndpoint.java
catalog-be/src/main/java/org/openecomp/sdc/be/servlets/TypesUploadServlet.java
catalog-be/src/main/java/org/openecomp/sdc/be/servlets/UserAdminServlet.java
catalog-be/src/main/java/org/openecomp/sdc/be/servlets/exception/ComponentExceptionMapper.java
catalog-be/src/main/java/org/openecomp/sdc/be/servlets/exception/ConstraintViolationExceptionMapper.java
catalog-be/src/main/java/org/openecomp/sdc/be/servlets/exception/DefaultExceptionMapper.java
catalog-be/src/main/java/org/openecomp/sdc/be/servlets/exception/PropertyConstraintExceptionMapper.java
catalog-be/src/main/java/org/openecomp/sdc/be/servlets/exception/StorageExceptionMapper.java
catalog-be/src/main/java/org/openecomp/sdc/be/switchover/detector/SwitchoverDetector.java
catalog-be/src/main/java/org/openecomp/sdc/be/togglz/CassandraCustomStateRepository.java
catalog-be/src/main/java/org/openecomp/sdc/be/tosca/AttributeConverter.java
catalog-be/src/main/java/org/openecomp/sdc/be/tosca/CapabilityRequirementConverter.java
catalog-be/src/main/java/org/openecomp/sdc/be/tosca/ComponentCache.java
catalog-be/src/main/java/org/openecomp/sdc/be/tosca/CsarUtils.java
catalog-be/src/main/java/org/openecomp/sdc/be/tosca/FJToVavrHelper.java
catalog-be/src/main/java/org/openecomp/sdc/be/tosca/GroupExportParser.java
catalog-be/src/main/java/org/openecomp/sdc/be/tosca/GroupExportParserImpl.java
catalog-be/src/main/java/org/openecomp/sdc/be/tosca/InterfacesOperationsConverter.java
catalog-be/src/main/java/org/openecomp/sdc/be/tosca/PolicyExportParser.java
catalog-be/src/main/java/org/openecomp/sdc/be/tosca/PolicyExportParserImpl.java
catalog-be/src/main/java/org/openecomp/sdc/be/tosca/PropertyConvertor.java
catalog-be/src/main/java/org/openecomp/sdc/be/tosca/ToscaError.java
catalog-be/src/main/java/org/openecomp/sdc/be/tosca/ToscaExportHandler.java
catalog-be/src/main/java/org/openecomp/sdc/be/tosca/ToscaExportRelationshipTemplatesHandler.java
catalog-be/src/main/java/org/openecomp/sdc/be/tosca/ToscaRepresentation.java
catalog-be/src/main/java/org/openecomp/sdc/be/tosca/ToscaUtils.java
catalog-be/src/main/java/org/openecomp/sdc/be/tosca/ZipWriter.java
catalog-be/src/main/java/org/openecomp/sdc/be/tosca/builder/ToscaRelationshipBuilder.java
catalog-be/src/main/java/org/openecomp/sdc/be/tosca/exception/ToscaConversionException.java
catalog-be/src/main/java/org/openecomp/sdc/be/tosca/model/CapabilityFilter.java
catalog-be/src/main/java/org/openecomp/sdc/be/tosca/model/IToscaMetadata.java
catalog-be/src/main/java/org/openecomp/sdc/be/tosca/model/NodeFilter.java
catalog-be/src/main/java/org/openecomp/sdc/be/tosca/model/SubstitutionMapping.java
catalog-be/src/main/java/org/openecomp/sdc/be/tosca/model/ToscaAnnotation.java
catalog-be/src/main/java/org/openecomp/sdc/be/tosca/model/ToscaAttribute.java
catalog-be/src/main/java/org/openecomp/sdc/be/tosca/model/ToscaCapability.java
catalog-be/src/main/java/org/openecomp/sdc/be/tosca/model/ToscaDataType.java
catalog-be/src/main/java/org/openecomp/sdc/be/tosca/model/ToscaGroupTemplate.java
catalog-be/src/main/java/org/openecomp/sdc/be/tosca/model/ToscaInput.java
catalog-be/src/main/java/org/openecomp/sdc/be/tosca/model/ToscaInterfaceDefinition.java
catalog-be/src/main/java/org/openecomp/sdc/be/tosca/model/ToscaInterfaceNodeType.java
catalog-be/src/main/java/org/openecomp/sdc/be/tosca/model/ToscaLifecycleOperationDefinition.java
catalog-be/src/main/java/org/openecomp/sdc/be/tosca/model/ToscaMetadata.java
catalog-be/src/main/java/org/openecomp/sdc/be/tosca/model/ToscaNodeTemplate.java
catalog-be/src/main/java/org/openecomp/sdc/be/tosca/model/ToscaNodeType.java
catalog-be/src/main/java/org/openecomp/sdc/be/tosca/model/ToscaOperationAssignment.java
catalog-be/src/main/java/org/openecomp/sdc/be/tosca/model/ToscaOutput.java
catalog-be/src/main/java/org/openecomp/sdc/be/tosca/model/ToscaPolicyTemplate.java
catalog-be/src/main/java/org/openecomp/sdc/be/tosca/model/ToscaProperty.java
catalog-be/src/main/java/org/openecomp/sdc/be/tosca/model/ToscaPropertyAssignment.java
catalog-be/src/main/java/org/openecomp/sdc/be/tosca/model/ToscaPropertyConstraint.java
catalog-be/src/main/java/org/openecomp/sdc/be/tosca/model/ToscaPropertyConstraintValidValues.java
catalog-be/src/main/java/org/openecomp/sdc/be/tosca/model/ToscaRelationship.java
catalog-be/src/main/java/org/openecomp/sdc/be/tosca/model/ToscaRelationshipTemplate.java
catalog-be/src/main/java/org/openecomp/sdc/be/tosca/model/ToscaRequirement.java
catalog-be/src/main/java/org/openecomp/sdc/be/tosca/model/ToscaSchemaDefinition.java
catalog-be/src/main/java/org/openecomp/sdc/be/tosca/model/ToscaTemplate.java
catalog-be/src/main/java/org/openecomp/sdc/be/tosca/model/ToscaTemplateArtifact.java
catalog-be/src/main/java/org/openecomp/sdc/be/tosca/model/ToscaTemplateCapability.java
catalog-be/src/main/java/org/openecomp/sdc/be/tosca/model/ToscaTemplateRequirement.java
catalog-be/src/main/java/org/openecomp/sdc/be/tosca/model/ToscaTopolgyTemplate.java
catalog-be/src/main/java/org/openecomp/sdc/be/tosca/model/VfModuleToscaMetadata.java
catalog-be/src/main/java/org/openecomp/sdc/be/tosca/utils/ForwardingPathToscaUtil.java
catalog-be/src/main/java/org/openecomp/sdc/be/tosca/utils/InputConverter.java
catalog-be/src/main/java/org/openecomp/sdc/be/tosca/utils/InterfaceTypesNameUtil.java
catalog-be/src/main/java/org/openecomp/sdc/be/tosca/utils/NodeFilterConverter.java
catalog-be/src/main/java/org/openecomp/sdc/be/tosca/utils/OperationArtifactUtil.java
catalog-be/src/main/java/org/openecomp/sdc/be/tosca/utils/OutputConverter.java
catalog-be/src/main/java/org/openecomp/sdc/be/tosca/utils/SubstitutionFilterConverter.java
catalog-be/src/main/java/org/openecomp/sdc/be/types/ServiceConsumptionData.java
catalog-be/src/main/java/org/openecomp/sdc/be/types/ServiceConsumptionSource.java
catalog-be/src/main/java/org/openecomp/sdc/be/user/Role.java
catalog-be/src/main/java/org/openecomp/sdc/be/user/UserAdminAction.java
catalog-be/src/main/java/org/openecomp/sdc/be/user/UserAdminValidator.java
catalog-be/src/main/java/org/openecomp/sdc/be/user/UserBusinessLogic.java
catalog-be/src/main/java/org/openecomp/sdc/be/user/UserBusinessLogicExt.java
catalog-be/src/main/java/org/openecomp/sdc/be/user/UserMessage.java
catalog-be/src/main/java/org/openecomp/sdc/be/user/UserOperationEnum.java
catalog-be/src/main/java/org/openecomp/sdc/be/view/Mixin.java
catalog-be/src/main/java/org/openecomp/sdc/be/view/MixinModelWriter.java
catalog-be/src/main/java/org/openecomp/sdc/be/view/MixinSourceTarget.java
catalog-be/src/main/java/org/openecomp/sdc/be/view/MixinTarget.java
catalog-be/src/main/java/org/openecomp/sdc/be/view/ResponseView.java
catalog-be/src/main/java/org/openecomp/sdc/config/CatalogBESpringConfig.java
catalog-be/src/main/java/org/openecomp/sdc/config/HttpClientFactory.java
catalog-be/src/main/java/org/openecomp/sdc/config/ObjectMapperProvider.java
catalog-be/src/main/java/org/openecomp/sdc/externalupload/utils/ServiceUtils.java

index 541fea8..3359285 100644 (file)
@@ -17,7 +17,6 @@
  * limitations under the License.
  * ============LICENSE_END=========================================================
  */
-
 package org.openecomp.sdc.be.auditing.api;
 
 import java.util.List;
index e3d4313..66f67c3 100644 (file)
@@ -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.
@@ -17,7 +17,6 @@
  * limitations under the License.
  * ============LICENSE_END=========================================================
  */
-
 package org.openecomp.sdc.be.auditing.impl;
 
 import org.openecomp.sdc.be.resources.data.auditing.AuditingActionEnum;
@@ -27,7 +26,7 @@ import org.openecomp.sdc.be.resources.data.auditing.model.CommonAuditData;
 
 public class AuditAuthRequestEventFactory extends AuditBaseEventFactory {
 
-    private static final String LOG_STR =  "ACTION = \"%s\" URL = \"%s\" USER = \"%s\" AUTH_STATUS = \"%s\" REALM = \"%s\"";
+    private static final String LOG_STR = "ACTION = \"%s\" URL = \"%s\" USER = \"%s\" AUTH_STATUS = \"%s\" REALM = \"%s\"";
     private final AuthEvent event;
 
     public AuditAuthRequestEventFactory(CommonAuditData commonFields, String authUser, String authUrl, String realm, String authStatus) {
@@ -35,10 +34,10 @@ public class AuditAuthRequestEventFactory extends AuditBaseEventFactory {
         event = new AuthEvent(getAction().getName(), commonFields, authUser, authUrl, realm, authStatus);
     }
 
-    public AuditAuthRequestEventFactory(CommonAuditData commonFields, String authUser, String authUrl, String realm,
-                                        String authStatus, String timestamp) {
-       this(commonFields, authUser, authUrl, realm, authStatus);
-       this.event.setTimestamp1(timestamp);
+    public AuditAuthRequestEventFactory(CommonAuditData commonFields, String authUser, String authUrl, String realm, String authStatus,
+                                        String timestamp) {
+        this(commonFields, authUser, authUrl, realm, authStatus);
+        this.event.setTimestamp1(timestamp);
     }
 
     @Override
@@ -48,10 +47,11 @@ public class AuditAuthRequestEventFactory extends AuditBaseEventFactory {
 
     @Override
     public String[] getLogMessageParams() {
-        return new String[] {event.getAction(), event.getUrl(), event.getUser(),
-                event.getAuthStatus(), event.getRealm()};
+        return new String[]{event.getAction(), event.getUrl(), event.getUser(), event.getAuthStatus(), event.getRealm()};
     }
 
     @Override
-    public AuditingGenericEvent getDbEvent() { return event; }
+    public AuditingGenericEvent getDbEvent() {
+        return event;
+    }
 }
index 91212ad..986b60b 100644 (file)
@@ -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.
  * limitations under the License.
  * ============LICENSE_END=========================================================
  */
-
 package org.openecomp.sdc.be.auditing.impl;
 
+import java.util.Arrays;
+import java.util.Collections;
+import java.util.List;
+import java.util.Objects;
 import org.apache.commons.lang.StringUtils;
 import org.javatuples.Pair;
 import org.openecomp.sdc.be.auditing.api.AuditEventFactory;
@@ -27,10 +30,6 @@ import org.openecomp.sdc.be.model.User;
 import org.openecomp.sdc.be.resources.data.auditing.AuditingActionEnum;
 import org.openecomp.sdc.common.api.Constants;
 
-import java.util.Arrays;
-import java.util.Collections;
-import java.util.List;
-import java.util.Objects;
 public abstract class AuditBaseEventFactory implements AuditEventFactory {
 
     private AuditingActionEnum action;
@@ -39,32 +38,24 @@ public abstract class AuditBaseEventFactory implements AuditEventFactory {
         this.action = Objects.requireNonNull(action);
     }
 
-    public AuditBaseEventFactory() {}
-
-    public AuditingActionEnum getAction() {
-        return action;
+    public AuditBaseEventFactory() {
     }
 
     public static String buildUserNameExtended(User user) {
         if (user == null) {
             return null;
         }
-
         StringBuilder builder = new StringBuilder();
         appendIfNotEmpty(user.getUserId(), builder);
-
         String firstName = replaceNullNameWithEmpty(user.getFirstName());
         String lastName = replaceNullNameWithEmpty(user.getLastName());
-
         if (appendIfNotEmpty(firstName, builder)) {
             appendIfNotEmpty(lastName, builder, " ");
-        }
-        else {
+        } else {
             appendIfNotEmpty(lastName, builder);
         }
         appendIfNotEmpty(user.getEmail(), builder);
         appendIfNotEmpty(user.getRole(), builder);
-
         return builder.toString();
     }
 
@@ -119,6 +110,10 @@ public abstract class AuditBaseEventFactory implements AuditEventFactory {
         return StringUtils.EMPTY;
     }
 
+    public AuditingActionEnum getAction() {
+        return action;
+    }
+
     @Override
     //TODO implement in derived classes for ci testing
     public List<Pair<String, String>> getQueryParams() {
@@ -127,20 +122,14 @@ public abstract class AuditBaseEventFactory implements AuditEventFactory {
 
     @Override
     public final String getLogMessage() {
-       return String.format(getLogPattern(), getLogArgs());
+        return String.format(getLogPattern(), getLogArgs());
     }
 
     private Object[] getLogArgs() {
-        return Arrays.stream(getLogMessageParams())
-                .map(AuditBaseEventFactory::buildValue)
-                .toArray(String[]::new);
+        return Arrays.stream(getLogMessageParams()).map(AuditBaseEventFactory::buildValue).toArray(String[]::new);
     }
 
     public abstract String getLogPattern();
 
     public abstract String[] getLogMessageParams();
-
-
-
-
 }
index 9176a1a..9233a1a 100644 (file)
@@ -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.
@@ -17,7 +17,6 @@
  * limitations under the License.
  * ============LICENSE_END=========================================================
  */
-
 package org.openecomp.sdc.be.auditing.impl;
 
 import org.openecomp.sdc.be.model.ConsumerDefinition;
@@ -36,18 +35,26 @@ public class AuditConsumerEventFactory extends AuditBaseEventFactory {
         this(action, commonFields, buildConsumerName(ecompUser), buildUserName(modifier));
     }
 
-    public AuditConsumerEventFactory(AuditingActionEnum action, CommonAuditData commonFields,
-                                     String ecompUser, String modifier, String timestamp) {
+    public AuditConsumerEventFactory(AuditingActionEnum action, CommonAuditData commonFields, String ecompUser, String modifier, String timestamp) {
         this(action, commonFields, ecompUser, modifier);
         this.event.setTimestamp1(timestamp);
     }
 
-    private AuditConsumerEventFactory(AuditingActionEnum action, CommonAuditData commonFields,
-                                      String ecompUser, String modifier) {
+    private AuditConsumerEventFactory(AuditingActionEnum action, CommonAuditData commonFields, String ecompUser, String modifier) {
         super(action);
         event = new ConsumerEvent(getAction().getName(), commonFields, ecompUser, modifier);
     }
 
+    static String buildConsumerName(ConsumerDefinition consumer) {
+        StringBuilder ecompUser = new StringBuilder();
+        if (consumer != null) {
+            appendIfNotEmpty(consumer.getConsumerName(), ecompUser, ",");
+            appendIfNotEmpty(consumer.getConsumerSalt(), ecompUser, ",");
+            appendIfNotEmpty(consumer.getConsumerPassword(), ecompUser, ",");
+        }
+        return ecompUser.toString();
+    }
+
     @Override
     public String getLogPattern() {
         return LOG_STR;
@@ -55,21 +62,11 @@ public class AuditConsumerEventFactory extends AuditBaseEventFactory {
 
     @Override
     public String[] getLogMessageParams() {
-        return new String[] {event.getAction(), event.getModifier(), event.getEcompUser(), event.getStatus(), event.getDesc()};
+        return new String[]{event.getAction(), event.getModifier(), event.getEcompUser(), event.getStatus(), event.getDesc()};
     }
 
     @Override
     public AuditingGenericEvent getDbEvent() {
         return event;
     }
-
-    static String buildConsumerName(ConsumerDefinition consumer) {
-        StringBuilder ecompUser = new StringBuilder();
-        if (consumer != null) {
-            appendIfNotEmpty(consumer.getConsumerName(), ecompUser, ",");
-            appendIfNotEmpty(consumer.getConsumerSalt(), ecompUser, ",");
-            appendIfNotEmpty(consumer.getConsumerPassword(), ecompUser, ",");
-        }
-        return ecompUser.toString();
-    }
 }
index db394cc..8bed7fe 100644 (file)
@@ -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.
@@ -17,7 +17,6 @@
  * limitations under the License.
  * ============LICENSE_END=========================================================
  */
-
 package org.openecomp.sdc.be.auditing.impl;
 
 import org.openecomp.sdc.be.resources.data.auditing.AuditingActionEnum;
@@ -25,15 +24,16 @@ import org.openecomp.sdc.be.resources.data.auditing.AuditingGenericEvent;
 import org.openecomp.sdc.be.resources.data.auditing.EcompOperationalEnvironmentEvent;
 
 public class AuditEcompOpEnvEventFactory extends AuditBaseEventFactory {
-    private static final String LOG_STR =  "ACTION = \"%s\" OPERATIONAL_ENVIRONMENT_ACTION = \"%s\" OPERATIONAL_ENVIRONMENT_ID = \"%s\"" +
-            " OPERATIONAL_ENVIRONMENT_NAME = \"%s\" OPERATIONAL_ENVIRONMENT_TYPE = \"%s\" TENANT_CONTEXT = \"%s\"";
+
+    private static final String LOG_STR = "ACTION = \"%s\" OPERATIONAL_ENVIRONMENT_ACTION = \"%s\" OPERATIONAL_ENVIRONMENT_ID = \"%s\""
+        + " OPERATIONAL_ENVIRONMENT_NAME = \"%s\" OPERATIONAL_ENVIRONMENT_TYPE = \"%s\" TENANT_CONTEXT = \"%s\"";
     private final EcompOperationalEnvironmentEvent event;
 
     public AuditEcompOpEnvEventFactory(AuditingActionEnum action, String operationalEnvironmentId, String operationalEnvironmentName,
                                        String operationalEnvironmentType, String operationalEnvironmentAction, String tenantContext) {
         super(action);
         event = new EcompOperationalEnvironmentEvent(getAction().getName(), operationalEnvironmentId, operationalEnvironmentName,
-                                                            operationalEnvironmentType, operationalEnvironmentAction, tenantContext);
+            operationalEnvironmentType, operationalEnvironmentAction, tenantContext);
     }
 
     @Override
@@ -43,11 +43,12 @@ public class AuditEcompOpEnvEventFactory extends AuditBaseEventFactory {
 
     @Override
     public String[] getLogMessageParams() {
-        return new String[] {event.getAction(), event.getOperationalEnvironmentAction(),
-                event.getOperationalEnvironmentId(), event.getOperationalEnvironmentName(),
-                event.getOperationalEnvironmentType(), event.getTenantContext()};
+        return new String[]{event.getAction(), event.getOperationalEnvironmentAction(), event.getOperationalEnvironmentId(),
+            event.getOperationalEnvironmentName(), event.getOperationalEnvironmentType(), event.getTenantContext()};
     }
 
-   @Override
-    public AuditingGenericEvent getDbEvent() { return event; }
+    @Override
+    public AuditingGenericEvent getDbEvent() {
+        return event;
+    }
 }
index 9994f04..5239801 100644 (file)
@@ -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.
@@ -17,7 +17,6 @@
  * limitations under the License.
  * ============LICENSE_END=========================================================
  */
-
 package org.openecomp.sdc.be.auditing.impl;
 
 import org.openecomp.sdc.be.resources.data.auditing.AuditingActionEnum;
@@ -31,7 +30,6 @@ public class AuditGetUebClusterEventFactory extends AuditBaseEventFactory {
     private final AuditingGetUebClusterEvent event;
 
     public AuditGetUebClusterEventFactory(CommonAuditData commonFields, String consumerId) {
-
         super(AuditingActionEnum.GET_UEB_CLUSTER);
         event = new AuditingGetUebClusterEvent(getAction().getName(), commonFields, consumerId);
     }
@@ -48,12 +46,11 @@ public class AuditGetUebClusterEventFactory extends AuditBaseEventFactory {
 
     @Override
     public String[] getLogMessageParams() {
-        return new String[] {event.getAction(), event.getConsumerId(), event.getTimestamp(), event.getStatus(), event.getDesc()};
+        return new String[]{event.getAction(), event.getConsumerId(), event.getTimestamp(), event.getStatus(), event.getDesc()};
     }
 
     @Override
     public AuditingGenericEvent getDbEvent() {
         return event;
     }
-
 }
index 0f94ad2..7130666 100644 (file)
@@ -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,7 +19,6 @@
  * Modifications copyright (c) 2019 Nokia
  * ================================================================================
  */
-
 package org.openecomp.sdc.be.auditing.impl;
 
 import org.onap.logging.ref.slf4j.ONAPLogConstants;
@@ -39,7 +38,6 @@ import org.springframework.stereotype.Component;
 public class AuditingManager {
 
     private static final Logger log = Logger.getLogger(AuditingManager.class.getName());
-
     private final AuditCassandraDao cassandraDao;
     private final ConfigurationProvider configurationProvider;
 
@@ -54,7 +52,6 @@ public class AuditingManager {
         }
         String msg = factory.getLogMessage();
         logAuditEvent(msg);
-
         saveEventToCassandra(factory.getDbEvent());
         return msg;
     }
@@ -66,9 +63,8 @@ public class AuditingManager {
     }
 
     private void logAuditEvent(String msg, LoggerSdcAudit audit, String requestId) {
-        if(audit != null) {
-            audit.logEntry(LogLevel.INFO, Severity.OK, msg,
-                    MarkerFactory.getMarker(ONAPLogConstants.Markers.ENTRY.getName()), requestId);
+        if (audit != null) {
+            audit.logEntry(LogLevel.INFO, Severity.OK, msg, MarkerFactory.getMarker(ONAPLogConstants.Markers.ENTRY.getName()), requestId);
         }
     }
 
@@ -82,12 +78,10 @@ public class AuditingManager {
     private void logAuditEvent(final String formattedString) {
         log.trace("logAuditEvent - start");
         log.debug(formattedString);
-        LogFieldsMdcHandler.getInstance()
-                .setAuditMessage(formattedString);
-        if (!LoggerSdcAudit.isFlowBeingTakenCare()){
+        LogFieldsMdcHandler.getInstance().setAuditMessage(formattedString);
+        if (!LoggerSdcAudit.isFlowBeingTakenCare()) {
             log.debug("MOVED FROM AUDIT LOG: {}", formattedString);
         }
         log.trace("logAuditEvent - end");
     }
-
 }
index 919963b..d4e1c37 100644 (file)
@@ -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.
@@ -17,7 +17,6 @@
  * limitations under the License.
  * ============LICENSE_END=========================================================
  */
-
 package org.openecomp.sdc.be.auditing.impl.category;
 
 import org.openecomp.sdc.be.auditing.impl.AuditBaseEventFactory;
@@ -29,20 +28,18 @@ import org.openecomp.sdc.be.resources.data.auditing.model.CommonAuditData;
 
 public class AuditCategoryEventFactory extends AuditBaseEventFactory {
 
-    private static final  String LOG_STR = "ACTION = \"%s\" MODIFIER = \"%s\" CATEGORY_NAME = \"%s\" SUB_CATEGORY_NAME = \"%s\"" +
-            " GROUPING_NAME = \"%s\" RESOURCE_TYPE = \"%s\" STATUS = \"%s\" DESC = \"%s\"";
+    private static final String LOG_STR = "ACTION = \"%s\" MODIFIER = \"%s\" CATEGORY_NAME = \"%s\" SUB_CATEGORY_NAME = \"%s\""
+        + " GROUPING_NAME = \"%s\" RESOURCE_TYPE = \"%s\" STATUS = \"%s\" DESC = \"%s\"";
     private final CategoryEvent event;
 
-
     private AuditCategoryEventFactory(AuditingActionEnum action, CommonAuditData commonFields, String modifier, String categoryName,
                                       String subCategoryName, String groupingName, String resourceType) {
         super(action);
-        event = new CategoryEvent(getAction().getName(), commonFields, modifier, categoryName,
-                subCategoryName, groupingName, resourceType);
+        event = new CategoryEvent(getAction().getName(), commonFields, modifier, categoryName, subCategoryName, groupingName, resourceType);
     }
 
-    public AuditCategoryEventFactory(AuditingActionEnum action, CommonAuditData commonFields, User modifier,
-                                     String categoryName, String subCategoryName, String groupingName, String resourceType) {
+    public AuditCategoryEventFactory(AuditingActionEnum action, CommonAuditData commonFields, User modifier, String categoryName,
+                                     String subCategoryName, String groupingName, String resourceType) {
         this(action, commonFields, buildUserName(modifier), categoryName, subCategoryName, groupingName, resourceType);
     }
 
@@ -59,14 +56,12 @@ public class AuditCategoryEventFactory extends AuditBaseEventFactory {
 
     @Override
     public String[] getLogMessageParams() {
-        return new String[] {event.getAction(), event.getModifier(), event.getCategoryName(), event.getSubCategoryName(),
-                event.getGroupingName(), event.getResourceType(), event.getStatus(), event.getDesc()};
+        return new String[]{event.getAction(), event.getModifier(), event.getCategoryName(), event.getSubCategoryName(), event.getGroupingName(),
+            event.getResourceType(), event.getStatus(), event.getDesc()};
     }
 
     @Override
     public AuditingGenericEvent getDbEvent() {
         return event;
     }
-
-
 }
index 621d0b9..2038c1f 100644 (file)
@@ -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.
@@ -17,7 +17,6 @@
  * limitations under the License.
  * ============LICENSE_END=========================================================
  */
-
 package org.openecomp.sdc.be.auditing.impl.category;
 
 import org.openecomp.sdc.be.auditing.impl.AuditBaseEventFactory;
@@ -30,7 +29,7 @@ import org.openecomp.sdc.be.resources.data.auditing.model.CommonAuditData;
 public class AuditGetCategoryHierarchyEventFactory extends AuditBaseEventFactory {
 
     private static final String LOG_STR = "ACTION = \"%s\" MODIFIER = \"%s\" DETAILS = \"%s\" STATUS = \"%s\" DESC = \"%s\"";
-    private final  GetCategoryHierarchyEvent event;
+    private final GetCategoryHierarchyEvent event;
 
     public AuditGetCategoryHierarchyEventFactory(CommonAuditData commonFields, User modifier, String details) {
         this(commonFields, buildUserName(modifier), details);
@@ -53,13 +52,11 @@ public class AuditGetCategoryHierarchyEventFactory extends AuditBaseEventFactory
 
     @Override
     public String[] getLogMessageParams() {
-        return new String[] {event.getAction(), event.getModifier(), event.getDetails(), event.getStatus(), event.getDesc()};
+        return new String[]{event.getAction(), event.getModifier(), event.getDetails(), event.getStatus(), event.getDesc()};
     }
 
     @Override
     public AuditingGenericEvent getDbEvent() {
         return event;
     }
-
-
 }
index f6dee4c..e7ea41b 100644 (file)
@@ -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.
@@ -17,7 +17,6 @@
  * limitations under the License.
  * ============LICENSE_END=========================================================
  */
-
 package org.openecomp.sdc.be.auditing.impl.distribution;
 
 import org.openecomp.sdc.be.resources.data.auditing.AuditingActionEnum;
@@ -26,11 +25,10 @@ import org.openecomp.sdc.be.resources.data.auditing.model.DistributionTopicData;
 
 public class AuditAddRemoveKeyDistributionEngineEventFactory extends AuditDistributionEngineEventFactory {
 
-    private static final String LOG_STR = "ACTION = \"%s\" D_ENV = \"%s\" TOPIC_NAME = \"%s\" ROLE = \"%s\" " +
-            "API_KEY = \"%s\" STATUS = \"%s\"";
+    private static final String LOG_STR = "ACTION = \"%s\" D_ENV = \"%s\" TOPIC_NAME = \"%s\" ROLE = \"%s\" " + "API_KEY = \"%s\" STATUS = \"%s\"";
 
-    AuditAddRemoveKeyDistributionEngineEventFactory(AuditingActionEnum action, CommonAuditData commonFields, DistributionTopicData distributionTopicData,
-                                                           String apiKey, String envName, String role) {
+    AuditAddRemoveKeyDistributionEngineEventFactory(AuditingActionEnum action, CommonAuditData commonFields,
+                                                    DistributionTopicData distributionTopicData, String apiKey, String envName, String role) {
         super(action, commonFields, distributionTopicData, null, apiKey, envName, role);
     }
 
@@ -42,8 +40,6 @@ public class AuditAddRemoveKeyDistributionEngineEventFactory extends AuditDistri
     @Override
     public String[] getLogMessageParams() {
         String topicName = event.getDnotifTopic() != null ? event.getDnotifTopic() : event.getDstatusTopic();
-        return new String[] {event.getAction(), event.getEnvironmentName(), topicName,
-                event.getRole(), event.getApiKey(), event.getStatus()};
+        return new String[]{event.getAction(), event.getEnvironmentName(), topicName, event.getRole(), event.getApiKey(), event.getStatus()};
     }
-
 }
index 0389934..3cfc669 100644 (file)
@@ -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.
@@ -17,7 +17,6 @@
  * limitations under the License.
  * ============LICENSE_END=========================================================
  */
-
 package org.openecomp.sdc.be.auditing.impl.distribution;
 
 import org.openecomp.sdc.be.resources.data.auditing.AuditingActionEnum;
@@ -28,9 +27,9 @@ public class AuditCreateTopicDistributionEngineEventFactory extends AuditDistrib
 
     private static final String LOG_STR = "ACTION = \"%s\" D_ENV = \"%s\" TOPIC_NAME = \"%s\" STATUS = \"%s\"";
 
-    AuditCreateTopicDistributionEngineEventFactory(CommonAuditData commonFields, DistributionTopicData distributionTopicData,
-                                                          String apiKey, String envName, String role) {
-        super(AuditingActionEnum.CREATE_DISTRIBUTION_TOPIC, commonFields, distributionTopicData,null, apiKey, envName, role);
+    AuditCreateTopicDistributionEngineEventFactory(CommonAuditData commonFields, DistributionTopicData distributionTopicData, String apiKey,
+                                                   String envName, String role) {
+        super(AuditingActionEnum.CREATE_DISTRIBUTION_TOPIC, commonFields, distributionTopicData, null, apiKey, envName, role);
     }
 
     @Override
@@ -40,7 +39,6 @@ public class AuditCreateTopicDistributionEngineEventFactory extends AuditDistrib
 
     @Override
     public String[] getLogMessageParams() {
-        return new String[] {event.getAction(), event.getEnvironmentName(), getTopicName(), event.getStatus()};
+        return new String[]{event.getAction(), event.getEnvironmentName(), getTopicName(), event.getStatus()};
     }
-
 }
index b02c37c..eb04ab8 100644 (file)
@@ -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.
@@ -17,7 +17,6 @@
  * limitations under the License.
  * ============LICENSE_END=========================================================
  */
-
 package org.openecomp.sdc.be.auditing.impl.distribution;
 
 import org.openecomp.sdc.be.auditing.impl.AuditBaseEventFactory;
@@ -30,26 +29,25 @@ import org.openecomp.sdc.be.resources.data.auditing.model.ResourceCommonInfo;
 
 public class AuditDistributionDeployEventFactory extends AuditBaseEventFactory {
 
-    private static final String LOG_STR = "ACTION = \"%s\" RESOURCE_NAME = \"%s\" RESOURCE_TYPE = \"%s\" " +
-            "SERVICE_INSTANCE_ID = \"%s\" CURR_VERSION = \"%s\" MODIFIER = \"%s\" DID = \"%s\" STATUS = \"%s\" DESC = \"%s\"";
+    private static final String LOG_STR = "ACTION = \"%s\" RESOURCE_NAME = \"%s\" RESOURCE_TYPE = \"%s\" "
+        + "SERVICE_INSTANCE_ID = \"%s\" CURR_VERSION = \"%s\" MODIFIER = \"%s\" DID = \"%s\" STATUS = \"%s\" DESC = \"%s\"";
     private final DistributionDeployEvent event;
 
-    public AuditDistributionDeployEventFactory(CommonAuditData commonFields, ResourceCommonInfo resourceCommonInfo,
-                                               String did, User modifier, String currentVersion) {
+    public AuditDistributionDeployEventFactory(CommonAuditData commonFields, ResourceCommonInfo resourceCommonInfo, String did, User modifier,
+                                               String currentVersion) {
         this(commonFields, resourceCommonInfo, did, buildUserName(modifier), currentVersion);
     }
 
-    public AuditDistributionDeployEventFactory(CommonAuditData commonFields, ResourceCommonInfo resourceCommonInfo,
-                                               String did, String modifier, String currentVersion, String timestamp) {
+    public AuditDistributionDeployEventFactory(CommonAuditData commonFields, ResourceCommonInfo resourceCommonInfo, String did, String modifier,
+                                               String currentVersion, String timestamp) {
         this(commonFields, resourceCommonInfo, did, modifier, currentVersion);
         this.event.setTimestamp1(timestamp);
     }
 
-    private AuditDistributionDeployEventFactory(CommonAuditData commonFields, ResourceCommonInfo resourceCommonInfo,
-                                               String did, String modifier, String currentVersion) {
+    private AuditDistributionDeployEventFactory(CommonAuditData commonFields, ResourceCommonInfo resourceCommonInfo, String did, String modifier,
+                                                String currentVersion) {
         super(AuditingActionEnum.DISTRIBUTION_DEPLOY);
-        event = new DistributionDeployEvent(getAction().getName(), commonFields, resourceCommonInfo, did, modifier,
-                currentVersion);
+        event = new DistributionDeployEvent(getAction().getName(), commonFields, resourceCommonInfo, did, modifier, currentVersion);
     }
 
     @Override
@@ -59,13 +57,12 @@ public class AuditDistributionDeployEventFactory extends AuditBaseEventFactory {
 
     @Override
     public String[] getLogMessageParams() {
-        return new String[] {event.getAction(), event.getResourceName(), event.getResourceType(), event.getServiceInstanceId(),
-                event.getCurrVersion(), event.getModifier(), event.getDid(), event.getStatus(), event.getDesc()};
+        return new String[]{event.getAction(), event.getResourceName(), event.getResourceType(), event.getServiceInstanceId(), event.getCurrVersion(),
+            event.getModifier(), event.getDid(), event.getStatus(), event.getDesc()};
     }
 
     @Override
     public AuditingGenericEvent getDbEvent() {
         return event;
     }
-
 }
index 0f1093e..b18ac6a 100644 (file)
@@ -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.
@@ -17,7 +17,6 @@
  * limitations under the License.
  * ============LICENSE_END=========================================================
  */
-
 package org.openecomp.sdc.be.auditing.impl.distribution;
 
 import org.openecomp.sdc.be.auditing.impl.AuditBaseEventFactory;
@@ -38,8 +37,8 @@ public class AuditDistributionDownloadEventFactory extends AuditBaseEventFactory
     }
 
     public AuditDistributionDownloadEventFactory(CommonAuditData commonFields, DistributionData distributionData, String timestamp) {
-       this(commonFields, distributionData);
-       this.event.setTimestamp1(timestamp);
+        this(commonFields, distributionData);
+        this.event.setTimestamp1(timestamp);
     }
 
     @Override
@@ -49,8 +48,7 @@ public class AuditDistributionDownloadEventFactory extends AuditBaseEventFactory
 
     @Override
     public String[] getLogMessageParams() {
-        return new String[] {event.getAction(), event.getConsumerId(), event.getResourceUrl(),
-                event.getStatus(), event.getDesc()};
+        return new String[]{event.getAction(), event.getConsumerId(), event.getResourceUrl(), event.getStatus(), event.getDesc()};
     }
 
     @Override
index 38b240d..28b1de7 100644 (file)
@@ -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.
@@ -17,7 +17,6 @@
  * limitations under the License.
  * ============LICENSE_END=========================================================
  */
-
 package org.openecomp.sdc.be.auditing.impl.distribution;
 
 import org.openecomp.sdc.be.auditing.impl.AuditBaseEventFactory;
@@ -27,20 +26,18 @@ import org.openecomp.sdc.be.resources.data.auditing.DistributionEngineEvent;
 import org.openecomp.sdc.be.resources.data.auditing.model.CommonAuditData;
 import org.openecomp.sdc.be.resources.data.auditing.model.DistributionTopicData;
 
-public abstract class AuditDistributionEngineEventFactory extends AuditBaseEventFactory{
+public abstract class AuditDistributionEngineEventFactory extends AuditBaseEventFactory {
 
     protected final DistributionEngineEvent event;
 
-    AuditDistributionEngineEventFactory(AuditingActionEnum action, CommonAuditData commonFields,
-                                               DistributionTopicData distributionTopicData, String consumerId,
-                                               String apiKey, String envName, String role) {
+    AuditDistributionEngineEventFactory(AuditingActionEnum action, CommonAuditData commonFields, DistributionTopicData distributionTopicData,
+                                        String consumerId, String apiKey, String envName, String role) {
         super(action);
         event = new DistributionEngineEvent(getAction().getName(), commonFields, consumerId, distributionTopicData, apiKey, envName, role);
     }
 
-    AuditDistributionEngineEventFactory(AuditingActionEnum action, CommonAuditData commonFields,
-                                               DistributionTopicData distributionTopicData, String consumerId,
-                                               String apiKey, String envName, String role, String timestamp) {
+    AuditDistributionEngineEventFactory(AuditingActionEnum action, CommonAuditData commonFields, DistributionTopicData distributionTopicData,
+                                        String consumerId, String apiKey, String envName, String role, String timestamp) {
         this(action, commonFields, distributionTopicData, consumerId, apiKey, envName, role);
         this.event.setTimestamp1(timestamp);
     }
index a964d13..f4bb5be 100644 (file)
@@ -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.
@@ -17,7 +17,6 @@
  * limitations under the License.
  * ============LICENSE_END=========================================================
  */
-
 package org.openecomp.sdc.be.auditing.impl.distribution;
 
 import org.openecomp.sdc.be.auditing.api.AuditEventFactory;
@@ -29,32 +28,24 @@ import org.openecomp.sdc.common.util.ThreadLocalsHolder;
 public class AuditDistributionEngineEventFactoryManager {
 
     public static AuditEventFactory createDistributionEngineEventFactory(AuditingActionEnum action, String environmentName,
-                                                                         DistributionTopicData distributionTopicData, String role, String apiKey, String status) {
+                                                                         DistributionTopicData distributionTopicData, String role, String apiKey,
+                                                                         String status) {
         AuditEventFactory factory;
-
         switch (action) {
             case CREATE_DISTRIBUTION_TOPIC:
                 factory = new AuditCreateTopicDistributionEngineEventFactory(
-                        CommonAuditData.newBuilder()
-                                .status(status)
-                                .requestId(ThreadLocalsHolder.getUuid())
-                                .build(),
-                        distributionTopicData, apiKey, environmentName, role);
+                    CommonAuditData.newBuilder().status(status).requestId(ThreadLocalsHolder.getUuid()).build(), distributionTopicData, apiKey,
+                    environmentName, role);
                 break;
             case ADD_KEY_TO_TOPIC_ACL:
             case REMOVE_KEY_FROM_TOPIC_ACL:
                 factory = new AuditAddRemoveKeyDistributionEngineEventFactory(action,
-                        CommonAuditData.newBuilder()
-                                .status(status)
-                                .requestId(ThreadLocalsHolder.getUuid())
-                                .build(),
-                        distributionTopicData, apiKey, environmentName, role);
+                    CommonAuditData.newBuilder().status(status).requestId(ThreadLocalsHolder.getUuid()).build(), distributionTopicData, apiKey,
+                    environmentName, role);
                 break;
             default:
                 throw new UnsupportedOperationException();
-
         }
         return factory;
-
     }
 }
index 1750d51..1c8a200 100644 (file)
@@ -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.
@@ -17,7 +17,6 @@
  * limitations under the License.
  * ============LICENSE_END=========================================================
  */
-
 package org.openecomp.sdc.be.auditing.impl.distribution;
 
 import org.openecomp.sdc.be.resources.data.auditing.AuditingActionEnum;
@@ -27,8 +26,8 @@ import org.openecomp.sdc.be.resources.data.auditing.model.DistributionTopicData;
 public class AuditDistributionEngineEventMigrationFactory extends AuditDistributionEngineEventFactory {
 
     public AuditDistributionEngineEventMigrationFactory(AuditingActionEnum action, CommonAuditData commonFields,
-                                                        DistributionTopicData distributionTopicData, String consumerId,
-                                                        String apiKey, String envName, String role, String timestamp) {
+                                                        DistributionTopicData distributionTopicData, String consumerId, String apiKey, String envName,
+                                                        String role, String timestamp) {
         super(action, commonFields, distributionTopicData, consumerId, apiKey, envName, role, timestamp);
     }
 
index 05a08cd..05664b9 100644 (file)
@@ -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.
@@ -17,7 +17,6 @@
  * limitations under the License.
  * ============LICENSE_END=========================================================
  */
-
 package org.openecomp.sdc.be.auditing.impl.distribution;
 
 import org.openecomp.sdc.be.auditing.impl.AuditBaseEventFactory;
@@ -32,35 +31,30 @@ import org.openecomp.sdc.be.resources.data.auditing.model.ResourceVersionInfo;
 
 public class AuditDistributionNotificationEventFactory extends AuditBaseEventFactory {
 
-    private static final String LOG_STR = "ACTION = \"%s\" RESOURCE_NAME = \"%s\" RESOURCE_TYPE = \"%s\" " +
-            "SERVICE_INSTANCE_ID = \"%s\" CURR_VERSION = \"%s\" MODIFIER = \"%s\" CURR_STATE = \"%s\" DID = \"%s\" " +
-            "TOPIC_NAME = \"%s\" STATUS = \"%s\" DESC = \"%s\" TENANT = \"%s\" VNF_WORKLOAD_CONTEXT = \"%s\" ENV_ID = \"%s\"";
+    private static final String LOG_STR = "ACTION = \"%s\" RESOURCE_NAME = \"%s\" RESOURCE_TYPE = \"%s\" "
+        + "SERVICE_INSTANCE_ID = \"%s\" CURR_VERSION = \"%s\" MODIFIER = \"%s\" CURR_STATE = \"%s\" DID = \"%s\" "
+        + "TOPIC_NAME = \"%s\" STATUS = \"%s\" DESC = \"%s\" TENANT = \"%s\" VNF_WORKLOAD_CONTEXT = \"%s\" ENV_ID = \"%s\"";
     private final DistributionNotificationEvent event;
 
     public AuditDistributionNotificationEventFactory(CommonAuditData commonAuditData, ResourceCommonInfo resourceCommonInfo,
-                                                     ResourceVersionInfo resourceVersionInfo,
-                                                     String did, User modifier, String topicName,
+                                                     ResourceVersionInfo resourceVersionInfo, String did, User modifier, String topicName,
                                                      OperationalEnvAuditData opEnvFields) {
-        this(commonAuditData, resourceCommonInfo,
-                resourceVersionInfo, did, AuditBaseEventFactory.buildUserName(modifier),
-                topicName, opEnvFields);
+        this(commonAuditData, resourceCommonInfo, resourceVersionInfo, did, AuditBaseEventFactory.buildUserName(modifier), topicName, opEnvFields);
     }
 
     public AuditDistributionNotificationEventFactory(CommonAuditData commonAuditData, ResourceCommonInfo resourceCommonInfo,
-                                                     ResourceVersionInfo resourceVersionInfo,
-                                                     String did, String modifier, String topicName,
+                                                     ResourceVersionInfo resourceVersionInfo, String did, String modifier, String topicName,
                                                      OperationalEnvAuditData opEnvFields, String timestamp) {
         this(commonAuditData, resourceCommonInfo, resourceVersionInfo, did, modifier, topicName, opEnvFields);
         this.event.setTimestamp1(timestamp);
     }
 
     private AuditDistributionNotificationEventFactory(CommonAuditData commonAuditData, ResourceCommonInfo resourceCommonInfo,
-                                                     ResourceVersionInfo resourceVersionInfo,
-                                                     String did, String modifier, String topicName,
-                                                     OperationalEnvAuditData opEnvFields) {
+                                                      ResourceVersionInfo resourceVersionInfo, String did, String modifier, String topicName,
+                                                      OperationalEnvAuditData opEnvFields) {
         super(AuditingActionEnum.DISTRIBUTION_NOTIFY);
-        this.event = new DistributionNotificationEvent(getAction().getName(), commonAuditData, resourceCommonInfo,
-                resourceVersionInfo, did, modifier, topicName, opEnvFields);
+        this.event = new DistributionNotificationEvent(getAction().getName(), commonAuditData, resourceCommonInfo, resourceVersionInfo, did, modifier,
+            topicName, opEnvFields);
     }
 
     @Override
@@ -70,14 +64,13 @@ public class AuditDistributionNotificationEventFactory extends AuditBaseEventFac
 
     @Override
     public String[] getLogMessageParams() {
-        return new String[] {event.getAction(), event.getResourceName(), event.getResourceType(), event.getServiceInstanceId(),
-                event.getCurrVersion(), event.getModifier(), event.getCurrState(), event.getDid(), event.getTopicName(),
-                event.getStatus(), event.getDesc(), event.getTenant(), event.getVnfWorkloadContext(), event.getEnvId()};
+        return new String[]{event.getAction(), event.getResourceName(), event.getResourceType(), event.getServiceInstanceId(), event.getCurrVersion(),
+            event.getModifier(), event.getCurrState(), event.getDid(), event.getTopicName(), event.getStatus(), event.getDesc(), event.getTenant(),
+            event.getVnfWorkloadContext(), event.getEnvId()};
     }
 
     @Override
     public AuditingGenericEvent getDbEvent() {
         return event;
     }
-
 }
index 6309bff..5cf312f 100644 (file)
@@ -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.
@@ -17,7 +17,6 @@
  * limitations under the License.
  * ============LICENSE_END=========================================================
  */
-
 package org.openecomp.sdc.be.auditing.impl.distribution;
 
 import org.openecomp.sdc.be.auditing.impl.AuditBaseEventFactory;
@@ -29,19 +28,18 @@ import org.openecomp.sdc.be.resources.data.auditing.model.DistributionData;
 
 public class AuditDistributionStatusEventFactory extends AuditBaseEventFactory {
 
-    private static final String LOG_STR = "ACTION = \"%s\" DID = \"%s\" CONSUMER_ID = \"%s\" " +
-            "TOPIC_NAME = \"%s\" RESOURCE_URL = \"%s\" STATUS_TIME = \"%s\" STATUS = \"%s\" DESC = \"%s\"";
+    private static final String LOG_STR = "ACTION = \"%s\" DID = \"%s\" CONSUMER_ID = \"%s\" "
+        + "TOPIC_NAME = \"%s\" RESOURCE_URL = \"%s\" STATUS_TIME = \"%s\" STATUS = \"%s\" DESC = \"%s\"";
     private final DistributionStatusEvent event;
 
-    public AuditDistributionStatusEventFactory(CommonAuditData commonFields, DistributionData distributionData,
-                                               String did, String topicName, String statusTime) {
+    public AuditDistributionStatusEventFactory(CommonAuditData commonFields, DistributionData distributionData, String did, String topicName,
+                                               String statusTime) {
         super(AuditingActionEnum.DISTRIBUTION_STATUS);
-        this.event = new DistributionStatusEvent(getAction().getName(), commonFields, distributionData, did,
-                topicName, statusTime);
+        this.event = new DistributionStatusEvent(getAction().getName(), commonFields, distributionData, did, topicName, statusTime);
     }
 
-    public AuditDistributionStatusEventFactory(CommonAuditData commonFields, DistributionData distributionData,
-                                               String did, String topicName, String statusTime, String timestamp) {
+    public AuditDistributionStatusEventFactory(CommonAuditData commonFields, DistributionData distributionData, String did, String topicName,
+                                               String statusTime, String timestamp) {
         this(commonFields, distributionData, did, topicName, statusTime);
         this.event.setTimestamp1(timestamp);
     }
@@ -53,8 +51,8 @@ public class AuditDistributionStatusEventFactory extends AuditBaseEventFactory {
 
     @Override
     public String[] getLogMessageParams() {
-        return new String[] {event.getAction(), event.getDid(), event.getConsumerId(), event.getTopicName(),
-                event.getResoureURL(), event.getStatusTime(), event.getStatus(), event.getDesc()};
+        return new String[]{event.getAction(), event.getDid(), event.getConsumerId(), event.getTopicName(), event.getResoureURL(),
+            event.getStatusTime(), event.getStatus(), event.getDesc()};
     }
 
     @Override
index 88f1807..a57bc98 100644 (file)
@@ -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.
@@ -17,7 +17,6 @@
  * limitations under the License.
  * ============LICENSE_END=========================================================
  */
-
 package org.openecomp.sdc.be.auditing.impl.distribution;
 
 import org.openecomp.sdc.be.resources.data.auditing.AuditingActionEnum;
@@ -26,11 +25,11 @@ import org.openecomp.sdc.be.resources.data.auditing.model.DistributionTopicData;
 
 public class AuditRegUnregDistributionEngineEventFactory extends AuditDistributionEngineEventFactory {
 
-    private static final String LOG_STR = "ACTION = \"%s\" CONSUMER_ID = \"%s\" API_KEY = \"%s\" D_ENV = \"%s\" STATUS = \"%s\"" +
-            " DESC = \"%s\" DNOTIF_TOPIC = \"%s\" DSTATUS_TOPIC = \"%s\"";
+    private static final String LOG_STR = "ACTION = \"%s\" CONSUMER_ID = \"%s\" API_KEY = \"%s\" D_ENV = \"%s\" STATUS = \"%s\""
+        + " DESC = \"%s\" DNOTIF_TOPIC = \"%s\" DSTATUS_TOPIC = \"%s\"";
 
-    public AuditRegUnregDistributionEngineEventFactory(AuditingActionEnum action, CommonAuditData commonFields,
-                                                       DistributionTopicData distrTopicData, String consumerId, String apiKey, String envName) {
+    public AuditRegUnregDistributionEngineEventFactory(AuditingActionEnum action, CommonAuditData commonFields, DistributionTopicData distrTopicData,
+                                                       String consumerId, String apiKey, String envName) {
         super(action, commonFields, distrTopicData, consumerId, apiKey, envName, null);
     }
 
@@ -41,8 +40,7 @@ public class AuditRegUnregDistributionEngineEventFactory extends AuditDistributi
 
     @Override
     public String[] getLogMessageParams() {
-        return new String[] {event.getAction(), event.getConsumerId(), event.getApiKey(),
-                event.getEnvironmentName(), event.getStatus(), event.getDesc(),
-                event.getDnotifTopic(), event.getDstatusTopic()};
+        return new String[]{event.getAction(), event.getConsumerId(), event.getApiKey(), event.getEnvironmentName(), event.getStatus(),
+            event.getDesc(), event.getDnotifTopic(), event.getDstatusTopic()};
     }
 }
index 1c77d03..2f80cac 100644 (file)
@@ -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.
@@ -17,7 +17,6 @@
  * limitations under the License.
  * ============LICENSE_END=========================================================
  */
-
 package org.openecomp.sdc.be.auditing.impl.externalapi;
 
 import org.openecomp.sdc.be.model.User;
@@ -29,17 +28,13 @@ import org.openecomp.sdc.be.resources.data.auditing.model.ResourceVersionInfo;
 
 public class AuditActivateServiceExternalApiEventFactory extends AuditExternalApiEventFactory {
 
-    private static final String LOG_STR = "ACTION = \"%s\" RESOURCE_TYPE = \"%s\" CONSUMER_ID = \"%s\"" +
-            " RESOURCE_URL = \"%s\" MODIFIER = \"%s\" STATUS = \"%s\" SERVICE_INSTANCE_ID = \"%s\" INVARIANT_UUID = \"%s\" DESC = \"%s\"";
+    private static final String LOG_STR = "ACTION = \"%s\" RESOURCE_TYPE = \"%s\" CONSUMER_ID = \"%s\""
+        + " RESOURCE_URL = \"%s\" MODIFIER = \"%s\" STATUS = \"%s\" SERVICE_INSTANCE_ID = \"%s\" INVARIANT_UUID = \"%s\" DESC = \"%s\"";
 
     public AuditActivateServiceExternalApiEventFactory(CommonAuditData commonFields, ResourceCommonInfo resourceCommonInfo,
                                                        DistributionData distributionData, String invariantUuid, User modifier) {
         super(AuditingActionEnum.ACTIVATE_SERVICE_BY_API, commonFields, resourceCommonInfo, distributionData,
-                ResourceVersionInfo.newBuilder()
-                    .build(),
-                ResourceVersionInfo.newBuilder()
-                    .build(),
-                invariantUuid, modifier, null);
+            ResourceVersionInfo.newBuilder().build(), ResourceVersionInfo.newBuilder().build(), invariantUuid, modifier, null);
     }
 
     @Override
@@ -49,8 +44,7 @@ public class AuditActivateServiceExternalApiEventFactory extends AuditExternalAp
 
     @Override
     public String[] getLogMessageParams() {
-        return new String[] {event.getAction(), event.getResourceType(), event.getConsumerId(),
-                event.getResourceURL(), event.getModifier(), event.getStatus(),
-                event.getServiceInstanceId(), event.getInvariantUuid(), event.getDesc()};
+        return new String[]{event.getAction(), event.getResourceType(), event.getConsumerId(), event.getResourceURL(), event.getModifier(),
+            event.getStatus(), event.getServiceInstanceId(), event.getInvariantUuid(), event.getDesc()};
     }
 }
index 109c839..74c0eb0 100644 (file)
@@ -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.
@@ -17,7 +17,6 @@
  * limitations under the License.
  * ============LICENSE_END=========================================================
  */
-
 package org.openecomp.sdc.be.auditing.impl.externalapi;
 
 import org.openecomp.sdc.be.resources.data.auditing.AuditingActionEnum;
@@ -28,17 +27,13 @@ import org.openecomp.sdc.be.resources.data.auditing.model.ResourceVersionInfo;
 
 public class AuditAssetExternalApiEventFactory extends AuditExternalApiEventFactory {
 
-    private static final String LOG_STR = "ACTION = \"%s\" CONSUMER_ID = \"%s\" RESOURCE_URL = \"%s\" RESOURCE_NAME = \"%s\" " +
-            "RESOURCE_TYPE = \"%s\" SERVICE_INSTANCE_ID = \"%s\" STATUS = \"%s\" DESC = \"%s\"";
+    private static final String LOG_STR = "ACTION = \"%s\" CONSUMER_ID = \"%s\" RESOURCE_URL = \"%s\" RESOURCE_NAME = \"%s\" "
+        + "RESOURCE_TYPE = \"%s\" SERVICE_INSTANCE_ID = \"%s\" STATUS = \"%s\" DESC = \"%s\"";
 
     public AuditAssetExternalApiEventFactory(AuditingActionEnum action, CommonAuditData commonFields, ResourceCommonInfo resourceCommonInfo,
                                              DistributionData distributionData) {
-        super(action, commonFields, resourceCommonInfo, distributionData,
-                ResourceVersionInfo.newBuilder()
-                        .build(),
-                ResourceVersionInfo.newBuilder()
-                        .build(),
-                null, null, null);
+        super(action, commonFields, resourceCommonInfo, distributionData, ResourceVersionInfo.newBuilder().build(),
+            ResourceVersionInfo.newBuilder().build(), null, null, null);
     }
 
     @Override
@@ -48,7 +43,7 @@ public class AuditAssetExternalApiEventFactory extends AuditExternalApiEventFact
 
     @Override
     public String[] getLogMessageParams() {
-        return new String[] {event.getAction(), event.getConsumerId(), event.getResourceURL(), event.getResourceName(),
-                event.getResourceType(), event.getServiceInstanceId(), event.getStatus(), event.getDesc()};
+        return new String[]{event.getAction(), event.getConsumerId(), event.getResourceURL(), event.getResourceName(), event.getResourceType(),
+            event.getServiceInstanceId(), event.getStatus(), event.getDesc()};
     }
 }
index 3ab5efb..cc5faf6 100644 (file)
@@ -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.
@@ -17,7 +17,6 @@
  * limitations under the License.
  * ============LICENSE_END=========================================================
  */
-
 package org.openecomp.sdc.be.auditing.impl.externalapi;
 
 import org.openecomp.sdc.be.resources.data.auditing.AuditingActionEnum;
@@ -30,14 +29,9 @@ public class AuditAssetListExternalApiEventFactory extends AuditExternalApiEvent
 
     private static final String LOG_STR = "ACTION = \"%s\" CONSUMER_ID = \"%s\" RESOURCE_URL = \"%s\" STATUS = \"%s\" DESC = \"%s\"";
 
-    public AuditAssetListExternalApiEventFactory(AuditingActionEnum action, CommonAuditData commonFields,
-                                                  DistributionData distributionData) {
-         super(action, commonFields, new ResourceCommonInfo(), distributionData,
-                 ResourceVersionInfo.newBuilder()
-                         .build(),
-                 ResourceVersionInfo.newBuilder()
-                         .build(),
-                 null, null, null);
+    public AuditAssetListExternalApiEventFactory(AuditingActionEnum action, CommonAuditData commonFields, DistributionData distributionData) {
+        super(action, commonFields, new ResourceCommonInfo(), distributionData, ResourceVersionInfo.newBuilder().build(),
+            ResourceVersionInfo.newBuilder().build(), null, null, null);
     }
 
     @Override
@@ -47,7 +41,6 @@ public class AuditAssetListExternalApiEventFactory extends AuditExternalApiEvent
 
     @Override
     public String[] getLogMessageParams() {
-        return new String[] {event.getAction(), event.getConsumerId(), event.getResourceURL(),
-                event.getStatus(), event.getDesc()};
+        return new String[]{event.getAction(), event.getConsumerId(), event.getResourceURL(), event.getStatus(), event.getDesc()};
     }
 }
index 523560a..726550b 100644 (file)
@@ -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.
@@ -17,7 +17,6 @@
  * limitations under the License.
  * ============LICENSE_END=========================================================
  */
-
 package org.openecomp.sdc.be.auditing.impl.externalapi;
 
 import org.openecomp.sdc.be.model.User;
@@ -29,15 +28,15 @@ import org.openecomp.sdc.be.resources.data.auditing.model.ResourceVersionInfo;
 
 public class AuditChangeLifecycleExternalApiEventFactory extends AuditExternalApiEventFactory {
 
-    private static final String LOG_STR = "ACTION = \"%s\" RESOURCE_NAME = \"%s\" RESOURCE_TYPE = \"%s\" CONSUMER_ID = \"%s\"" +
-            " RESOURCE_URL = \"%s\" MODIFIER = \"%s\" PREV_VERSION = \"%s\" CURR_VERSION = \"%s\"" +
-            " PREV_STATE = \"%s\" CURR_STATE = \"%s\" SERVICE_INSTANCE_ID = \"%s\" INVARIANT_UUID = \"%s\" STATUS = \"%s\" DESC = \"%s\"";
+    private static final String LOG_STR = "ACTION = \"%s\" RESOURCE_NAME = \"%s\" RESOURCE_TYPE = \"%s\" CONSUMER_ID = \"%s\""
+        + " RESOURCE_URL = \"%s\" MODIFIER = \"%s\" PREV_VERSION = \"%s\" CURR_VERSION = \"%s\""
+        + " PREV_STATE = \"%s\" CURR_STATE = \"%s\" SERVICE_INSTANCE_ID = \"%s\" INVARIANT_UUID = \"%s\" STATUS = \"%s\" DESC = \"%s\"";
 
     public AuditChangeLifecycleExternalApiEventFactory(CommonAuditData commonFields, ResourceCommonInfo resourceCommonInfo,
-                                                       DistributionData distributionData, ResourceVersionInfo prevParams, ResourceVersionInfo currParams,
-                                                       String invariantUuid, User modifier) {
-        super(AuditingActionEnum.CHANGE_LIFECYCLE_BY_API, commonFields, resourceCommonInfo, distributionData, prevParams, currParams,
-                invariantUuid, modifier, null);
+                                                       DistributionData distributionData, ResourceVersionInfo prevParams,
+                                                       ResourceVersionInfo currParams, String invariantUuid, User modifier) {
+        super(AuditingActionEnum.CHANGE_LIFECYCLE_BY_API, commonFields, resourceCommonInfo, distributionData, prevParams, currParams, invariantUuid,
+            modifier, null);
     }
 
     @Override
@@ -47,9 +46,8 @@ public class AuditChangeLifecycleExternalApiEventFactory extends AuditExternalAp
 
     @Override
     public String[] getLogMessageParams() {
-        return new String[] {event.getAction(), event.getResourceName(), event.getResourceType(), event.getConsumerId(),
-                event.getResourceURL(), event.getModifier(), event.getPrevVersion(), event.getCurrVersion(),
-                event.getPrevState(), event.getCurrState(), event.getServiceInstanceId(), event.getInvariantUuid(),
-                event.getStatus(), event.getDesc()};
+        return new String[]{event.getAction(), event.getResourceName(), event.getResourceType(), event.getConsumerId(), event.getResourceURL(),
+            event.getModifier(), event.getPrevVersion(), event.getCurrVersion(), event.getPrevState(), event.getCurrState(),
+            event.getServiceInstanceId(), event.getInvariantUuid(), event.getStatus(), event.getDesc()};
     }
 }
index 931bc08..011a069 100644 (file)
@@ -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.
@@ -17,7 +17,6 @@
  * limitations under the License.
  * ============LICENSE_END=========================================================
  */
-
 package org.openecomp.sdc.be.auditing.impl.externalapi;
 
 import org.openecomp.sdc.be.model.User;
@@ -29,18 +28,15 @@ import org.openecomp.sdc.be.resources.data.auditing.model.ResourceVersionInfo;
 
 public class AuditCreateResourceExternalApiEventFactory extends AuditExternalApiEventFactory {
 
-    private static final String LOG_STR = "ACTION = \"%s\" RESOURCE_NAME = \"%s\" RESOURCE_TYPE = \"%s\" CONSUMER_ID = \"%s\"" +
-            " RESOURCE_URL = \"%s\" MODIFIER = \"%s\" CURR_VERSION = \"%s\" CURR_STATE = \"%s\" CURR_ARTIFACT_UUID = \"%s\" " +
-            "STATUS = \"%s\" SERVICE_INSTANCE_ID = \"%s\" INVARIANT_UUID = \"%s\" DESC = \"%s\"";
+    private static final String LOG_STR = "ACTION = \"%s\" RESOURCE_NAME = \"%s\" RESOURCE_TYPE = \"%s\" CONSUMER_ID = \"%s\""
+        + " RESOURCE_URL = \"%s\" MODIFIER = \"%s\" CURR_VERSION = \"%s\" CURR_STATE = \"%s\" CURR_ARTIFACT_UUID = \"%s\" "
+        + "STATUS = \"%s\" SERVICE_INSTANCE_ID = \"%s\" INVARIANT_UUID = \"%s\" DESC = \"%s\"";
 
     public AuditCreateResourceExternalApiEventFactory(CommonAuditData commonFields, ResourceCommonInfo resourceCommonInfo,
                                                       DistributionData distributionData, ResourceVersionInfo currResourceVersionInfo,
                                                       String invariantUuid, User modifier) {
-        super(AuditingActionEnum.CREATE_RESOURCE_BY_API, commonFields, resourceCommonInfo, distributionData,
-                ResourceVersionInfo.newBuilder()
-                        .build(),
-                currResourceVersionInfo,
-                invariantUuid, modifier, null);
+        super(AuditingActionEnum.CREATE_RESOURCE_BY_API, commonFields, resourceCommonInfo, distributionData, ResourceVersionInfo.newBuilder().build(),
+            currResourceVersionInfo, invariantUuid, modifier, null);
     }
 
     @Override
@@ -50,10 +46,8 @@ public class AuditCreateResourceExternalApiEventFactory extends AuditExternalApi
 
     @Override
     public String[] getLogMessageParams() {
-        return new String[] {event.getAction(), event.getResourceName(), event.getResourceType(),
-                event.getConsumerId(), event.getResourceURL(), event.getModifier(),
-                event.getCurrVersion(), event.getCurrState(), event.getCurrArtifactUuid(),
-                event.getStatus(), event.getServiceInstanceId(), event.getInvariantUuid(),
-                event.getDesc()};
+        return new String[]{event.getAction(), event.getResourceName(), event.getResourceType(), event.getConsumerId(), event.getResourceURL(),
+            event.getModifier(), event.getCurrVersion(), event.getCurrState(), event.getCurrArtifactUuid(), event.getStatus(),
+            event.getServiceInstanceId(), event.getInvariantUuid(), event.getDesc()};
     }
 }
index 640b537..bd9603e 100644 (file)
@@ -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.
@@ -17,7 +17,6 @@
  * limitations under the License.
  * ============LICENSE_END=========================================================
  */
-
 package org.openecomp.sdc.be.auditing.impl.externalapi;
 
 import org.openecomp.sdc.be.model.User;
@@ -29,17 +28,13 @@ import org.openecomp.sdc.be.resources.data.auditing.model.ResourceVersionInfo;
 
 public class AuditCreateServiceExternalApiEventFactory extends AuditExternalApiEventFactory {
 
-    private static final String LOG_STR = "ACTION = \"%s\" RESOURCE_TYPE = \"%s\" CONSUMER_ID = \"%s\"" +
-            " RESOURCE_URL = \"%s\" MODIFIER = \"%s\" STATUS = \"%s\" SERVICE_INSTANCE_ID = \"%s\" INVARIANT_UUID = \"%s\" DESC = \"%s\"";
+    private static final String LOG_STR = "ACTION = \"%s\" RESOURCE_TYPE = \"%s\" CONSUMER_ID = \"%s\""
+        + " RESOURCE_URL = \"%s\" MODIFIER = \"%s\" STATUS = \"%s\" SERVICE_INSTANCE_ID = \"%s\" INVARIANT_UUID = \"%s\" DESC = \"%s\"";
 
     public AuditCreateServiceExternalApiEventFactory(CommonAuditData commonFields, ResourceCommonInfo resourceCommonInfo,
-                                                       DistributionData distributionData, String invariantUuid, User modifier) {
-        super(AuditingActionEnum.CREATE_SERVICE_BY_API, commonFields, resourceCommonInfo, distributionData,
-                ResourceVersionInfo.newBuilder()
-                    .build(),
-                ResourceVersionInfo.newBuilder()
-                    .build(),
-                invariantUuid, modifier, null);
+                                                     DistributionData distributionData, String invariantUuid, User modifier) {
+        super(AuditingActionEnum.CREATE_SERVICE_BY_API, commonFields, resourceCommonInfo, distributionData, ResourceVersionInfo.newBuilder().build(),
+            ResourceVersionInfo.newBuilder().build(), invariantUuid, modifier, null);
     }
 
     @Override
@@ -49,8 +44,7 @@ public class AuditCreateServiceExternalApiEventFactory extends AuditExternalApiE
 
     @Override
     public String[] getLogMessageParams() {
-        return new String[] {event.getAction(), event.getResourceType(), event.getConsumerId(),
-                event.getResourceURL(), event.getModifier(), event.getStatus(),
-                event.getServiceInstanceId(), event.getInvariantUuid(), event.getDesc()};
+        return new String[]{event.getAction(), event.getResourceType(), event.getConsumerId(), event.getResourceURL(), event.getModifier(),
+            event.getStatus(), event.getServiceInstanceId(), event.getInvariantUuid(), event.getDesc()};
     }
 }
index 80dc24d..af13447 100644 (file)
@@ -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.
@@ -17,7 +17,6 @@
  * limitations under the License.
  * ============LICENSE_END=========================================================
  */
-
 package org.openecomp.sdc.be.auditing.impl.externalapi;
 
 import org.openecomp.sdc.be.model.User;
@@ -29,15 +28,14 @@ import org.openecomp.sdc.be.resources.data.auditing.model.ResourceVersionInfo;
 
 public class AuditCrudExternalApiArtifactEventFactory extends AuditExternalApiEventFactory {
 
-    private static final String LOG_STR = "ACTION = \"%s\" RESOURCE_NAME = \"%s\" RESOURCE_TYPE = \"%s\" CONSUMER_ID = \"%s\"" +
-            " RESOURCE_URL = \"%s\" MODIFIER = \"%s\" PREV_ARTIFACT_UUID = \"%s\" CURR_ARTIFACT_UUID = \"%s\" ARTIFACT_DATA = \"%s\"" +
-            " STATUS = \"%s\" DESC = \"%s\"";
+    private static final String LOG_STR = "ACTION = \"%s\" RESOURCE_NAME = \"%s\" RESOURCE_TYPE = \"%s\" CONSUMER_ID = \"%s\""
+        + " RESOURCE_URL = \"%s\" MODIFIER = \"%s\" PREV_ARTIFACT_UUID = \"%s\" CURR_ARTIFACT_UUID = \"%s\" ARTIFACT_DATA = \"%s\""
+        + " STATUS = \"%s\" DESC = \"%s\"";
 
     public AuditCrudExternalApiArtifactEventFactory(AuditingActionEnum action, CommonAuditData commonFields, ResourceCommonInfo resourceCommonInfo,
                                                     DistributionData distributionData, ResourceVersionInfo prevParams, ResourceVersionInfo currParams,
                                                     String invariantUuid, User modifier, String artifactData) {
-        super(action, commonFields, resourceCommonInfo, distributionData, prevParams, currParams,
-                invariantUuid, modifier, artifactData);
+        super(action, commonFields, resourceCommonInfo, distributionData, prevParams, currParams, invariantUuid, modifier, artifactData);
     }
 
     @Override
@@ -47,9 +45,8 @@ public class AuditCrudExternalApiArtifactEventFactory extends AuditExternalApiEv
 
     @Override
     public String[] getLogMessageParams() {
-        return new String[] {event.getAction(), event.getResourceName(), event.getResourceType(),
-                event.getConsumerId(), event.getResourceURL(), event.getModifier(),
-                event.getPrevArtifactUuid(), event.getCurrArtifactUuid(), event.getArtifactData(),
-                event.getStatus(), event.getDesc()};
+        return new String[]{event.getAction(), event.getResourceName(), event.getResourceType(), event.getConsumerId(), event.getResourceURL(),
+            event.getModifier(), event.getPrevArtifactUuid(), event.getCurrArtifactUuid(), event.getArtifactData(), event.getStatus(),
+            event.getDesc()};
     }
 }
index 93d2d70..a915eaa 100644 (file)
@@ -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.
@@ -17,7 +17,6 @@
  * limitations under the License.
  * ============LICENSE_END=========================================================
  */
-
 package org.openecomp.sdc.be.auditing.impl.externalapi;
 
 import org.openecomp.sdc.be.model.User;
@@ -34,10 +33,8 @@ public class AuditDownloadArtifactExternalApiEventFactory extends AuditExternalA
     public AuditDownloadArtifactExternalApiEventFactory(CommonAuditData commonFields, ResourceCommonInfo resourceCommonInfo,
                                                         DistributionData distributionData, ResourceVersionInfo currResourceVersionInfo,
                                                         User modifier) {
-        super(AuditingActionEnum.DOWNLOAD_ARTIFACT, commonFields, resourceCommonInfo, distributionData,
-                ResourceVersionInfo.newBuilder()
-                        .build(),
-                currResourceVersionInfo, null, modifier, null);
+        super(AuditingActionEnum.DOWNLOAD_ARTIFACT, commonFields, resourceCommonInfo, distributionData, ResourceVersionInfo.newBuilder().build(),
+            currResourceVersionInfo, null, modifier, null);
     }
 
     @Override
@@ -47,7 +44,6 @@ public class AuditDownloadArtifactExternalApiEventFactory extends AuditExternalA
 
     @Override
     public String[] getLogMessageParams() {
-        return new String[] {event.getAction(), event.getConsumerId(), event.getResourceURL(),
-                event.getStatus(), event.getDesc()};
+        return new String[]{event.getAction(), event.getConsumerId(), event.getResourceURL(), event.getStatus(), event.getDesc()};
     }
 }
index 2b9002f..3fa8c8f 100644 (file)
@@ -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.
@@ -17,7 +17,6 @@
  * limitations under the License.
  * ============LICENSE_END=========================================================
  */
-
 package org.openecomp.sdc.be.auditing.impl.externalapi;
 
 import org.openecomp.sdc.be.auditing.impl.AuditBaseEventFactory;
@@ -42,10 +41,12 @@ public abstract class AuditExternalApiEventFactory extends AuditBaseEventFactory
         if (commonAuditData.getRequestId() == null) {
             commonAuditData.setRequestId(ThreadLocalsHolder.getUuid());
         }
-        event = new ExternalApiEvent(getAction().getName(), commonAuditData, resourceCommonInfo, distributionData,
-                prevParams, currParams, AuditBaseEventFactory.buildUserName(modifier), invariantUuid, artifactData) ;
+        event = new ExternalApiEvent(getAction().getName(), commonAuditData, resourceCommonInfo, distributionData, prevParams, currParams,
+            AuditBaseEventFactory.buildUserName(modifier), invariantUuid, artifactData);
     }
 
     @Override
-    public AuditingGenericEvent getDbEvent() { return event; }
+    public AuditingGenericEvent getDbEvent() {
+        return event;
+    }
 }
index 746fd2f..8f693a6 100644 (file)
@@ -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.
@@ -17,7 +17,6 @@
  * limitations under the License.
  * ============LICENSE_END=========================================================
  */
-
 package org.openecomp.sdc.be.auditing.impl.resourceadmin;
 
 import org.openecomp.sdc.be.model.User;
@@ -29,16 +28,15 @@ import org.openecomp.sdc.common.api.Constants;
 
 public class AuditArtifactResourceAdminEventFactory extends AuditResourceAdminEventFactory {
 
-    private static final String LOG_STR = "ACTION = \"%s\" RESOURCE_NAME = \"%s\" RESOURCE_TYPE = \"%s\" SERVICE_INSTANCE_ID = \"%s\"" +
-            " INVARIANT_UUID = \"%s\" PREV_VERSION = \"%s\" CURR_VERSION = \"%s\" MODIFIER = \"%s\" PREV_STATE = \"%s\" CURR_STATE = \"%s\"" +
-            " PREV_ARTIFACT_UUID = \"%s\" CURR_ARTIFACT_UUID = \"%s\" ARTIFACT_DATA = \"%s\" STATUS = \"%s\" DESC = \"%s\"";
-
+    private static final String LOG_STR = "ACTION = \"%s\" RESOURCE_NAME = \"%s\" RESOURCE_TYPE = \"%s\" SERVICE_INSTANCE_ID = \"%s\""
+        + " INVARIANT_UUID = \"%s\" PREV_VERSION = \"%s\" CURR_VERSION = \"%s\" MODIFIER = \"%s\" PREV_STATE = \"%s\" CURR_STATE = \"%s\""
+        + " PREV_ARTIFACT_UUID = \"%s\" CURR_ARTIFACT_UUID = \"%s\" ARTIFACT_DATA = \"%s\" STATUS = \"%s\" DESC = \"%s\"";
 
     public AuditArtifactResourceAdminEventFactory(AuditingActionEnum action, CommonAuditData commonFields, ResourceCommonInfo resourceCommonInfo,
-                                                  ResourceVersionInfo prevParams, ResourceVersionInfo currParams,
-                                                  String invariantUuid, User modifier, String artifactData, String comment, String did) {
-        super(action, commonFields, resourceCommonInfo, prevParams, currParams, invariantUuid,
-                modifier, artifactData, comment, did, Constants.EMPTY_STRING);
+                                                  ResourceVersionInfo prevParams, ResourceVersionInfo currParams, String invariantUuid, User modifier,
+                                                  String artifactData, String comment, String did) {
+        super(action, commonFields, resourceCommonInfo, prevParams, currParams, invariantUuid, modifier, artifactData, comment, did,
+            Constants.EMPTY_STRING);
     }
 
     @Override
@@ -48,10 +46,8 @@ public class AuditArtifactResourceAdminEventFactory extends AuditResourceAdminEv
 
     @Override
     public String[] getLogMessageParams() {
-        return new String[] {event.getAction(), event.getResourceName(), event.getResourceType(),
-                event.getServiceInstanceId(), event.getInvariantUUID(), event.getPrevVersion(),
-                event.getCurrVersion(), event.getModifier(), event.getPrevState(),
-                event.getCurrState(), event.getPrevArtifactUUID(), event.getCurrArtifactUUID(),
-                event.getArtifactData(), event.getStatus(), event.getDesc()};
+        return new String[]{event.getAction(), event.getResourceName(), event.getResourceType(), event.getServiceInstanceId(),
+            event.getInvariantUUID(), event.getPrevVersion(), event.getCurrVersion(), event.getModifier(), event.getPrevState(), event.getCurrState(),
+            event.getPrevArtifactUUID(), event.getCurrArtifactUUID(), event.getArtifactData(), event.getStatus(), event.getDesc()};
     }
 }
index d82f378..9a48360 100644 (file)
@@ -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.
@@ -17,7 +17,6 @@
  * limitations under the License.
  * ============LICENSE_END=========================================================
  */
-
 package org.openecomp.sdc.be.auditing.impl.resourceadmin;
 
 import org.openecomp.sdc.be.model.User;
@@ -29,14 +28,15 @@ import org.openecomp.sdc.common.api.Constants;
 
 public class AuditCertificationResourceAdminEventFactory extends AuditResourceAdminEventFactory {
 
-    private static final String LOG_STR = "ACTION = \"%s\" RESOURCE_NAME = \"%s\" RESOURCE_TYPE = \"%s\" SERVICE_INSTANCE_ID = \"%s\"" +
-            " INVARIANT_UUID = \"%s\" PREV_VERSION = \"%s\" CURR_VERSION = \"%s\" MODIFIER = \"%s\" PREV_STATE = \"%s\" CURR_STATE = \"%s\"" +
-            " COMMENT = \"%s\" STATUS = \"%s\" DESC = \"%s\"";
+    private static final String LOG_STR = "ACTION = \"%s\" RESOURCE_NAME = \"%s\" RESOURCE_TYPE = \"%s\" SERVICE_INSTANCE_ID = \"%s\""
+        + " INVARIANT_UUID = \"%s\" PREV_VERSION = \"%s\" CURR_VERSION = \"%s\" MODIFIER = \"%s\" PREV_STATE = \"%s\" CURR_STATE = \"%s\""
+        + " COMMENT = \"%s\" STATUS = \"%s\" DESC = \"%s\"";
 
-    public AuditCertificationResourceAdminEventFactory(AuditingActionEnum action, CommonAuditData commonFields, ResourceCommonInfo resourceCommonInfo, ResourceVersionInfo prevParams, ResourceVersionInfo currParams,
-                                                       String invariantUuid, User modifier, String artifactData, String comment, String did) {
-        super(action, commonFields, resourceCommonInfo, prevParams, currParams, invariantUuid,
-                modifier, artifactData, comment, did, Constants.EMPTY_STRING);
+    public AuditCertificationResourceAdminEventFactory(AuditingActionEnum action, CommonAuditData commonFields, ResourceCommonInfo resourceCommonInfo,
+                                                       ResourceVersionInfo prevParams, ResourceVersionInfo currParams, String invariantUuid,
+                                                       User modifier, String artifactData, String comment, String did) {
+        super(action, commonFields, resourceCommonInfo, prevParams, currParams, invariantUuid, modifier, artifactData, comment, did,
+            Constants.EMPTY_STRING);
     }
 
     @Override
@@ -46,9 +46,8 @@ public class AuditCertificationResourceAdminEventFactory extends AuditResourceAd
 
     @Override
     public String[] getLogMessageParams() {
-        return new String[] {event.getAction(), event.getResourceName(), event.getResourceType(),
-                event.getServiceInstanceId(), event.getInvariantUUID(), event.getPrevVersion(),
-                event.getCurrVersion(), event.getModifier(), event.getPrevState(),
-                event.getCurrState(), event.getComment(), event.getStatus(), event.getDesc()};
+        return new String[]{event.getAction(), event.getResourceName(), event.getResourceType(), event.getServiceInstanceId(),
+            event.getInvariantUUID(), event.getPrevVersion(), event.getCurrVersion(), event.getModifier(), event.getPrevState(), event.getCurrState(),
+            event.getComment(), event.getStatus(), event.getDesc()};
     }
 }
index 237ce52..723d47a 100644 (file)
@@ -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.
@@ -17,7 +17,6 @@
  * limitations under the License.
  * ============LICENSE_END=========================================================
  */
-
 package org.openecomp.sdc.be.auditing.impl.resourceadmin;
 
 import org.openecomp.sdc.be.model.User;
@@ -28,27 +27,27 @@ import org.openecomp.sdc.be.resources.data.auditing.model.ResourceVersionInfo;
 
 public class AuditCreateUpdateResourceAdminEventFactory extends AuditResourceAdminEventFactory {
 
-    protected static final String LOG_STR = "ACTION = \"%s\" RESOURCE_NAME = \"%s\" RESOURCE_TYPE = \"%s\" SERVICE_INSTANCE_ID = \"%s\"" +
-            " INVARIANT_UUID = \"%s\" PREV_VERSION = \"%s\" CURR_VERSION = \"%s\" MODIFIER = \"%s\" PREV_STATE = \"%s\" CURR_STATE = \"%s\"" +
-            " STATUS = \"%s\" DESC = \"%s\"";
+    protected static final String LOG_STR = "ACTION = \"%s\" RESOURCE_NAME = \"%s\" RESOURCE_TYPE = \"%s\" SERVICE_INSTANCE_ID = \"%s\""
+        + " INVARIANT_UUID = \"%s\" PREV_VERSION = \"%s\" CURR_VERSION = \"%s\" MODIFIER = \"%s\" PREV_STATE = \"%s\" CURR_STATE = \"%s\""
+        + " STATUS = \"%s\" DESC = \"%s\"";
 
-    public AuditCreateUpdateResourceAdminEventFactory(AuditingActionEnum action, CommonAuditData commonAuditData, ResourceCommonInfo resourceCommonInfo,
-                                                      ResourceVersionInfo prevParams, ResourceVersionInfo currParams,
-                                                      String invariantUuid, User modifier, String artifactData, String comment, String did, String toscaNodeType) {
-        super(action, commonAuditData, resourceCommonInfo, prevParams, currParams, invariantUuid,
-                modifier, artifactData, comment, did, toscaNodeType);
+    public AuditCreateUpdateResourceAdminEventFactory(AuditingActionEnum action, CommonAuditData commonAuditData,
+                                                      ResourceCommonInfo resourceCommonInfo, ResourceVersionInfo prevParams,
+                                                      ResourceVersionInfo currParams, String invariantUuid, User modifier, String artifactData,
+                                                      String comment, String did, String toscaNodeType) {
+        super(action, commonAuditData, resourceCommonInfo, prevParams, currParams, invariantUuid, modifier, artifactData, comment, did,
+            toscaNodeType);
     }
 
     @Override
-        public String getLogPattern() {
-            return LOG_STR;
-        }
+    public String getLogPattern() {
+        return LOG_STR;
+    }
 
-        @Override
-        public String[] getLogMessageParams() {
-            return new String[] {event.getAction(), event.getResourceName(), event.getResourceType(),
-                event.getServiceInstanceId(), event.getInvariantUUID(), event.getPrevVersion(),
-                event.getCurrVersion(), event.getModifier(), event.getPrevState(),
-                event.getCurrState(), event.getStatus(), event.getDesc()};
+    @Override
+    public String[] getLogMessageParams() {
+        return new String[]{event.getAction(), event.getResourceName(), event.getResourceType(), event.getServiceInstanceId(),
+            event.getInvariantUUID(), event.getPrevVersion(), event.getCurrVersion(), event.getModifier(), event.getPrevState(), event.getCurrState(),
+            event.getStatus(), event.getDesc()};
     }
 }
index 2167744..8fc09d9 100644 (file)
@@ -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.
@@ -17,7 +17,6 @@
  * limitations under the License.
  * ============LICENSE_END=========================================================
  */
-
 package org.openecomp.sdc.be.auditing.impl.resourceadmin;
 
 import org.openecomp.sdc.be.model.User;
@@ -29,15 +28,15 @@ import org.openecomp.sdc.common.api.Constants;
 
 public class AuditDistStateChangeRequestResourceAdminEventFactory extends AuditResourceAdminEventFactory {
 
-    private static final String LOG_STR = "ACTION = \"%s\" RESOURCE_NAME = \"%s\" RESOURCE_TYPE = \"%s\" SERVICE_INSTANCE_ID = \"%s\"" +
-            " CURR_VERSION = \"%s\" MODIFIER = \"%s\" CURR_STATE = \"%s\"" +
-            " DPREV_STATUS = \"%s\" DCURR_STATUS = \"%s\" DID = \"%s\" STATUS = \"%s\" DESC = \"%s\"";
+    private static final String LOG_STR = "ACTION = \"%s\" RESOURCE_NAME = \"%s\" RESOURCE_TYPE = \"%s\" SERVICE_INSTANCE_ID = \"%s\""
+        + " CURR_VERSION = \"%s\" MODIFIER = \"%s\" CURR_STATE = \"%s\""
+        + " DPREV_STATUS = \"%s\" DCURR_STATUS = \"%s\" DID = \"%s\" STATUS = \"%s\" DESC = \"%s\"";
 
     public AuditDistStateChangeRequestResourceAdminEventFactory(CommonAuditData commonFields, ResourceCommonInfo resourceCommonInfo,
-                                                                ResourceVersionInfo prevParams, ResourceVersionInfo currParams,
-                                                                String invariantUuid, User modifier, String artifactData, String comment, String did) {
-        super(AuditingActionEnum.DISTRIBUTION_STATE_CHANGE_REQUEST, commonFields, resourceCommonInfo, prevParams, currParams, invariantUuid,
-                modifier, artifactData, comment, did, Constants.EMPTY_STRING);
+                                                                ResourceVersionInfo prevParams, ResourceVersionInfo currParams, String invariantUuid,
+                                                                User modifier, String artifactData, String comment, String did) {
+        super(AuditingActionEnum.DISTRIBUTION_STATE_CHANGE_REQUEST, commonFields, resourceCommonInfo, prevParams, currParams, invariantUuid, modifier,
+            artifactData, comment, did, Constants.EMPTY_STRING);
     }
 
     @Override
@@ -47,9 +46,8 @@ public class AuditDistStateChangeRequestResourceAdminEventFactory extends AuditR
 
     @Override
     public String[] getLogMessageParams() {
-        return new String[] {event.getAction(), event.getResourceName(), event.getResourceType(),
-                event.getServiceInstanceId(), event.getCurrVersion(), event.getModifier(),
-                event.getCurrState(), event.getDprevStatus(), event.getDcurrStatus(),
-                event.getDid(), event.getStatus(), event.getDesc()};
+        return new String[]{event.getAction(), event.getResourceName(), event.getResourceType(), event.getServiceInstanceId(), event.getCurrVersion(),
+            event.getModifier(), event.getCurrState(), event.getDprevStatus(), event.getDcurrStatus(), event.getDid(), event.getStatus(),
+            event.getDesc()};
     }
 }
index c8a34b3..0b8d6e7 100644 (file)
@@ -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.
@@ -17,7 +17,6 @@
  * limitations under the License.
  * ============LICENSE_END=========================================================
  */
-
 package org.openecomp.sdc.be.auditing.impl.resourceadmin;
 
 import org.openecomp.sdc.be.model.User;
@@ -29,16 +28,16 @@ import org.openecomp.sdc.common.api.Constants;
 
 public class AuditDistStateChangeResourceAdminEventFactory extends AuditResourceAdminEventFactory {
 
-    private static final String LOG_STR = "ACTION = \"%s\" RESOURCE_NAME = \"%s\" RESOURCE_TYPE = \"%s\" SERVICE_INSTANCE_ID = \"%s\"" +
-            " CURR_VERSION = \"%s\" MODIFIER = \"%s\" CURR_STATE = \"%s\"" +
-            " DPREV_STATUS = \"%s\" DCURR_STATUS = \"%s\" STATUS = \"%s\" DESC = \"%s\" COMMENT = \"%s\"";
-
+    private static final String LOG_STR = "ACTION = \"%s\" RESOURCE_NAME = \"%s\" RESOURCE_TYPE = \"%s\" SERVICE_INSTANCE_ID = \"%s\""
+        + " CURR_VERSION = \"%s\" MODIFIER = \"%s\" CURR_STATE = \"%s\""
+        + " DPREV_STATUS = \"%s\" DCURR_STATUS = \"%s\" STATUS = \"%s\" DESC = \"%s\" COMMENT = \"%s\"";
 
-    public AuditDistStateChangeResourceAdminEventFactory(AuditingActionEnum action, CommonAuditData commonFields, ResourceCommonInfo resourceCommonInfo,
-                                                         ResourceVersionInfo prevParams, ResourceVersionInfo currParams, String invariantUuid,
-                                                         User modifier, String artifactData, String comment, String did) {
-        super(action, commonFields, resourceCommonInfo, prevParams, currParams, invariantUuid,
-                modifier, artifactData, comment, did, Constants.EMPTY_STRING);
+    public AuditDistStateChangeResourceAdminEventFactory(AuditingActionEnum action, CommonAuditData commonFields,
+                                                         ResourceCommonInfo resourceCommonInfo, ResourceVersionInfo prevParams,
+                                                         ResourceVersionInfo currParams, String invariantUuid, User modifier, String artifactData,
+                                                         String comment, String did) {
+        super(action, commonFields, resourceCommonInfo, prevParams, currParams, invariantUuid, modifier, artifactData, comment, did,
+            Constants.EMPTY_STRING);
     }
 
     @Override
@@ -48,10 +47,8 @@ public class AuditDistStateChangeResourceAdminEventFactory extends AuditResource
 
     @Override
     public String[] getLogMessageParams() {
-        return new String[] {event.getAction(), event.getResourceName(), event.getResourceType(),
-                event.getServiceInstanceId(), event.getCurrVersion(), event.getModifier(),
-                event.getCurrState(), event.getDprevStatus(), event.getDcurrStatus(),
-                event.getStatus(), event.getDesc(), event.getComment()};
+        return new String[]{event.getAction(), event.getResourceName(), event.getResourceType(), event.getServiceInstanceId(), event.getCurrVersion(),
+            event.getModifier(), event.getCurrState(), event.getDprevStatus(), event.getDcurrStatus(), event.getStatus(), event.getDesc(),
+            event.getComment()};
     }
-
 }
index 947e5ad..af5a7ae 100644 (file)
@@ -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.
@@ -17,7 +17,6 @@
  * limitations under the License.
  * ============LICENSE_END=========================================================
  */
-
 package org.openecomp.sdc.be.auditing.impl.resourceadmin;
 
 import org.openecomp.sdc.be.model.User;
@@ -28,18 +27,20 @@ import org.openecomp.sdc.be.resources.data.auditing.model.ResourceVersionInfo;
 
 public class AuditImportResourceAdminEventFactory extends AuditCreateUpdateResourceAdminEventFactory {
 
-    private static final String LOG_STR_TOSCA = LOG_STR + " TOSCA_NODE_TYPE = \"%s\"" ;
+    private static final String LOG_STR_TOSCA = LOG_STR + " TOSCA_NODE_TYPE = \"%s\"";
 
-    public AuditImportResourceAdminEventFactory(CommonAuditData commonAuditData, ResourceCommonInfo resourceCommonInfo, ResourceVersionInfo prevParams, ResourceVersionInfo currParams,
-                                                String invariantUuid, User modifier, String artifactData, String comment, String did, String toscaNodeType) {
-        super(AuditingActionEnum.IMPORT_RESOURCE, commonAuditData, resourceCommonInfo, prevParams, currParams, invariantUuid,
-                modifier, artifactData, comment, did, toscaNodeType);
+    public AuditImportResourceAdminEventFactory(CommonAuditData commonAuditData, ResourceCommonInfo resourceCommonInfo,
+                                                ResourceVersionInfo prevParams, ResourceVersionInfo currParams, String invariantUuid, User modifier,
+                                                String artifactData, String comment, String did, String toscaNodeType) {
+        super(AuditingActionEnum.IMPORT_RESOURCE, commonAuditData, resourceCommonInfo, prevParams, currParams, invariantUuid, modifier, artifactData,
+            comment, did, toscaNodeType);
     }
 
-    public AuditImportResourceAdminEventFactory(CommonAuditData commonAuditData, ResourceCommonInfo resourceCommonInfo, ResourceVersionInfo prevParams, ResourceVersionInfo currParams,
-                                                String invariantUuid, User modifier, String toscaNodeType) {
-        super(AuditingActionEnum.IMPORT_RESOURCE, commonAuditData, resourceCommonInfo, prevParams, currParams, invariantUuid,
-                   modifier, null, null, null, toscaNodeType);
+    public AuditImportResourceAdminEventFactory(CommonAuditData commonAuditData, ResourceCommonInfo resourceCommonInfo,
+                                                ResourceVersionInfo prevParams, ResourceVersionInfo currParams, String invariantUuid, User modifier,
+                                                String toscaNodeType) {
+        super(AuditingActionEnum.IMPORT_RESOURCE, commonAuditData, resourceCommonInfo, prevParams, currParams, invariantUuid, modifier, null, null,
+            null, toscaNodeType);
     }
 
     @Override
@@ -49,9 +50,8 @@ public class AuditImportResourceAdminEventFactory extends AuditCreateUpdateResou
 
     @Override
     public String[] getLogMessageParams() {
-        return new String[] {event.getAction(), event.getResourceName(), event.getResourceType(),
-                event.getServiceInstanceId(), event.getInvariantUUID(), event.getPrevVersion(),
-                event.getCurrVersion(), event.getModifier(), event.getPrevState(),
-                event.getCurrState(), event.getStatus(), event.getDesc(), event.getToscaNodeType()};
+        return new String[]{event.getAction(), event.getResourceName(), event.getResourceType(), event.getServiceInstanceId(),
+            event.getInvariantUUID(), event.getPrevVersion(), event.getCurrVersion(), event.getModifier(), event.getPrevState(), event.getCurrState(),
+            event.getStatus(), event.getDesc(), event.getToscaNodeType()};
     }
 }
index 1de2031..9cccd3b 100644 (file)
@@ -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.
@@ -17,7 +17,6 @@
  * limitations under the License.
  * ============LICENSE_END=========================================================
  */
-
 package org.openecomp.sdc.be.auditing.impl.resourceadmin;
 
 import org.openecomp.sdc.be.auditing.impl.AuditBaseEventFactory;
@@ -33,34 +32,30 @@ public abstract class AuditResourceAdminEventFactory extends AuditBaseEventFacto
 
     protected final ResourceAdminEvent event;
 
-    AuditResourceAdminEventFactory(AuditingActionEnum action, CommonAuditData commonFields, ResourceCommonInfo resourceCommonInfo, ResourceVersionInfo prevParams,
-                                          ResourceVersionInfo currParams, String invariantUuid,
-                                          User modifier, String artifactData, String comment, String did, String toscaNodeType) {
+    AuditResourceAdminEventFactory(AuditingActionEnum action, CommonAuditData commonFields, ResourceCommonInfo resourceCommonInfo,
+                                   ResourceVersionInfo prevParams, ResourceVersionInfo currParams, String invariantUuid, User modifier,
+                                   String artifactData, String comment, String did, String toscaNodeType) {
         this(action, commonFields, resourceCommonInfo, prevParams, currParams, invariantUuid, AuditBaseEventFactory.buildUserName(modifier),
-                artifactData, AuditBaseEventFactory.replaceNullNameWithEmpty(comment), did, toscaNodeType);
+            artifactData, AuditBaseEventFactory.replaceNullNameWithEmpty(comment), did, toscaNodeType);
     }
 
     AuditResourceAdminEventFactory(AuditingActionEnum action, CommonAuditData commonFields, ResourceCommonInfo resourceCommonInfo,
-                                          ResourceVersionInfo prevParams, ResourceVersionInfo currParams, String invariantUuid,
-                                          String modifier, String artifactData, String comment, String did,
-                                          String toscaNodeType, String timestamp) {
-        this(action, commonFields, resourceCommonInfo, prevParams, currParams, invariantUuid, modifier,
-                artifactData, comment, did, toscaNodeType);
+                                   ResourceVersionInfo prevParams, ResourceVersionInfo currParams, String invariantUuid, String modifier,
+                                   String artifactData, String comment, String did, String toscaNodeType, String timestamp) {
+        this(action, commonFields, resourceCommonInfo, prevParams, currParams, invariantUuid, modifier, artifactData, comment, did, toscaNodeType);
         this.event.setTimestamp1(timestamp);
     }
 
     private AuditResourceAdminEventFactory(AuditingActionEnum action, CommonAuditData commonFields, ResourceCommonInfo resourceCommonInfo,
-                                          ResourceVersionInfo prevParams, ResourceVersionInfo currParams, String invariantUuid,
-                                          String modifier, String artifactData, String comment, String did,
-                                          String toscaNodeType) {
+                                           ResourceVersionInfo prevParams, ResourceVersionInfo currParams, String invariantUuid, String modifier,
+                                           String artifactData, String comment, String did, String toscaNodeType) {
         super(action);
         this.event = new ResourceAdminEvent(getAction().getName(), commonFields, resourceCommonInfo, prevParams, currParams, invariantUuid, modifier,
-                artifactData, comment, did, toscaNodeType);
+            artifactData, comment, did, toscaNodeType);
     }
 
     @Override
     public AuditingGenericEvent getDbEvent() {
         return event;
     }
-
 }
index 75ba231..579971d 100644 (file)
@@ -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.
@@ -17,7 +17,6 @@
  * limitations under the License.
  * ============LICENSE_END=========================================================
  */
-
 package org.openecomp.sdc.be.auditing.impl.resourceadmin;
 
 import org.openecomp.sdc.be.resources.data.auditing.AuditingActionEnum;
@@ -29,10 +28,10 @@ public class AuditResourceAdminEventMigrationFactory extends AuditResourceAdminE
 
     public AuditResourceAdminEventMigrationFactory(AuditingActionEnum action, CommonAuditData commonFields, ResourceCommonInfo resourceCommonInfo,
                                                    ResourceVersionInfo prevParams, ResourceVersionInfo currParams, String invariantUuid,
-                                                   String modifier, String artifactData, String comment, String did,
-                                                   String toscaNodeType, String timestamp) {
-        super(action, commonFields, resourceCommonInfo, prevParams, currParams, invariantUuid, modifier,
-                artifactData, comment, did, toscaNodeType, timestamp);
+                                                   String modifier, String artifactData, String comment, String did, String toscaNodeType,
+                                                   String timestamp) {
+        super(action, commonFields, resourceCommonInfo, prevParams, currParams, invariantUuid, modifier, artifactData, comment, did, toscaNodeType,
+            timestamp);
     }
 
     @Override
index 53b6f4b..78cd70f 100644 (file)
@@ -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.
@@ -17,7 +17,6 @@
  * limitations under the License.
  * ============LICENSE_END=========================================================
  */
-
 package org.openecomp.sdc.be.auditing.impl.resourceadmin;
 
 import org.openecomp.sdc.be.auditing.api.AuditEventFactory;
@@ -30,16 +29,15 @@ import org.openecomp.sdc.be.resources.data.auditing.model.ResourceVersionInfo;
 
 public class AuditResourceEventFactoryManager {
 
-
-    public static AuditEventFactory createResourceEventFactory(AuditingActionEnum action, CommonAuditData commonFields, ResourceCommonInfo resourceCommonInfo,
-                                                               ResourceVersionInfo prevParams, ResourceVersionInfo currParams, String invariantUuid,
-                                                               User modifier, String artifactData, String comment, String did, String toscaNodeType) {
+    public static AuditEventFactory createResourceEventFactory(AuditingActionEnum action, CommonAuditData commonFields,
+                                                               ResourceCommonInfo resourceCommonInfo, ResourceVersionInfo prevParams,
+                                                               ResourceVersionInfo currParams, String invariantUuid, User modifier,
+                                                               String artifactData, String comment, String did, String toscaNodeType) {
         AuditBaseEventFactory factory = null;
-
         switch (action) {
             case IMPORT_RESOURCE:
-                factory = new AuditImportResourceAdminEventFactory(commonFields, resourceCommonInfo, prevParams, currParams,
-                        invariantUuid, modifier, artifactData, comment, did, toscaNodeType);
+                factory = new AuditImportResourceAdminEventFactory(commonFields, resourceCommonInfo, prevParams, currParams, invariantUuid, modifier,
+                    artifactData, comment, did, toscaNodeType);
                 break;
             case CREATE_RESOURCE:
             case CREATE_SERVICE:
@@ -48,7 +46,7 @@ public class AuditResourceEventFactoryManager {
             case RESTORE_COMPONENT:
             case UPDATE_SERVICE_METADATA:
                 factory = new AuditCreateUpdateResourceAdminEventFactory(action, commonFields, resourceCommonInfo, prevParams, currParams,
-                        invariantUuid, modifier, artifactData, comment, did, org.openecomp.sdc.common.api.Constants.EMPTY_STRING);
+                    invariantUuid, modifier, artifactData, comment, did, org.openecomp.sdc.common.api.Constants.EMPTY_STRING);
                 break;
             case CHECKIN_RESOURCE:
             case CHECKOUT_RESOURCE:
@@ -61,29 +59,28 @@ public class AuditResourceEventFactoryManager {
             case UPDATE_SERVICE_REFERENCE:
             case VF_UPGRADE_SERVICES:
                 factory = new AuditCertificationResourceAdminEventFactory(action, commonFields, resourceCommonInfo, prevParams, currParams,
-                        invariantUuid, modifier, artifactData, comment, did);
+                    invariantUuid, modifier, artifactData, comment, did);
                 break;
             case ARTIFACT_UPLOAD:
             case ARTIFACT_DELETE:
             case ARTIFACT_METADATA_UPDATE:
             case ARTIFACT_PAYLOAD_UPDATE:
             case ARTIFACT_DOWNLOAD:
-                factory = new AuditArtifactResourceAdminEventFactory(action, commonFields, resourceCommonInfo, prevParams, currParams,
-                        invariantUuid, modifier, artifactData, comment, did);
+                factory = new AuditArtifactResourceAdminEventFactory(action, commonFields, resourceCommonInfo, prevParams, currParams, invariantUuid,
+                    modifier, artifactData, comment, did);
                 break;
             case DISTRIBUTION_STATE_CHANGE_REQUEST:
                 factory = new AuditDistStateChangeRequestResourceAdminEventFactory(commonFields, resourceCommonInfo, prevParams, currParams,
-                         invariantUuid, modifier, artifactData, comment, did);
+                    invariantUuid, modifier, artifactData, comment, did);
                 break;
             case DISTRIBUTION_STATE_CHANGE_APPROV:
             case DISTRIBUTION_STATE_CHANGE_REJECT:
                 factory = new AuditDistStateChangeResourceAdminEventFactory(action, commonFields, resourceCommonInfo, prevParams, currParams,
-                         invariantUuid, modifier, artifactData, comment, did);
+                    invariantUuid, modifier, artifactData, comment, did);
                 break;
             default:
                 throw new UnsupportedOperationException();
         }
         return factory;
     }
-
 }
index ae31873..75d99a3 100644 (file)
@@ -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.
@@ -17,7 +17,6 @@
  * limitations under the License.
  * ============LICENSE_END=========================================================
  */
-
 package org.openecomp.sdc.be.auditing.impl.usersadmin;
 
 import org.openecomp.sdc.be.auditing.impl.AuditBaseEventFactory;
@@ -32,13 +31,11 @@ public class AuditGetUsersListEventFactory extends AuditBaseEventFactory {
     private static final String LOG_STR = "ACTION = \"%s\" MODIFIER = \"%s\" DETAILS = \"%s\" STATUS = \"%s\" DESC = \"%s\"";
     private final GetUsersListEvent event;
 
-    public AuditGetUsersListEventFactory(CommonAuditData commonFields, User modifier,
-                                         String userDetails) {
+    public AuditGetUsersListEventFactory(CommonAuditData commonFields, User modifier, String userDetails) {
         this(commonFields, AuditBaseEventFactory.buildUserName(modifier), userDetails);
     }
 
-    public AuditGetUsersListEventFactory(CommonAuditData commonFields, String modifier,
-                                         String userDetails, String timestamp) {
+    public AuditGetUsersListEventFactory(CommonAuditData commonFields, String modifier, String userDetails, String timestamp) {
         this(commonFields, modifier, userDetails);
         this.event.setTimestamp1(timestamp);
     }
@@ -55,12 +52,11 @@ public class AuditGetUsersListEventFactory extends AuditBaseEventFactory {
 
     @Override
     public String[] getLogMessageParams() {
-        return new String[] {event.getAction(), event.getModifier(), event.getDetails(), event.getStatus(), event.getDesc()};
+        return new String[]{event.getAction(), event.getModifier(), event.getDetails(), event.getStatus(), event.getDesc()};
     }
 
     @Override
     public AuditingGenericEvent getDbEvent() {
         return event;
     }
-
 }
index 821c13f..7063091 100644 (file)
@@ -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.
@@ -17,7 +17,6 @@
  * limitations under the License.
  * ============LICENSE_END=========================================================
  */
-
 package org.openecomp.sdc.be.auditing.impl.usersadmin;
 
 import org.openecomp.sdc.be.auditing.impl.AuditBaseEventFactory;
@@ -53,12 +52,11 @@ public class AuditUserAccessEventFactory extends AuditBaseEventFactory {
 
     @Override
     public String[] getLogMessageParams() {
-        return new String[] {event.getAction(), event.getUserUid(), event.getStatus(), event.getDesc()};
+        return new String[]{event.getAction(), event.getUserUid(), event.getStatus(), event.getDesc()};
     }
 
     @Override
     public AuditingGenericEvent getDbEvent() {
         return event;
     }
-
 }
index 8123642..3d2b133 100644 (file)
@@ -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.
@@ -17,7 +17,6 @@
  * limitations under the License.
  * ============LICENSE_END=========================================================
  */
-
 package org.openecomp.sdc.be.auditing.impl.usersadmin;
 
 import org.openecomp.sdc.be.auditing.impl.AuditBaseEventFactory;
@@ -33,20 +32,19 @@ public class AuditUserAdminEventFactory extends AuditBaseEventFactory {
     private final UserAdminEvent event;
 
     public AuditUserAdminEventFactory(AuditingActionEnum action, CommonAuditData commonFields, User modifier, User userBefore, User userAfter) {
-        this(action, commonFields, AuditBaseEventFactory.buildUserName(modifier),
-                AuditBaseEventFactory.buildUserNameExtended(userBefore),
-                AuditBaseEventFactory.buildUserNameExtended(userAfter));
+        this(action, commonFields, AuditBaseEventFactory.buildUserName(modifier), AuditBaseEventFactory.buildUserNameExtended(userBefore),
+            AuditBaseEventFactory.buildUserNameExtended(userAfter));
     }
 
     //Used by migration util
-    public AuditUserAdminEventFactory(AuditingActionEnum action, CommonAuditData commonFields, String modifier, String userBefore,
-                                      String userAfter, String timestamp) {
+    public AuditUserAdminEventFactory(AuditingActionEnum action, CommonAuditData commonFields, String modifier, String userBefore, String userAfter,
+                                      String timestamp) {
         this(action, commonFields, modifier, userBefore, userAfter);
         this.event.setTimestamp1(timestamp);
     }
 
     private AuditUserAdminEventFactory(AuditingActionEnum action, CommonAuditData commonFields, String modifier, String userBefore,
-                                      String userAfter) {
+                                       String userAfter) {
         super(action);
         event = new UserAdminEvent(action.getName(), commonFields, modifier, userBefore, userAfter);
     }
@@ -58,14 +56,11 @@ public class AuditUserAdminEventFactory extends AuditBaseEventFactory {
 
     @Override
     public String[] getLogMessageParams() {
-        return new String[] {event.getAction(), event.getModifier(), event.getUserBefore(),
-                event.getUserAfter(), event.getStatus(), event.getDesc()};
+        return new String[]{event.getAction(), event.getModifier(), event.getUserBefore(), event.getUserAfter(), event.getStatus(), event.getDesc()};
     }
 
     @Override
     public AuditingGenericEvent getDbEvent() {
         return event;
     }
-
-
 }
index 42a8691..588bddb 100644 (file)
  * limitations under the License.
  * ============LICENSE_END=========================================================
  */
-
 package org.openecomp.sdc.be.catalog.api;
 
+import java.io.Serializable;
 import org.openecomp.sdc.be.catalog.enums.ChangeTypeEnum;
 import org.openecomp.sdc.be.model.CatalogUpdateTimestamp;
 
-import java.io.Serializable;
-
-
-
 /**
- * Represent Component (service, resource etc...) change message added to the
- * message queue by sdc backend.<br>
- * 
- * @author ms172g
+ * Represent Component (service, resource etc...) change message added to the message queue by sdc backend.<br>
  *
+ * @author ms172g
  */
 public interface IComponentMessage extends Serializable, ITypeMessage {
-       /**
-        * Change Type
-        * @return
-        */
-       ChangeTypeEnum getChangeType();
-       CatalogUpdateTimestamp getCatalogUpdateTimestamp();
 
+    /**
+     * Change Type
+     *
+     * @return
+     */
+    ChangeTypeEnum getChangeType();
+
+    CatalogUpdateTimestamp getCatalogUpdateTimestamp();
 }
index 21c3ac8..c898825 100644 (file)
  * limitations under the License.
  * ============LICENSE_END=========================================================
  */
-
 package org.openecomp.sdc.be.catalog.api;
 
 public interface IMessageQueueHandlerProducer {
-    
+
     IStatus pushMessage(ITypeMessage message);
-    IStatus init();
 
+    IStatus init();
 }
index dd21c29..7ffb6d0 100644 (file)
  * limitations under the License.
  * ============LICENSE_END=========================================================
  */
-
 package org.openecomp.sdc.be.catalog.api;
 
 import org.openecomp.sdc.be.catalog.enums.ResultStatusEnum;
 
 @FunctionalInterface
 public interface IStatus {
-    
+
     static IStatus getSuccessStatus() {
-        
         return () -> ResultStatusEnum.SUCCESS;
     }
 
@@ -39,5 +37,4 @@ public interface IStatus {
     }
 
     ResultStatusEnum getResultStatus();
-
-}
\ No newline at end of file
+}
index a58e5f8..cec7313 100644 (file)
@@ -17,9 +17,9 @@
  * limitations under the License.
  * ============LICENSE_END=========================================================
  */
-
 package org.openecomp.sdc.be.catalog.api;
 
 public interface ITypeMessage {
+
     String getMessageType();
 }
index 5107468..776c00b 100644 (file)
  * limitations under the License.
  * ============LICENSE_END=========================================================
  */
-
 package org.openecomp.sdc.be.catalog.enums;
 
 /**
- * Represents The change type SDC Backend requests on the Component.<br> 
- * @author ms172g
+ * Represents The change type SDC Backend requests on the Component.<br>
  *
+ * @author ms172g
  */
-public enum ChangeTypeEnum {   
-    LIFECYCLE, DELETE, ARCHIVE, RESTORE    
-}
\ No newline at end of file
+public enum ChangeTypeEnum {
+    LIFECYCLE, DELETE, ARCHIVE, RESTORE
+}
index 53a2423..925bd47 100644 (file)
  * limitations under the License.
  * ============LICENSE_END=========================================================
  */
-
 package org.openecomp.sdc.be.catalog.enums;
 
 /**
  * Simple Status Enum
- * @author ms172g
  *
+ * @author ms172g
  */
 public enum ResultStatusEnum {
-       SUCCESS, FAIL , SERVICE_DISABLED
-}
\ No newline at end of file
+    SUCCESS, FAIL, SERVICE_DISABLED
+}
index 82b6467..69a04e1 100644 (file)
  * limitations under the License.
  * ============LICENSE_END=========================================================
  */
-
 package org.openecomp.sdc.be.catalog.impl;
 
 import com.fasterxml.jackson.annotation.JsonProperty;
+import java.util.List;
 import org.openecomp.sdc.be.catalog.api.IComponentMessage;
 import org.openecomp.sdc.be.catalog.enums.ChangeTypeEnum;
 import org.openecomp.sdc.be.datatypes.enums.ComponentTypeEnum;
@@ -32,120 +32,116 @@ import org.openecomp.sdc.be.model.catalog.CatalogComponent;
 import org.openecomp.sdc.be.model.category.CategoryDefinition;
 import org.openecomp.sdc.be.model.category.SubCategoryDefinition;
 
-import java.util.List;
-
 public class ComponentMessage extends CatalogComponent implements IComponentMessage {
-       /**
-        * 
-        */
-       private static final long serialVersionUID = 3233307722573636520L;
-       @JsonProperty("changeTypeEnum")
-       ChangeTypeEnum changeTypeEnum;
-       @JsonProperty("catalogUpdateTimestamp")
-       private CatalogUpdateTimestamp catalogUpdateTimestamp;
-       private Boolean isArchived;
-
-       public ComponentMessage(Component component, ChangeTypeEnum changeTypeEnum,
-                       CatalogUpdateTimestamp catalogUpdateTimestamp) {
-               super();
-
-               this.changeTypeEnum = changeTypeEnum;
-               this.catalogUpdateTimestamp = catalogUpdateTimestamp;
-
-               setUniqueId(component.getUniqueId());// uniqueId
-               setUuid(component.getUUID()); // uuid
-               setInvariantUUID(component.getInvariantUUID()); // invariantUUID
-
-               // View Fields
-               setName(component.getName()); // name
-               setSystemName(component.getSystemName()); // systemName
-
-               setVersion(component.getVersion());// version
-               setLifecycleState(component.getLifecycleState()
-                               .name()); // lifecycleState
-               setIcon(component.getIcon()); // icon
-
-               ComponentTypeEnum componentType = component.getComponentType();
-               setComponentType(componentType);// componentType
-
-               buildCategories(component.getCategories()); // categoryNormalizedName,
-                                                                                                       // subCategoryNormalizedName
-               if (componentType == ComponentTypeEnum.SERVICE) {
-                       Service service = (Service) component;
-                       setDistributionStatus(service.getDistributionStatus()
-                                       .name()); // distributionStatus
-               } else {
-                       Resource r = (Resource) component;
-                       this.setResourceType(r.getResourceType()
-                                       .name()); // resourceType
-               }
-               setIsArchived(component.isArchived()); // isArchived
-               setIsHighestVersion(component.isHighestVersion()); // isHighestVersion
-               setDescription(component.getDescription()); // description
-               if (component.getTags() != null) {
-                       setTags(component.getTags()); // tags
-               }
-               setLastUpdateDate(component.getLastUpdateDate());// lastUpdateDate
-               setLastUpdaterUserId(component.getLastUpdaterUserId());
-       }
-
-       private void buildCategories(List<CategoryDefinition> categories) {
-               if (categories != null) {
-                       setCategories(categories);
-                       CategoryDefinition categoryDefinition = categories.get(0);
-
-                       if (categoryDefinition != null) {
-                               setCategoryNormalizedName(categoryDefinition.getName());
-                               List<SubCategoryDefinition> subcategories = categoryDefinition.getSubcategories();
-                               if (null != subcategories) {
-                                       SubCategoryDefinition subCategoryDefinition = subcategories.get(0);
-
-                                       if (subCategoryDefinition != null) {
-                                               setSubCategoryNormalizedName(subCategoryDefinition.getName());
-                                       }
-                               }
-                       }
-               }
-       }
-
-       @Override
-       public ChangeTypeEnum getChangeType() {
-               return changeTypeEnum;
-       }
-
-       @Override
-       public CatalogUpdateTimestamp getCatalogUpdateTimestamp() {
-               return catalogUpdateTimestamp;
-       }
-
-       @Override
-       public String toString() {
-               return "ComponentMessage [ getChangeType()=" + getChangeType() + ", getCatalogUpdateTimestamp()="
-                               + getCatalogUpdateTimestamp() + ", getIsArchived()=" + getIsArchived() + ", getUuid()=" + getUuid()
-                               + ", getInvariantUUID()=" + getInvariantUUID() + ", getSystemName()=" + getSystemName()
-                               + ", getDescription()=" + getDescription() + ", getIsHighestVersion()=" + getIsHighestVersion()
-                               + ", getCategoryNormalizedName()=" + getCategoryNormalizedName() + ", getSubCategoryNormalizedName()="
-                               + getSubCategoryNormalizedName() + ", getResourceType()=" + getResourceType() + ", getName()="
-                               + getName() + ", getLastUpdateDate()=" + getLastUpdateDate() + ", getVersion()=" + getVersion()
-                               + ", getComponentType()=" + getComponentType() + ", getIcon()=" + getIcon() + ", getUniqueId()="
-                               + getUniqueId() + ", getLifecycleState()=" + getLifecycleState() + ", getDistributionStatus()="
-                               + getDistributionStatus() + ", getTags()=" + getTags() + ", getCategories()=" + getCategories()
-                               + ", getClass()=" + getClass() + ", hashCode()=" + hashCode() + ", toString()=" + super.toString()
-                               + "]";
-       }
-
-       public Boolean getIsArchived() {
-               return isArchived;
-       }
-
-       public void setIsArchived(Boolean isArchived) {
-               this.isArchived = isArchived;
-       }
 
+    /**
+     *
+     */
+    private static final long serialVersionUID = 3233307722573636520L;
+    @JsonProperty("changeTypeEnum")
+    ChangeTypeEnum changeTypeEnum;
+    @JsonProperty("catalogUpdateTimestamp")
+    private CatalogUpdateTimestamp catalogUpdateTimestamp;
+    private Boolean isArchived;
+
+    public ComponentMessage(Component component, ChangeTypeEnum changeTypeEnum, CatalogUpdateTimestamp catalogUpdateTimestamp) {
+        super();
+        this.changeTypeEnum = changeTypeEnum;
+        this.catalogUpdateTimestamp = catalogUpdateTimestamp;
+        setUniqueId(component.getUniqueId());// uniqueId
+
+        setUuid(component.getUUID()); // uuid
+
+        setInvariantUUID(component.getInvariantUUID()); // invariantUUID
+
+        // View Fields
+
+        setName(component.getName()); // name
+
+        setSystemName(component.getSystemName()); // systemName
+
+        setVersion(component.getVersion());// version
+        setLifecycleState(component.getLifecycleState()
+            .name()); // lifecycleState
+
+        setIcon(component.getIcon()); // icon
+        ComponentTypeEnum componentType = component.getComponentType();
+        setComponentType(componentType);// componentType
+
+        buildCategories(component.getCategories()); // categoryNormalizedName,
+
+        // subCategoryNormalizedName
+        if (componentType == ComponentTypeEnum.SERVICE) {
+            Service service = (Service) component;
+            setDistributionStatus(service.getDistributionStatus()
+                .name()); // distributionStatus
+        } else {
+            Resource r = (Resource) component;
+            this.setResourceType(r.getResourceType()
+                .name()); // resourceType
+        }
+        setIsArchived(component.isArchived()); // isArchived
+
+        setIsHighestVersion(component.isHighestVersion()); // isHighestVersion
+
+        setDescription(component.getDescription()); // description
+        if (component.getTags() != null) {
+            setTags(component.getTags()); // tags
+        }
+        setLastUpdateDate(component.getLastUpdateDate());// lastUpdateDate
+        setLastUpdaterUserId(component.getLastUpdaterUserId());
+    }
+
+    private void buildCategories(List<CategoryDefinition> categories) {
+        if (categories != null) {
+            setCategories(categories);
+            CategoryDefinition categoryDefinition = categories.get(0);
+            if (categoryDefinition != null) {
+                setCategoryNormalizedName(categoryDefinition.getName());
+                List<SubCategoryDefinition> subcategories = categoryDefinition.getSubcategories();
+                if (null != subcategories) {
+                    SubCategoryDefinition subCategoryDefinition = subcategories.get(0);
+                    if (subCategoryDefinition != null) {
+                        setSubCategoryNormalizedName(subCategoryDefinition.getName());
+                    }
+                }
+            }
+        }
+    }
+
+    @Override
+    public ChangeTypeEnum getChangeType() {
+        return changeTypeEnum;
+    }
+
+    @Override
+    public CatalogUpdateTimestamp getCatalogUpdateTimestamp() {
+        return catalogUpdateTimestamp;
+    }
+
+    @Override
+    public String toString() {
+        return "ComponentMessage [ getChangeType()=" + getChangeType() + ", getCatalogUpdateTimestamp()=" + getCatalogUpdateTimestamp()
+            + ", getIsArchived()=" + getIsArchived() + ", getUuid()=" + getUuid() + ", getInvariantUUID()=" + getInvariantUUID()
+            + ", getSystemName()=" + getSystemName() + ", getDescription()=" + getDescription() + ", getIsHighestVersion()=" + getIsHighestVersion()
+            + ", getCategoryNormalizedName()=" + getCategoryNormalizedName() + ", getSubCategoryNormalizedName()=" + getSubCategoryNormalizedName()
+            + ", getResourceType()=" + getResourceType() + ", getName()=" + getName() + ", getLastUpdateDate()=" + getLastUpdateDate()
+            + ", getVersion()=" + getVersion() + ", getComponentType()=" + getComponentType() + ", getIcon()=" + getIcon() + ", getUniqueId()="
+            + getUniqueId() + ", getLifecycleState()=" + getLifecycleState() + ", getDistributionStatus()=" + getDistributionStatus() + ", getTags()="
+            + getTags() + ", getCategories()=" + getCategories() + ", getClass()=" + getClass() + ", hashCode()=" + hashCode() + ", toString()="
+            + super.toString() + "]";
+    }
+
+    public Boolean getIsArchived() {
+        return isArchived;
+    }
+
+    public void setIsArchived(Boolean isArchived) {
+        this.isArchived = isArchived;
+    }
 
     @Override
     public String getMessageType() {
         return getClass().getSimpleName();
     }
-
 }
index a442481..855ef64 100644 (file)
@@ -17,7 +17,6 @@
  * limitations under the License.
  * ============LICENSE_END=========================================================
  */
-
 package org.openecomp.sdc.be.catalog.impl;
 
 import com.att.nsa.mr.client.MRBatchingPublisher;
@@ -45,8 +44,7 @@ public class DmaapProducer implements IMessageQueueHandlerProducer {
     private final ConfigurationManager configurationManager = ConfigurationManager.getConfigurationManager();
     private MRBatchingPublisher publisher;
 
-    public DmaapProducer(final DmaapClientFactory dmaapClientFactory,
-                         final DmaapProducerHealth dmaapHealth) {
+    public DmaapProducer(final DmaapClientFactory dmaapClientFactory, final DmaapProducerHealth dmaapHealth) {
         this.dmaapClientFactory = dmaapClientFactory;
         this.dmaapHealth = dmaapHealth;
     }
@@ -54,18 +52,15 @@ public class DmaapProducer implements IMessageQueueHandlerProducer {
     @Override
     public IStatus pushMessage(ITypeMessage message) {
         try {
-            DmaapProducerConfiguration producerConfiguration = configurationManager.getConfiguration()
-                .getDmaapProducerConfiguration();
+            DmaapProducerConfiguration producerConfiguration = configurationManager.getConfiguration().getDmaapProducerConfiguration();
             if (!producerConfiguration.getActive()) {
-                LOG.info(
-                    "[Microservice DMAAP] producer is disabled [re-enable in configuration->isActive],message not sent.");
+                LOG.info("[Microservice DMAAP] producer is disabled [re-enable in configuration->isActive],message not sent.");
                 dmaapHealth.report(false);
                 return IStatus.getServiceDisabled();
             }
             if (publisher == null) {
                 IStatus initStatus = init();
                 if (initStatus.getResultStatus() != ResultStatusEnum.SUCCESS) {
-
                     return initStatus;
                 }
             }
@@ -73,23 +68,17 @@ public class DmaapProducer implements IMessageQueueHandlerProducer {
             String jsonInString = mapper.writeValueAsString(message);
             if (publisher != null) {
                 LOG.info("before send message . response {}", jsonInString);
-
-                LOG.invoke("Dmaap Producer", "DmaapProducer-pushMessage", DmaapProducer.class.getName(),
-                    message.toString());
-
+                LOG.invoke("Dmaap Producer", "DmaapProducer-pushMessage", DmaapProducer.class.getName(), message.toString());
                 int pendingMsg = publisher.send(jsonInString);
                 LOG.info("sent message . response {}", pendingMsg);
-                LOG.invokeReturn(producerConfiguration.getConsumerId(), "Dmaap Producer",
-                    StatusCode.COMPLETE.getStatusCode(), "DmaapProducer-pushMessage", message.toString(), pendingMsg);
-
+                LOG.invokeReturn(producerConfiguration.getConsumerId(), "Dmaap Producer", StatusCode.COMPLETE.getStatusCode(),
+                    "DmaapProducer-pushMessage", message.toString(), pendingMsg);
             }
-
             dmaapHealth.report(true);
         } catch (Exception e) {
             LOG.error(EcompLoggerErrorCode.BUSINESS_PROCESS_ERROR, "Failed to send message . Exception {}", e.getMessage());
             return IStatus.getFailStatus();
         }
-
         return IStatus.getSuccessStatus();
     }
 
@@ -97,8 +86,7 @@ public class DmaapProducer implements IMessageQueueHandlerProducer {
     @Override
     public IStatus init() {
         LOG.debug("MessageQueueHandlerProducer:: Start initializing");
-        DmaapProducerConfiguration configuration = configurationManager.getConfiguration()
-            .getDmaapProducerConfiguration();
+        DmaapProducerConfiguration configuration = configurationManager.getConfiguration().getDmaapProducerConfiguration();
         if (configuration.getActive()) {
             try {
                 publisher = dmaapClientFactory.createProducer(configuration);
@@ -107,7 +95,6 @@ public class DmaapProducer implements IMessageQueueHandlerProducer {
                     dmaapHealth.report(false);
                     return IStatus.getFailStatus();
                 }
-
             } catch (Exception e) {
                 LOG.error("Failed to connect to topic . Exeption {}", e.getMessage());
                 dmaapHealth.report(false);
@@ -130,9 +117,6 @@ public class DmaapProducer implements IMessageQueueHandlerProducer {
             }
         } catch (Exception e) {
             LOG.error("Failed to close  messageQ . Exeption {}", e.getMessage());
-
         }
-
     }
-
 }
index b62df86..4000be3 100644 (file)
  * limitations under the License.
  * ============LICENSE_END=========================================================
  */
-
 package org.openecomp.sdc.be.catalog.impl;
 
+import java.util.concurrent.Executors;
+import java.util.concurrent.ScheduledExecutorService;
+import java.util.concurrent.ScheduledFuture;
+import java.util.concurrent.TimeUnit;
+import java.util.concurrent.atomic.AtomicBoolean;
+import javax.annotation.PostConstruct;
+import javax.annotation.PreDestroy;
 import org.openecomp.sdc.be.config.BeEcompErrorManager;
 import org.openecomp.sdc.be.config.ConfigurationManager;
 import org.openecomp.sdc.be.config.DmaapProducerConfiguration;
@@ -28,75 +34,37 @@ import org.openecomp.sdc.common.api.HealthCheckInfo;
 import org.openecomp.sdc.common.log.wrappers.Logger;
 import org.springframework.stereotype.Component;
 
-import javax.annotation.PostConstruct;
-import javax.annotation.PreDestroy;
-import java.util.concurrent.Executors;
-import java.util.concurrent.ScheduledExecutorService;
-import java.util.concurrent.ScheduledFuture;
-import java.util.concurrent.TimeUnit;
-import java.util.concurrent.atomic.AtomicBoolean;
-
 @Component("dmaapProducerHealth")
 public class DmaapProducerHealth {
 
-
     private static final String DMAAP_HEALTH_LOG_CONTEXT = "dmaapProducer.healthcheck";
     private static final String DMAAP_HEALTH_CHECK_STR = "dmaapProducerHealthCheck";
     private static final Logger log = Logger.getLogger(DmaapProducerHealth.class.getName());
     private static final Logger logHealth = Logger.getLogger(DMAAP_HEALTH_LOG_CONTEXT);
+    private final ScheduledExecutorService scheduler = Executors.newScheduledThreadPool(1);
     private HealthCheckInfo healthCheckInfo = DmaapProducerHealth.HealthCheckInfoResult.UNAVAILABLE.getHealthCheckInfo();
     private long healthCheckReadTimeout = 20;
     private long reconnectInterval = 5;
-    private HealthCheckScheduledTask healthCheckScheduledTask = null ;
-    private final ScheduledExecutorService scheduler = Executors.newScheduledThreadPool(1);
+    private HealthCheckScheduledTask healthCheckScheduledTask = null;
     private ScheduledFuture<?> scheduledFuture = null;
-    private DmaapProducerConfiguration configuration = null ;
-
+    private DmaapProducerConfiguration configuration = null;
     private volatile AtomicBoolean lastHealthState = new AtomicBoolean(false);
     private volatile AtomicBoolean reportedHealthState = null;
 
-    public enum HealthCheckInfoResult {
-        OK(new HealthCheckInfo(Constants.HC_COMPONENT_DMAAP_PRODUCER, HealthCheckInfo.HealthCheckStatus.UP, null, DmaapStatusDescription.OK.getDescription())),
-        UNAVAILABLE(new HealthCheckInfo(Constants.HC_COMPONENT_DMAAP_PRODUCER, HealthCheckInfo.HealthCheckStatus.DOWN, null, DmaapStatusDescription.UNAVAILABLE.getDescription())),
-        DOWN(new HealthCheckInfo(Constants.HC_COMPONENT_DMAAP_PRODUCER, HealthCheckInfo.HealthCheckStatus.DOWN, null, DmaapStatusDescription.DOWN.getDescription()));
-
-        private HealthCheckInfo healthCheckInfo;
-        HealthCheckInfoResult(HealthCheckInfo healthCheckInfo) {
-            this.healthCheckInfo = healthCheckInfo;
-        }
-        public HealthCheckInfo getHealthCheckInfo() {
-            return healthCheckInfo;
-        }
-    }
-
-    public enum DmaapStatusDescription {
-        OK("OK"), UNAVAILABLE("DmaapProducer is not available"),DOWN("DOWN"), NOT_CONFIGURED("DmaapProducer configuration is missing/wrong ");
-
-        private String desc;
-        DmaapStatusDescription(String desc) {
-            this.desc = desc;
-        }
-        public String getDescription() {
-            return desc;
-        }
-
-    }
-
     @PostConstruct
     public DmaapProducerHealth init() {
         log.trace("Enter init method of DmaapProducer health");
-        synchronized (DmaapProducerHealth.class){
+        synchronized (DmaapProducerHealth.class) {
             this.configuration = ConfigurationManager.getConfigurationManager().getConfiguration().getDmaapProducerConfiguration();
-
             Integer pollingInterval = configuration.getPollingInterval();
-            if (pollingInterval != null && pollingInterval!=0) {
+            if (pollingInterval != null && pollingInterval != 0) {
                 reconnectInterval = pollingInterval;
             }
             Integer healthCheckReadTimeoutConfig = configuration.getTimeoutMs();
             if (healthCheckReadTimeoutConfig != null) {
                 this.healthCheckReadTimeout = healthCheckReadTimeoutConfig;
             }
-            this.healthCheckScheduledTask = new HealthCheckScheduledTask( configuration ); //what is the representation? csv? delimiter? json or other
+            this.healthCheckScheduledTask = new HealthCheckScheduledTask(configuration); //what is the representation? csv? delimiter? json or other
             startHealthCheckTask(true);
         }
         log.trace("Exit init method of DistributionEngineClusterHealth");
@@ -120,75 +88,108 @@ public class DmaapProducerHealth {
      * @param startTask
      */
     private void startHealthCheckTask(boolean startTask) {
-        synchronized (DmaapProducerHealth.class){
+        synchronized (DmaapProducerHealth.class) {
             if (startTask && this.scheduledFuture == null) {
-                this.scheduledFuture = this.scheduler.scheduleAtFixedRate(this.healthCheckScheduledTask , 0, reconnectInterval, TimeUnit.SECONDS);
+                this.scheduledFuture = this.scheduler.scheduleAtFixedRate(this.healthCheckScheduledTask, 0, reconnectInterval, TimeUnit.SECONDS);
             }
         }
     }
 
-    void report(Boolean isUp){
-        if (reportedHealthState == null)
+    void report(Boolean isUp) {
+        if (reportedHealthState == null) {
             reportedHealthState = new AtomicBoolean(isUp);
+        }
         reportedHealthState.set(isUp);
     }
 
-
     public HealthCheckInfo getHealthCheckInfo() {
         return healthCheckInfo;
     }
 
+    public enum HealthCheckInfoResult {
+        // @formatter:off
+        OK(new HealthCheckInfo(Constants.HC_COMPONENT_DMAAP_PRODUCER, HealthCheckInfo.HealthCheckStatus.UP, null, DmaapStatusDescription.OK.getDescription())),
+        UNAVAILABLE(new HealthCheckInfo(Constants.HC_COMPONENT_DMAAP_PRODUCER, HealthCheckInfo.HealthCheckStatus.DOWN, null, DmaapStatusDescription.UNAVAILABLE.getDescription())),
+        DOWN(new HealthCheckInfo(Constants.HC_COMPONENT_DMAAP_PRODUCER, HealthCheckInfo.HealthCheckStatus.DOWN, null, DmaapStatusDescription.DOWN.getDescription()));
+        // @formatter:on
+
+        private HealthCheckInfo healthCheckInfo;
+
+        HealthCheckInfoResult(HealthCheckInfo healthCheckInfo) {
+            this.healthCheckInfo = healthCheckInfo;
+        }
+
+        public HealthCheckInfo getHealthCheckInfo() {
+            return healthCheckInfo;
+        }
+    }
+
+    public enum DmaapStatusDescription {
+        // @formatter:off
+        OK("OK"),
+        UNAVAILABLE("DmaapProducer is not available"),
+        DOWN("DOWN"),
+        NOT_CONFIGURED("DmaapProducer configuration is missing/wrong ");
+        // @formatter:on
+
+        private String desc;
+
+        DmaapStatusDescription(String desc) {
+            this.desc = desc;
+        }
+
+        public String getDescription() {
+            return desc;
+        }
+
+    }
+
     /**
      * Health Check Task Scheduler - infinite check.
      */
     public class HealthCheckScheduledTask implements Runnable {
-        private final DmaapProducerConfiguration config;
+
         private static final int TIMEOUT = 8192;
+        private final DmaapProducerConfiguration config;
 
-        HealthCheckScheduledTask(final DmaapProducerConfiguration config){
+        HealthCheckScheduledTask(final DmaapProducerConfiguration config) {
             this.config = config;
         }
+
         @Override
         public void run() {
             logHealth.trace("Executing Dmaap Health Check Task - Start");
             boolean prevIsReachable;
             boolean reachable;
             //first try simple ping
-            try{
-                if ( reportedHealthState != null ){
+            try {
+                if (reportedHealthState != null) {
                     reachable = reportedHealthState.get();
+                } else {
+                    reachable = false;
                 }
-                else{
-                    reachable =  false;
-                }
-                prevIsReachable = lastHealthState.getAndSet( reachable );
+                prevIsReachable = lastHealthState.getAndSet(reachable);
                 healthCheckInfo = reachable ? HealthCheckInfoResult.OK.healthCheckInfo : HealthCheckInfoResult.DOWN.healthCheckInfo;
-            }
-            catch( Exception e ){
-                log.debug("{} - cannot check connectivity -> {}",DMAAP_HEALTH_CHECK_STR, e );
+            } catch (Exception e) {
+                log.debug("{} - cannot check connectivity -> {}", DMAAP_HEALTH_CHECK_STR, e);
                 prevIsReachable = lastHealthState.getAndSet(false);
                 healthCheckInfo = HealthCheckInfoResult.UNAVAILABLE.healthCheckInfo;
             }
-            if (prevIsReachable != lastHealthState.get())
-                logAlarm( lastHealthState.get() );
+            if (prevIsReachable != lastHealthState.get()) {
+                logAlarm(lastHealthState.get());
+            }
         }
 
-
-       
-
         private void logAlarm(boolean lastHealthState) {
-            try{
-                if ( lastHealthState ) {
-                    BeEcompErrorManager.getInstance().logDmaapHealthCheckRecovery( DMAAP_HEALTH_CHECK_STR );
+            try {
+                if (lastHealthState) {
+                    BeEcompErrorManager.getInstance().logDmaapHealthCheckRecovery(DMAAP_HEALTH_CHECK_STR);
                 } else {
-                    BeEcompErrorManager.getInstance().logDmaapHealthCheckError( DMAAP_HEALTH_CHECK_STR );
+                    BeEcompErrorManager.getInstance().logDmaapHealthCheckError(DMAAP_HEALTH_CHECK_STR);
                 }
-            }catch( Exception e ){
-                log.debug("cannot logAlarm -> {}" ,e );
+            } catch (Exception e) {
+                log.debug("cannot logAlarm -> {}", e);
             }
         }
-
     }
-
-   
 }
index 0762872..e548649 100644 (file)
@@ -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.
@@ -17,7 +17,6 @@
  * limitations under the License.
  * ============LICENSE_END=========================================================
  */
-
 package org.openecomp.sdc.be.components;
 
 import org.openecomp.sdc.be.datatypes.enums.ComponentTypeEnum;
@@ -29,19 +28,20 @@ public interface ArtifactsResolver {
 
     /**
      * searching for an artifact with the give {@code artifactId} on the given {@code component}
-     * @param component the component to look for artifact in
+     *
+     * @param component     the component to look for artifact in
      * @param componentType the type of the component to look for artifact in
-     * @param artifactId the id of the artifact to find
+     * @param artifactId    the id of the artifact to find
      * @return the found artifact or null if not exist
      */
     ArtifactDefinition findArtifactOnComponent(Component component, ComponentTypeEnum componentType, String artifactId);
 
     /**
      * searching for an artifact with the give {@code artifactId} on the given {@code componentInstance}
+     *
      * @param componentInstance the component instance to look for the artifact in
-     * @param artifactId the if of the artifact to find
+     * @param artifactId        the if of the artifact to find
      * @return the found artifact or null if not exist
      */
     ArtifactDefinition findArtifactOnComponentInstance(ComponentInstance componentInstance, String artifactId);
-
 }
index e023be4..7ad04ab 100644 (file)
@@ -17,7 +17,6 @@
  * limitations under the License.
  * ============LICENSE_END=========================================================
  */
-
 package org.openecomp.sdc.be.components.attribute;
 
 import static org.apache.commons.collections.MapUtils.isNotEmpty;
@@ -55,8 +54,7 @@ public class AttributeDeclarationOrchestrator {
         return attributeDeclarator.declareAttributesAsOutputs(component, attributesToDeclare.getLeft(), attributesToDeclare.getRight());
     }
 
-    public StorageOperationStatus unDeclareAttributesAsOutputs(final Component component,
-                                                               final OutputDefinition outputToDelete) {
+    public StorageOperationStatus unDeclareAttributesAsOutputs(final Component component, final OutputDefinition outputToDelete) {
         log.debug("#unDeclareAttributesAsOutputs - removing output declaration for output {} on component {}", outputToDelete.getName(),
             component.getUniqueId());
         for (final AttributeDeclarator attributeDeclarator : attributeDeclaratorsToOutput) {
@@ -68,7 +66,6 @@ public class AttributeDeclarationOrchestrator {
             }
         }
         return StorageOperationStatus.OK;
-
     }
 
     private AttributeDeclarator getAttributeDeclarator(final ComponentInstOutputsMap componentInstOutputsMap) {
@@ -79,7 +76,5 @@ public class AttributeDeclarationOrchestrator {
             return componentInstanceAttributeDeclarator;
         }
         throw new IllegalStateException("there are no properties selected for declaration");
-
     }
-
 }
index 3fa68fa..80d1e5b 100644 (file)
@@ -17,7 +17,6 @@
  * limitations under the License.
  * ============LICENSE_END=========================================================
  */
-
 package org.openecomp.sdc.be.components.attribute;
 
 import fj.data.Either;
@@ -33,21 +32,19 @@ public interface AttributeDeclarator {
      * creates a list of outputs from the given list of attributes and updates the attributes accordingly
      *
      * @param component         the container
-     * @param propertiesOwnerId the id of the owner of the attributes to declare (e.g ComponentInstance, Policy, Group
-     *                          etc)
-     * @param attribsToDeclare    the list of attributes that are being declared as outputs
+     * @param propertiesOwnerId the id of the owner of the attributes to declare (e.g ComponentInstance, Policy, Group etc)
+     * @param attribsToDeclare  the list of attributes that are being declared as outputs
      * @return the list of outputs that were created from the given attributes
      */
-    Either<List<OutputDefinition>, StorageOperationStatus> declareAttributesAsOutputs(final Component component,
-                                                                                      final String propertiesOwnerId,
+    Either<List<OutputDefinition>, StorageOperationStatus> declareAttributesAsOutputs(final Component component, final String propertiesOwnerId,
                                                                                       final List<ComponentInstanceAttribOutput> attribsToDeclare);
 
     /**
-     * returns the values of declared attributes to each original state before it was declared as an input. this
-     * function is to be called when an input, that was created by declaring a property, is deleted.
+     * returns the values of declared attributes to each original state before it was declared as an input. this function is to be called when an
+     * input, that was created by declaring a property, is deleted.
      *
      * @param component the container of the input to be deleted
-     * @param output     the input to be deleted
+     * @param output    the input to be deleted
      */
     StorageOperationStatus unDeclareAttributesAsOutputs(final Component component, final OutputDefinition output);
 }
index 56dec5d..9b3487d 100644 (file)
@@ -17,7 +17,6 @@
  * limitations under the License.
  * ============LICENSE_END=========================================================
  */
-
 package org.openecomp.sdc.be.components.attribute;
 
 import fj.data.Either;
@@ -39,102 +38,83 @@ import org.openecomp.sdc.be.model.operations.impl.AttributeOperation;
 @org.springframework.stereotype.Component
 public class ComponentAttributeDeclarator extends DefaultAttributeDeclarator<Component, AttributeDataDefinition> {
 
-  private final ToscaOperationFacade toscaOperationFacade;
-  private final AttributeBusinessLogic attributeBusinessLogic;
+    private final ToscaOperationFacade toscaOperationFacade;
+    private final AttributeBusinessLogic attributeBusinessLogic;
 
-  public ComponentAttributeDeclarator(final ComponentsUtils componentsUtils,
-                                      final AttributeOperation attributeOperation,
-                                      final ToscaOperationFacade toscaOperationFacade,
-                                      final AttributeBusinessLogic attributeBusinessLogic) {
+    public ComponentAttributeDeclarator(final ComponentsUtils componentsUtils, final AttributeOperation attributeOperation,
+                                        final ToscaOperationFacade toscaOperationFacade, final AttributeBusinessLogic attributeBusinessLogic) {
 //    super(componentsUtils, attributeOperation);
-    this.toscaOperationFacade = toscaOperationFacade;
-    this.attributeBusinessLogic = attributeBusinessLogic;
-  }
-
-  @Override
-  public AttributeDataDefinition createDeclaredAttribute(final AttributeDataDefinition attributeDataDefinition) {
-    return new AttributeDataDefinition(attributeDataDefinition);
-  }
-
-  @Override
-  public Either<?, StorageOperationStatus> updateAttributesValues(final Component component,
-                                                                  final String propertiesOwnerId,
-                                                                  final List<AttributeDataDefinition> attributetypeList) {
-    if (CollectionUtils.isNotEmpty(attributetypeList)) {
-      for (AttributeDataDefinition attribute : attributetypeList) {
-        Either<AttributeDefinition, StorageOperationStatus>
-            storageStatus = toscaOperationFacade
-            .updateAttributeOfComponent(component, new AttributeDefinition(attribute));
-        if (storageStatus.isRight()) {
-          return Either.right(storageStatus.right().value());
-        }
-      }
+        this.toscaOperationFacade = toscaOperationFacade;
+        this.attributeBusinessLogic = attributeBusinessLogic;
     }
-    return Either.left(attributetypeList);
-  }
-
-  @Override
-  public Optional<Component> resolvePropertiesOwner(final Component component, final String propertiesOwnerId) {
-    return Optional.of(component);
-  }
 
-  @Override
-  public StorageOperationStatus unDeclareAttributesAsOutputs(final Component component,
-                                                             final OutputDefinition output) {
-    AttributeDefinition attributeDefinition = new AttributeDefinition(output);
-
-    // TODO - do we need this one
-    if (attributeBusinessLogic.isAttributeUsedByOperation(component, attributeDefinition)) {
-      return StorageOperationStatus.DECLARED_INPUT_USED_BY_OPERATION;
+    @Override
+    public AttributeDataDefinition createDeclaredAttribute(final AttributeDataDefinition attributeDataDefinition) {
+        return new AttributeDataDefinition(attributeDataDefinition);
     }
 
-    Optional<AttributeDefinition> attributeToUpdateCandidate =
-        getDeclaredAttributeByOutputId(component, output.getUniqueId());
-
-    if (attributeToUpdateCandidate.isPresent()) {
-      AttributeDefinition attributeToUpdate = attributeToUpdateCandidate.get();
-      return unDeclareOutput(component, output, attributeToUpdate);
+    @Override
+    public Either<?, StorageOperationStatus> updateAttributesValues(final Component component, final String propertiesOwnerId,
+                                                                    final List<AttributeDataDefinition> attributetypeList) {
+        if (CollectionUtils.isNotEmpty(attributetypeList)) {
+            for (AttributeDataDefinition attribute : attributetypeList) {
+                Either<AttributeDefinition, StorageOperationStatus> storageStatus = toscaOperationFacade
+                    .updateAttributeOfComponent(component, new AttributeDefinition(attribute));
+                if (storageStatus.isRight()) {
+                    return Either.right(storageStatus.right().value());
+                }
+            }
+        }
+        return Either.left(attributetypeList);
     }
 
-    return StorageOperationStatus.OK;
-  }
-
-  private StorageOperationStatus unDeclareOutput(final Component component,
-                                                 final OutputDefinition output,
-                                                 final AttributeDefinition attributeToUpdate) {
-    prepareValueBeforeDelete(output, attributeToUpdate, Collections.emptyList());
-    attributeToUpdate.setValue(output.getDefaultValue());
-    Either<AttributeDefinition, StorageOperationStatus> status = toscaOperationFacade
-        .updateAttributeOfComponent(component, attributeToUpdate);
-    if (status.isRight()) {
-      return status.right().value();
+    @Override
+    public Optional<Component> resolvePropertiesOwner(final Component component, final String propertiesOwnerId) {
+        return Optional.of(component);
     }
 
-    return StorageOperationStatus.OK;
-  }
-
-  private Optional<AttributeDefinition> getDeclaredAttributeByOutputId(final Component component, final String outputId) {
-    List<AttributeDefinition> attributes = component.getAttributes();
-
-    if (CollectionUtils.isEmpty(attributes)) {
-      return Optional.empty();
+    @Override
+    public StorageOperationStatus unDeclareAttributesAsOutputs(final Component component, final OutputDefinition output) {
+        AttributeDefinition attributeDefinition = new AttributeDefinition(output);
+        // TODO - do we need this one
+        if (attributeBusinessLogic.isAttributeUsedByOperation(component, attributeDefinition)) {
+            return StorageOperationStatus.DECLARED_INPUT_USED_BY_OPERATION;
+        }
+        Optional<AttributeDefinition> attributeToUpdateCandidate = getDeclaredAttributeByOutputId(component, output.getUniqueId());
+        if (attributeToUpdateCandidate.isPresent()) {
+            AttributeDefinition attributeToUpdate = attributeToUpdateCandidate.get();
+            return unDeclareOutput(component, output, attributeToUpdate);
+        }
+        return StorageOperationStatus.OK;
     }
 
-    for (AttributeDefinition attributeDefinition : attributes) {
-      List<GetOutputValueDataDefinition> getOutputValues = attributeDefinition.getGetOutputValues();
-      if (CollectionUtils.isEmpty(getOutputValues)) {
-        continue;
-      }
-
-      Optional<GetOutputValueDataDefinition> getOutputCandidate =
-          getOutputValues.stream().filter(getOutput -> getOutput.getOutputId().equals(outputId)).findAny();
-
-      if (getOutputCandidate.isPresent()) {
-        return Optional.of(attributeDefinition);
-      }
+    private StorageOperationStatus unDeclareOutput(final Component component, final OutputDefinition output,
+                                                   final AttributeDefinition attributeToUpdate) {
+        prepareValueBeforeDelete(output, attributeToUpdate, Collections.emptyList());
+        attributeToUpdate.setValue(output.getDefaultValue());
+        Either<AttributeDefinition, StorageOperationStatus> status = toscaOperationFacade.updateAttributeOfComponent(component, attributeToUpdate);
+        if (status.isRight()) {
+            return status.right().value();
+        }
+        return StorageOperationStatus.OK;
     }
 
-    return Optional.empty();
-  }
-
+    private Optional<AttributeDefinition> getDeclaredAttributeByOutputId(final Component component, final String outputId) {
+        List<AttributeDefinition> attributes = component.getAttributes();
+        if (CollectionUtils.isEmpty(attributes)) {
+            return Optional.empty();
+        }
+        for (AttributeDefinition attributeDefinition : attributes) {
+            List<GetOutputValueDataDefinition> getOutputValues = attributeDefinition.getGetOutputValues();
+            if (CollectionUtils.isEmpty(getOutputValues)) {
+                continue;
+            }
+            Optional<GetOutputValueDataDefinition> getOutputCandidate = getOutputValues.stream()
+                .filter(getOutput -> getOutput.getOutputId().equals(outputId)).findAny();
+            if (getOutputCandidate.isPresent()) {
+                return Optional.of(attributeDefinition);
+            }
+        }
+        return Optional.empty();
+    }
 }
index 8981515..0882eda 100644 (file)
@@ -17,7 +17,6 @@
  * limitations under the License.
  * ============LICENSE_END=========================================================
  */
-
 package org.openecomp.sdc.be.components.attribute;
 
 import fj.data.Either;
@@ -39,15 +38,13 @@ import org.openecomp.sdc.be.model.operations.impl.AttributeOperation;
 import org.openecomp.sdc.common.log.wrappers.Logger;
 
 @org.springframework.stereotype.Component
-public class ComponentInstanceAttributeDeclarator extends
-    DefaultAttributeDeclarator<ComponentInstance, ComponentInstanceAttribute> {
+public class ComponentInstanceAttributeDeclarator extends DefaultAttributeDeclarator<ComponentInstance, ComponentInstanceAttribute> {
 
     private static final Logger log = Logger.getLogger(ComponentInstanceAttributeDeclarator.class);
     private ToscaOperationFacade toscaOperationFacade;
     private ComponentInstanceBusinessLogic componentInstanceBusinessLogic;
 
-    public ComponentInstanceAttributeDeclarator(final ComponentsUtils componentsUtils,
-                                                final AttributeOperation attributeOperation,
+    public ComponentInstanceAttributeDeclarator(final ComponentsUtils componentsUtils, final AttributeOperation attributeOperation,
                                                 final ToscaOperationFacade toscaOperationFacade,
                                                 final ComponentInstanceBusinessLogic componentInstanceBusinessLogic) {
 //        super(componentsUtils, attributeOperation);
@@ -61,8 +58,7 @@ public class ComponentInstanceAttributeDeclarator extends
     }
 
     @Override
-    public Either<?, StorageOperationStatus> updateAttributesValues(final Component component,
-                                                                    final String cmptInstanceId,
+    public Either<?, StorageOperationStatus> updateAttributesValues(final Component component, final String cmptInstanceId,
                                                                     final List<ComponentInstanceAttribute> attributetypeList) {
         log.debug("#updateAttributesValues - updating component instance attributes for instance {} on component {}", cmptInstanceId,
             component.getUniqueId());
@@ -78,17 +74,15 @@ public class ComponentInstanceAttributeDeclarator extends
 
     @Override
     public StorageOperationStatus unDeclareAttributesAsOutputs(final Component component, final OutputDefinition output) {
-
-        final List<ComponentInstanceAttribute> componentInstancePropertiesDeclaredAsInput
-            = componentInstanceBusinessLogic.getComponentInstanceAttributesByOutputId(component, output.getUniqueId());
+        final List<ComponentInstanceAttribute> componentInstancePropertiesDeclaredAsInput = componentInstanceBusinessLogic
+            .getComponentInstanceAttributesByOutputId(component, output.getUniqueId());
         if (CollectionUtils.isEmpty(componentInstancePropertiesDeclaredAsInput)) {
             return StorageOperationStatus.OK;
         }
-        componentInstancePropertiesDeclaredAsInput.forEach(cmptInstanceProperty -> prepareValueBeforeDelete(output,
-            cmptInstanceProperty, cmptInstanceProperty.getPath()));
-        return toscaOperationFacade.updateComponentInstanceAttributes(component,
-            componentInstancePropertiesDeclaredAsInput.get(0).getComponentInstanceId(),
-            componentInstancePropertiesDeclaredAsInput);
+        componentInstancePropertiesDeclaredAsInput
+            .forEach(cmptInstanceProperty -> prepareValueBeforeDelete(output, cmptInstanceProperty, cmptInstanceProperty.getPath()));
+        return toscaOperationFacade
+            .updateComponentInstanceAttributes(component, componentInstancePropertiesDeclaredAsInput.get(0).getComponentInstanceId(),
+                componentInstancePropertiesDeclaredAsInput);
     }
-
 }
index 7ded7c1..989cc97 100644 (file)
@@ -17,7 +17,6 @@
  * limitations under the License.
  * ============LICENSE_END=========================================================
  */
-
 package org.openecomp.sdc.be.components.attribute;
 
 import static org.apache.commons.collections4.CollectionUtils.isEmpty;
@@ -46,8 +45,7 @@ public class ComponentInstanceOutputAttributeDeclarator extends DefaultAttribute
     private final ToscaOperationFacade toscaOperationFacade;
     private final ComponentInstanceBusinessLogic componentInstanceBusinessLogic;
 
-    public ComponentInstanceOutputAttributeDeclarator(final ComponentsUtils componentsUtils,
-                                                      final AttributeOperation attributeOperation,
+    public ComponentInstanceOutputAttributeDeclarator(final ComponentsUtils componentsUtils, final AttributeOperation attributeOperation,
                                                       final ToscaOperationFacade toscaOperationFacade,
                                                       final ComponentInstanceBusinessLogic componentInstanceBusinessLogic) {
 //        super(componentsUtils, attributeOperation);
@@ -61,8 +59,7 @@ public class ComponentInstanceOutputAttributeDeclarator extends DefaultAttribute
     }
 
     @Override
-    public Either<?, StorageOperationStatus> updateAttributesValues(final Component component,
-                                                                    final String cmptInstanceId,
+    public Either<?, StorageOperationStatus> updateAttributesValues(final Component component, final String cmptInstanceId,
                                                                     final List<ComponentInstanceOutput> attributetypeList) {
         log.debug("#updateAttributesValues - updating component instance outputs for instance {} on component {}", cmptInstanceId,
             component.getUniqueId());
@@ -78,8 +75,7 @@ public class ComponentInstanceOutputAttributeDeclarator extends DefaultAttribute
 
     public StorageOperationStatus unDeclareAttributesAsOutputs(final Component component, final OutputDefinition output) {
         List<ComponentInstanceOutput> componentInstanceInputsByInputId = componentInstanceBusinessLogic
-            .getComponentInstanceOutputsByOutputId(component, output
-                .getUniqueId());
+            .getComponentInstanceOutputsByOutputId(component, output.getUniqueId());
         if (isEmpty(componentInstanceInputsByInputId)) {
             return StorageOperationStatus.OK;
         }
@@ -88,5 +84,4 @@ public class ComponentInstanceOutputAttributeDeclarator extends DefaultAttribute
         return toscaOperationFacade.updateComponentInstanceOutputs(component, componentInstanceInputsByInputId.get(0).getComponentInstanceId(),
             componentInstanceInputsByInputId);
     }
-
 }
index e53a362..915959b 100644 (file)
@@ -17,7 +17,6 @@
  * limitations under the License.
  * ============LICENSE_END=========================================================
  */
-
 package org.openecomp.sdc.be.components.attribute;
 
 import static org.openecomp.sdc.common.api.Constants.GET_ATTRIBUTE;
@@ -53,8 +52,8 @@ import org.openecomp.sdc.common.log.wrappers.Logger;
 import org.openecomp.sdc.exception.ResponseFormat;
 import org.yaml.snakeyaml.Yaml;
 
-public abstract class DefaultAttributeDeclarator<PROPERTYOWNER extends PropertiesOwner, ATTRIBUTETYPE extends AttributeDataDefinition>
-    implements AttributeDeclarator {
+public abstract class DefaultAttributeDeclarator<PROPERTYOWNER extends PropertiesOwner, ATTRIBUTETYPE extends AttributeDataDefinition> implements
+    AttributeDeclarator {
 
     private static final Logger log = Logger.getLogger(DefaultAttributeDeclarator.class);
     private static final short LOOP_PROTECTION_LEVEL = 10;
@@ -68,9 +67,8 @@ public abstract class DefaultAttributeDeclarator<PROPERTYOWNER extends Propertie
     public Either<List<OutputDefinition>, StorageOperationStatus> declareAttributesAsOutputs(final Component component,
                                                                                              final String propertiesOwnerId,
                                                                                              final List<ComponentInstanceAttribOutput> attribsToDeclare) {
-        log.debug(
-            "#declarePropertiesAsInputs - declaring properties as inputs for component {} from properties owner {}",
-            component.getUniqueId(), propertiesOwnerId);
+        log.debug("#declarePropertiesAsInputs - declaring properties as inputs for component {} from properties owner {}", component.getUniqueId(),
+            propertiesOwnerId);
         return resolvePropertiesOwner(component, propertiesOwnerId)
             .map(propertyOwner -> declareAttributesAsOutputs(component, propertyOwner, attribsToDeclare))
             .orElse(Either.right(onPropertiesOwnerNotFound(component.getUniqueId(), propertiesOwnerId)));
@@ -78,31 +76,26 @@ public abstract class DefaultAttributeDeclarator<PROPERTYOWNER extends Propertie
 
     protected abstract ATTRIBUTETYPE createDeclaredAttribute(final AttributeDataDefinition attributeDataDefinition);
 
-    protected abstract Either<?, StorageOperationStatus> updateAttributesValues(final Component component,
-                                                                                final String propertiesOwnerId,
+    protected abstract Either<?, StorageOperationStatus> updateAttributesValues(final Component component, final String propertiesOwnerId,
                                                                                 final List<ATTRIBUTETYPE> attributetypeList);
 
     protected abstract Optional<PROPERTYOWNER> resolvePropertiesOwner(final Component component, final String propertiesOwnerId);
 
     private StorageOperationStatus onPropertiesOwnerNotFound(final String componentId, final String propertiesOwnerId) {
-        log.debug("#declarePropertiesAsInputs - properties owner {} was not found on component {}", propertiesOwnerId,
-            componentId);
+        log.debug("#declarePropertiesAsInputs - properties owner {} was not found on component {}", propertiesOwnerId, componentId);
         return StorageOperationStatus.NOT_FOUND;
     }
 
     private Either<List<OutputDefinition>, StorageOperationStatus> declareAttributesAsOutputs(final Component component,
                                                                                               final PROPERTYOWNER propertiesOwner,
                                                                                               final List<ComponentInstanceAttribOutput> attributesToDeclare) {
-        final AttributesDeclarationData attributesDeclarationData
-            = createOutputsAndOverrideAttributesValues(component, propertiesOwner, attributesToDeclare);
-        return updateAttributesValues(component, propertiesOwner.getUniqueId(),
-            attributesDeclarationData.getAttributesToUpdate())
-            .left()
+        final AttributesDeclarationData attributesDeclarationData = createOutputsAndOverrideAttributesValues(component, propertiesOwner,
+            attributesToDeclare);
+        return updateAttributesValues(component, propertiesOwner.getUniqueId(), attributesDeclarationData.getAttributesToUpdate()).left()
             .map(updatePropsRes -> attributesDeclarationData.getOutputsToCreate());
     }
 
-    private AttributesDeclarationData createOutputsAndOverrideAttributesValues(final Component component,
-                                                                               final PROPERTYOWNER propertiesOwner,
+    private AttributesDeclarationData createOutputsAndOverrideAttributesValues(final Component component, final PROPERTYOWNER propertiesOwner,
                                                                                final List<ComponentInstanceAttribOutput> attributesToDeclare) {
         final List<ATTRIBUTETYPE> declaredAttributes = new ArrayList<>();
         final List<OutputDefinition> createdInputs = attributesToDeclare.stream()
@@ -111,10 +104,8 @@ public abstract class DefaultAttributeDeclarator<PROPERTYOWNER extends Propertie
         return new AttributesDeclarationData(createdInputs, declaredAttributes);
     }
 
-    private OutputDefinition declareAttributeOutput(final Component component,
-                                                    final PROPERTYOWNER propertiesOwner,
-                                                    final List<ATTRIBUTETYPE> declaredAttributes,
-                                                    final ComponentInstanceAttribOutput attribOutput) {
+    private OutputDefinition declareAttributeOutput(final Component component, final PROPERTYOWNER propertiesOwner,
+                                                    final List<ATTRIBUTETYPE> declaredAttributes, final ComponentInstanceAttribOutput attribOutput) {
         final AttributeDataDefinition attribute = resolveAttribute(declaredAttributes, attribOutput);
         final OutputDefinition outputDefinition = createOutput(component, propertiesOwner, attribOutput, attribute);
         final ATTRIBUTETYPE declaredAttribute = createDeclaredAttribute(attribute);
@@ -124,40 +115,34 @@ public abstract class DefaultAttributeDeclarator<PROPERTYOWNER extends Propertie
         return outputDefinition;
     }
 
-    private OutputDefinition createOutput(final Component component,
-                                          final PROPERTYOWNER propertiesOwner,
-                                          final ComponentInstanceAttribOutput attribOutput,
-                                          final AttributeDataDefinition attributeDataDefinition) {
+    private OutputDefinition createOutput(final Component component, final PROPERTYOWNER propertiesOwner,
+                                          final ComponentInstanceAttribOutput attribOutput, final AttributeDataDefinition attributeDataDefinition) {
         String generatedInputPrefix = propertiesOwner.getNormalizedName();
         if (propertiesOwner.getUniqueId().equals(attribOutput.getParentUniqueId())) {
             //Creating input from property create on self using add property..Do not add the prefix
             generatedInputPrefix = null;
         }
-
         final String generatedOutputName = generateOutputName(generatedInputPrefix, attribOutput);
-        log.debug("createInput: propOwner.uniqueId={}, attribOutput.parentUniqueId={}",
-            propertiesOwner.getUniqueId(), attribOutput.getParentUniqueId());
+        log.debug("createInput: propOwner.uniqueId={}, attribOutput.parentUniqueId={}", propertiesOwner.getUniqueId(),
+            attribOutput.getParentUniqueId());
         return createOutputFromAttribute(component.getUniqueId(), propertiesOwner, generatedOutputName, attribOutput, attributeDataDefinition);
     }
 
     private String generateOutputName(final String outputName, final ComponentInstanceAttribOutput attribOutput) {
         final String declaredInputName;
         final String[] parsedPropNames = attribOutput.getParsedAttribNames();
-
         if (parsedPropNames != null) {
             declaredInputName = handleInputName(outputName, parsedPropNames);
         } else {
             final String[] propName = {attribOutput.getName()};
             declaredInputName = handleInputName(outputName, propName);
         }
-
         return declaredInputName;
     }
 
     private String handleInputName(final String outputName, final String[] parsedPropNames) {
         final StringBuilder prefix = new StringBuilder();
         int startingIndex;
-
         if (Objects.isNull(outputName)) {
             prefix.append(parsedPropNames[0]);
             startingIndex = 1;
@@ -165,29 +150,22 @@ public abstract class DefaultAttributeDeclarator<PROPERTYOWNER extends Propertie
             prefix.append(outputName);
             startingIndex = 0;
         }
-
         while (startingIndex < parsedPropNames.length) {
             prefix.append(UNDERSCORE);
             prefix.append(parsedPropNames[startingIndex]);
             startingIndex++;
         }
-
         return prefix.toString();
     }
 
-    private AttributeDataDefinition resolveAttribute(final List<ATTRIBUTETYPE> attributesToCreate,
-                                                     final ComponentInstanceAttribOutput attribOutput) {
-        final Optional<ATTRIBUTETYPE> resolvedAttribute = attributesToCreate.stream()
-            .filter(p -> p.getName().equals(attribOutput.getName()))
+    private AttributeDataDefinition resolveAttribute(final List<ATTRIBUTETYPE> attributesToCreate, final ComponentInstanceAttribOutput attribOutput) {
+        final Optional<ATTRIBUTETYPE> resolvedAttribute = attributesToCreate.stream().filter(p -> p.getName().equals(attribOutput.getName()))
             .findFirst();
         return resolvedAttribute.isPresent() ? resolvedAttribute.get() : attribOutput;
     }
 
-    OutputDefinition createOutputFromAttribute(final String componentId,
-                                               final PROPERTYOWNER propertiesOwner,
-                                               final String outputName,
-                                               final ComponentInstanceAttribOutput attributeOutput,
-                                               final AttributeDataDefinition attribute) {
+    OutputDefinition createOutputFromAttribute(final String componentId, final PROPERTYOWNER propertiesOwner, final String outputName,
+                                               final ComponentInstanceAttribOutput attributeOutput, final AttributeDataDefinition attribute) {
         final String attributesName = attributeOutput.getAttributesName();
         final AttributeDefinition selectedAttrib = attributeOutput.getOutput();
         final String[] parsedAttribNames = attributeOutput.getParsedAttribNames();
@@ -207,7 +185,6 @@ public abstract class DefaultAttributeDeclarator<PROPERTYOWNER extends Propertie
         outputDefinition.setInstanceUniqueId(propertiesOwner.getUniqueId());
         outputDefinition.setAttributeId(attributeOutput.getUniqueId());
         outputDefinition.setAttributes(Arrays.asList(attributeOutput));
-
         if (attribute instanceof IComponentInstanceConnectedElement) {
             ((IComponentInstanceConnectedElement) attribute).setComponentInstanceId(propertiesOwner.getUniqueId());
             ((IComponentInstanceConnectedElement) attribute).setComponentInstanceName(propertiesOwner.getName());
@@ -216,11 +193,8 @@ public abstract class DefaultAttributeDeclarator<PROPERTYOWNER extends Propertie
         return outputDefinition;
     }
 
-    private void changeOutputValueToGetAttributeValue(final String outputName,
-                                                      final String[] parsedPropNames,
-                                                      final OutputDefinition output,
-                                                      final AttributeDataDefinition attributeDataDefinition,
-                                                      final boolean complexProperty) {
+    private void changeOutputValueToGetAttributeValue(final String outputName, final String[] parsedPropNames, final OutputDefinition output,
+                                                      final AttributeDataDefinition attributeDataDefinition, final boolean complexProperty) {
         JSONObject jsonObject = new JSONObject();
         final String value = attributeDataDefinition.getValue();
         if (StringUtils.isEmpty(value)) {
@@ -228,36 +202,32 @@ public abstract class DefaultAttributeDeclarator<PROPERTYOWNER extends Propertie
                 jsonObject = createJSONValueForProperty(parsedPropNames.length - 1, parsedPropNames, jsonObject, outputName);
                 attributeDataDefinition.setValue(jsonObject.toJSONString());
             } else {
-                jsonObject.put(
-                    GET_ATTRIBUTE, Arrays.asList(output.getAttributes().get(0).getComponentInstanceName(), attributeDataDefinition.getName()));
+                jsonObject
+                    .put(GET_ATTRIBUTE, Arrays.asList(output.getAttributes().get(0).getComponentInstanceName(), attributeDataDefinition.getName()));
                 output.setValue(jsonObject.toJSONString());
             }
         } else {
             final Object objValue = new Yaml().load(value);
             if (objValue instanceof Map || objValue instanceof List) {
                 if (!complexProperty) {
-                    jsonObject.put(
-                        GET_ATTRIBUTE, Arrays.asList(output.getAttributes().get(0).getComponentInstanceName(), attributeDataDefinition.getName()));
+                    jsonObject.put(GET_ATTRIBUTE,
+                        Arrays.asList(output.getAttributes().get(0).getComponentInstanceName(), attributeDataDefinition.getName()));
                     output.setValue(jsonObject.toJSONString());
                 } else {
                     final Map<String, Object> mappedToscaTemplate = (Map<String, Object>) objValue;
                     createOutputValue(mappedToscaTemplate, 1, parsedPropNames, outputName);
-
                     output.setValue(gson.toJson(mappedToscaTemplate));
                 }
-
             } else {
-                jsonObject.put(
-                    GET_ATTRIBUTE, Arrays.asList(output.getAttributes().get(0).getComponentInstanceName(), attributeDataDefinition.getName()));
+                jsonObject
+                    .put(GET_ATTRIBUTE, Arrays.asList(output.getAttributes().get(0).getComponentInstanceName(), attributeDataDefinition.getName()));
                 output.setValue(jsonObject.toJSONString());
             }
         }
-
         if (CollectionUtils.isEmpty(attributeDataDefinition.getGetOutputValues())) {
             attributeDataDefinition.setGetOutputValues(new ArrayList<>());
         }
         final List<GetOutputValueDataDefinition> getOutputValues = attributeDataDefinition.getGetOutputValues();
-
         final GetOutputValueDataDefinition getOutputValueDataDefinition = new GetOutputValueDataDefinition();
         getOutputValueDataDefinition.setOutputId(output.getUniqueId());
         getOutputValueDataDefinition.setOutputName(output.getName());
@@ -265,7 +235,6 @@ public abstract class DefaultAttributeDeclarator<PROPERTYOWNER extends Propertie
     }
 
     private JSONObject createJSONValueForProperty(int i, final String[] parsedPropNames, final JSONObject ooj, final String outputName) {
-
         while (i >= 1) {
             if (i == parsedPropNames.length - 1) {
                 final JSONObject jobProp = new JSONObject();
@@ -280,7 +249,6 @@ public abstract class DefaultAttributeDeclarator<PROPERTYOWNER extends Propertie
                 return createJSONValueForProperty(i, parsedPropNames, res, outputName);
             }
         }
-
         return ooj;
     }
 
@@ -319,43 +287,33 @@ public abstract class DefaultAttributeDeclarator<PROPERTYOWNER extends Propertie
         return lhm1;
     }
 
-    private class AttributesDeclarationData {
-
-        private final List<OutputDefinition> outputsToCreate;
-        private final List<ATTRIBUTETYPE> attributesToUpdate;
-
-        AttributesDeclarationData(final List<OutputDefinition> outputsToCreate,
-                                  final List<ATTRIBUTETYPE> attributesToUpdate) {
-            this.outputsToCreate = outputsToCreate;
-            this.attributesToUpdate = attributesToUpdate;
-        }
-
-        List<OutputDefinition> getOutputsToCreate() {
-            return outputsToCreate;
-        }
-
-        List<ATTRIBUTETYPE> getAttributesToUpdate() {
-            return attributesToUpdate;
-        }
-    }
-
-    Either<OutputDefinition, ResponseFormat> prepareValueBeforeDelete(final OutputDefinition inputForDelete,
-                                                                      final AttributeDataDefinition inputValue,
+    Either<OutputDefinition, ResponseFormat> prepareValueBeforeDelete(final OutputDefinition inputForDelete, final AttributeDataDefinition inputValue,
                                                                       final List<String> pathOfComponentInstances) {
         final Either<OutputDefinition, ResponseFormat> deleteEither = prepareValueBeforeDelete(inputForDelete, inputValue);
-
 //        Either<String, JanusGraphOperationStatus> findDefaultValue = propertyOperation
+
 //            .findDefaultValueFromSecondPosition(pathOfComponentInstances, inputValue.getUniqueId(),
+
 //                (String) inputValue.get_default());
+
 //        if (findDefaultValue.isRight()) {
+
 //            deleteEither = Either.right(componentsUtils.getResponseFormat(componentsUtils
+
 //                .convertFromStorageResponse(
+
 //                    DaoStatusConverter.convertJanusGraphStatusToStorageStatus(findDefaultValue.right().value()))));
+
 //            return deleteEither;
+
 //
+
 //        }
+
 //        String defaultValue = findDefaultValue.left().value();
+
 //        inputValue.set_default(defaultValue);
+
 //        log.debug("The returned default value in ResourceInstanceProperty is {}", defaultValue);
         return deleteEither;
     }
@@ -365,9 +323,7 @@ public abstract class DefaultAttributeDeclarator<PROPERTYOWNER extends Propertie
         final Either<OutputDefinition, ResponseFormat> deleteEither = Either.left(outputForDelete);
         String value = outputValue.getValue();
         final Map<String, Object> mappedToscaTemplate = (Map<String, Object>) new Yaml().load(value);
-
         resetOutputName(mappedToscaTemplate, outputForDelete.getName());
-
         value = "";
         if (MapUtils.isNotEmpty(mappedToscaTemplate)) {
             final Either result = cleanNestedMap(mappedToscaTemplate, true);
@@ -380,11 +336,10 @@ public abstract class DefaultAttributeDeclarator<PROPERTYOWNER extends Propertie
             value = gson.toJson(modifiedMappedToscaTemplate);
         }
         outputValue.setValue(value);
-
         final List<GetOutputValueDataDefinition> getInputsValues = outputValue.getGetOutputValues();
         if (getInputsValues != null && !getInputsValues.isEmpty()) {
-            final Optional<GetOutputValueDataDefinition> op =
-                getInputsValues.stream().filter(gi -> gi.getOutputId().equals(outputForDelete.getUniqueId())).findAny();
+            final Optional<GetOutputValueDataDefinition> op = getInputsValues.stream()
+                .filter(gi -> gi.getOutputId().equals(outputForDelete.getUniqueId())).findAny();
             op.ifPresent(getInputsValues::remove);
         }
         outputValue.setGetOutputValues(getInputsValues);
@@ -410,9 +365,7 @@ public abstract class DefaultAttributeDeclarator<PROPERTYOWNER extends Propertie
         if (MapUtils.isNotEmpty(mappedToscaTemplate)) {
             if (deepClone) {
                 if (!(mappedToscaTemplate instanceof HashMap)) {
-                    return Either.right(
-                        "expecting mappedToscaTemplate as HashMap ,recieved " + mappedToscaTemplate.getClass()
-                            .getSimpleName());
+                    return Either.right("expecting mappedToscaTemplate as HashMap ,recieved " + mappedToscaTemplate.getClass().getSimpleName());
                 } else {
                     mappedToscaTemplate = (HashMap) ((HashMap) mappedToscaTemplate).clone();
                 }
@@ -449,7 +402,6 @@ public abstract class DefaultAttributeDeclarator<PROPERTYOWNER extends Propertie
             if (CollectionUtils.isNotEmpty(set)) {
                 set.removeAll(keysToRemove);
             }
-
             if (isEmptyNestedMap(toscaElement)) {
                 return null;
             }
@@ -480,4 +432,22 @@ public abstract class DefaultAttributeDeclarator<PROPERTYOWNER extends Propertie
         return isEmpty;
     }
 
+    private class AttributesDeclarationData {
+
+        private final List<OutputDefinition> outputsToCreate;
+        private final List<ATTRIBUTETYPE> attributesToUpdate;
+
+        AttributesDeclarationData(final List<OutputDefinition> outputsToCreate, final List<ATTRIBUTETYPE> attributesToUpdate) {
+            this.outputsToCreate = outputsToCreate;
+            this.attributesToUpdate = attributesToUpdate;
+        }
+
+        List<OutputDefinition> getOutputsToCreate() {
+            return outputsToCreate;
+        }
+
+        List<ATTRIBUTETYPE> getAttributesToUpdate() {
+            return attributesToUpdate;
+        }
+    }
 }
index 0565bc6..e5d390a 100644 (file)
@@ -17,7 +17,6 @@
  * limitations under the License.
  * ============LICENSE_END=========================================================
  */
-
 package org.openecomp.sdc.be.components.attribute;
 
 import org.openecomp.sdc.be.datatypes.elements.GetOutputValueDataDefinition;
@@ -28,7 +27,7 @@ public class GetOutputUtils {
     }
 
     public static boolean isGetOutputValueForOutput(GetOutputValueDataDefinition outputData, String outputId) {
-        return outputData.getOutputId().equals(outputId)
-            || (outputData.getGetOutputIndex() != null && outputData.getGetOutputIndex().getOutputId().equals(outputId));
+        return outputData.getOutputId().equals(outputId) || (outputData.getGetOutputIndex() != null && outputData.getGetOutputIndex().getOutputId()
+            .equals(outputId));
     }
 }
index 6bde6ba..2ab68e8 100644 (file)
@@ -17,7 +17,6 @@
  * limitations under the License.
  * ============LICENSE_END=========================================================
  */
-
 package org.openecomp.sdc.be.components.csar;
 
 import static org.openecomp.sdc.be.components.impl.ArtifactsBusinessLogic.FAILED_UPLOAD_ARTIFACT_TO_COMPONENT;
@@ -50,12 +49,12 @@ import org.apache.commons.lang3.StringUtils;
 import org.apache.commons.lang3.tuple.ImmutablePair;
 import org.openecomp.sdc.be.components.impl.ArtifactsBusinessLogic;
 import org.openecomp.sdc.be.components.impl.ArtifactsBusinessLogic.ArtifactOperationEnum;
-import org.openecomp.sdc.be.components.impl.artifact.ArtifactOperationInfo;
 import org.openecomp.sdc.be.components.impl.BaseBusinessLogic;
 import org.openecomp.sdc.be.components.impl.CsarValidationUtils;
 import org.openecomp.sdc.be.components.impl.GroupBusinessLogic;
 import org.openecomp.sdc.be.components.impl.ImportUtils;
 import org.openecomp.sdc.be.components.impl.ImportUtils.ResultStatusEnum;
+import org.openecomp.sdc.be.components.impl.artifact.ArtifactOperationInfo;
 import org.openecomp.sdc.be.components.impl.exceptions.ComponentException;
 import org.openecomp.sdc.be.config.BeEcompErrorManager;
 import org.openecomp.sdc.be.config.BeEcompErrorManager.ErrorSeverity;
@@ -65,7 +64,6 @@ import org.openecomp.sdc.be.dao.api.ActionStatus;
 import org.openecomp.sdc.be.datamodel.utils.ArtifactUtils;
 import org.openecomp.sdc.be.datatypes.elements.ArtifactDataDefinition;
 import org.openecomp.sdc.be.datatypes.elements.PropertyDataDefinition;
-import org.openecomp.sdc.be.datatypes.enums.ComponentTypeEnum;
 import org.openecomp.sdc.be.datatypes.enums.NodeTypeEnum;
 import org.openecomp.sdc.be.impl.ComponentsUtils;
 import org.openecomp.sdc.be.info.ArtifactTemplateInfo;
@@ -108,38 +106,32 @@ public class CsarArtifactsAndGroupsBusinessLogic extends BaseBusinessLogic {
     private static final String ARTIFACT_FILE_IS_NOT_IN_EXPECTED_FORMAT_FILE_NAME = "Artifact  file is not in expected format, fileName  {}";
     private static final String ARTIFACT_INTERNALS_ARE_INVALID = "Artifact internals are invalid";
     private static final String ARTIFACT_WITH_NAME_AND_TYPE_ALREADY_EXIST_WITH_TYPE = "Artifact with name {} and type {} already exist with type  {}";
-    private final Gson gson = new Gson();
     private static final Pattern pattern = Pattern.compile("\\..(.*?)\\..");
     private static final String LABEL_COUNTER_DELIMITER = "[^0-9]+";
     protected final ArtifactsBusinessLogic artifactsBusinessLogic;
+    private final Gson gson = new Gson();
     private final GroupBusinessLogic groupBusinessLogic;
 
     @Autowired
-    public CsarArtifactsAndGroupsBusinessLogic(IElementOperation elementDao,
-        IGroupOperation groupOperation,
-        IGroupInstanceOperation groupInstanceOperation,
-        IGroupTypeOperation groupTypeOperation,
-        GroupBusinessLogic groupBusinessLogic,
-        InterfaceOperation interfaceOperation,
-        InterfaceLifecycleOperation interfaceLifecycleTypeOperation,
-        ArtifactsBusinessLogic artifactsBusinessLogic, ArtifactsOperations artifactToscaOperation) {
-        super(elementDao, groupOperation, groupInstanceOperation, groupTypeOperation,
-            interfaceOperation, interfaceLifecycleTypeOperation, artifactToscaOperation);
+    public CsarArtifactsAndGroupsBusinessLogic(IElementOperation elementDao, IGroupOperation groupOperation,
+                                               IGroupInstanceOperation groupInstanceOperation, IGroupTypeOperation groupTypeOperation,
+                                               GroupBusinessLogic groupBusinessLogic, InterfaceOperation interfaceOperation,
+                                               InterfaceLifecycleOperation interfaceLifecycleTypeOperation,
+                                               ArtifactsBusinessLogic artifactsBusinessLogic, ArtifactsOperations artifactToscaOperation) {
+        super(elementDao, groupOperation, groupInstanceOperation, groupTypeOperation, interfaceOperation, interfaceLifecycleTypeOperation,
+            artifactToscaOperation);
         this.artifactsBusinessLogic = artifactsBusinessLogic;
         this.groupBusinessLogic = groupBusinessLogic;
     }
 
-    public Either<Resource, ResponseFormat> createResourceArtifactsFromCsar(CsarInfo csarInfo, Resource resource,
-            String artifactsMetaFile, String artifactsMetaFileName, List<ArtifactDefinition> createdArtifacts) {
-
+    public Either<Resource, ResponseFormat> createResourceArtifactsFromCsar(CsarInfo csarInfo, Resource resource, String artifactsMetaFile,
+                                                                            String artifactsMetaFileName, List<ArtifactDefinition> createdArtifacts) {
         log.debug("parseResourceArtifactsInfoFromFile start");
-        return  parseResourceArtifactsInfoFromFile(resource, artifactsMetaFile, artifactsMetaFileName)
-                .left()
-                .bind( p-> createResourceArtifacts(csarInfo, resource, p, createdArtifacts))
-                .right()
-                .map(rf -> { componentsUtils.auditResource(rf, csarInfo.getModifier(), resource, AuditingActionEnum.IMPORT_RESOURCE); return rf;})
-                .left()
-                .bind(c -> checkoutRes(c));
+        return parseResourceArtifactsInfoFromFile(resource, artifactsMetaFile, artifactsMetaFileName).left()
+            .bind(p -> createResourceArtifacts(csarInfo, resource, p, createdArtifacts)).right().map(rf -> {
+                componentsUtils.auditResource(rf, csarInfo.getModifier(), resource, AuditingActionEnum.IMPORT_RESOURCE);
+                return rf;
+            }).left().bind(c -> checkoutRes(c));
     }
 
     private Either<Resource, ResponseFormat> checkoutRes(Component component) {
@@ -149,33 +141,25 @@ public class CsarArtifactsAndGroupsBusinessLogic extends BaseBusinessLogic {
         return checkoutRes1;
     }
 
-    public Either<Service, ResponseFormat> createResourceArtifactsFromCsar(CsarInfo csarInfo, Service resource,
-            String artifactsMetaFile, String artifactsMetaFileName, List<ArtifactDefinition> createdArtifacts
-    ) {
-
+    public Either<Service, ResponseFormat> createResourceArtifactsFromCsar(CsarInfo csarInfo, Service resource, String artifactsMetaFile,
+                                                                           String artifactsMetaFileName, List<ArtifactDefinition> createdArtifacts) {
         log.debug("parseResourceArtifactsInfoFromFile start");
-        return parseResourceArtifactsInfoFromFile(resource, artifactsMetaFile, artifactsMetaFileName)
-                .left()
-                .bind(p -> createResourceArtifacts(csarInfo, resource, p, createdArtifacts))
-                .right()
-                .map(rf -> rf)
-                .left()
-                .bind(c -> {
-                    Either<? extends Component, ResponseFormat> checkoutRes = getResourcetFromGraph(c);
-                    Service resource1 = (Service) checkoutRes.left().value();
-                    Either<Service, ResponseFormat> checkoutRes1 = Either.left(resource1);
-                    return checkoutRes1;
-                });
+        return parseResourceArtifactsInfoFromFile(resource, artifactsMetaFile, artifactsMetaFileName).left()
+            .bind(p -> createResourceArtifacts(csarInfo, resource, p, createdArtifacts)).right().map(rf -> rf).left().bind(c -> {
+                Either<? extends Component, ResponseFormat> checkoutRes = getResourcetFromGraph(c);
+                Service resource1 = (Service) checkoutRes.left().value();
+                Either<Service, ResponseFormat> checkoutRes1 = Either.left(resource1);
+                return checkoutRes1;
+            });
     }
-       
-    public Either<Component, ResponseFormat> updateResourceArtifactsFromCsar(CsarInfo csarInfo, Component resource,
-            String artifactsMetaFile, String artifactsMetaFileName, List<ArtifactDefinition> createdNewArtifacts,
-            boolean shouldLock, boolean inTransaction){
 
+    public Either<Component, ResponseFormat> updateResourceArtifactsFromCsar(CsarInfo csarInfo, Component resource, String artifactsMetaFile,
+                                                                             String artifactsMetaFileName,
+                                                                             List<ArtifactDefinition> createdNewArtifacts, boolean shouldLock,
+                                                                             boolean inTransaction) {
         Component updatedResource = resource;
-
         Either<Map<String, List<ArtifactTemplateInfo>>, ResponseFormat> parseResourceInfoFromYamlEither = parseResourceArtifactsInfoFromFile(
-                updatedResource, artifactsMetaFile, artifactsMetaFileName);
+            updatedResource, artifactsMetaFile, artifactsMetaFileName);
         if (parseResourceInfoFromYamlEither.isRight()) {
             ResponseFormat responseFormat = parseResourceInfoFromYamlEither.right().value();
             if (resource instanceof Resource) {
@@ -183,135 +167,113 @@ public class CsarArtifactsAndGroupsBusinessLogic extends BaseBusinessLogic {
             }
             return Either.right(responseFormat);
         }
-
         List<GroupDefinition> groups = updatedResource.getGroups();
         Map<String, ArtifactDefinition> deploymentArtifact = updatedResource.getDeploymentArtifacts();
         if (MapUtils.isEmpty(deploymentArtifact)) {
             deleteGroupsByType(groups, Constants.DEFAULT_GROUP_VF_MODULE, updatedResource);
-            return createResourceArtifacts(csarInfo, updatedResource, parseResourceInfoFromYamlEither.left().value(),
-                    createdNewArtifacts);
+            return createResourceArtifacts(csarInfo, updatedResource, parseResourceInfoFromYamlEither.left().value(), createdNewArtifacts);
         }
-
-        List<ArtifactDefinition> createdDeploymentArtifactsAfterDelete = deploymentArtifact.values().stream()
-                                                                                                  .collect(Collectors.toList());
-
-        int labelCounter = createdDeploymentArtifactsAfterDelete
-                .stream()
-                .map(ArtifactDefinition::getArtifactLabel)
-                .filter(this::isLastCharacterInLabelADigit)
-                .map(this::getNextInt)
-                .flatMapToInt(this::toStream)
-                .max()
-                .orElse(-1) + 1;
-
+        List<ArtifactDefinition> createdDeploymentArtifactsAfterDelete = deploymentArtifact.values().stream().collect(Collectors.toList());
+        int labelCounter =
+            createdDeploymentArtifactsAfterDelete.stream().map(ArtifactDefinition::getArtifactLabel).filter(this::isLastCharacterInLabelADigit)
+                .map(this::getNextInt).flatMapToInt(this::toStream).max().orElse(-1) + 1;
         ////////////////////////////////////// create set parsed
+
         ////////////////////////////////////// artifacts///////////////////////////////////////////
         Map<String, List<ArtifactTemplateInfo>> parsedArtifactsMap = parseResourceInfoFromYamlEither.left().value();
-
         List<ArtifactTemplateInfo> artifactsWithoutGroups = parsedArtifactsMap.remove(ArtifactTemplateInfo.CSAR_ARTIFACT);
         Collection<List<ArtifactTemplateInfo>> parsedArifactsCollection = parsedArtifactsMap.values();
-
-        Either<Map<ArtifactTemplateInfo, Set<ArtifactTemplateInfo>>, ResponseFormat> parsedArtifactsPerGroupEither = createArtifactsTemplateCollection(csarInfo, updatedResource, createdNewArtifacts,
-                createdDeploymentArtifactsAfterDelete, labelCounter, parsedArifactsCollection);
+        Either<Map<ArtifactTemplateInfo, Set<ArtifactTemplateInfo>>, ResponseFormat> parsedArtifactsPerGroupEither = createArtifactsTemplateCollection(
+            csarInfo, updatedResource, createdNewArtifacts, createdDeploymentArtifactsAfterDelete, labelCounter, parsedArifactsCollection);
         if (parsedArtifactsPerGroupEither.isRight()) {
             log.error("Failed to parse artifacts. Status is {} ", parsedArtifactsPerGroupEither.right().value());
             return Either.right(parsedArtifactsPerGroupEither.right().value());
         }
-
         Map<ArtifactTemplateInfo, Set<ArtifactTemplateInfo>> parsedGroup = parsedArtifactsPerGroupEither.left().value();
-
         // find master in group
-        Map<GroupDefinition, Map<ArtifactDefinition, List<ArtifactDefinition>>> groupArtifact = findMasterArtifactInGroup(
-                groups, deploymentArtifact);
-
+        Map<GroupDefinition, Map<ArtifactDefinition, List<ArtifactDefinition>>> groupArtifact = findMasterArtifactInGroup(groups, deploymentArtifact);
         ///////////////////////////////// find artifacts to
-        ///////////////////////////////// delete////////////////////////////////////////////////////
-
 
+        ///////////////////////////////// delete////////////////////////////////////////////////////
         Map<String, List<ArtifactDefinition>> groupToDelete = new HashMap<>();
         Set<ArtifactDefinition> artifactsToDelete = findArtifactThatNotInGroupToDelete(parsedGroup, createdDeploymentArtifactsAfterDelete);
-
         Set<ArtifactTemplateInfo> jsonMasterArtifacts = parsedGroup.keySet();
-        Map<GroupDefinition, MergedArtifactInfo> mergedgroup = mergeGroupInUpdateFlow(groupArtifact, parsedGroup,
-                artifactsToDelete, groupToDelete, jsonMasterArtifacts, createdDeploymentArtifactsAfterDelete);
-
+        Map<GroupDefinition, MergedArtifactInfo> mergedgroup = mergeGroupInUpdateFlow(groupArtifact, parsedGroup, artifactsToDelete, groupToDelete,
+            jsonMasterArtifacts, createdDeploymentArtifactsAfterDelete);
         List<ArtifactDefinition> deletedArtifacts = new ArrayList<>();
-        Either<Component, ResponseFormat> deletedArtifactsEither = deleteArtifactsInUpdateCsarFlow(
-                updatedResource, csarInfo.getModifier(), shouldLock, inTransaction, artifactsToDelete, groupToDelete, deletedArtifacts);
+        Either<Component, ResponseFormat> deletedArtifactsEither = deleteArtifactsInUpdateCsarFlow(updatedResource, csarInfo.getModifier(),
+            shouldLock, inTransaction, artifactsToDelete, groupToDelete, deletedArtifacts);
         if (deletedArtifactsEither.isRight()) {
             log.debug("Failed to delete artifacts. Status is {} ", deletedArtifactsEither.right().value());
-
             return Either.right(deletedArtifactsEither.right().value());
-
         }
         updatedResource = deletedArtifactsEither.left().value();
-
         // need to update resource if we updated artifacts
         excludeDeletedArtifacts(deletedArtifacts, createdDeploymentArtifactsAfterDelete);
-
         ////////////// dissociate, associate or create
+
         ////////////// artifacts////////////////////////////
-        Either<Component, ResponseFormat> assDissotiateEither = associateAndDissociateArtifactsToGroup(csarInfo,
-                updatedResource, createdNewArtifacts, labelCounter,
-                createdDeploymentArtifactsAfterDelete, mergedgroup, deletedArtifacts);
+        Either<Component, ResponseFormat> assDissotiateEither = associateAndDissociateArtifactsToGroup(csarInfo, updatedResource, createdNewArtifacts,
+            labelCounter, createdDeploymentArtifactsAfterDelete, mergedgroup, deletedArtifacts);
         groups = updatedResource.getGroups();
         if (assDissotiateEither.isRight()) {
             log.debug("Failed to delete artifacts. Status is {} ", assDissotiateEither.right().value());
             return Either.right(assDissotiateEither.right().value());
         }
-
         updatedResource = assDissotiateEither.left().value();
         deploymentArtifact = updatedResource.getDeploymentArtifacts();
-
-        createdDeploymentArtifactsAfterDelete = deploymentArtifact.values().stream()
-                                                                        .collect(Collectors.toList());
-
+        createdDeploymentArtifactsAfterDelete = deploymentArtifact.values().stream().collect(Collectors.toList());
         // update vfModule names
         Set<GroupDefinition> groupForAssociateWithMembers = mergedgroup.keySet();
-        Either<Component, ResponseFormat> validateUpdateVfGroupNamesRes = updateVfModuleNames(createdNewArtifacts,
-                updatedResource, groups, createdDeploymentArtifactsAfterDelete, groupForAssociateWithMembers);
-        if (validateUpdateVfGroupNamesRes != null) return validateUpdateVfGroupNamesRes;
-
+        Either<Component, ResponseFormat> validateUpdateVfGroupNamesRes = updateVfModuleNames(createdNewArtifacts, updatedResource, groups,
+            createdDeploymentArtifactsAfterDelete, groupForAssociateWithMembers);
+        if (validateUpdateVfGroupNamesRes != null) {
+            return validateUpdateVfGroupNamesRes;
+        }
         //////////////// create new artifacts in update
+
         //////////////// flow////////////////////////////
         List<ArtifactTemplateInfo> newArtifactsGroup = createNewArtifcats(parsedGroup, groupArtifact);
-        Either<Component, ResponseFormat> validateGroupNamesRes = handleArtifactsInGroup(csarInfo, createdNewArtifacts,
-                updatedResource, groups, createdDeploymentArtifactsAfterDelete, labelCounter, newArtifactsGroup);
-        if (validateGroupNamesRes != null) return validateGroupNamesRes;
-
+        Either<Component, ResponseFormat> validateGroupNamesRes = handleArtifactsInGroup(csarInfo, createdNewArtifacts, updatedResource, groups,
+            createdDeploymentArtifactsAfterDelete, labelCounter, newArtifactsGroup);
+        if (validateGroupNamesRes != null) {
+            return validateGroupNamesRes;
+        }
         // updatedGroup
         Either<Component, ResponseFormat> updateVersionEither = updateGroupVersion(updatedResource, groupForAssociateWithMembers);
-        if (updateVersionEither != null) return updateVersionEither;
+        if (updateVersionEither != null) {
+            return updateVersionEither;
+        }
         if (!CollectionUtils.isEmpty(artifactsWithoutGroups)) {
             for (ArtifactTemplateInfo t : artifactsWithoutGroups) {
                 List<ArtifactTemplateInfo> artifacts = new ArrayList<>();
                 artifacts.add(t);
-                Either<Component, ResponseFormat> resStatus = createGroupDeploymentArtifactsFromCsar(csarInfo, updatedResource,
-                        artifacts, createdNewArtifacts, createdDeploymentArtifactsAfterDelete, labelCounter);
-                if (checkResponse(resStatus)) return resStatus;
+                Either<Component, ResponseFormat> resStatus = createGroupDeploymentArtifactsFromCsar(csarInfo, updatedResource, artifacts,
+                    createdNewArtifacts, createdDeploymentArtifactsAfterDelete, labelCounter);
+                if (checkResponse(resStatus)) {
+                    return resStatus;
+                }
             }
-
         }
-
         Either<Component, StorageOperationStatus> eitherGetResource = toscaOperationFacade.getToscaElement(updatedResource.getUniqueId());
         return mapResult(eitherGetResource, updatedResource);
     }
 
     private Either<Component, ResponseFormat> handleArtifactsInGroup(CsarInfo csarInfo, List<ArtifactDefinition> createdNewArtifacts,
-                                                                    Component updatedResource, List<GroupDefinition> groups,
-                                                                    List<ArtifactDefinition> createdDeploymentArtifactsAfterDelete,
-                                                                    int labelCounter, List<ArtifactTemplateInfo> newArtifactsGroup) {
+                                                                     Component updatedResource, List<GroupDefinition> groups,
+                                                                     List<ArtifactDefinition> createdDeploymentArtifactsAfterDelete, int labelCounter,
+                                                                     List<ArtifactTemplateInfo> newArtifactsGroup) {
         if (!newArtifactsGroup.isEmpty()) {
             Collections.sort(newArtifactsGroup, ArtifactTemplateInfo::compareByGroupName);
             int startGroupCounter = groupBusinessLogic.getNextVfModuleNameCounter(groups);
             Either<Boolean, ResponseFormat> validateGroupNamesRes = groupBusinessLogic
-                    .validateGenerateVfModuleGroupNames(newArtifactsGroup, updatedResource.getSystemName(), startGroupCounter);
+                .validateGenerateVfModuleGroupNames(newArtifactsGroup, updatedResource.getSystemName(), startGroupCounter);
             if (validateGroupNamesRes.isRight()) {
                 return Either.right(validateGroupNamesRes.right().value());
             }
-            Either<Component, ResponseFormat> resStatus = createGroupDeploymentArtifactsFromCsar(csarInfo, updatedResource,
-                    newArtifactsGroup, createdNewArtifacts, createdDeploymentArtifactsAfterDelete, labelCounter);
-          checkResponse(resStatus);
+            Either<Component, ResponseFormat> resStatus = createGroupDeploymentArtifactsFromCsar(csarInfo, updatedResource, newArtifactsGroup,
+                createdNewArtifacts, createdDeploymentArtifactsAfterDelete, labelCounter);
+            checkResponse(resStatus);
         }
         return null;
     }
@@ -320,10 +282,13 @@ public class CsarArtifactsAndGroupsBusinessLogic extends BaseBusinessLogic {
         return (resStatus.isRight());
     }
 
-    private Either<Component, ResponseFormat> updateVfModuleNames(List<ArtifactDefinition> createdNewArtifacts, Component updatedResource, List<GroupDefinition> groups, List<ArtifactDefinition> createdDeploymentArtifactsAfterDelete, Set<GroupDefinition> groupForAssociateWithMembers) {
+    private Either<Component, ResponseFormat> updateVfModuleNames(List<ArtifactDefinition> createdNewArtifacts, Component updatedResource,
+                                                                  List<GroupDefinition> groups,
+                                                                  List<ArtifactDefinition> createdDeploymentArtifactsAfterDelete,
+                                                                  Set<GroupDefinition> groupForAssociateWithMembers) {
         if (!CollectionUtils.isEmpty(groups)) {
             Either<List<GroupDefinition>, ResponseFormat> validateUpdateVfGroupNamesRes = groupBusinessLogic
-                    .validateUpdateVfGroupNamesOnGraph(groups, updatedResource);
+                .validateUpdateVfGroupNamesOnGraph(groups, updatedResource);
             if (validateUpdateVfGroupNamesRes.isRight()) {
                 return Either.right(validateUpdateVfGroupNamesRes.right().value());
             }
@@ -334,17 +299,11 @@ public class CsarArtifactsAndGroupsBusinessLogic extends BaseBusinessLogic {
 
     private Either<Component, ResponseFormat> updateGroupVersion(Component updatedResource, Set<GroupDefinition> groupForAssociateWithMembers) {
         if (!groupForAssociateWithMembers.isEmpty()) {
-
-            List<GroupDefinition> groupsId = groupForAssociateWithMembers.stream()
-                                                                         .collect(Collectors.toList());
-
-            Either<List<GroupDefinition>, ResponseFormat> updateVersionEither = groupBusinessLogic
-                    .updateGroups(updatedResource, groupsId, true);
+            List<GroupDefinition> groupsId = groupForAssociateWithMembers.stream().collect(Collectors.toList());
+            Either<List<GroupDefinition>, ResponseFormat> updateVersionEither = groupBusinessLogic.updateGroups(updatedResource, groupsId, true);
             if (updateVersionEither.isRight()) {
                 log.debug("Failed to update groups version. Status is {} ", updateVersionEither.right().value());
-
                 return Either.right(updateVersionEither.right().value());
-
             }
         }
         return null;
@@ -358,7 +317,7 @@ public class CsarArtifactsAndGroupsBusinessLogic extends BaseBusinessLogic {
     }
 
     private OptionalInt getNextInt(String artifactLabel) {
-        try(Scanner scanner = new Scanner(artifactLabel).useDelimiter(LABEL_COUNTER_DELIMITER)) {
+        try (Scanner scanner = new Scanner(artifactLabel).useDelimiter(LABEL_COUNTER_DELIMITER)) {
             if (scanner.hasNextInt()) {
                 return OptionalInt.of(scanner.nextInt());
             }
@@ -367,44 +326,37 @@ public class CsarArtifactsAndGroupsBusinessLogic extends BaseBusinessLogic {
     }
 
     private boolean isLastCharacterInLabelADigit(String artifactLabel) {
-        return Character.isDigit(artifactLabel.charAt(artifactLabel.length()-1));
+        return Character.isDigit(artifactLabel.charAt(artifactLabel.length() - 1));
     }
 
     private Either<Component, ResponseFormat> mapResult(Either<Component, StorageOperationStatus> result, Component resource) {
         return result.right()
-                     .map(status -> componentsUtils.getResponseFormatByResource(
-                             componentsUtils.convertFromStorageResponse(status), resource));
+            .map(status -> componentsUtils.getResponseFormatByResource(componentsUtils.convertFromStorageResponse(status), resource));
     }
 
-
-    private void updateGroupMemebers(List<GroupDefinition> groups, Set<GroupDefinition> groupForAssociateWithMembers, List<ArtifactDefinition> createdNewArtifacts, List<ArtifactDefinition> createdDeploymentArtifactsAfterDelete) {
+    private void updateGroupMemebers(List<GroupDefinition> groups, Set<GroupDefinition> groupForAssociateWithMembers,
+                                     List<ArtifactDefinition> createdNewArtifacts, List<ArtifactDefinition> createdDeploymentArtifactsAfterDelete) {
         List<GroupDefinition> heatGroups = collectGroupsWithMembers(groups);
-
         for (GroupDefinition updatedGroupDef : groupForAssociateWithMembers) {
             Map<String, String> members = new HashMap<>();
             Set<String> artifactsGroup = new HashSet<>();
             artifactsGroup.addAll(updatedGroupDef.getArtifacts());
-            associateMembersToArtifacts(createdNewArtifacts, createdDeploymentArtifactsAfterDelete, heatGroups,
-                    artifactsGroup, members);
-
+            associateMembersToArtifacts(createdNewArtifacts, createdDeploymentArtifactsAfterDelete, heatGroups, artifactsGroup, members);
             updatedGroupDef.setMembers(members);
         }
     }
 
-
     /**
      * @param groups
      * @return
      */
     private List<GroupDefinition> collectGroupsWithMembers(List<GroupDefinition> groups) {
-        return groups.stream()
-                     .filter(e -> e.getMembers() != null)
-                     .collect(Collectors.toList());
+        return groups.stream().filter(e -> e.getMembers() != null).collect(Collectors.toList());
     }
 
-
     /**
      * Exclude deleted Artificats from Deployment Artifcats
+     *
      * @param deletedArtifacts
      * @param createdDeploymentArtifactsAfterDelete
      */
@@ -420,30 +372,23 @@ public class CsarArtifactsAndGroupsBusinessLogic extends BaseBusinessLogic {
             if (artToRemove != null) {
                 createdDeploymentArtifactsAfterDelete.remove(artToRemove);
             }
-
         }
     }
 
-
     private void deleteGroupsByType(List<GroupDefinition> groups, String groupType, Component resource) {
-        if(groups != null){
-            List<GroupDefinition> listToDelete =  groups.stream()
-                                                        .filter(g -> g.getType().equals(groupType))
-                                                        .collect(Collectors.toList());
-
+        if (groups != null) {
+            List<GroupDefinition> listToDelete = groups.stream().filter(g -> g.getType().equals(groupType)).collect(Collectors.toList());
             groupBusinessLogic.deleteGroups(resource, listToDelete);
         }
     }
 
-
-    private List<ArtifactTemplateInfo> createNewArtifcats(Map<ArtifactTemplateInfo, Set<ArtifactTemplateInfo>> parsedGroup, Map<GroupDefinition, Map<ArtifactDefinition, List<ArtifactDefinition>>> groupArtifact) {
+    private List<ArtifactTemplateInfo> createNewArtifcats(Map<ArtifactTemplateInfo, Set<ArtifactTemplateInfo>> parsedGroup,
+                                                          Map<GroupDefinition, Map<ArtifactDefinition, List<ArtifactDefinition>>> groupArtifact) {
         List<ArtifactTemplateInfo> newArtifactsGroup = new ArrayList<>();
-
         for (Entry<ArtifactTemplateInfo, Set<ArtifactTemplateInfo>> parsedGroupSetEntry : parsedGroup.entrySet()) {
             ArtifactTemplateInfo parsedArtifactMaster = parsedGroupSetEntry.getKey();
             boolean isNewGroup = true;
-            for (Entry<GroupDefinition, Map<ArtifactDefinition, List<ArtifactDefinition>>> groupListEntry : groupArtifact
-                    .entrySet()) {
+            for (Entry<GroupDefinition, Map<ArtifactDefinition, List<ArtifactDefinition>>> groupListEntry : groupArtifact.entrySet()) {
                 Map<ArtifactDefinition, List<ArtifactDefinition>> groupArtifacts = groupListEntry.getValue();
                 Set<ArtifactDefinition> group = groupArtifacts.keySet();
                 for (ArtifactDefinition artifactInfo : group) {
@@ -456,64 +401,52 @@ public class CsarArtifactsAndGroupsBusinessLogic extends BaseBusinessLogic {
             if (isNewGroup) {
                 newArtifactsGroup.add(parsedArtifactMaster);
             }
-
         }
         return newArtifactsGroup;
     }
 
-    private Set<ArtifactDefinition> findArtifactThatNotInGroupToDelete(
-            Map<ArtifactTemplateInfo, Set<ArtifactTemplateInfo>> parsedGroup,
-            List<ArtifactDefinition> createdDeploymentArtifactsAfterDelete) {
+    private Set<ArtifactDefinition> findArtifactThatNotInGroupToDelete(Map<ArtifactTemplateInfo, Set<ArtifactTemplateInfo>> parsedGroup,
+                                                                       List<ArtifactDefinition> createdDeploymentArtifactsAfterDelete) {
         Set<ArtifactDefinition> artifactsToDelete = new HashSet<>();
         for (Entry<ArtifactTemplateInfo, Set<ArtifactTemplateInfo>> parsedGroupSetEntry : parsedGroup.entrySet()) {
             Set<ArtifactTemplateInfo> artifactsNames = parsedGroupSetEntry.getValue();
             for (ArtifactTemplateInfo template : artifactsNames) {
-                if(template.getType().equals(ArtifactTypeEnum.HEAT_ARTIFACT.getType())){
-                    Optional<ArtifactDefinition> op = createdDeploymentArtifactsAfterDelete.stream().filter(a -> a.getArtifactName().equalsIgnoreCase(template.getFileName())).findAny();
+                if (template.getType().equals(ArtifactTypeEnum.HEAT_ARTIFACT.getType())) {
+                    Optional<ArtifactDefinition> op = createdDeploymentArtifactsAfterDelete.stream()
+                        .filter(a -> a.getArtifactName().equalsIgnoreCase(template.getFileName())).findAny();
                     if (op.isPresent() && !op.get().getArtifactType().equalsIgnoreCase(template.getType())) {
                         artifactsToDelete.add(op.get());
                     }
                 }
             }
         }
-
         return artifactsToDelete;
     }
 
-
     private Either<Component, ResponseFormat> createResourceArtifacts(CsarInfo csarInfo, Component resource,
-            Map<String, List<ArtifactTemplateInfo>> artifactsMap,
-            List<ArtifactDefinition> createdArtifacts) {
-
+                                                                      Map<String, List<ArtifactTemplateInfo>> artifactsMap,
+                                                                      List<ArtifactDefinition> createdArtifacts) {
         Either<Component, ResponseFormat> resStatus = Either.left(resource);
-
         Collection<List<ArtifactTemplateInfo>> arifactsCollection = artifactsMap.values();
-
         for (List<ArtifactTemplateInfo> groupTemplateList : arifactsCollection) {
             if (groupTemplateList != null) {
-                resStatus = createGroupDeploymentArtifactsFromCsar(csarInfo, resource, groupTemplateList,
-                        createdArtifacts, 0);
+                resStatus = createGroupDeploymentArtifactsFromCsar(csarInfo, resource, groupTemplateList, createdArtifacts, 0);
                 if (resStatus.isRight()) {
                     return resStatus;
                 }
             }
         }
-
         return resStatus;
-
     }
 
-
-    private Either<Map<ArtifactTemplateInfo, Set<ArtifactTemplateInfo>>, ResponseFormat> createArtifactsTemplateCollection(
-               CsarInfo csarInfo, Component resource,
-            List<ArtifactDefinition> createdNewArtifacts,
-            List<ArtifactDefinition> createdDeploymentArtifactsAfterDelete, int labelCounter,
-            Collection<List<ArtifactTemplateInfo>> parsedArifactsCollection) {
-
+    private Either<Map<ArtifactTemplateInfo, Set<ArtifactTemplateInfo>>, ResponseFormat> createArtifactsTemplateCollection(CsarInfo csarInfo,
+                                                                                                                           Component resource,
+                                                                                                                           List<ArtifactDefinition> createdNewArtifacts,
+                                                                                                                           List<ArtifactDefinition> createdDeploymentArtifactsAfterDelete,
+                                                                                                                           int labelCounter,
+                                                                                                                           Collection<List<ArtifactTemplateInfo>> parsedArifactsCollection) {
         Map<ArtifactTemplateInfo, Set<ArtifactTemplateInfo>> parsedGroup = new HashMap<>();
-
         for (List<ArtifactTemplateInfo> parsedGroupTemplateList : parsedArifactsCollection) {
-
             for (ArtifactTemplateInfo parsedGroupTemplate : parsedGroupTemplateList) {
                 if (parsedGroupTemplate.getGroupName() != null) {
                     parsedGroupTemplate.setGroupName("");
@@ -527,64 +460,55 @@ public class CsarArtifactsAndGroupsBusinessLogic extends BaseBusinessLogic {
                 } else {
                     List<ArtifactTemplateInfo> arrtifacts = new ArrayList<>();
                     arrtifacts.add(parsedGroupTemplate);
-                    Either<Component, ResponseFormat> resStatus = createGroupDeploymentArtifactsFromCsar(csarInfo,
-                            resource, arrtifacts, createdNewArtifacts, createdDeploymentArtifactsAfterDelete,
-                            labelCounter);
+                    Either<Component, ResponseFormat> resStatus = createGroupDeploymentArtifactsFromCsar(csarInfo, resource, arrtifacts,
+                        createdNewArtifacts, createdDeploymentArtifactsAfterDelete, labelCounter);
                     if (resStatus.isRight()) {
                         return Either.right(resStatus.right().value());
                     }
-
                 }
             }
-
         }
         return Either.left(parsedGroup);
     }
 
-    @SuppressWarnings({ "unchecked", "static-access" })
-    public Either<Map<String, List<ArtifactTemplateInfo>>, ResponseFormat> parseResourceArtifactsInfoFromFile(
-            Component resource, String artifactsMetaFile, String artifactFileName) {
-
+    @SuppressWarnings({"unchecked", "static-access"})
+    public Either<Map<String, List<ArtifactTemplateInfo>>, ResponseFormat> parseResourceArtifactsInfoFromFile(Component resource,
+                                                                                                              String artifactsMetaFile,
+                                                                                                              String artifactFileName) {
         try {
             JsonObject jsonElement = new JsonObject();
             jsonElement = gson.fromJson(artifactsMetaFile, jsonElement.getClass());
-
             JsonElement importStructureElement = jsonElement.get(Constants.IMPORT_STRUCTURE);
             if (importStructureElement == null || importStructureElement.isJsonNull()) {
                 log.debug(ARTIFACT_FILE_IS_NOT_IN_EXPECTED_FORMAT_FILE_NAME, artifactFileName);
-                BeEcompErrorManager.getInstance().logInternalDataError(
-                        ARTIFACT_FILE_IS_NOT_IN_EXPECTED_FORMAT_FILE_NAME + artifactFileName,
-                        ARTIFACT_INTERNALS_ARE_INVALID, ErrorSeverity.ERROR);
-                return Either
-                        .right(componentsUtils.getResponseFormat(ActionStatus.CSAR_INVALID_FORMAT, artifactFileName));
+                BeEcompErrorManager.getInstance()
+                    .logInternalDataError(ARTIFACT_FILE_IS_NOT_IN_EXPECTED_FORMAT_FILE_NAME + artifactFileName, ARTIFACT_INTERNALS_ARE_INVALID,
+                        ErrorSeverity.ERROR);
+                return Either.right(componentsUtils.getResponseFormat(ActionStatus.CSAR_INVALID_FORMAT, artifactFileName));
             }
-
             Map<String, List<Map<String, Object>>> artifactTemplateMap;
             artifactTemplateMap = ComponentsUtils.parseJsonToObject(importStructureElement.toString(), HashMap.class);
             if (artifactTemplateMap.isEmpty()) {
                 log.debug(ARTIFACT_FILE_IS_NOT_IN_EXPECTED_FORMAT_FILE_NAME, artifactFileName);
-                BeEcompErrorManager.getInstance().logInternalDataError(
-                        ARTIFACT_FILE_IS_NOT_IN_EXPECTED_FORMAT_FILE_NAME + artifactFileName,
-                        ARTIFACT_INTERNALS_ARE_INVALID, ErrorSeverity.ERROR);
-                return Either
-                        .right(componentsUtils.getResponseFormat(ActionStatus.CSAR_INVALID_FORMAT, artifactFileName));
+                BeEcompErrorManager.getInstance()
+                    .logInternalDataError(ARTIFACT_FILE_IS_NOT_IN_EXPECTED_FORMAT_FILE_NAME + artifactFileName, ARTIFACT_INTERNALS_ARE_INVALID,
+                        ErrorSeverity.ERROR);
+                return Either.right(componentsUtils.getResponseFormat(ActionStatus.CSAR_INVALID_FORMAT, artifactFileName));
             }
-
             Set<String> artifactsTypeKeys = artifactTemplateMap.keySet();
             Map<String, List<ArtifactTemplateInfo>> artifactsMap = new HashMap<>();
             List<ArtifactTemplateInfo> allGroups = new ArrayList<>();
             for (String artifactsTypeKey : artifactsTypeKeys) {
-
-                Either <List<ArtifactTemplateInfo>, ResponseFormat> artifactTemplateInfoListEither = parseArtifactTemplateList(artifactFileName,
-                        artifactTemplateMap, allGroups, artifactsTypeKey);
-                if(artifactTemplateInfoListEither.isRight()){
+                Either<List<ArtifactTemplateInfo>, ResponseFormat> artifactTemplateInfoListEither = parseArtifactTemplateList(artifactFileName,
+                    artifactTemplateMap, allGroups, artifactsTypeKey);
+                if (artifactTemplateInfoListEither.isRight()) {
                     return Either.right(artifactTemplateInfoListEither.right().value());
                 }
                 artifactsMap.put(artifactsTypeKey, artifactTemplateInfoListEither.left().value());
             }
             int counter = groupBusinessLogic.getNextVfModuleNameCounter(resource.getGroups());
             Either<Boolean, ResponseFormat> validateGroupNamesRes = groupBusinessLogic
-                    .validateGenerateVfModuleGroupNames(allGroups, resource.getSystemName(), counter);
+                .validateGenerateVfModuleGroupNames(allGroups, resource.getSystemName(), counter);
             if (validateGroupNamesRes.isRight()) {
                 return Either.right(validateGroupNamesRes.right().value());
             }
@@ -592,36 +516,33 @@ public class CsarArtifactsAndGroupsBusinessLogic extends BaseBusinessLogic {
         } catch (Exception e) {
             log.debug(ARTIFACT_FILE_IS_NOT_IN_EXPECTED_FORMAT_FILE_NAME, artifactFileName);
             log.debug("failed with exception.", e);
-            BeEcompErrorManager.getInstance().logInternalDataError(
-                    ARTIFACT_FILE_IS_NOT_IN_EXPECTED_FORMAT_FILE_NAME + artifactFileName,
-                    ARTIFACT_INTERNALS_ARE_INVALID, ErrorSeverity.ERROR);
+            BeEcompErrorManager.getInstance()
+                .logInternalDataError(ARTIFACT_FILE_IS_NOT_IN_EXPECTED_FORMAT_FILE_NAME + artifactFileName, ARTIFACT_INTERNALS_ARE_INVALID,
+                    ErrorSeverity.ERROR);
             return Either.right(componentsUtils.getResponseFormat(ActionStatus.CSAR_INVALID_FORMAT, artifactFileName));
         }
-
     }
 
-    private Either< List<ArtifactTemplateInfo>, ResponseFormat> parseArtifactTemplateList(String artifactFileName,
-            Map<String, List<Map<String, Object>>> artifactTemplateMap, List<ArtifactTemplateInfo> allGroups,
-            String artifactsTypeKey) {
+    private Either<List<ArtifactTemplateInfo>, ResponseFormat> parseArtifactTemplateList(String artifactFileName,
+                                                                                         Map<String, List<Map<String, Object>>> artifactTemplateMap,
+                                                                                         List<ArtifactTemplateInfo> allGroups,
+                                                                                         String artifactsTypeKey) {
         List<Map<String, Object>> o = artifactTemplateMap.get(artifactsTypeKey);
-        Either<List<ArtifactTemplateInfo>, ResponseFormat> artifactTemplateInfoListPairStatus = createArtifactTemplateInfoModule(
-                artifactsTypeKey, o);
+        Either<List<ArtifactTemplateInfo>, ResponseFormat> artifactTemplateInfoListPairStatus = createArtifactTemplateInfoModule(artifactsTypeKey, o);
         if (artifactTemplateInfoListPairStatus.isRight()) {
             log.debug(ARTIFACT_FILE_IS_NOT_IN_EXPECTED_FORMAT_FILE_NAME, artifactFileName);
-            BeEcompErrorManager.getInstance().logInternalDataError(
-                    ARTIFACT_FILE_IS_NOT_IN_EXPECTED_FORMAT_FILE_NAME + artifactFileName,
-                    ARTIFACT_INTERNALS_ARE_INVALID, ErrorSeverity.ERROR);
+            BeEcompErrorManager.getInstance()
+                .logInternalDataError(ARTIFACT_FILE_IS_NOT_IN_EXPECTED_FORMAT_FILE_NAME + artifactFileName, ARTIFACT_INTERNALS_ARE_INVALID,
+                    ErrorSeverity.ERROR);
             return Either.right(artifactTemplateInfoListPairStatus.right().value());
         }
         List<ArtifactTemplateInfo> artifactTemplateInfoList = artifactTemplateInfoListPairStatus.left().value();
         if (artifactTemplateInfoList == null) {
             log.debug(ARTIFACT_FILE_IS_NOT_IN_EXPECTED_FORMAT_FILE_NAME, artifactFileName);
-            BeEcompErrorManager.getInstance().logInternalDataError(
-                    ARTIFACT_FILE_IS_NOT_IN_EXPECTED_FORMAT_FILE_NAME + artifactFileName,
-                    ARTIFACT_INTERNALS_ARE_INVALID, ErrorSeverity.ERROR);
-            return Either.right(
-                    componentsUtils.getResponseFormat(ActionStatus.CSAR_INVALID_FORMAT, artifactFileName));
-
+            BeEcompErrorManager.getInstance()
+                .logInternalDataError(ARTIFACT_FILE_IS_NOT_IN_EXPECTED_FORMAT_FILE_NAME + artifactFileName, ARTIFACT_INTERNALS_ARE_INVALID,
+                    ErrorSeverity.ERROR);
+            return Either.right(componentsUtils.getResponseFormat(ActionStatus.CSAR_INVALID_FORMAT, artifactFileName));
         }
         if (!artifactsTypeKey.equalsIgnoreCase(ArtifactTemplateInfo.CSAR_ARTIFACT)) {
             allGroups.addAll(artifactTemplateInfoList);
@@ -630,30 +551,25 @@ public class CsarArtifactsAndGroupsBusinessLogic extends BaseBusinessLogic {
     }
 
     private Either<List<ArtifactTemplateInfo>, ResponseFormat> createArtifactTemplateInfoModule(String artifactsTypeKey,
-            List<Map<String, Object>> jsonObject) {
+                                                                                                List<Map<String, Object>> jsonObject) {
         List<ArtifactTemplateInfo> artifactTemplateInfoList = new ArrayList<>();
         for (Map<String, Object> o : jsonObject) {
             Either<ArtifactTemplateInfo, ResponseFormat> artifacttemplateInfoStatus = ArtifactTemplateInfo
-                    .createArtifactTemplateInfoFromJson(componentsUtils, artifactsTypeKey, o, artifactTemplateInfoList,
-                            null);
+                .createArtifactTemplateInfoFromJson(componentsUtils, artifactsTypeKey, o, artifactTemplateInfoList, null);
             if (artifacttemplateInfoStatus.isRight()) {
                 return Either.right(artifacttemplateInfoStatus.right().value());
             }
-
             ArtifactTemplateInfo artifacttemplateInfo = artifacttemplateInfoStatus.left().value();
             if (artifacttemplateInfo != null) {
                 artifactTemplateInfoList.add(artifacttemplateInfo);
             }
-
         }
         return Either.left(artifactTemplateInfoList);
     }
 
-
-
-    private Either<Component, ResponseFormat> createGroupDeploymentArtifactsFromCsar(CsarInfo csarInfo,
-            Component resource, List<ArtifactTemplateInfo> artifactsTemplateList,
-            List<ArtifactDefinition> createdArtifacts, int labelCounter) {
+    private Either<Component, ResponseFormat> createGroupDeploymentArtifactsFromCsar(CsarInfo csarInfo, Component resource,
+                                                                                     List<ArtifactTemplateInfo> artifactsTemplateList,
+                                                                                     List<ArtifactDefinition> createdArtifacts, int labelCounter) {
         List<GroupDefinition> createdGroups = resource.getGroups();
         List<GroupDefinition> heatGroups = null;
         if (!CollectionUtils.isEmpty(createdGroups)) {
@@ -664,57 +580,47 @@ public class CsarArtifactsAndGroupsBusinessLogic extends BaseBusinessLogic {
             String groupName = groupTemplateInfo.getGroupName();
             Set<String> artifactsGroup = new HashSet<>();
             Set<String> artifactsUUIDGroup = new HashSet<>();
-
             log.debug("createDeploymentArtifactsFromCsar start");
             Either<Component, ResponseFormat> resStatus = createDeploymentArtifactFromCsar(csarInfo, ARTIFACTS_PATH, resource, artifactsGroup,
-                    artifactsUUIDGroup, groupTemplateInfo, createdArtifacts, labelCounter);
+                artifactsUUIDGroup, groupTemplateInfo, createdArtifacts, labelCounter);
             log.debug("createDeploymentArtifactsFromCsar end");
             if (resStatus.isRight()) {
                 return resStatus;
             }
-            Map<String, ArtifactDefinition> createdArtifactsMap = createdArtifacts.stream().collect(Collectors.toMap(
-                    ArtifactDataDefinition::getArtifactLabel, artifact -> artifact));
+            Map<String, ArtifactDefinition> createdArtifactsMap = createdArtifacts.stream()
+                .collect(Collectors.toMap(ArtifactDataDefinition::getArtifactLabel, artifact -> artifact));
             resource.setDeploymentArtifacts(createdArtifactsMap);
             if (groupName != null && !groupName.isEmpty()) {
-
                 Either<GroupDefinition, ResponseFormat> groupDefinitionEither = buildGroupDefinition(createdArtifacts, heatGroups, groupTemplateInfo,
-                        groupName, artifactsGroup, artifactsUUIDGroup);
+                    groupName, artifactsGroup, artifactsUUIDGroup);
                 if (groupDefinitionEither.isRight()) {
                     return Either.right(groupDefinitionEither.right().value());
                 }
                 needToCreate.add(groupDefinitionEither.left().value());
             }
         }
-        Map<String, ArtifactDefinition> createdArtifactsMap = createdArtifacts.stream().collect(Collectors.toMap(
-                ArtifactDataDefinition::getArtifactLabel, artifact -> artifact));
+        Map<String, ArtifactDefinition> createdArtifactsMap = createdArtifacts.stream()
+            .collect(Collectors.toMap(ArtifactDataDefinition::getArtifactLabel, artifact -> artifact));
         resource.setDeploymentArtifacts(createdArtifactsMap);
-
-        Either<List<GroupDefinition>, ResponseFormat> createGroups = groupBusinessLogic
-                .addGroups(resource, needToCreate, false);
+        Either<List<GroupDefinition>, ResponseFormat> createGroups = groupBusinessLogic.addGroups(resource, needToCreate, false);
         if (createGroups.isRight()) {
             return Either.right(createGroups.right().value());
         }
-
         return Either.left(resource);
     }
 
-    private Either<GroupDefinition, ResponseFormat>  buildGroupDefinition(List<ArtifactDefinition> createdArtifacts,
-            List<GroupDefinition> heatGroups, ArtifactTemplateInfo groupTemplateInfo, String groupName,
-            Set<String> artifactsGroup, Set<String> artifactsUUIDGroup) {
-
+    private Either<GroupDefinition, ResponseFormat> buildGroupDefinition(List<ArtifactDefinition> createdArtifacts, List<GroupDefinition> heatGroups,
+                                                                         ArtifactTemplateInfo groupTemplateInfo, String groupName,
+                                                                         Set<String> artifactsGroup, Set<String> artifactsUUIDGroup) {
         Map<String, String> members = new HashMap<>();
-
         associateMembersToArtifacts(createdArtifacts, null, heatGroups, artifactsGroup, members);
-
         List<String> artifactsList = new ArrayList<>(artifactsGroup);
         List<String> artifactsUUIDList = new ArrayList<>(artifactsUUIDGroup);
-
         GroupDefinition groupDefinition = new GroupDefinition();
         groupDefinition.setName(groupName);
         groupDefinition.setType(Constants.DEFAULT_GROUP_VF_MODULE);
         groupDefinition.setArtifacts(artifactsList);
         groupDefinition.setArtifactsUuid(artifactsUUIDList);
-
         if (!members.isEmpty()) {
             groupDefinition.setMembers(members);
         }
@@ -724,38 +630,34 @@ public class CsarArtifactsAndGroupsBusinessLogic extends BaseBusinessLogic {
         prop.setValue(Boolean.toString(groupTemplateInfo.isBase()));
         properties.add(prop);
         Either<GroupTypeDefinition, StorageOperationStatus> getLatestGroupTypeRes = groupTypeOperation
-                .getLatestGroupTypeByType(Constants.DEFAULT_GROUP_VF_MODULE, true);
+            .getLatestGroupTypeByType(Constants.DEFAULT_GROUP_VF_MODULE, true);
         if (getLatestGroupTypeRes.isRight()) {
-            return Either.right(componentsUtils.getResponseFormat(
-                    componentsUtils.convertFromStorageResponse(getLatestGroupTypeRes.right().value())));
+            return Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(getLatestGroupTypeRes.right().value())));
         }
-        properties = createVfModuleAdditionalProperties(groupTemplateInfo.isBase(), groupName, properties,
-                createdArtifacts, artifactsList, getLatestGroupTypeRes.left().value());
+        properties = createVfModuleAdditionalProperties(groupTemplateInfo.isBase(), groupName, properties, createdArtifacts, artifactsList,
+            getLatestGroupTypeRes.left().value());
         groupDefinition.convertFromGroupProperties(properties);
         log.debug("createGroup start");
         return Either.left(groupDefinition);
     }
 
-    private Either<Component, ResponseFormat> createDeploymentArtifactFromCsar(CsarInfo csarInfo, String artifactPath,
-            Component resource, Set<String> artifactsGroup, Set<String> artifactsUUIDGroup,
-            ArtifactTemplateInfo artifactTemplateInfo, List<ArtifactDefinition> createdArtifacts, int labelCounter) {
+    private Either<Component, ResponseFormat> createDeploymentArtifactFromCsar(CsarInfo csarInfo, String artifactPath, Component resource,
+                                                                               Set<String> artifactsGroup, Set<String> artifactsUUIDGroup,
+                                                                               ArtifactTemplateInfo artifactTemplateInfo,
+                                                                               List<ArtifactDefinition> createdArtifacts, int labelCounter) {
         Either<Component, ResponseFormat> resStatus = Either.left(resource);
-
         String artifactUid = "";
         String artifactEnvUid = "";
         String artifactUUID = "";
-
-
         // check if artifacts already exist
         Either<ArtifactDefinition, ResponseFormat> createdArtifactEther = checkIfArtifactAlreadyExist(artifactTemplateInfo, createdArtifacts);
-        if(createdArtifactEther.isRight()){
+        if (createdArtifactEther.isRight()) {
             return Either.right(createdArtifactEther.right().value());
         }
         ArtifactDefinition createdArtifact = createdArtifactEther.left().value();
-        if(createdArtifact == null){
-
-            Either<ArtifactDefinition, ResponseFormat> newArtifactEither = createDeploymentArtifact(csarInfo, resource,
-                    artifactPath, artifactTemplateInfo, createdArtifacts, labelCounter);
+        if (createdArtifact == null) {
+            Either<ArtifactDefinition, ResponseFormat> newArtifactEither = createDeploymentArtifact(csarInfo, resource, artifactPath,
+                artifactTemplateInfo, createdArtifacts, labelCounter);
             if (newArtifactEither.isRight()) {
                 resStatus = Either.right(newArtifactEither.right().value());
                 return resStatus;
@@ -763,17 +665,14 @@ public class CsarArtifactsAndGroupsBusinessLogic extends BaseBusinessLogic {
             ArtifactDefinition newArtifact = newArtifactEither.left().value();
             artifactUid = newArtifact.getUniqueId();
             artifactUUID = newArtifact.getArtifactUUID();
-
             final ArtifactTypeEnum artifactType = ArtifactTypeEnum.parse(newArtifact.getArtifactType());
-            if (artifactType == ArtifactTypeEnum.HEAT || artifactType == ArtifactTypeEnum.HEAT_NET
-                    || artifactType == ArtifactTypeEnum.HEAT_VOL) {
+            if (artifactType == ArtifactTypeEnum.HEAT || artifactType == ArtifactTypeEnum.HEAT_NET || artifactType == ArtifactTypeEnum.HEAT_VOL) {
                 ArtifactDefinition createHeatEnvPlaceHolder = artifactsBusinessLogic
-                        .createHeatEnvPlaceHolder(createdArtifacts, newArtifact, ArtifactsBusinessLogic.HEAT_VF_ENV_NAME,
-                                resource.getUniqueId(), NodeTypeEnum.Resource, resource.getName(),
-                                csarInfo.getModifier(), resource, null);
+                    .createHeatEnvPlaceHolder(createdArtifacts, newArtifact, ArtifactsBusinessLogic.HEAT_VF_ENV_NAME, resource.getUniqueId(),
+                        NodeTypeEnum.Resource, resource.getName(), csarInfo.getModifier(), resource, null);
                 artifactEnvUid = createHeatEnvPlaceHolder.getUniqueId();
             }
-        }else{
+        } else {
             artifactUid = createdArtifact.getUniqueId();
             artifactUUID = createdArtifact.getArtifactUUID();
             artifactEnvUid = checkAndGetHeatEnvId(createdArtifact);
@@ -783,12 +682,11 @@ public class CsarArtifactsAndGroupsBusinessLogic extends BaseBusinessLogic {
         if (!artifactEnvUid.isEmpty()) {
             artifactsGroup.add(artifactEnvUid);
         }
-
         List<ArtifactTemplateInfo> relatedArtifacts = artifactTemplateInfo.getRelatedArtifactsInfo();
         if (relatedArtifacts != null) {
             for (ArtifactTemplateInfo relatedArtifactTemplateInfo : relatedArtifacts) {
-                resStatus = createDeploymentArtifactFromCsar(csarInfo, artifactPath, resource, artifactsGroup,
-                        artifactsUUIDGroup, relatedArtifactTemplateInfo, createdArtifacts, labelCounter);
+                resStatus = createDeploymentArtifactFromCsar(csarInfo, artifactPath, resource, artifactsGroup, artifactsUUIDGroup,
+                    relatedArtifactTemplateInfo, createdArtifacts, labelCounter);
                 if (resStatus.isRight()) {
                     return resStatus;
                 }
@@ -800,171 +698,136 @@ public class CsarArtifactsAndGroupsBusinessLogic extends BaseBusinessLogic {
     private String checkAndGetHeatEnvId(ArtifactDefinition createdArtifact) {
         String artifactEnvUid = "";
         final ArtifactTypeEnum artifactType = ArtifactTypeEnum.parse(createdArtifact.getArtifactType());
-        if (artifactType == ArtifactTypeEnum.HEAT || artifactType == ArtifactTypeEnum.HEAT_NET
-                || artifactType == ArtifactTypeEnum.HEAT_VOL) {
+        if (artifactType == ArtifactTypeEnum.HEAT || artifactType == ArtifactTypeEnum.HEAT_NET || artifactType == ArtifactTypeEnum.HEAT_VOL) {
             artifactEnvUid = createdArtifact.getUniqueId() + ArtifactsBusinessLogic.HEAT_ENV_SUFFIX;
         }
         return artifactEnvUid;
     }
 
-    private Either<ArtifactDefinition, ResponseFormat> checkIfArtifactAlreadyExist(ArtifactTemplateInfo artifactTemplateInfo, List<ArtifactDefinition> createdArtifacts){
-
+    private Either<ArtifactDefinition, ResponseFormat> checkIfArtifactAlreadyExist(ArtifactTemplateInfo artifactTemplateInfo,
+                                                                                   List<ArtifactDefinition> createdArtifacts) {
         ArtifactDefinition res = null;
         String artifactFileName = artifactTemplateInfo.getFileName();
         Optional<ArtifactDefinition> op = createdArtifacts.stream().filter(a -> a.getArtifactName().equals(artifactFileName)).findAny();
-        if(op.isPresent()){
+        if (op.isPresent()) {
             res = op.get();
             if (!res.getArtifactType().equalsIgnoreCase(artifactTemplateInfo.getType())) {
-                log.debug(ARTIFACT_WITH_NAME_AND_TYPE_ALREADY_EXIST_WITH_TYPE, artifactFileName,
-                        artifactTemplateInfo.getType(), res.getArtifactType());
-                BeEcompErrorManager.getInstance().logInternalDataError(
-                        ARTIFACT_FILE_IS_NOT_IN_EXPECTED_FORMAT_FILE_NAME + artifactFileName,
-                        ARTIFACT_INTERNALS_ARE_INVALID, ErrorSeverity.ERROR);
-                return Either.right(componentsUtils.getResponseFormat(
-                        ActionStatus.ARTIFACT_ALREADY_EXIST_IN_DIFFERENT_TYPE_IN_CSAR, artifactFileName,
-                        artifactTemplateInfo.getType(), res.getArtifactType()));
+                log.debug(ARTIFACT_WITH_NAME_AND_TYPE_ALREADY_EXIST_WITH_TYPE, artifactFileName, artifactTemplateInfo.getType(),
+                    res.getArtifactType());
+                BeEcompErrorManager.getInstance()
+                    .logInternalDataError(ARTIFACT_FILE_IS_NOT_IN_EXPECTED_FORMAT_FILE_NAME + artifactFileName, ARTIFACT_INTERNALS_ARE_INVALID,
+                        ErrorSeverity.ERROR);
+                return Either.right(componentsUtils.getResponseFormat(ActionStatus.ARTIFACT_ALREADY_EXIST_IN_DIFFERENT_TYPE_IN_CSAR, artifactFileName,
+                    artifactTemplateInfo.getType(), res.getArtifactType()));
             }
         }
         return Either.left(res);
-
-
     }
 
-    private Either<ArtifactDefinition, ResponseFormat> createDeploymentArtifact(CsarInfo csarInfo, Component resource,
-                                                                                String artifactPath, ArtifactTemplateInfo artifactTemplateInfo, List<ArtifactDefinition> createdArtifacts,
-                                                                                int label) {
+    private Either<ArtifactDefinition, ResponseFormat> createDeploymentArtifact(CsarInfo csarInfo, Component resource, String artifactPath,
+                                                                                ArtifactTemplateInfo artifactTemplateInfo,
+                                                                                List<ArtifactDefinition> createdArtifacts, int label) {
         int updatedlabel = label;
         final String artifactFileName = artifactTemplateInfo.getFileName();
         Either<ImmutablePair<String, byte[]>, ResponseFormat> artifactContentStatus = CsarValidationUtils
-                .getArtifactContent(csarInfo.getCsarUUID(), csarInfo.getCsar(), artifactPath + artifactFileName,
-                        artifactFileName, componentsUtils);
+            .getArtifactContent(csarInfo.getCsarUUID(), csarInfo.getCsar(), artifactPath + artifactFileName, artifactFileName, componentsUtils);
         if (artifactContentStatus.isRight()) {
             return Either.right(artifactContentStatus.right().value());
         }
         updatedlabel += createdArtifacts.size();
-
-        Map<String, Object> json = ArtifactUtils.buildJsonForArtifact(artifactTemplateInfo,
-                artifactContentStatus.left().value().getValue(), updatedlabel, true);
-
-        Either<Either<ArtifactDefinition, Operation>, ResponseFormat> uploadArtifactToService = createOrUpdateCsarArtifactFromJson(
-                resource, csarInfo.getModifier(), json,
-                new ArtifactOperationInfo(false, false, ArtifactOperationEnum.CREATE));
-
+        Map<String, Object> json = ArtifactUtils
+            .buildJsonForArtifact(artifactTemplateInfo, artifactContentStatus.left().value().getValue(), updatedlabel, true);
+        Either<Either<ArtifactDefinition, Operation>, ResponseFormat> uploadArtifactToService = createOrUpdateCsarArtifactFromJson(resource,
+            csarInfo.getModifier(), json, new ArtifactOperationInfo(false, false, ArtifactOperationEnum.CREATE));
         if (uploadArtifactToService.isRight()) {
             return Either.right(uploadArtifactToService.right().value());
         }
-
         ArtifactDefinition currentInfo = uploadArtifactToService.left().value().left().value();
         if (currentInfo.getHeatParameters() != null) {
-
-            Either<ArtifactDefinition, ResponseFormat> updateEnvEither = updateHeatParamsFromCsar(resource, csarInfo,
-                    artifactTemplateInfo, currentInfo, false);
+            Either<ArtifactDefinition, ResponseFormat> updateEnvEither = updateHeatParamsFromCsar(resource, csarInfo, artifactTemplateInfo,
+                currentInfo, false);
             if (updateEnvEither.isRight()) {
                 log.debug("failed to update parameters to artifact {}", artifactFileName);
                 return Either.right(updateEnvEither.right().value());
-
             }
             currentInfo = updateEnvEither.left().value();
-
         }
-
         createdArtifacts.add(currentInfo);
-
         return Either.left(currentInfo);
-
     }
 
-
-
     private Either<ArtifactDefinition, ResponseFormat> updateHeatParamsFromCsar(Component resource, CsarInfo csarInfo,
-            ArtifactTemplateInfo artifactTemplateInfo, ArtifactDefinition currentInfo, boolean isUpdateEnv) {
-
+                                                                                ArtifactTemplateInfo artifactTemplateInfo,
+                                                                                ArtifactDefinition currentInfo, boolean isUpdateEnv) {
         Component updatedResource = resource;
         Either<ArtifactDefinition, ResponseFormat> resStatus = Either.left(currentInfo);
         if (artifactTemplateInfo.getEnv() != null && !artifactTemplateInfo.getEnv().isEmpty()) {
-
             Either<ImmutablePair<String, byte[]>, ResponseFormat> artifactParamsStatus = CsarValidationUtils
-                    .getArtifactContent(csarInfo.getCsarUUID(), csarInfo.getCsar(),
-                            CsarUtils.ARTIFACTS_PATH + artifactTemplateInfo.getEnv(), artifactTemplateInfo.getEnv(),
-                            componentsUtils);
+                .getArtifactContent(csarInfo.getCsarUUID(), csarInfo.getCsar(), CsarUtils.ARTIFACTS_PATH + artifactTemplateInfo.getEnv(),
+                    artifactTemplateInfo.getEnv(), componentsUtils);
             if (artifactParamsStatus.isRight()) {
                 resStatus = Either.right(artifactParamsStatus.right().value());
                 return resStatus;
             }
-            Either<List<HeatParameterDefinition>, ResponseFormat> propsStatus = extractHeatParameters(
-                    ArtifactTypeEnum.HEAT_ENV.getType(), artifactTemplateInfo.getEnv(),
-                    artifactParamsStatus.left().value().getValue(), false);
-
+            Either<List<HeatParameterDefinition>, ResponseFormat> propsStatus = extractHeatParameters(ArtifactTypeEnum.HEAT_ENV.getType(),
+                artifactTemplateInfo.getEnv(), artifactParamsStatus.left().value().getValue(), false);
             if (propsStatus.isLeft()) {
                 List<HeatParameterDefinition> updatedHeatEnvParams = propsStatus.left().value();
                 resStatus = updateHeatParams(updatedResource, currentInfo, updatedHeatEnvParams);
                 if (resStatus.isRight()) {
                     return resStatus;
                 }
-
             }
         }
         if (isUpdateEnv) {
             Map<String, ArtifactDefinition> artifacts = updatedResource.getDeploymentArtifacts();
-            Optional<ArtifactDefinition> op = artifacts.values().stream().filter(
-                    p -> p.getGeneratedFromId() != null && p.getGeneratedFromId().equals(currentInfo.getUniqueId()))
-                    .findAny();
+            Optional<ArtifactDefinition> op = artifacts.values().stream()
+                .filter(p -> p.getGeneratedFromId() != null && p.getGeneratedFromId().equals(currentInfo.getUniqueId())).findAny();
             if (op.isPresent()) {
                 ArtifactDefinition artifactInfoHeatEnv = op.get();
                 artifactInfoHeatEnv.setHeatParamUpdated(true);
                 Either<ArtifactDefinition, StorageOperationStatus> updateArtifactOnResource = artifactToscaOperation
-                        .updateArtifactOnResource(artifactInfoHeatEnv, updatedResource,
-                                artifactInfoHeatEnv.getUniqueId(), null, null,true);
+                    .updateArtifactOnResource(artifactInfoHeatEnv, updatedResource, artifactInfoHeatEnv.getUniqueId(), null, null, true);
                 if (updateArtifactOnResource.isRight()) {
-                    log.debug("Failed to update heat env on CSAR flow for component {} artifact {} label {}",
-                            updatedResource.getUniqueId(), artifactInfoHeatEnv.getUniqueId(),
-                            artifactInfoHeatEnv.getArtifactLabel());
-                    return Either.right(componentsUtils.getResponseFormat(
-                            componentsUtils.convertFromStorageResponse(updateArtifactOnResource.right().value())));
+                    log.debug("Failed to update heat env on CSAR flow for component {} artifact {} label {}", updatedResource.getUniqueId(),
+                        artifactInfoHeatEnv.getUniqueId(), artifactInfoHeatEnv.getArtifactLabel());
+                    return Either.right(
+                        componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(updateArtifactOnResource.right().value())));
                 }
-                resource.getDeploymentArtifacts().put(updateArtifactOnResource.left().value().getArtifactLabel(), updateArtifactOnResource.left().value());
+                resource.getDeploymentArtifacts()
+                    .put(updateArtifactOnResource.left().value().getArtifactLabel(), updateArtifactOnResource.left().value());
                 resStatus = Either.left(updateArtifactOnResource.left().value());
             }
-
         }
         return resStatus;
     }
 
-    private Either<List<HeatParameterDefinition>, ResponseFormat> extractHeatParameters(String artifactType,
-            String fileName, byte[] content, boolean is64Encoded) {
+    private Either<List<HeatParameterDefinition>, ResponseFormat> extractHeatParameters(String artifactType, String fileName, byte[] content,
+                                                                                        boolean is64Encoded) {
         // extract heat parameters
         String heatDecodedPayload = is64Encoded ? new String(Base64.decodeBase64(content)) : new String(content);
         Either<List<HeatParameterDefinition>, ResultStatusEnum> heatParameters = ImportUtils
-                .getHeatParamsWithoutImplicitTypes(heatDecodedPayload, artifactType);
+            .getHeatParamsWithoutImplicitTypes(heatDecodedPayload, artifactType);
         if (heatParameters.isRight()) {
             log.debug("File {} is not in expected key-value form in csar ", fileName);
-            BeEcompErrorManager.getInstance().logInternalDataError(
-                    "File " + fileName + " is not in expected key-value form in csar ", "CSAR internals are invalid",
+            BeEcompErrorManager.getInstance()
+                .logInternalDataError("File " + fileName + " is not in expected key-value form in csar ", "CSAR internals are invalid",
                     ErrorSeverity.ERROR);
-            return Either
-                    .right(componentsUtils.getResponseFormat(ActionStatus.INVALID_DEPLOYMENT_ARTIFACT_HEAT, fileName));
-
+            return Either.right(componentsUtils.getResponseFormat(ActionStatus.INVALID_DEPLOYMENT_ARTIFACT_HEAT, fileName));
         }
         return Either.left(heatParameters.left().value());
-
     }
 
-    private Either<ArtifactDefinition, ResponseFormat> updateHeatParams(Component resource,
-            ArtifactDefinition currentInfo, List<HeatParameterDefinition> updatedHeatEnvParams) {
-
+    private Either<ArtifactDefinition, ResponseFormat> updateHeatParams(Component resource, ArtifactDefinition currentInfo,
+                                                                        List<HeatParameterDefinition> updatedHeatEnvParams) {
         Either<ArtifactDefinition, ResponseFormat> resStatus = Either.left(currentInfo);
         List<HeatParameterDefinition> currentHeatEnvParams = currentInfo.getListHeatParameters();
-
-        if (updatedHeatEnvParams != null && !updatedHeatEnvParams.isEmpty() && currentHeatEnvParams != null
-                && !currentHeatEnvParams.isEmpty()) {
-
+        if (updatedHeatEnvParams != null && !updatedHeatEnvParams.isEmpty() && currentHeatEnvParams != null && !currentHeatEnvParams.isEmpty()) {
             String paramName;
             for (HeatParameterDefinition heatEnvParam : updatedHeatEnvParams) {
-
                 paramName = heatEnvParam.getName();
                 for (HeatParameterDefinition currHeatParam : currentHeatEnvParams) {
                     if (paramName.equalsIgnoreCase(currHeatParam.getName())) {
-
                         String updatedParamValue = heatEnvParam.getCurrentValue();
                         if (updatedParamValue == null) {
                             updatedParamValue = heatEnvParam.getDefaultValue();
@@ -972,28 +835,24 @@ public class CsarArtifactsAndGroupsBusinessLogic extends BaseBusinessLogic {
                         HeatParameterType paramType = HeatParameterType.isValidType(currHeatParam.getType());
                         if (!paramType.getValidator().isValid(updatedParamValue, null)) {
                             ActionStatus status = ActionStatus.INVALID_HEAT_PARAMETER_VALUE;
-                            ResponseFormat responseFormat = componentsUtils.getResponseFormat(status,
-                                    ArtifactTypeEnum.HEAT_ENV.getType(), paramType.getType(), paramName);
+                            ResponseFormat responseFormat = componentsUtils
+                                .getResponseFormat(status, ArtifactTypeEnum.HEAT_ENV.getType(), paramType.getType(), paramName);
                             resStatus = Either.right(responseFormat);
                             return resStatus;
                         }
-                        currHeatParam.setCurrentValue(
-                                paramType.getConverter().convert(updatedParamValue, null, null));
-
+                        currHeatParam.setCurrentValue(paramType.getConverter().convert(updatedParamValue, null, null));
                         break;
                     }
                 }
             }
             currentInfo.setListHeatParameters(currentHeatEnvParams);
             Either<ArtifactDefinition, StorageOperationStatus> updateArtifactOnResource = artifactToscaOperation
-                    .updateArtifactOnResource(currentInfo, resource, currentInfo.getUniqueId(),
-                            null, null, true);
+                .updateArtifactOnResource(currentInfo, resource, currentInfo.getUniqueId(), null, null, true);
             if (updateArtifactOnResource.isRight()) {
-                log.debug(
-                        "Failed to update heat parameters of heat on CSAR flow for component {} artifact {} label {}",
-                        resource.getUniqueId(), currentInfo.getUniqueId(), currentInfo.getArtifactLabel());
-                return Either.right(componentsUtils.getResponseFormat(
-                        componentsUtils.convertFromStorageResponse(updateArtifactOnResource.right().value())));
+                log.debug("Failed to update heat parameters of heat on CSAR flow for component {} artifact {} label {}", resource.getUniqueId(),
+                    currentInfo.getUniqueId(), currentInfo.getArtifactLabel());
+                return Either
+                    .right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(updateArtifactOnResource.right().value())));
             }
             resource.getDeploymentArtifacts().put(currentInfo.getArtifactLabel(), currentInfo);
             resStatus = Either.left(updateArtifactOnResource.left().value());
@@ -1001,17 +860,15 @@ public class CsarArtifactsAndGroupsBusinessLogic extends BaseBusinessLogic {
         return resStatus;
     }
 
-    public Either<Either<ArtifactDefinition, Operation>, ResponseFormat> createOrUpdateCsarArtifactFromJson(
-            Component component, User user, Map<String, Object> json, ArtifactOperationInfo operation) {
-
+    public Either<Either<ArtifactDefinition, Operation>, ResponseFormat> createOrUpdateCsarArtifactFromJson(Component component, User user,
+                                                                                                            Map<String, Object> json,
+                                                                                                            ArtifactOperationInfo operation) {
         String jsonStr = gson.toJson(json);
-        ArtifactDefinition artifactDefinitionFromJson = RepresentationUtils.convertJsonToArtifactDefinition(jsonStr,
-                ArtifactDefinition.class, false);
-
+        ArtifactDefinition artifactDefinitionFromJson = RepresentationUtils.convertJsonToArtifactDefinition(jsonStr, ArtifactDefinition.class, false);
         Either<ArtifactDefinition, Operation> result;
         try {
-             result = artifactsBusinessLogic.handleLoadedArtifact(
-                     component, user, operation, false, true, component.getComponentType(), artifactDefinitionFromJson);
+            result = artifactsBusinessLogic
+                .handleLoadedArtifact(component, user, operation, false, true, component.getComponentType(), artifactDefinitionFromJson);
         } catch (ComponentException e) {
             log.debug(FAILED_UPLOAD_ARTIFACT_TO_COMPONENT, component.getComponentType(), component.getName());
             return Either.right(componentsUtils.getResponseFormat(e));
@@ -1023,9 +880,8 @@ public class CsarArtifactsAndGroupsBusinessLogic extends BaseBusinessLogic {
         return Either.left(result);
     }
 
-    private void associateMembersToArtifacts(List<ArtifactDefinition> createdArtifacts,
-            List<ArtifactDefinition> artifactsFromResource, List<GroupDefinition> heatGroups,
-            Set<String> artifactsGroup, Map<String, String> members) {
+    private void associateMembersToArtifacts(List<ArtifactDefinition> createdArtifacts, List<ArtifactDefinition> artifactsFromResource,
+                                             List<GroupDefinition> heatGroups, Set<String> artifactsGroup, Map<String, String> members) {
         if (heatGroups != null && !heatGroups.isEmpty()) {
             for (GroupDefinition heatGroup : heatGroups) {
                 List<GroupProperty> grpoupProps = heatGroup.convertToGroupProperties();
@@ -1036,9 +892,10 @@ public class CsarArtifactsAndGroupsBusinessLogic extends BaseBusinessLogic {
         }
     }
 
-    private void associateMembersToVFgroups(List<ArtifactDefinition> createdArtifacts, List<ArtifactDefinition> artifactsFromResource, List<GroupProperty> grpoupProps, Set<String> artifactsGroup, GroupDefinition heatGroup, Map<String, String> members){
-        Optional<GroupProperty> op = grpoupProps.stream()
-                .filter(p -> p.getName().equals(Constants.HEAT_FILE_PROPS)).findAny();
+    private void associateMembersToVFgroups(List<ArtifactDefinition> createdArtifacts, List<ArtifactDefinition> artifactsFromResource,
+                                            List<GroupProperty> grpoupProps, Set<String> artifactsGroup, GroupDefinition heatGroup,
+                                            Map<String, String> members) {
+        Optional<GroupProperty> op = grpoupProps.stream().filter(p -> p.getName().equals(Constants.HEAT_FILE_PROPS)).findAny();
         if (op.isPresent()) {
             GroupProperty prop = op.get();
             String heatFileNAme = prop.getValue();
@@ -1047,26 +904,22 @@ public class CsarArtifactsAndGroupsBusinessLogic extends BaseBusinessLogic {
             }
             List<ArtifactDefinition> artifacts = new ArrayList<>();
             for (String artifactId : artifactsGroup) {
-                Optional<ArtifactDefinition> opArt = createdArtifacts.stream()
-                        .filter(p -> p.getUniqueId().equals(artifactId)).findAny();
+                Optional<ArtifactDefinition> opArt = createdArtifacts.stream().filter(p -> p.getUniqueId().equals(artifactId)).findAny();
                 opArt.ifPresent(artifacts::add);
                 if (artifactsFromResource != null) {
-                    opArt = artifactsFromResource.stream().filter(p -> p.getUniqueId().equals(artifactId))
-                            .findAny();
+                    opArt = artifactsFromResource.stream().filter(p -> p.getUniqueId().equals(artifactId)).findAny();
                     opArt.ifPresent(artifacts::add);
                 }
             }
-            Optional<ArtifactDefinition> resOp = artifacts.stream()
-                    .filter(p -> heatFileNAme.contains(p.getArtifactName())).findAny();
+            Optional<ArtifactDefinition> resOp = artifacts.stream().filter(p -> heatFileNAme.contains(p.getArtifactName())).findAny();
             resOp.ifPresent(artifactDefinition -> members.putAll(heatGroup.getMembers()));
         }
     }
 
-    public List<GroupProperty> createVfModuleAdditionalProperties(boolean isBase, String moduleName,
-            List<GroupProperty> properties, List<ArtifactDefinition> deploymentArtifacts, List<String> artifactsInGroup,
-            GroupTypeDefinition groupType) {
-        Map<String, VfModuleProperty> vfModuleProperties = ConfigurationManager.getConfigurationManager()
-                .getConfiguration().getVfModuleProperties();
+    public List<GroupProperty> createVfModuleAdditionalProperties(boolean isBase, String moduleName, List<GroupProperty> properties,
+                                                                  List<ArtifactDefinition> deploymentArtifacts, List<String> artifactsInGroup,
+                                                                  GroupTypeDefinition groupType) {
+        Map<String, VfModuleProperty> vfModuleProperties = ConfigurationManager.getConfigurationManager().getConfiguration().getVfModuleProperties();
         vfModuleProperties.entrySet().forEach(p -> {
             GroupProperty prop = new GroupProperty();
             prop.setName(p.getKey());
@@ -1078,13 +931,10 @@ public class CsarArtifactsAndGroupsBusinessLogic extends BaseBusinessLogic {
                 prop.setDefaultValue(p.getValue().getForNonBaseModule());
             }
             properties.add(prop);
-
         });
         GroupProperty proplabel = new GroupProperty();
         proplabel.setName("vf_module_label");
-
         Matcher matcher = pattern.matcher(moduleName);
-
         if (matcher.find()) {
             proplabel.setValue(matcher.group(1));
             proplabel.setDefaultValue(matcher.group(1));
@@ -1093,15 +943,13 @@ public class CsarArtifactsAndGroupsBusinessLogic extends BaseBusinessLogic {
             proplabel.setDefaultValue(moduleName);
         }
         properties.add(proplabel);
-
         GroupProperty propvolume = new GroupProperty();
         propvolume.setName("volume_group");
         boolean isVolume = false;
         for (String artifactId : artifactsInGroup) {
             ArtifactDefinition artifactDef = null;
             artifactDef = ArtifactUtils.findArtifactInList(deploymentArtifacts, artifactId);
-            if (artifactDef != null
-                    && artifactDef.getArtifactType().equalsIgnoreCase(ArtifactTypeEnum.HEAT_VOL.getType())) {
+            if (artifactDef != null && artifactDef.getArtifactType().equalsIgnoreCase(ArtifactTypeEnum.HEAT_VOL.getType())) {
                 isVolume = true;
                 break;
             }
@@ -1113,11 +961,8 @@ public class CsarArtifactsAndGroupsBusinessLogic extends BaseBusinessLogic {
         return properties;
     }
 
-    private void mergeWithGroupTypeProperties(List<GroupProperty> properties,
-            List<PropertyDefinition> groupTypeProperties) {
-
-        Map<String, GroupProperty> propertiesMap = properties.stream()
-                .collect(Collectors.toMap(PropertyDataDefinition::getName, p -> p));
+    private void mergeWithGroupTypeProperties(List<GroupProperty> properties, List<PropertyDefinition> groupTypeProperties) {
+        Map<String, GroupProperty> propertiesMap = properties.stream().collect(Collectors.toMap(PropertyDataDefinition::getName, p -> p));
         for (PropertyDefinition groupTypeProperty : groupTypeProperties) {
             if (!propertiesMap.containsKey(groupTypeProperty.getName())) {
                 properties.add(new GroupProperty(groupTypeProperty));
@@ -1126,50 +971,53 @@ public class CsarArtifactsAndGroupsBusinessLogic extends BaseBusinessLogic {
     }
 
     private Map<GroupDefinition, MergedArtifactInfo> mergeGroupInUpdateFlow(
-            Map<GroupDefinition, Map<ArtifactDefinition, List<ArtifactDefinition>>> groupArtifact,
-            Map<ArtifactTemplateInfo, Set<ArtifactTemplateInfo>> parsedGroup, Set<ArtifactDefinition> artifactsToDelete,
-            Map<String, List<ArtifactDefinition>> groupToDelete, Set<ArtifactTemplateInfo> jsonMasterArtifacts,
-            List<ArtifactDefinition> createdDeploymentArtifacts) {
+        Map<GroupDefinition, Map<ArtifactDefinition, List<ArtifactDefinition>>> groupArtifact,
+        Map<ArtifactTemplateInfo, Set<ArtifactTemplateInfo>> parsedGroup, Set<ArtifactDefinition> artifactsToDelete,
+        Map<String, List<ArtifactDefinition>> groupToDelete, Set<ArtifactTemplateInfo> jsonMasterArtifacts,
+        List<ArtifactDefinition> createdDeploymentArtifacts) {
         Map<GroupDefinition, MergedArtifactInfo> mergedgroup = new HashMap<>();
-        for (Entry<GroupDefinition, Map<ArtifactDefinition, List<ArtifactDefinition>>> groupListEntry : groupArtifact
-                .entrySet()) {
+        for (Entry<GroupDefinition, Map<ArtifactDefinition, List<ArtifactDefinition>>> groupListEntry : groupArtifact.entrySet()) {
             Map<ArtifactDefinition, List<ArtifactDefinition>> createdArtifactMap = groupListEntry.getValue();
             boolean isNeedToDeleteGroup = true;
             List<ArtifactDefinition> listToDelete = null;
             for (ArtifactDefinition maserArtifact : createdArtifactMap.keySet()) {
-                listToDelete = prepareArtifactsToDelete(parsedGroup, artifactsToDelete, createdDeploymentArtifacts, createdArtifactMap, maserArtifact);
+                listToDelete = prepareArtifactsToDelete(parsedGroup, artifactsToDelete, createdDeploymentArtifacts, createdArtifactMap,
+                    maserArtifact);
                 if (artifactsToDelete != null && !artifactsToDelete.isEmpty()) {
                     GroupDefinition group = groupListEntry.getKey();
                     deleteArtifacts(artifactsToDelete, group);
-
                 }
-
                 for (ArtifactTemplateInfo jsonMasterArtifact : jsonMasterArtifacts) {
-                    isNeedToDeleteGroup = isNeedToDeleteGroup(mergedgroup, groupListEntry, createdArtifactMap, isNeedToDeleteGroup, maserArtifact, jsonMasterArtifact);
+                    isNeedToDeleteGroup = isNeedToDeleteGroup(mergedgroup, groupListEntry, createdArtifactMap, isNeedToDeleteGroup, maserArtifact,
+                        jsonMasterArtifact);
                 }
-
             }
             if (isNeedToDeleteGroup) {
                 groupToDelete.put(groupListEntry.getKey().getUniqueId(), listToDelete);
             }
-
         }
         return mergedgroup;
     }
 
-    private boolean isNeedToDeleteGroup(Map<GroupDefinition, MergedArtifactInfo> mergedgroup, Entry<GroupDefinition, Map<ArtifactDefinition, List<ArtifactDefinition>>> groupListEntry, Map<ArtifactDefinition, List<ArtifactDefinition>> createdArtifactMap, boolean isNeedToDeleteGroup, ArtifactDefinition maserArtifact, ArtifactTemplateInfo jsonMasterArtifact) {
+    private boolean isNeedToDeleteGroup(Map<GroupDefinition, MergedArtifactInfo> mergedgroup,
+                                        Entry<GroupDefinition, Map<ArtifactDefinition, List<ArtifactDefinition>>> groupListEntry,
+                                        Map<ArtifactDefinition, List<ArtifactDefinition>> createdArtifactMap, boolean isNeedToDeleteGroup,
+                                        ArtifactDefinition maserArtifact, ArtifactTemplateInfo jsonMasterArtifact) {
         if (maserArtifact.getArtifactName().equalsIgnoreCase(jsonMasterArtifact.getFileName())) {
             MergedArtifactInfo mergedGroup = new MergedArtifactInfo();
             mergedGroup.setJsonArtifactTemplate(jsonMasterArtifact);
             mergedGroup.setCreatedArtifact(createdArtifactMap.get(maserArtifact));
             mergedgroup.put(groupListEntry.getKey(), mergedGroup);
             isNeedToDeleteGroup = false;
-
         }
         return isNeedToDeleteGroup;
     }
 
-    private List<ArtifactDefinition> prepareArtifactsToDelete(Map<ArtifactTemplateInfo, Set<ArtifactTemplateInfo>> parsedGroup, Set<ArtifactDefinition> artifactsToDelete, List<ArtifactDefinition> createdDeploymentArtifacts, Map<ArtifactDefinition, List<ArtifactDefinition>> createdArtifactMap, ArtifactDefinition maserArtifact) {
+    private List<ArtifactDefinition> prepareArtifactsToDelete(Map<ArtifactTemplateInfo, Set<ArtifactTemplateInfo>> parsedGroup,
+                                                              Set<ArtifactDefinition> artifactsToDelete,
+                                                              List<ArtifactDefinition> createdDeploymentArtifacts,
+                                                              Map<ArtifactDefinition, List<ArtifactDefinition>> createdArtifactMap,
+                                                              ArtifactDefinition maserArtifact) {
         List<ArtifactDefinition> listToDelete;
         listToDelete = createdArtifactMap.get(maserArtifact);
         for (ArtifactDefinition artToDelete : listToDelete) {
@@ -1180,92 +1028,76 @@ public class CsarArtifactsAndGroupsBusinessLogic extends BaseBusinessLogic {
 
     private void deleteArtifacts(Set<ArtifactDefinition> artifactsToDelete, GroupDefinition group) {
         for (ArtifactDefinition artifactDefinition : artifactsToDelete) {
-            if (CollectionUtils.isNotEmpty(group.getArtifacts())
-                    && group.getArtifacts().contains(artifactDefinition.getUniqueId())) {
+            if (CollectionUtils.isNotEmpty(group.getArtifacts()) && group.getArtifacts().contains(artifactDefinition.getUniqueId())) {
                 group.getArtifacts().remove(artifactDefinition.getUniqueId());
-
             }
-            if (CollectionUtils.isNotEmpty(group.getArtifactsUuid())
-                    && group.getArtifactsUuid().contains(artifactDefinition.getArtifactUUID())) {
+            if (CollectionUtils.isNotEmpty(group.getArtifactsUuid()) && group.getArtifactsUuid().contains(artifactDefinition.getArtifactUUID())) {
                 group.getArtifactsUuid().remove(artifactDefinition.getArtifactUUID());
-
             }
         }
     }
 
-    private void findArtifactToDelete(Map<ArtifactTemplateInfo, Set<ArtifactTemplateInfo>> parsedGroup,
-            Set<ArtifactDefinition> artifactsToDelete, ArtifactDefinition artifact,
-            List<ArtifactDefinition> createdDeploymentArtifacts) {
+    private void findArtifactToDelete(Map<ArtifactTemplateInfo, Set<ArtifactTemplateInfo>> parsedGroup, Set<ArtifactDefinition> artifactsToDelete,
+                                      ArtifactDefinition artifact, List<ArtifactDefinition> createdDeploymentArtifacts) {
         boolean isNeedToDeleteArtifact = true;
         String artifactType = artifact.getArtifactType();
         ArtifactDefinition generatedFromArt = null;
         if (artifact.getGeneratedFromId() != null && !artifact.getGeneratedFromId().isEmpty()) {
-            Optional<ArtifactDefinition> op = createdDeploymentArtifacts.stream()
-                    .filter(p -> p.getUniqueId().equals(artifact.getGeneratedFromId())).findAny();
+            Optional<ArtifactDefinition> op = createdDeploymentArtifacts.stream().filter(p -> p.getUniqueId().equals(artifact.getGeneratedFromId()))
+                .findAny();
             if (op.isPresent()) {
                 generatedFromArt = op.get();
             }
-
         }
-
         isNeedToDeleteArtifact(parsedGroup, artifactsToDelete, artifact, isNeedToDeleteArtifact, artifactType, generatedFromArt);
     }
 
-    private void isNeedToDeleteArtifact(Map<ArtifactTemplateInfo, Set<ArtifactTemplateInfo>> parsedGroup, Set<ArtifactDefinition>
-            artifactsToDelete, ArtifactDefinition artifact, boolean isNeedToDeleteArtifact, String artifactType, ArtifactDefinition generatedFromArt) {
-
+    private void isNeedToDeleteArtifact(Map<ArtifactTemplateInfo, Set<ArtifactTemplateInfo>> parsedGroup, Set<ArtifactDefinition> artifactsToDelete,
+                                        ArtifactDefinition artifact, boolean isNeedToDeleteArtifact, String artifactType,
+                                        ArtifactDefinition generatedFromArt) {
         for (Entry<ArtifactTemplateInfo, Set<ArtifactTemplateInfo>> parsedGroupSetEntry : parsedGroup.entrySet()) {
             Set<ArtifactTemplateInfo> artifactsNames = parsedGroupSetEntry.getValue();
             for (ArtifactTemplateInfo template : artifactsNames) {
-                if (artifact.getArtifactName().equalsIgnoreCase(template.getFileName())
-                        && artifactType.equalsIgnoreCase(template.getType())) {
+                if (artifact.getArtifactName().equalsIgnoreCase(template.getFileName()) && artifactType.equalsIgnoreCase(template.getType())) {
                     isNeedToDeleteArtifact = false;
                     break;
                 } else {
-                    if (generatedFromArt != null
-                            && generatedFromArt.getArtifactName().equalsIgnoreCase(template.getFileName())
-                            && generatedFromArt.getArtifactType().equalsIgnoreCase(template.getType())) {
-                            isNeedToDeleteArtifact = false;
-                            break;
+                    if (generatedFromArt != null && generatedFromArt.getArtifactName().equalsIgnoreCase(template.getFileName()) && generatedFromArt
+                        .getArtifactType().equalsIgnoreCase(template.getType())) {
+                        isNeedToDeleteArtifact = false;
+                        break;
                     }
                 }
             }
-
         }
         if (isNeedToDeleteArtifact) {
             artifactsToDelete.add(artifact);
-
         }
     }
 
-    private Map<GroupDefinition, Map<ArtifactDefinition, List<ArtifactDefinition>>> findMasterArtifactInGroup(
-            List<GroupDefinition> groups, Map<String, ArtifactDefinition> deploymentArtifact) {
+    private Map<GroupDefinition, Map<ArtifactDefinition, List<ArtifactDefinition>>> findMasterArtifactInGroup(List<GroupDefinition> groups,
+                                                                                                              Map<String, ArtifactDefinition> deploymentArtifact) {
         Map<GroupDefinition, Map<ArtifactDefinition, List<ArtifactDefinition>>> groupArtifact = new HashMap<>();
-
         for (GroupDefinition group : groups) {
             Map<ArtifactDefinition, List<ArtifactDefinition>> gupsMap = new HashMap<>();
             List<ArtifactDefinition> artifacts = new ArrayList<>();
             List<String> artifactsList = group.getArtifacts();
             if (artifactsList != null && !artifactsList.isEmpty()) {
-
-                ArtifactDefinition masterArtifact = ArtifactUtils.findMasterArtifact(deploymentArtifact, artifacts,
-                        artifactsList);
+                ArtifactDefinition masterArtifact = ArtifactUtils.findMasterArtifact(deploymentArtifact, artifacts, artifactsList);
                 if (masterArtifact != null) {
                     gupsMap.put(masterArtifact, artifacts);
                 }
                 groupArtifact.put(group, gupsMap);
-
             }
         }
         return groupArtifact;
     }
 
-    private Either<Component, ResponseFormat> deleteArtifactsInUpdateCsarFlow(Component resource,
-            User user, boolean shouldLock, boolean inTransaction, Set<ArtifactDefinition> artifactsToDelete,
-            Map<String, List<ArtifactDefinition>> groupToDelete, List<ArtifactDefinition> deletedArtifacts) {
-
+    private Either<Component, ResponseFormat> deleteArtifactsInUpdateCsarFlow(Component resource, User user, boolean shouldLock,
+                                                                              boolean inTransaction, Set<ArtifactDefinition> artifactsToDelete,
+                                                                              Map<String, List<ArtifactDefinition>> groupToDelete,
+                                                                              List<ArtifactDefinition> deletedArtifacts) {
         Component updatedResource = resource;
-
         String resourceId = updatedResource.getUniqueId();
         if (!artifactsToDelete.isEmpty()) {
             for (ArtifactDefinition artifact : artifactsToDelete) {
@@ -1273,16 +1105,12 @@ public class CsarArtifactsAndGroupsBusinessLogic extends BaseBusinessLogic {
                 final ArtifactTypeEnum artifactTypeEnum = ArtifactTypeEnum.parse(artifactType);
                 if (artifactTypeEnum != ArtifactTypeEnum.HEAT_ENV) {
                     Either<ArtifactDefinition, ResponseFormat> handleDelete = artifactsBusinessLogic
-                            .handleDelete(resourceId, artifact.getUniqueId(), user,
-                                updatedResource, shouldLock, inTransaction);
-
+                        .handleDelete(resourceId, artifact.getUniqueId(), user, updatedResource, shouldLock, inTransaction);
                     if (handleDelete.isRight()) {
                         return Either.right(handleDelete.right().value());
                     }
-
                     deletedArtifacts.add(handleDelete.left().value());
                 }
-
             }
         }
         if (!groupToDelete.isEmpty()) {
@@ -1290,12 +1118,10 @@ public class CsarArtifactsAndGroupsBusinessLogic extends BaseBusinessLogic {
             List<GroupDefinition> groupDefinitionstoDelete = new ArrayList<>();
             List<GroupDefinition> groups = updatedResource.getGroups();
             for (Entry<String, List<ArtifactDefinition>> deleteGroup : groupToDelete.entrySet()) {
-                Optional<GroupDefinition> op = groups.stream()
-                        .filter(gr -> gr.getUniqueId().equals(deleteGroup.getKey())).findAny();
+                Optional<GroupDefinition> op = groups.stream().filter(gr -> gr.getUniqueId().equals(deleteGroup.getKey())).findAny();
                 if (op.isPresent()) {
                     groupDefinitionstoDelete.add(op.get());
                 }
-
             }
             if (!groupDefinitionstoDelete.isEmpty()) {
                 Either<List<GroupDefinition>, ResponseFormat> prepareGroups = groupBusinessLogic.deleteGroups(resource, groupDefinitionstoDelete);
@@ -1305,23 +1131,19 @@ public class CsarArtifactsAndGroupsBusinessLogic extends BaseBusinessLogic {
             }
         }
         List<GroupDefinition> oldGroups = updatedResource.getGroups();
-        Either<Resource, StorageOperationStatus> eitherGerResource = toscaOperationFacade
-                .getToscaElement(updatedResource.getUniqueId());
+        Either<Resource, StorageOperationStatus> eitherGerResource = toscaOperationFacade.getToscaElement(updatedResource.getUniqueId());
         if (eitherGerResource.isRight()) {
-            ResponseFormat responseFormat = componentsUtils.getResponseFormatByComponent(
-                    componentsUtils.convertFromStorageResponse(eitherGerResource.right().value()), updatedResource, resource.getComponentType());
-
+            ResponseFormat responseFormat = componentsUtils
+                .getResponseFormatByComponent(componentsUtils.convertFromStorageResponse(eitherGerResource.right().value()), updatedResource,
+                    resource.getComponentType());
             return Either.right(responseFormat);
-
         }
         updatedResource = eitherGerResource.left().value();
         updatedResource.setGroups(oldGroups);
         return Either.left(updatedResource);
     }
 
-    private void createArtifactsGroupSet(List<ArtifactTemplateInfo> parsedGroupTemplateList,
-            Set<ArtifactTemplateInfo> parsedArtifactsName) {
-
+    private void createArtifactsGroupSet(List<ArtifactTemplateInfo> parsedGroupTemplateList, Set<ArtifactTemplateInfo> parsedArtifactsName) {
         for (ArtifactTemplateInfo parsedGroupTemplate : parsedGroupTemplateList) {
             parsedArtifactsName.add(parsedGroupTemplate);
             List<ArtifactTemplateInfo> relatedArtifacts = parsedGroupTemplate.getRelatedArtifactsInfo();
@@ -1331,68 +1153,58 @@ public class CsarArtifactsAndGroupsBusinessLogic extends BaseBusinessLogic {
         }
     }
 
-    private Either<Component, ResponseFormat> createGroupDeploymentArtifactsFromCsar(CsarInfo csarInfo,
-            Component resource, List<ArtifactTemplateInfo> artifactsTemplateList,
-            List<ArtifactDefinition> createdNewArtifacts, List<ArtifactDefinition> artifactsFromResource,
-            int labelCounter) {
-
+    private Either<Component, ResponseFormat> createGroupDeploymentArtifactsFromCsar(CsarInfo csarInfo, Component resource,
+                                                                                     List<ArtifactTemplateInfo> artifactsTemplateList,
+                                                                                     List<ArtifactDefinition> createdNewArtifacts,
+                                                                                     List<ArtifactDefinition> artifactsFromResource,
+                                                                                     int labelCounter) {
         Component updatedResource = resource;
-
         Either<Component, ResponseFormat> resStatus = Either.left(updatedResource);
         List<GroupDefinition> createdGroups = updatedResource.getGroups();
         List<GroupDefinition> heatGroups = null;
         if (createdGroups != null && !createdGroups.isEmpty()) {
             heatGroups = collectGroupsWithMembers(createdGroups);
         }
-
         List<GroupDefinition> needToAdd = new ArrayList<>();
         for (ArtifactTemplateInfo groupTemplateInfo : artifactsTemplateList) {
             String groupName = groupTemplateInfo.getGroupName();
             Set<String> artifactsGroup = new HashSet<>();
             Set<String> artifactsUUIDGroup = new HashSet<>();
-
-            resStatus = createDeploymentArtifactsFromCsar(csarInfo, updatedResource, artifactsGroup, artifactsUUIDGroup,
-                    groupTemplateInfo, createdNewArtifacts, artifactsFromResource, labelCounter);
+            resStatus = createDeploymentArtifactsFromCsar(csarInfo, updatedResource, artifactsGroup, artifactsUUIDGroup, groupTemplateInfo,
+                createdNewArtifacts, artifactsFromResource, labelCounter);
             if (resStatus.isRight()) {
                 return resStatus;
             }
             if (!StringUtils.isEmpty(groupName)) {
                 Map<String, String> members = new HashMap<>();
-                associateMembersToArtifacts(createdNewArtifacts, artifactsFromResource, heatGroups, artifactsGroup,
-                        members);
-
+                associateMembersToArtifacts(createdNewArtifacts, artifactsFromResource, heatGroups, artifactsGroup, members);
                 List<String> artifactsList = new ArrayList<>(artifactsGroup);
                 List<String> artifactsUUIDList = new ArrayList<>(artifactsUUIDGroup);
-
                 GroupDefinition groupDefinition = new GroupDefinition();
                 groupDefinition.setName(groupName);
                 groupDefinition.setType(Constants.DEFAULT_GROUP_VF_MODULE);
                 groupDefinition.setArtifacts(artifactsList);
                 groupDefinition.setArtifactsUuid(artifactsUUIDList);
-
                 if (!members.isEmpty()) {
                     groupDefinition.setMembers(members);
                 }
-
                 List<GroupProperty> properties = new ArrayList<>();
                 GroupProperty prop = new GroupProperty();
                 prop.setName(Constants.IS_BASE);
                 prop.setValue(Boolean.toString(groupTemplateInfo.isBase()));
                 properties.add(prop);
-
                 List<ArtifactDefinition> createdArtifacts = new ArrayList<>();
                 createdArtifacts.addAll(createdNewArtifacts);
                 createdArtifacts.addAll(artifactsFromResource);
                 Either<GroupTypeDefinition, StorageOperationStatus> getLatestGroupTypeRes = groupTypeOperation
-                        .getLatestGroupTypeByType(Constants.DEFAULT_GROUP_VF_MODULE, true);
+                    .getLatestGroupTypeByType(Constants.DEFAULT_GROUP_VF_MODULE, true);
                 if (getLatestGroupTypeRes.isRight()) {
-                    return Either.right(componentsUtils.getResponseFormat(
-                            componentsUtils.convertFromStorageResponse(getLatestGroupTypeRes.right().value())));
+                    return Either
+                        .right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(getLatestGroupTypeRes.right().value())));
                 }
-                properties = createVfModuleAdditionalProperties(groupTemplateInfo.isBase(), groupName, properties,
-                        createdArtifacts, artifactsList, getLatestGroupTypeRes.left().value());
+                properties = createVfModuleAdditionalProperties(groupTemplateInfo.isBase(), groupName, properties, createdArtifacts, artifactsList,
+                    getLatestGroupTypeRes.left().value());
                 groupDefinition.convertFromGroupProperties(properties);
-
                 needToAdd.add(groupDefinition);
             }
         }
@@ -1401,32 +1213,30 @@ public class CsarArtifactsAndGroupsBusinessLogic extends BaseBusinessLogic {
         componentParametersView.setIgnoreArtifacts(false);
         componentParametersView.setIgnoreGroups(false);
         componentParametersView.setIgnoreComponentInstances(false);
-
         Either<Resource, StorageOperationStatus> component = toscaOperationFacade
-                .getToscaElement(updatedResource.getUniqueId(), componentParametersView);
+            .getToscaElement(updatedResource.getUniqueId(), componentParametersView);
         if (component.isRight()) {
             return Either.right(componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR));
         }
         updatedResource = component.left().value();
-
-         Either<List<GroupDefinition>, ResponseFormat> addGroups = groupBusinessLogic.addGroups(updatedResource, needToAdd, false);
+        Either<List<GroupDefinition>, ResponseFormat> addGroups = groupBusinessLogic.addGroups(updatedResource, needToAdd, false);
         if (addGroups.isRight()) {
             return Either.right(addGroups.right().value());
         }
-
         return resStatus;
     }
 
-    private Either<Component, ResponseFormat> createDeploymentArtifactsFromCsar(CsarInfo csarInfo, Component resource,
-            Set<String> artifactsGroup, Set<String> artifactsUUIDGroup, ArtifactTemplateInfo artifactTemplateInfo,
-            List<ArtifactDefinition> createdArtifacts, List<ArtifactDefinition> artifactsFromResource, int labelCounter) {
+    private Either<Component, ResponseFormat> createDeploymentArtifactsFromCsar(CsarInfo csarInfo, Component resource, Set<String> artifactsGroup,
+                                                                                Set<String> artifactsUUIDGroup,
+                                                                                ArtifactTemplateInfo artifactTemplateInfo,
+                                                                                List<ArtifactDefinition> createdArtifacts,
+                                                                                List<ArtifactDefinition> artifactsFromResource, int labelCounter) {
         Either<Component, ResponseFormat> resStatus = Either.left(resource);
         String artifactFileName = artifactTemplateInfo.getFileName();
         String artifactUid = "";
         String artifactUUID = "";
         String artifactEnvUid = "";
         boolean alreadyExist = false;
-
         // check if artifacts already exist
         if (artifactsFromResource != null && !artifactsFromResource.isEmpty()) {
             for (ArtifactDefinition artifactFromResource : artifactsFromResource) {
@@ -1434,51 +1244,44 @@ public class CsarArtifactsAndGroupsBusinessLogic extends BaseBusinessLogic {
                     artifactUid = artifactFromResource.getUniqueId();
                     artifactUUID = artifactFromResource.getArtifactUUID();
                     if (!artifactFromResource.getArtifactType().equalsIgnoreCase(artifactTemplateInfo.getType())) {
-                        log.debug(ARTIFACT_WITH_NAME_AND_TYPE_ALREADY_EXIST_WITH_TYPE, artifactFileName,
-                                artifactTemplateInfo.getType(), artifactFromResource.getArtifactType());
-                        BeEcompErrorManager.getInstance().logInternalDataError(
-                                ARTIFACT_FILE_IS_NOT_IN_EXPECTED_FORMAT_FILE_NAME + artifactFileName,
-                                ARTIFACT_INTERNALS_ARE_INVALID, ErrorSeverity.ERROR);
-                        return Either.right(componentsUtils.getResponseFormat(
-                                ActionStatus.ARTIFACT_ALREADY_EXIST_IN_DIFFERENT_TYPE_IN_CSAR, artifactFileName,
+                        log.debug(ARTIFACT_WITH_NAME_AND_TYPE_ALREADY_EXIST_WITH_TYPE, artifactFileName, artifactTemplateInfo.getType(),
+                            artifactFromResource.getArtifactType());
+                        BeEcompErrorManager.getInstance().logInternalDataError(ARTIFACT_FILE_IS_NOT_IN_EXPECTED_FORMAT_FILE_NAME + artifactFileName,
+                            ARTIFACT_INTERNALS_ARE_INVALID, ErrorSeverity.ERROR);
+                        return Either.right(componentsUtils
+                            .getResponseFormat(ActionStatus.ARTIFACT_ALREADY_EXIST_IN_DIFFERENT_TYPE_IN_CSAR, artifactFileName,
                                 artifactTemplateInfo.getType(), artifactFromResource.getArtifactType()));
                     }
                     alreadyExist = true;
                     artifactEnvUid = checkAndGetHeatEnvId(artifactFromResource);
                     break;
                 }
-
             }
-
         }
         if (!alreadyExist) {
             for (ArtifactDefinition createdArtifact : createdArtifacts) {
                 if (createdArtifact.getArtifactName().equals(artifactFileName)) {
                     artifactUid = createdArtifact.getUniqueId();
                     artifactUUID = createdArtifact.getArtifactUUID();
-
                     if (!createdArtifact.getArtifactType().equalsIgnoreCase(artifactTemplateInfo.getType())) {
-                        log.debug(ARTIFACT_WITH_NAME_AND_TYPE_ALREADY_EXIST_WITH_TYPE, artifactFileName,
-                                artifactTemplateInfo.getType(), createdArtifact.getArtifactType());
-                        BeEcompErrorManager.getInstance().logInternalDataError(
-                                ARTIFACT_FILE_IS_NOT_IN_EXPECTED_FORMAT_FILE_NAME + artifactFileName,
-                                ARTIFACT_INTERNALS_ARE_INVALID, ErrorSeverity.ERROR);
-                        return Either.right(componentsUtils.getResponseFormat(
-                                ActionStatus.ARTIFACT_ALREADY_EXIST_IN_DIFFERENT_TYPE_IN_CSAR, artifactFileName,
+                        log.debug(ARTIFACT_WITH_NAME_AND_TYPE_ALREADY_EXIST_WITH_TYPE, artifactFileName, artifactTemplateInfo.getType(),
+                            createdArtifact.getArtifactType());
+                        BeEcompErrorManager.getInstance().logInternalDataError(ARTIFACT_FILE_IS_NOT_IN_EXPECTED_FORMAT_FILE_NAME + artifactFileName,
+                            ARTIFACT_INTERNALS_ARE_INVALID, ErrorSeverity.ERROR);
+                        return Either.right(componentsUtils
+                            .getResponseFormat(ActionStatus.ARTIFACT_ALREADY_EXIST_IN_DIFFERENT_TYPE_IN_CSAR, artifactFileName,
                                 artifactTemplateInfo.getType(), createdArtifact.getArtifactType()));
                     }
                     alreadyExist = true;
                     artifactEnvUid = checkAndGetHeatEnvId(createdArtifact);
                     break;
                 }
-
             }
         }
         // if not exist need to create
         if (!alreadyExist) {
-
-            Either<ArtifactDefinition, ResponseFormat> newArtifactEither = createDeploymentArtifact(csarInfo, resource,
-                    ARTIFACTS_PATH, artifactTemplateInfo, createdArtifacts, labelCounter);
+            Either<ArtifactDefinition, ResponseFormat> newArtifactEither = createDeploymentArtifact(csarInfo, resource, ARTIFACTS_PATH,
+                artifactTemplateInfo, createdArtifacts, labelCounter);
             if (newArtifactEither.isRight()) {
                 resStatus = Either.right(newArtifactEither.right().value());
                 return resStatus;
@@ -1487,27 +1290,23 @@ public class CsarArtifactsAndGroupsBusinessLogic extends BaseBusinessLogic {
             artifactUid = newArtifact.getUniqueId();
             artifactUUID = newArtifact.getArtifactUUID();
             final ArtifactTypeEnum artifactType = ArtifactTypeEnum.parse(newArtifact.getArtifactType());
-            if (artifactType == ArtifactTypeEnum.HEAT || artifactType == ArtifactTypeEnum.HEAT_NET
-                    || artifactType == ArtifactTypeEnum.HEAT_VOL) {
+            if (artifactType == ArtifactTypeEnum.HEAT || artifactType == ArtifactTypeEnum.HEAT_NET || artifactType == ArtifactTypeEnum.HEAT_VOL) {
                 ArtifactDefinition createHeatEnvPlaceHolder = artifactsBusinessLogic
-                        .createHeatEnvPlaceHolder(createdArtifacts, newArtifact, ArtifactsBusinessLogic.HEAT_VF_ENV_NAME,
-                                resource.getUniqueId(), NodeTypeEnum.Resource, resource.getName(),
-                                csarInfo.getModifier(), resource, null);
+                    .createHeatEnvPlaceHolder(createdArtifacts, newArtifact, ArtifactsBusinessLogic.HEAT_VF_ENV_NAME, resource.getUniqueId(),
+                        NodeTypeEnum.Resource, resource.getName(), csarInfo.getModifier(), resource, null);
                 artifactEnvUid = createHeatEnvPlaceHolder.getUniqueId();
             }
         }
-
         artifactsGroup.add(artifactUid);
         artifactsUUIDGroup.add(artifactUUID);
         if (!artifactEnvUid.isEmpty()) {
             artifactsGroup.add(artifactEnvUid);
         }
-
         List<ArtifactTemplateInfo> relatedArtifacts = artifactTemplateInfo.getRelatedArtifactsInfo();
         if (relatedArtifacts != null) {
             for (ArtifactTemplateInfo relatedArtifactTemplateInfo : relatedArtifacts) {
-                resStatus = createDeploymentArtifactsFromCsar(csarInfo, resource, artifactsGroup, artifactsUUIDGroup,
-                        relatedArtifactTemplateInfo, createdArtifacts, artifactsFromResource, labelCounter);
+                resStatus = createDeploymentArtifactsFromCsar(csarInfo, resource, artifactsGroup, artifactsUUIDGroup, relatedArtifactTemplateInfo,
+                    createdArtifacts, artifactsFromResource, labelCounter);
                 if (resStatus.isRight()) {
                     return resStatus;
                 }
@@ -1516,16 +1315,16 @@ public class CsarArtifactsAndGroupsBusinessLogic extends BaseBusinessLogic {
         return resStatus;
     }
 
-    private Either<Component, ResponseFormat> associateAndDissociateArtifactsToGroup(CsarInfo csarInfo,
-                                                                                    Component resource, List<ArtifactDefinition> createdNewArtifacts, int labelCounter,
-                                                                                    List<ArtifactDefinition> createdDeploymentArtifactsAfterDelete,
-                                                                                    Map<GroupDefinition, MergedArtifactInfo> mergedgroup, List<ArtifactDefinition> deletedArtifacts) {
+    private Either<Component, ResponseFormat> associateAndDissociateArtifactsToGroup(CsarInfo csarInfo, Component resource,
+                                                                                     List<ArtifactDefinition> createdNewArtifacts, int labelCounter,
+                                                                                     List<ArtifactDefinition> createdDeploymentArtifactsAfterDelete,
+                                                                                     Map<GroupDefinition, MergedArtifactInfo> mergedgroup,
+                                                                                     List<ArtifactDefinition> deletedArtifacts) {
         Map<GroupDefinition, List<ArtifactTemplateInfo>> artifactsToAssotiate = new HashMap<>();
         Map<GroupDefinition, List<ImmutablePair<ArtifactDefinition, ArtifactTemplateInfo>>> artifactsToUpdateMap = new HashMap<>();
         Either<Component, ResponseFormat> resEither;
         for (Entry<GroupDefinition, MergedArtifactInfo> entry : mergedgroup.entrySet()) {
-            List<ArtifactDefinition> dissArtifactsInGroup = entry.getValue()
-                    .getListToDissotiateArtifactFromGroup(deletedArtifacts);
+            List<ArtifactDefinition> dissArtifactsInGroup = entry.getValue().getListToDissotiateArtifactFromGroup(deletedArtifacts);
             GroupDefinition grDef = entry.getKey();
             if (dissArtifactsInGroup != null && !dissArtifactsInGroup.isEmpty()) {
                 for (ArtifactDefinition art : dissArtifactsInGroup) {
@@ -1533,70 +1332,63 @@ public class CsarArtifactsAndGroupsBusinessLogic extends BaseBusinessLogic {
                     grDef.getArtifactsUuid().remove(art.getArtifactUUID());
                 }
             }
-
             List<ArtifactTemplateInfo> newArtifactsInGroup = entry.getValue().getListToAssociateArtifactToGroup();
             if (newArtifactsInGroup != null && !newArtifactsInGroup.isEmpty()) {
                 artifactsToAssotiate.put(entry.getKey(), newArtifactsInGroup);
             }
-
-            List<ImmutablePair<ArtifactDefinition, ArtifactTemplateInfo>> artifactsToUpdate = entry.getValue()
-                    .getListToUpdateArtifactInGroup();
+            List<ImmutablePair<ArtifactDefinition, ArtifactTemplateInfo>> artifactsToUpdate = entry.getValue().getListToUpdateArtifactInGroup();
             if (artifactsToUpdate != null && !artifactsToUpdate.isEmpty()) {
                 artifactsToUpdateMap.put(entry.getKey(), artifactsToUpdate);
             }
         }
-
         if (!artifactsToUpdateMap.isEmpty()) {
             List<ArtifactDefinition> updatedArtifacts = new ArrayList<>();
             for (Entry<GroupDefinition, List<ImmutablePair<ArtifactDefinition, ArtifactTemplateInfo>>> artifactsToUpdateEntry : artifactsToUpdateMap
-                    .entrySet()) {
-                List<ImmutablePair<ArtifactDefinition, ArtifactTemplateInfo>> artifactsToUpdateList = artifactsToUpdateEntry
-                        .getValue();
+                .entrySet()) {
+                List<ImmutablePair<ArtifactDefinition, ArtifactTemplateInfo>> artifactsToUpdateList = artifactsToUpdateEntry.getValue();
                 GroupDefinition groupToUpdate = artifactsToUpdateEntry.getKey();
-
                 for (ImmutablePair<ArtifactDefinition, ArtifactTemplateInfo> artifact : artifactsToUpdateList) {
                     String prevUUID = artifact.getKey().getArtifactUUID();
                     String prevId = artifact.getKey().getUniqueId();
                     String prevHeatEnvId = checkAndGetHeatEnvId(artifact.getKey());
-                    Either<ArtifactDefinition, ResponseFormat> updateArtifactEither = updateDeploymentArtifactsFromCsar(
-                            csarInfo, resource, artifact.getKey(), artifact.getValue(), updatedArtifacts,
-                            artifact.getRight().getRelatedArtifactsInfo());
+                    Either<ArtifactDefinition, ResponseFormat> updateArtifactEither = updateDeploymentArtifactsFromCsar(csarInfo, resource,
+                        artifact.getKey(), artifact.getValue(), updatedArtifacts, artifact.getRight().getRelatedArtifactsInfo());
                     if (updateArtifactEither.isRight()) {
                         log.debug("failed to update artifacts. status is {}", updateArtifactEither.right().value());
                         resEither = Either.right(updateArtifactEither.right().value());
                         return resEither;
                     }
                     ArtifactDefinition artAfterUpdate = updateArtifactEither.left().value();
-                    if (!prevUUID.equals(artAfterUpdate.getArtifactUUID())
-                            || !prevId.equals(artAfterUpdate.getUniqueId())) {
+                    if (!prevUUID.equals(artAfterUpdate.getArtifactUUID()) || !prevId.equals(artAfterUpdate.getUniqueId())) {
                         groupToUpdate.getArtifacts().remove(prevId);
                         groupToUpdate.getArtifactsUuid().remove(prevUUID);
                         groupToUpdate.getArtifacts().add(artAfterUpdate.getUniqueId());
                         groupToUpdate.getArtifactsUuid().add(artAfterUpdate.getArtifactUUID());
                     }
                     Optional<ArtifactDefinition> op = updatedArtifacts.stream()
-                            .filter(p -> p.getGeneratedFromId() != null
-                            && p.getGeneratedFromId().equals(artAfterUpdate.getUniqueId()))
-                            .findAny();
+                        .filter(p -> p.getGeneratedFromId() != null && p.getGeneratedFromId().equals(artAfterUpdate.getUniqueId())).findAny();
                     if (op.isPresent()) {
                         ArtifactDefinition artifactInfoHeatEnv = op.get();
                         groupToUpdate.getArtifacts().remove(prevHeatEnvId);
                         groupToUpdate.getArtifacts().add(artifactInfoHeatEnv.getUniqueId());
                     }
-
                 }
             }
         }
-
         for (Entry<GroupDefinition, List<ArtifactTemplateInfo>> associateEntry : artifactsToAssotiate.entrySet()) {
             List<ArtifactTemplateInfo> associatedArtifact = associateEntry.getValue();
             Set<String> arifactsUids = new HashSet<>();
             Set<String> arifactsUuids = new HashSet<>();
             for (ArtifactTemplateInfo artifactTemplate : associatedArtifact) { // try
+
                 // to
+
                 // find
+
                 // artifact
+
                 // in
+
                 // resource
                 boolean isCreate = true;
                 for (ArtifactDefinition createdArtifact : createdDeploymentArtifactsAfterDelete) {
@@ -1608,17 +1400,13 @@ public class CsarArtifactsAndGroupsBusinessLogic extends BaseBusinessLogic {
                         if (!heatEnvId.isEmpty()) {
                             arifactsUids.add(heatEnvId);
                             Optional<ArtifactDefinition> op = createdDeploymentArtifactsAfterDelete.stream()
-                                    .filter(p -> p.getUniqueId().equals(heatEnvId)).findAny();
+                                .filter(p -> p.getUniqueId().equals(heatEnvId)).findAny();
                             if (op.isPresent()) {
-                                this.artifactToscaOperation.updateHeatEnvPlaceholder(op.get(), resource,
-                                        resource.getComponentType().getNodeType());
-
+                                this.artifactToscaOperation.updateHeatEnvPlaceholder(op.get(), resource, resource.getComponentType().getNodeType());
                             }
                         }
-
                         break;
                     }
-
                 }
                 if (isCreate) { // check if already created
                     for (ArtifactDefinition createdNewArtifact : createdNewArtifacts) {
@@ -1634,10 +1422,9 @@ public class CsarArtifactsAndGroupsBusinessLogic extends BaseBusinessLogic {
                         }
                     }
                 }
-
                 if (isCreate) {
-                    Either<ArtifactDefinition, ResponseFormat> createArtifactEither = createDeploymentArtifact(csarInfo,
-                            resource, ARTIFACTS_PATH, artifactTemplate, createdNewArtifacts, labelCounter);
+                    Either<ArtifactDefinition, ResponseFormat> createArtifactEither = createDeploymentArtifact(csarInfo, resource, ARTIFACTS_PATH,
+                        artifactTemplate, createdNewArtifacts, labelCounter);
                     if (createArtifactEither.isRight()) {
                         resEither = Either.right(createArtifactEither.right().value());
                         return resEither;
@@ -1647,16 +1434,14 @@ public class CsarArtifactsAndGroupsBusinessLogic extends BaseBusinessLogic {
                     arifactsUuids.add(createdArtifact.getArtifactUUID());
                     final ArtifactTypeEnum artifactType = ArtifactTypeEnum.parse(createdArtifact.getArtifactType());
                     if (artifactType == ArtifactTypeEnum.HEAT || artifactType == ArtifactTypeEnum.HEAT_NET
-                            || artifactType == ArtifactTypeEnum.HEAT_VOL) {
+                        || artifactType == ArtifactTypeEnum.HEAT_VOL) {
                         ArtifactDefinition createHeatEnvPlaceHolder = artifactsBusinessLogic
-                                .createHeatEnvPlaceHolder(new ArrayList<>(), createdArtifact, ArtifactsBusinessLogic.HEAT_VF_ENV_NAME,
-                                        resource.getUniqueId(), NodeTypeEnum.Resource, resource.getName(),
-                                        csarInfo.getModifier(), resource, null);
+                            .createHeatEnvPlaceHolder(new ArrayList<>(), createdArtifact, ArtifactsBusinessLogic.HEAT_VF_ENV_NAME,
+                                resource.getUniqueId(), NodeTypeEnum.Resource, resource.getName(), csarInfo.getModifier(), resource, null);
                         String heatEnvId = createHeatEnvPlaceHolder.getUniqueId();
                         arifactsUids.add(heatEnvId);
                     }
                 }
-
             }
             if (arifactsUids != null && !arifactsUids.isEmpty()) {
                 List<String> artifactsToAssociate = new ArrayList<>();
@@ -1666,86 +1451,71 @@ public class CsarArtifactsAndGroupsBusinessLogic extends BaseBusinessLogic {
                 assotiateGroup.getArtifactsUuid().addAll(arifactsUuids);
             }
         }
-
         ComponentParametersView parametersView = new ComponentParametersView();
         parametersView.disableAll();
         parametersView.setIgnoreComponentInstances(false);
         parametersView.setIgnoreUsers(false);
         parametersView.setIgnoreArtifacts(false);
         parametersView.setIgnoreGroups(false);
-
-        Either<Resource, StorageOperationStatus> eitherGerResource = toscaOperationFacade
-                .getToscaElement(resource.getUniqueId(), parametersView);
-
+        Either<Resource, StorageOperationStatus> eitherGerResource = toscaOperationFacade.getToscaElement(resource.getUniqueId(), parametersView);
         if (eitherGerResource.isRight()) {
-            ResponseFormat responseFormat = componentsUtils.getResponseFormatByComponent(
-                    componentsUtils.convertFromStorageResponse(eitherGerResource.right().value()), resource, resource.getComponentType());
-
+            ResponseFormat responseFormat = componentsUtils
+                .getResponseFormatByComponent(componentsUtils.convertFromStorageResponse(eitherGerResource.right().value()), resource,
+                    resource.getComponentType());
             resEither = Either.right(responseFormat);
             return resEither;
-
         }
         resEither = Either.left(eitherGerResource.left().value());
         return resEither;
     }
 
-    private Either<ArtifactDefinition, ResponseFormat> updateDeploymentArtifactsFromCsar(CsarInfo csarInfo,
-            Component resource, ArtifactDefinition oldArtifact, ArtifactTemplateInfo artifactTemplateInfo,
-            List<ArtifactDefinition> updatedArtifacts, List<ArtifactTemplateInfo> updatedRequiredArtifacts) {
-
+    private Either<ArtifactDefinition, ResponseFormat> updateDeploymentArtifactsFromCsar(CsarInfo csarInfo, Component resource,
+                                                                                         ArtifactDefinition oldArtifact,
+                                                                                         ArtifactTemplateInfo artifactTemplateInfo,
+                                                                                         List<ArtifactDefinition> updatedArtifacts,
+                                                                                         List<ArtifactTemplateInfo> updatedRequiredArtifacts) {
         String artifactFileName = artifactTemplateInfo.getFileName();
-
         // check if artifacts already exist
         for (ArtifactDefinition updatedArtifact : updatedArtifacts) {
             if (updatedArtifact.getArtifactName().equals(artifactFileName)) {
                 if (!updatedArtifact.getArtifactType().equalsIgnoreCase(artifactTemplateInfo.getType())) {
-                    log.debug("Artifact with name {} and type {} already updated with type  {}", artifactFileName,
-                            artifactTemplateInfo.getType(), updatedArtifact.getArtifactType());
-                    BeEcompErrorManager.getInstance().logInternalDataError(
-                            ARTIFACT_FILE_IS_NOT_IN_EXPECTED_FORMAT_FILE_NAME + artifactFileName,
-                            ARTIFACT_INTERNALS_ARE_INVALID, ErrorSeverity.ERROR);
-                    return Either.right(componentsUtils.getResponseFormat(
-                            ActionStatus.ARTIFACT_ALREADY_EXIST_IN_DIFFERENT_TYPE_IN_CSAR, artifactFileName,
+                    log.debug("Artifact with name {} and type {} already updated with type  {}", artifactFileName, artifactTemplateInfo.getType(),
+                        updatedArtifact.getArtifactType());
+                    BeEcompErrorManager.getInstance()
+                        .logInternalDataError(ARTIFACT_FILE_IS_NOT_IN_EXPECTED_FORMAT_FILE_NAME + artifactFileName, ARTIFACT_INTERNALS_ARE_INVALID,
+                            ErrorSeverity.ERROR);
+                    return Either.right(componentsUtils
+                        .getResponseFormat(ActionStatus.ARTIFACT_ALREADY_EXIST_IN_DIFFERENT_TYPE_IN_CSAR, artifactFileName,
                             artifactTemplateInfo.getType(), updatedArtifact.getArtifactType()));
                 }
                 return Either.left(updatedArtifact);
             }
-
         }
-
         Either<ImmutablePair<String, byte[]>, ResponseFormat> artifactContententStatus = CsarValidationUtils
-                .getArtifactContent(csarInfo.getCsarUUID(), csarInfo.getCsar(),
-                        CsarUtils.ARTIFACTS_PATH + artifactFileName, artifactFileName, componentsUtils);
+            .getArtifactContent(csarInfo.getCsarUUID(), csarInfo.getCsar(), CsarUtils.ARTIFACTS_PATH + artifactFileName, artifactFileName,
+                componentsUtils);
         if (artifactContententStatus.isRight()) {
             return Either.right(artifactContententStatus.right().value());
         }
-
-        Map<String, Object> json = ArtifactUtils.buildJsonForUpdateArtifact(oldArtifact.getUniqueId(), artifactFileName,
-                oldArtifact.getArtifactType(), ArtifactGroupTypeEnum.DEPLOYMENT, oldArtifact.getArtifactLabel(),
-                oldArtifact.getArtifactDisplayName(), oldArtifact.getDescription(),
+        Map<String, Object> json = ArtifactUtils
+            .buildJsonForUpdateArtifact(oldArtifact.getUniqueId(), artifactFileName, oldArtifact.getArtifactType(), ArtifactGroupTypeEnum.DEPLOYMENT,
+                oldArtifact.getArtifactLabel(), oldArtifact.getArtifactDisplayName(), oldArtifact.getDescription(),
                 artifactContententStatus.left().value().getRight(), updatedRequiredArtifacts, oldArtifact.getIsFromCsar());
-
-        Either<Either<ArtifactDefinition, Operation>, ResponseFormat> uploadArtifactToService = createOrUpdateCsarArtifactFromJson(
-                resource, csarInfo.getModifier(), json,
-                new ArtifactOperationInfo(false, false, ArtifactOperationEnum.UPDATE));
-
+        Either<Either<ArtifactDefinition, Operation>, ResponseFormat> uploadArtifactToService = createOrUpdateCsarArtifactFromJson(resource,
+            csarInfo.getModifier(), json, new ArtifactOperationInfo(false, false, ArtifactOperationEnum.UPDATE));
         if (uploadArtifactToService.isRight()) {
             return Either.right(uploadArtifactToService.right().value());
         }
         ArtifactDefinition previousInfo = uploadArtifactToService.left().value().left().value();
         ArtifactDefinition currentInfo = uploadArtifactToService.left().value().left().value();
         updatedArtifacts.add(currentInfo);
-
-        Either<ArtifactDefinition, ResponseFormat> updateEnvEither = updateHeatParamsFromCsar(resource, csarInfo,
-                artifactTemplateInfo, currentInfo, true);
-
+        Either<ArtifactDefinition, ResponseFormat> updateEnvEither = updateHeatParamsFromCsar(resource, csarInfo, artifactTemplateInfo, currentInfo,
+            true);
         if (updateEnvEither.isRight()) {
             log.debug("failed to update parameters to artifact {}", artifactFileName);
             return Either.right(updateEnvEither.right().value());
         }
-
         artifactsBusinessLogic.updateGroupForHeat(previousInfo, updateEnvEither.left().value(), resource);
-
         updatedArtifacts.add(updateEnvEither.left().value());
         return Either.left(currentInfo);
     }
@@ -1753,31 +1523,28 @@ public class CsarArtifactsAndGroupsBusinessLogic extends BaseBusinessLogic {
     public Either<Resource, ResponseFormat> deleteVFModules(Resource resource, CsarInfo csarInfo, boolean shouldLock, boolean inTransaction) {
         Resource updatedResource = resource;
         List<GroupDefinition> groupsToDelete = updatedResource.getGroups();
-        if(groupsToDelete != null && !groupsToDelete.isEmpty()){
-            List<GroupDefinition> vfGroupsToDelete = groupsToDelete.stream().filter(g -> g.getType().equals(Constants.DEFAULT_GROUP_VF_MODULE)).collect(Collectors.toList());
-            if(!vfGroupsToDelete.isEmpty()){
-                for(GroupDefinition gr : vfGroupsToDelete){
+        if (groupsToDelete != null && !groupsToDelete.isEmpty()) {
+            List<GroupDefinition> vfGroupsToDelete = groupsToDelete.stream().filter(g -> g.getType().equals(Constants.DEFAULT_GROUP_VF_MODULE))
+                .collect(Collectors.toList());
+            if (!vfGroupsToDelete.isEmpty()) {
+                for (GroupDefinition gr : vfGroupsToDelete) {
                     List<String> artifacts = gr.getArtifacts();
                     for (String artifactId : artifacts) {
-                        Either<ArtifactDefinition, ResponseFormat> handleDelete =
-                            artifactsBusinessLogic.handleDelete(
-                                updatedResource.getUniqueId(), artifactId, csarInfo.getModifier(),
-                                updatedResource, shouldLock, inTransaction);
+                        Either<ArtifactDefinition, ResponseFormat> handleDelete = artifactsBusinessLogic
+                            .handleDelete(updatedResource.getUniqueId(), artifactId, csarInfo.getModifier(), updatedResource, shouldLock,
+                                inTransaction);
                         if (handleDelete.isRight()) {
                             log.debug("Couldn't delete  artifact {}", artifactId);
                             return Either.right(handleDelete.right().value());
                         }
                     }
-
                 }
                 groupBusinessLogic.deleteGroups(updatedResource, vfGroupsToDelete);
-
                 Either<Resource, StorageOperationStatus> eitherGetResource = toscaOperationFacade.getToscaElement(updatedResource.getUniqueId());
                 if (eitherGetResource.isRight()) {
-                    ResponseFormat responseFormat = componentsUtils.getResponseFormatByResource(componentsUtils.convertFromStorageResponse(eitherGetResource.right().value()), updatedResource);
-
+                    ResponseFormat responseFormat = componentsUtils
+                        .getResponseFormatByResource(componentsUtils.convertFromStorageResponse(eitherGetResource.right().value()), updatedResource);
                     return Either.right(responseFormat);
-
                 }
                 updatedResource = eitherGetResource.left().value();
             }
@@ -1789,8 +1556,10 @@ public class CsarArtifactsAndGroupsBusinessLogic extends BaseBusinessLogic {
         Service updatedResource = resource;
         List<GroupDefinition> groupsToDelete = updatedResource.getGroups();
         if (groupsToDelete != null && !groupsToDelete.isEmpty()) {
-            List<GroupDefinition> vfGroupsToDelete = groupsToDelete.stream().filter(g -> g.getType().equals(Constants.DEFAULT_GROUP_VF_MODULE)).collect(Collectors.toList());
-            Either<Service, ResponseFormat> eitherGetResource = deleteVfGroups(vfGroupsToDelete, updatedResource, csarInfo, shouldLock, inTransaction);
+            List<GroupDefinition> vfGroupsToDelete = groupsToDelete.stream().filter(g -> g.getType().equals(Constants.DEFAULT_GROUP_VF_MODULE))
+                .collect(Collectors.toList());
+            Either<Service, ResponseFormat> eitherGetResource = deleteVfGroups(vfGroupsToDelete, updatedResource, csarInfo, shouldLock,
+                inTransaction);
             if (eitherGetResource.isRight()) {
                 return Either.right(eitherGetResource.right().value());
             }
@@ -1799,14 +1568,15 @@ public class CsarArtifactsAndGroupsBusinessLogic extends BaseBusinessLogic {
         return Either.left(updatedResource);
     }
 
-    private Either<Service, ResponseFormat> deleteVfGroups(List<GroupDefinition> vfGroupsToDelete, Service resource, CsarInfo csarInfo, boolean shouldLock, boolean inTransaction) {
+    private Either<Service, ResponseFormat> deleteVfGroups(List<GroupDefinition> vfGroupsToDelete, Service resource, CsarInfo csarInfo,
+                                                           boolean shouldLock, boolean inTransaction) {
         ResponseFormat responseFormat;
         if (vfGroupsToDelete != null && !vfGroupsToDelete.isEmpty()) {
             for (GroupDefinition gr : vfGroupsToDelete) {
                 List<String> artifacts = gr.getArtifacts();
                 for (String artifactId : artifacts) {
-                    Either<ArtifactDefinition, ResponseFormat> handleDelete = artifactsBusinessLogic.handleDelete(resource.getUniqueId(), artifactId, csarInfo.getModifier(),
-                            resource, shouldLock, inTransaction);
+                    Either<ArtifactDefinition, ResponseFormat> handleDelete = artifactsBusinessLogic
+                        .handleDelete(resource.getUniqueId(), artifactId, csarInfo.getModifier(), resource, shouldLock, inTransaction);
                     if (handleDelete.isRight()) {
                         log.debug("Couldn't delete  artifact {}", artifactId);
                         return Either.right(handleDelete.right().value());
@@ -1814,11 +1584,11 @@ public class CsarArtifactsAndGroupsBusinessLogic extends BaseBusinessLogic {
                 }
             }
             groupBusinessLogic.deleteGroups(resource, vfGroupsToDelete);
-
             Either<Service, StorageOperationStatus> eitherGetResource = toscaOperationFacade.getToscaElement(resource.getUniqueId());
             if (eitherGetResource.isRight()) {
-                responseFormat = componentsUtils.getResponseFormatByComponent(componentsUtils.convertFromStorageResponse(eitherGetResource.right().value()), resource, resource.getComponentType());
-
+                responseFormat = componentsUtils
+                    .getResponseFormatByComponent(componentsUtils.convertFromStorageResponse(eitherGetResource.right().value()), resource,
+                        resource.getComponentType());
                 return Either.right(responseFormat);
             }
             resource = eitherGetResource.left().value();
@@ -1828,14 +1598,10 @@ public class CsarArtifactsAndGroupsBusinessLogic extends BaseBusinessLogic {
         return Either.right(responseFormat);
     }
 
-
     private Either<? extends Component, ResponseFormat> getResourcetFromGraph(Component component) {
         log.debug("getResource start");
-        return toscaOperationFacade.getToscaElement(component.getUniqueId())
-                .right()
-                .map(rf -> componentsUtils.getResponseFormatByComponent(componentsUtils.convertFromStorageResponse(rf), component, component.getComponentType()))
-                .left()
-                .map(c -> c);
+        return toscaOperationFacade.getToscaElement(component.getUniqueId()).right().map(rf -> componentsUtils
+            .getResponseFormatByComponent(componentsUtils.convertFromStorageResponse(rf), component, component.getComponentType())).left()
+            .map(c -> c);
     }
-
 }
index 51199e6..6f530cc 100644 (file)
@@ -22,6 +22,7 @@
 package org.openecomp.sdc.be.components.csar;
 
 import fj.data.Either;
+import java.util.Map;
 import org.apache.commons.lang3.tuple.ImmutablePair;
 import org.openecomp.sdc.be.components.impl.BaseBusinessLogic;
 import org.openecomp.sdc.be.components.impl.CsarValidationUtils;
@@ -51,31 +52,22 @@ import org.openecomp.sdc.common.log.wrappers.Logger;
 import org.openecomp.sdc.exception.ResponseFormat;
 import org.springframework.beans.factory.annotation.Autowired;
 
-import java.util.Map;
-
 @org.springframework.stereotype.Component("csarBusinessLogic")
 public class CsarBusinessLogic extends BaseBusinessLogic {
 
     private static final Logger log = Logger.getLogger(CsarBusinessLogic.class);
-
     private static final String CREATING_RESOURCE_FROM_CSAR_FETCHING_CSAR_WITH_ID = "Creating resource from CSAR: fetching CSAR with id ";
     private static final String FAILED = " failed";
-
     private final YamlTemplateParsingHandler yamlHandler;
     private CsarOperation csarOperation;
 
     @Autowired
-    public CsarBusinessLogic(IElementOperation elementDao,
-        IGroupOperation groupOperation,
-        IGroupInstanceOperation groupInstanceOperation,
-        IGroupTypeOperation groupTypeOperation,
-        GroupBusinessLogic groupBusinessLogic,
-        InterfaceOperation interfaceOperation,
-        InterfaceLifecycleOperation interfaceLifecycleTypeOperation,
-        YamlTemplateParsingHandler yamlHandler,
-        ArtifactsOperations artifactToscaOperation) {
-        super(elementDao, groupOperation, groupInstanceOperation, groupTypeOperation,
-            interfaceOperation, interfaceLifecycleTypeOperation, artifactToscaOperation);
+    public CsarBusinessLogic(IElementOperation elementDao, IGroupOperation groupOperation, IGroupInstanceOperation groupInstanceOperation,
+                             IGroupTypeOperation groupTypeOperation, GroupBusinessLogic groupBusinessLogic, InterfaceOperation interfaceOperation,
+                             InterfaceLifecycleOperation interfaceLifecycleTypeOperation, YamlTemplateParsingHandler yamlHandler,
+                             ArtifactsOperations artifactToscaOperation) {
+        super(elementDao, groupOperation, groupInstanceOperation, groupTypeOperation, interfaceOperation, interfaceLifecycleTypeOperation,
+            artifactToscaOperation);
         this.yamlHandler = yamlHandler;
     }
 
@@ -86,121 +78,100 @@ public class CsarBusinessLogic extends BaseBusinessLogic {
 
     public void validateCsarBeforeCreate(Resource resource, AuditingActionEnum auditingAction, User user, String csarUUID) {
         // check if VF with the same Csar UUID or with he same name already
+
         // exists
         StorageOperationStatus status = toscaOperationFacade.validateCsarUuidUniqueness(csarUUID);
-        if(status == StorageOperationStatus.ENTITY_ALREADY_EXISTS){
-            log.debug("Failed to create resource {}, csarUUID {} already exist for a different VF ",
-                    resource.getSystemName(), csarUUID);
-            auditAndThrowException(resource, user, auditingAction, ActionStatus.VSP_ALREADY_EXISTS,
-                    csarUUID);
+        if (status == StorageOperationStatus.ENTITY_ALREADY_EXISTS) {
+            log.debug("Failed to create resource {}, csarUUID {} already exist for a different VF ", resource.getSystemName(), csarUUID);
+            auditAndThrowException(resource, user, auditingAction, ActionStatus.VSP_ALREADY_EXISTS, csarUUID);
         } else if (status != StorageOperationStatus.OK) {
-            log.debug("Failed to validate uniqueness of CsarUUID {} for resource", csarUUID,
-                    resource.getSystemName());
+            log.debug("Failed to validate uniqueness of CsarUUID {} for resource", csarUUID, resource.getSystemName());
             throw new ByActionStatusComponentException(componentsUtils.convertFromStorageResponse(status));
         }
     }
 
     public void validateCsarBeforeCreate(Service resource, String csarUUID) {
         // check if VF with the same Csar UUID or with he same name already
+
         // exists
         StorageOperationStatus status = toscaOperationFacade.validateCsarUuidUniqueness(csarUUID);
         log.debug("enter validateCsarBeforeCreate,get status:{}", status);
         if (status == StorageOperationStatus.ENTITY_ALREADY_EXISTS) {
-            log.debug("Failed to create resource {}, csarUUID {} already exist for a different VF ",
-                    resource.getSystemName(), csarUUID);
+            log.debug("Failed to create resource {}, csarUUID {} already exist for a different VF ", resource.getSystemName(), csarUUID);
         } else if (status != StorageOperationStatus.OK) {
-            log.debug("Failed to validate uniqueness of CsarUUID {} for resource", csarUUID,
-                    resource.getSystemName());
+            log.debug("Failed to validate uniqueness of CsarUUID {} for resource", csarUUID, resource.getSystemName());
             throw new ByActionStatusComponentException(componentsUtils.convertFromStorageResponse(status));
         }
     }
 
-    public CsarInfo getCsarInfo(Resource resource, Resource oldResource,User user, Map<String, byte[]> payload, String csarUUID){
+    public CsarInfo getCsarInfo(Resource resource, Resource oldResource, User user, Map<String, byte[]> payload, String csarUUID) {
         Map<String, byte[]> csar = getCsar(resource, user, payload, csarUUID);
-        ImmutablePair<String, String> toscaYamlCsarStatus = validateAndParseCsar(resource,
-                user, csar, csarUUID)
-                .left().on(this::throwComponentException);
-
-        String checksum = CsarValidationUtils.getToscaYamlChecksum(csar,
-                csarUUID, componentsUtils).left().on(r->logAndThrowComponentException(r, "Failed to calculate checksum for casrUUID {} error {} ", csarUUID));
-        if (oldResource!=null && !checksum.equals(
-                oldResource.getComponentMetadataDefinition().getMetadataDataDefinition().getImportedToscaChecksum())) {
-            log.debug("The checksum of main template yaml of csar with csarUUID {} is not equal to the previous one, existing checksum is {}, new one is {}.", csarUUID,
-                    oldResource.getComponentMetadataDefinition().getMetadataDataDefinition()
-                            .getImportedToscaChecksum(),
-                    checksum);
-            oldResource.getComponentMetadataDefinition().getMetadataDataDefinition()
-                    .setImportedToscaChecksum(checksum);
+        ImmutablePair<String, String> toscaYamlCsarStatus = validateAndParseCsar(resource, user, csar, csarUUID).left()
+            .on(this::throwComponentException);
+        String checksum = CsarValidationUtils.getToscaYamlChecksum(csar, csarUUID, componentsUtils).left()
+            .on(r -> logAndThrowComponentException(r, "Failed to calculate checksum for casrUUID {} error {} ", csarUUID));
+        if (oldResource != null && !checksum
+            .equals(oldResource.getComponentMetadataDefinition().getMetadataDataDefinition().getImportedToscaChecksum())) {
+            log.debug(
+                "The checksum of main template yaml of csar with csarUUID {} is not equal to the previous one, existing checksum is {}, new one is {}.",
+                csarUUID, oldResource.getComponentMetadataDefinition().getMetadataDataDefinition().getImportedToscaChecksum(), checksum);
+            oldResource.getComponentMetadataDefinition().getMetadataDataDefinition().setImportedToscaChecksum(checksum);
         }
-
-        return new CsarInfo(user, csarUUID, csar, resource.getName(),
-                toscaYamlCsarStatus.getKey(), toscaYamlCsarStatus.getValue(), true);
+        return new CsarInfo(user, csarUUID, csar, resource.getName(), toscaYamlCsarStatus.getKey(), toscaYamlCsarStatus.getValue(), true);
     }
 
-    public CsarInfo getCsarInfo(Service service, Service oldResource,User user, Map<String, byte[]> payload, String csarUUID){
+    public CsarInfo getCsarInfo(Service service, Service oldResource, User user, Map<String, byte[]> payload, String csarUUID) {
         Map<String, byte[]> csar = getCsar(service, user, payload, csarUUID);
-        ImmutablePair<String, String> toscaYamlCsarStatus = validateAndParseCsar(service,
-                user, csar, csarUUID)
-                                                                    .left().on(this::throwComponentException);
-
-        String checksum = CsarValidationUtils.getToscaYamlChecksum(csar,
-                csarUUID, componentsUtils).left().on(r->logAndThrowComponentException(r, "Failed to calculate checksum for casrUUID {} error {} ", csarUUID));
-        if (oldResource!=null && !checksum.equals(
-                oldResource.getComponentMetadataDefinition().getMetadataDataDefinition().getImportedToscaChecksum())) {
-            log.debug("The checksum of main template yaml of csar with csarUUID {} is not equal to the previous one, existing checksum is {}, new one is {}.", csarUUID,
-                    oldResource.getComponentMetadataDefinition().getMetadataDataDefinition()
-                            .getImportedToscaChecksum(),
-                    checksum);
-            oldResource.getComponentMetadataDefinition().getMetadataDataDefinition()
-                    .setImportedToscaChecksum(checksum);
+        ImmutablePair<String, String> toscaYamlCsarStatus = validateAndParseCsar(service, user, csar, csarUUID).left()
+            .on(this::throwComponentException);
+        String checksum = CsarValidationUtils.getToscaYamlChecksum(csar, csarUUID, componentsUtils).left()
+            .on(r -> logAndThrowComponentException(r, "Failed to calculate checksum for casrUUID {} error {} ", csarUUID));
+        if (oldResource != null && !checksum
+            .equals(oldResource.getComponentMetadataDefinition().getMetadataDataDefinition().getImportedToscaChecksum())) {
+            log.debug(
+                "The checksum of main template yaml of csar with csarUUID {} is not equal to the previous one, existing checksum is {}, new one is {}.",
+                csarUUID, oldResource.getComponentMetadataDefinition().getMetadataDataDefinition().getImportedToscaChecksum(), checksum);
+            oldResource.getComponentMetadataDefinition().getMetadataDataDefinition().setImportedToscaChecksum(checksum);
         }
-
-        return new CsarInfo(user, csarUUID, csar, service.getName(),
-                toscaYamlCsarStatus.getKey(), toscaYamlCsarStatus.getValue(), true);
+        return new CsarInfo(user, csarUUID, csar, service.getName(), toscaYamlCsarStatus.getKey(), toscaYamlCsarStatus.getValue(), true);
     }
-       
-    public ParsedToscaYamlInfo getParsedToscaYamlInfo(String topologyTemplateYaml, String yamlName, Map<String, NodeTypeInfo> nodeTypesInfo, CsarInfo csarInfo, String nodeName, Component component) {
-        return yamlHandler.parseResourceInfoFromYAML(
-                yamlName, topologyTemplateYaml, csarInfo.getCreatedNodesToscaResourceNames(), nodeTypesInfo,
-                nodeName, component);
+
+    public ParsedToscaYamlInfo getParsedToscaYamlInfo(String topologyTemplateYaml, String yamlName, Map<String, NodeTypeInfo> nodeTypesInfo,
+                                                      CsarInfo csarInfo, String nodeName, Component component) {
+        return yamlHandler
+            .parseResourceInfoFromYAML(yamlName, topologyTemplateYaml, csarInfo.getCreatedNodesToscaResourceNames(), nodeTypesInfo, nodeName,
+                component);
     }
 
-    private String logAndThrowComponentException(ResponseFormat responseFormat, String logMessage, String ...params) {
+    private String logAndThrowComponentException(ResponseFormat responseFormat, String logMessage, String... params) {
         log.debug(logMessage, params, responseFormat);
         throw new ByResponseFormatComponentException(responseFormat);
     }
 
-    private ImmutablePair<String,String> throwComponentException(ResponseFormat responseFormat) {
+    private ImmutablePair<String, String> throwComponentException(ResponseFormat responseFormat) {
         throw new ByResponseFormatComponentException(responseFormat);
     }
 
-    private Either<ImmutablePair<String, String>, ResponseFormat> validateAndParseCsar(Component component, User user,
-                                                                                      Map<String, byte[]> payload, String csarUUID) {
+    private Either<ImmutablePair<String, String>, ResponseFormat> validateAndParseCsar(Component component, User user, Map<String, byte[]> payload,
+                                                                                       String csarUUID) {
         Map<String, byte[]> csar = getCsar(component, user, payload, csarUUID);
-        Either<Boolean, ResponseFormat> validateCsarStatus = CsarValidationUtils.validateCsar(csar,
-                csarUUID, componentsUtils);
+        Either<Boolean, ResponseFormat> validateCsarStatus = CsarValidationUtils.validateCsar(csar, csarUUID, componentsUtils);
         if (validateCsarStatus.isRight()) {
             ResponseFormat responseFormat = validateCsarStatus.right().value();
             log.debug("Error when validate csar with ID {}, error: {}", csarUUID, responseFormat);
-            BeEcompErrorManager.getInstance()
-                    .logBeDaoSystemError(CREATING_RESOURCE_FROM_CSAR_FETCHING_CSAR_WITH_ID + csarUUID + FAILED);
-            if(component instanceof Resource){
-                componentsUtils.auditResource(responseFormat, user, (Resource)component, AuditingActionEnum.CREATE_RESOURCE);
+            BeEcompErrorManager.getInstance().logBeDaoSystemError(CREATING_RESOURCE_FROM_CSAR_FETCHING_CSAR_WITH_ID + csarUUID + FAILED);
+            if (component instanceof Resource) {
+                componentsUtils.auditResource(responseFormat, user, (Resource) component, AuditingActionEnum.CREATE_RESOURCE);
             }
-
             return Either.right(responseFormat);
         }
-
-        Either<ImmutablePair<String, String>, ResponseFormat> toscaYamlCsarStatus = CsarValidationUtils
-                .getToscaYaml(csar, csarUUID, componentsUtils);
-
+        Either<ImmutablePair<String, String>, ResponseFormat> toscaYamlCsarStatus = CsarValidationUtils.getToscaYaml(csar, csarUUID, componentsUtils);
         if (toscaYamlCsarStatus.isRight()) {
             ResponseFormat responseFormat = toscaYamlCsarStatus.right().value();
             log.debug("Error when try to get csar toscayamlFile with csar ID {}, error: {}", csarUUID, responseFormat);
-            BeEcompErrorManager.getInstance()
-                    .logBeDaoSystemError(CREATING_RESOURCE_FROM_CSAR_FETCHING_CSAR_WITH_ID + csarUUID + FAILED);
-            if(component instanceof Resource) {
-                componentsUtils.auditResource(responseFormat, user, (Resource)component, AuditingActionEnum.CREATE_RESOURCE);
+            BeEcompErrorManager.getInstance().logBeDaoSystemError(CREATING_RESOURCE_FROM_CSAR_FETCHING_CSAR_WITH_ID + csarUUID + FAILED);
+            if (component instanceof Resource) {
+                componentsUtils.auditResource(responseFormat, user, (Resource) component, AuditingActionEnum.CREATE_RESOURCE);
             }
             return Either.right(responseFormat);
         }
@@ -215,48 +186,38 @@ public class CsarBusinessLogic extends BaseBusinessLogic {
         if (csar.isRight()) {
             StorageOperationStatus value = csar.right().value();
             log.debug("#getCsar - failed to fetch csar with ID {}, error: {}", csarUUID, value);
-            BeEcompErrorManager.getInstance()
-                    .logBeDaoSystemError(CREATING_RESOURCE_FROM_CSAR_FETCHING_CSAR_WITH_ID + csarUUID + FAILED);
-            ResponseFormat responseFormat = componentsUtils
-                    .getResponseFormat(componentsUtils.convertFromStorageResponse(value), csarUUID);
-            if(component instanceof Resource){
+            BeEcompErrorManager.getInstance().logBeDaoSystemError(CREATING_RESOURCE_FROM_CSAR_FETCHING_CSAR_WITH_ID + csarUUID + FAILED);
+            ResponseFormat responseFormat = componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(value), csarUUID);
+            if (component instanceof Resource) {
                 Resource newResource = (Resource) component;
                 componentsUtils.auditResource(responseFormat, user, newResource, AuditingActionEnum.CREATE_RESOURCE);
             }
-
             throw new StorageException(csar.right().value());
         }
         return csar.left().value();
     }
 
-    private void auditAndThrowException(Resource resource, User user, AuditingActionEnum auditingAction, ActionStatus status, String... params){
+    private void auditAndThrowException(Resource resource, User user, AuditingActionEnum auditingAction, ActionStatus status, String... params) {
         ResponseFormat errorResponse = componentsUtils.getResponseFormat(status, params);
         componentsUtils.auditResource(errorResponse, user, resource, auditingAction);
         throw new ByResponseFormatComponentException(errorResponse, params);
     }
 
-    private Either<ImmutablePair<String, String>, ResponseFormat> validateAndParseCsar(Service service, User user,
-        Map<String, byte[]> payload, String csarUUID) {
+    private Either<ImmutablePair<String, String>, ResponseFormat> validateAndParseCsar(Service service, User user, Map<String, byte[]> payload,
+                                                                                       String csarUUID) {
         Map<String, byte[]> csar = getCsar(service, user, payload, csarUUID);
-        Either<Boolean, ResponseFormat> validateCsarStatus = CsarValidationUtils.validateCsar(csar,
-            csarUUID, componentsUtils);
+        Either<Boolean, ResponseFormat> validateCsarStatus = CsarValidationUtils.validateCsar(csar, csarUUID, componentsUtils);
         if (validateCsarStatus.isRight()) {
             ResponseFormat responseFormat = validateCsarStatus.right().value();
             log.debug("Error when validate csar with ID {}, error: {}", csarUUID, responseFormat);
-            BeEcompErrorManager.getInstance()
-                .logBeDaoSystemError(CREATING_RESOURCE_FROM_CSAR_FETCHING_CSAR_WITH_ID + csarUUID + FAILED);
-
+            BeEcompErrorManager.getInstance().logBeDaoSystemError(CREATING_RESOURCE_FROM_CSAR_FETCHING_CSAR_WITH_ID + csarUUID + FAILED);
             return Either.right(responseFormat);
         }
-
-        Either<ImmutablePair<String, String>, ResponseFormat> toscaYamlCsarStatus = CsarValidationUtils
-            .getToscaYaml(csar, csarUUID, componentsUtils);
-
+        Either<ImmutablePair<String, String>, ResponseFormat> toscaYamlCsarStatus = CsarValidationUtils.getToscaYaml(csar, csarUUID, componentsUtils);
         if (toscaYamlCsarStatus.isRight()) {
             ResponseFormat responseFormat = toscaYamlCsarStatus.right().value();
             log.debug("Error when try to get csar toscayamlFile with csar ID {}, error: {}", csarUUID, responseFormat);
-            BeEcompErrorManager.getInstance()
-                .logBeDaoSystemError(CREATING_RESOURCE_FROM_CSAR_FETCHING_CSAR_WITH_ID + csarUUID + FAILED);
+            BeEcompErrorManager.getInstance().logBeDaoSystemError(CREATING_RESOURCE_FROM_CSAR_FETCHING_CSAR_WITH_ID + csarUUID + FAILED);
             return Either.right(responseFormat);
         }
         return toscaYamlCsarStatus;
index feb18c2..f5a1409 100644 (file)
  */
 package org.openecomp.sdc.be.components.csar;
 
+import static org.openecomp.sdc.be.components.impl.ImportUtils.ResultStatusEnum;
+import static org.openecomp.sdc.be.components.impl.ImportUtils.ToscaElementTypeEnum;
+import static org.openecomp.sdc.be.components.impl.ImportUtils.findToscaElement;
+
 import com.google.common.annotations.VisibleForTesting;
 import fj.data.Either;
+import java.util.ArrayList;
+import java.util.Collections;
+import java.util.HashMap;
+import java.util.HashSet;
+import java.util.List;
+import java.util.Map;
+import java.util.Optional;
+import java.util.PriorityQueue;
+import java.util.Queue;
+import java.util.Set;
+import java.util.regex.Pattern;
 import lombok.Getter;
 import lombok.Setter;
 import org.apache.commons.collections.CollectionUtils;
@@ -42,25 +57,10 @@ import org.openecomp.sdc.common.api.Constants;
 import org.openecomp.sdc.common.log.wrappers.Logger;
 import org.yaml.snakeyaml.Yaml;
 
-import java.util.ArrayList;
-import java.util.Collections;
-import java.util.HashMap;
-import java.util.HashSet;
-import java.util.List;
-import java.util.Map;
-import java.util.Optional;
-import java.util.PriorityQueue;
-import java.util.Queue;
-import java.util.Set;
-import java.util.regex.Pattern;
-
-import static org.openecomp.sdc.be.components.impl.ImportUtils.ResultStatusEnum;
-import static org.openecomp.sdc.be.components.impl.ImportUtils.ToscaElementTypeEnum;
-import static org.openecomp.sdc.be.components.impl.ImportUtils.findToscaElement;
-
 public class CsarInfo {
-    private static final Logger log = Logger.getLogger(CsarInfo.class);
 
+    private static final Logger log = Logger.getLogger(CsarInfo.class);
+    private final NonManoConfiguration nonManoConfiguration;
     @Getter
     @Setter
     private String vfResourceName;
@@ -85,10 +85,10 @@ public class CsarInfo {
     private boolean isUpdate;
     @Getter
     private Map<String, Resource> createdNodes;
-    private final NonManoConfiguration nonManoConfiguration;
 
     @SuppressWarnings("unchecked")
-    public CsarInfo(User modifier, String csarUUID, Map<String, byte[]> csar, String vfResourceName, String mainTemplateName, String mainTemplateContent, boolean isUpdate){
+    public CsarInfo(User modifier, String csarUUID, Map<String, byte[]> csar, String vfResourceName, String mainTemplateName,
+                    String mainTemplateContent, boolean isUpdate) {
         this.vfResourceName = vfResourceName;
         this.modifier = modifier;
         this.csarUUID = csarUUID;
@@ -99,7 +99,7 @@ public class CsarInfo {
         this.createdNodesToscaResourceNames = new HashMap<>();
         this.cvfcToCreateQueue = new PriorityQueue<>();
         this.isUpdate = isUpdate;
-        this.createdNodes  = new HashMap<>();
+        this.createdNodes = new HashMap<>();
         this.nonManoConfiguration = NonManoConfigurationManager.getInstance().getNonManoConfiguration();
     }
 
@@ -108,14 +108,36 @@ public class CsarInfo {
         this.nonManoConfiguration = nonManoConfiguration;
     }
 
+    @SuppressWarnings("unchecked")
+    public static void markNestedVfc(Map<String, Object> mappedToscaTemplate, Map<String, NodeTypeInfo> nodeTypesInfo) {
+        findToscaElement(mappedToscaTemplate, TypeUtils.ToscaTagNamesEnum.NODE_TEMPLATES, ToscaElementTypeEnum.MAP).right()
+            .on(nts -> processNodeTemplates((Map<String, Object>) nts, nodeTypesInfo));
+    }
+
+    @SuppressWarnings("unchecked")
+    private static ResultStatusEnum processNodeTemplates(Map<String, Object> nodeTemplates, Map<String, NodeTypeInfo> nodeTypesInfo) {
+        nodeTemplates.values().forEach(nt -> processNodeTemplate(nodeTypesInfo, (Map<String, Object>) nt));
+        return ResultStatusEnum.OK;
+    }
+
+    private static void processNodeTemplate(Map<String, NodeTypeInfo> nodeTypesInfo, Map<String, Object> nodeTemplate) {
+        if (nodeTemplate.containsKey(TypeUtils.ToscaTagNamesEnum.TYPE.getElementName())) {
+            String type = (String) nodeTemplate.get(TypeUtils.ToscaTagNamesEnum.TYPE.getElementName());
+            if (nodeTypesInfo.containsKey(type)) {
+                NodeTypeInfo nodeTypeInfo = nodeTypesInfo.get(type);
+                if (nodeTypeInfo.isSubstitutionMapping() && type.contains(Constants.USER_DEFINED_RESOURCE_NAMESPACE_PREFIX)) {
+                    nodeTypeInfo.setNested(true);
+                }
+            }
+        }
+    }
+
     public void addNodeToQueue(String nodeName) {
-        if(!cvfcToCreateQueue.contains(nodeName)) {
+        if (!cvfcToCreateQueue.contains(nodeName)) {
             cvfcToCreateQueue.add(nodeName);
         } else {
-            log.debug("Failed to validate complex VFC {}. Loop detected, VSP {}. ", nodeName,
-                    getVfResourceName());
-            throw new ByActionStatusComponentException(ActionStatus.CFVC_LOOP_DETECTED,
-                    getVfResourceName(), nodeName);
+            log.debug("Failed to validate complex VFC {}. Loop detected, VSP {}. ", nodeName, getVfResourceName());
+            throw new ByActionStatusComponentException(ActionStatus.CFVC_LOOP_DETECTED, getVfResourceName(), nodeName);
         }
     }
 
@@ -131,7 +153,7 @@ public class CsarInfo {
         this.isUpdate = isUpdate;
     }
 
-    public Map<String,NodeTypeInfo> extractNodeTypesInfo() {
+    public Map<String, NodeTypeInfo> extractNodeTypesInfo() {
         Map<String, NodeTypeInfo> nodeTypesInfo = new HashMap<>();
         List<Map.Entry<String, byte[]>> globalSubstitutes = new ArrayList<>();
         final Set<String> nodeTypesUsedInNodeTemplates = new HashSet<>();
@@ -147,17 +169,15 @@ public class CsarInfo {
     }
 
     @SuppressWarnings("unchecked")
-    private void extractNodeTypeInfo(Map<String, NodeTypeInfo> nodeTypesInfo,
-                                     List<Map.Entry<String, byte[]>> globalSubstitutes, final Set<String> nodeTypesUsedInNodeTemplates, Map.Entry<String, byte[]> entry) {
+    private void extractNodeTypeInfo(Map<String, NodeTypeInfo> nodeTypesInfo, List<Map.Entry<String, byte[]>> globalSubstitutes,
+                                     final Set<String> nodeTypesUsedInNodeTemplates, Map.Entry<String, byte[]> entry) {
         if (isAServiceTemplate(entry.getKey())) {
             if (isGlobalSubstitute(entry.getKey())) {
                 globalSubstitutes.add(entry);
             } else {
                 Map<String, Object> mappedToscaTemplate = (Map<String, Object>) new Yaml().load(new String(entry.getValue()));
-                findToscaElement(mappedToscaTemplate, TypeUtils.ToscaTagNamesEnum.SUBSTITUTION_MAPPINGS, ToscaElementTypeEnum.MAP)
-                    .right()
-                    .on(sub->handleSubstitutionMappings(nodeTypesInfo, entry, mappedToscaTemplate, (Map<String, Object>)sub));
-                
+                findToscaElement(mappedToscaTemplate, TypeUtils.ToscaTagNamesEnum.SUBSTITUTION_MAPPINGS, ToscaElementTypeEnum.MAP).right()
+                    .on(sub -> handleSubstitutionMappings(nodeTypesInfo, entry, mappedToscaTemplate, (Map<String, Object>) sub));
                 final Either<Object, ResultStatusEnum> nodeTypesEither = findToscaElement(mappedToscaTemplate,
                     TypeUtils.ToscaTagNamesEnum.NODE_TEMPLATES, ToscaElementTypeEnum.MAP);
                 if (nodeTypesEither.isLeft()) {
@@ -167,37 +187,38 @@ public class CsarInfo {
             }
         }
     }
-    
+
     private boolean isAServiceTemplate(final String filePath) {
-      return Pattern.compile(CsarUtils.SERVICE_TEMPLATE_PATH_PATTERN).matcher(filePath).matches();
+        return Pattern.compile(CsarUtils.SERVICE_TEMPLATE_PATH_PATTERN).matcher(filePath).matches();
     }
-    
+
     private Set<String> findNodeTypesUsedInNodeTemplates(final Map<String, Map<String, Object>> nodeTemplates) {
-      final Set<String> nodeTypes = new HashSet<>();
-      for (final Map<String, Object> nodeTemplate : nodeTemplates.values()) {
-          nodeTypes.add((String)nodeTemplate.get(TypeUtils.ToscaTagNamesEnum.TYPE.getElementName()));
-      }
-      return nodeTypes;
+        final Set<String> nodeTypes = new HashSet<>();
+        for (final Map<String, Object> nodeTemplate : nodeTemplates.values()) {
+            nodeTypes.add((String) nodeTemplate.get(TypeUtils.ToscaTagNamesEnum.TYPE.getElementName()));
+        }
+        return nodeTypes;
     }
 
-    private ResultStatusEnum handleSubstitutionMappings(Map<String, NodeTypeInfo> nodeTypesInfo, Map.Entry<String, byte[]> entry, Map<String, Object> mappedToscaTemplate, Map<String, Object> substitutionMappings) {
-      final Set<String> nodeTypesDefinedInTemplate = findNodeTypesDefinedInTemplate(mappedToscaTemplate);  
-      if (substitutionMappings.containsKey(TypeUtils.ToscaTagNamesEnum.NODE_TYPE.getElementName()) && !nodeTypesDefinedInTemplate.contains(substitutionMappings.get(TypeUtils.ToscaTagNamesEnum.NODE_TYPE.getElementName()))) {
+    private ResultStatusEnum handleSubstitutionMappings(Map<String, NodeTypeInfo> nodeTypesInfo, Map.Entry<String, byte[]> entry,
+                                                        Map<String, Object> mappedToscaTemplate, Map<String, Object> substitutionMappings) {
+        final Set<String> nodeTypesDefinedInTemplate = findNodeTypesDefinedInTemplate(mappedToscaTemplate);
+        if (substitutionMappings.containsKey(TypeUtils.ToscaTagNamesEnum.NODE_TYPE.getElementName()) && !nodeTypesDefinedInTemplate
+            .contains(substitutionMappings.get(TypeUtils.ToscaTagNamesEnum.NODE_TYPE.getElementName()))) {
             NodeTypeInfo nodeTypeInfo = new NodeTypeInfo();
             nodeTypeInfo.setSubstitutionMapping(true);
-            nodeTypeInfo.setType(
-                    (String) substitutionMappings.get(TypeUtils.ToscaTagNamesEnum.NODE_TYPE.getElementName()));
+            nodeTypeInfo.setType((String) substitutionMappings.get(TypeUtils.ToscaTagNamesEnum.NODE_TYPE.getElementName()));
             nodeTypeInfo.setTemplateFileName(entry.getKey());
             nodeTypeInfo.setMappedToscaTemplate(mappedToscaTemplate);
             nodeTypesInfo.put(nodeTypeInfo.getType(), nodeTypeInfo);
         }
         return ResultStatusEnum.OK;
     }
-    
+
     @SuppressWarnings("unchecked")
-    private Set<String> findNodeTypesDefinedInTemplate(final Map<String, Object> mappedToscaTemplate) {     
-        final Either<Object, ResultStatusEnum> nodeTypesEither = findToscaElement(mappedToscaTemplate,
-                TypeUtils.ToscaTagNamesEnum.NODE_TYPES, ToscaElementTypeEnum.MAP);
+    private Set<String> findNodeTypesDefinedInTemplate(final Map<String, Object> mappedToscaTemplate) {
+        final Either<Object, ResultStatusEnum> nodeTypesEither = findToscaElement(mappedToscaTemplate, TypeUtils.ToscaTagNamesEnum.NODE_TYPES,
+            ToscaElementTypeEnum.MAP);
         if (nodeTypesEither.isLeft()) {
             final Map<String, Object> nodeTypes = (Map<String, Object>) nodeTypesEither.left().value();
             return nodeTypes.keySet();
@@ -206,18 +227,17 @@ public class CsarInfo {
     }
 
     private boolean isGlobalSubstitute(String fileName) {
-        return fileName.equalsIgnoreCase(Constants.GLOBAL_SUBSTITUTION_TYPES_SERVICE_TEMPLATE)
-                || fileName.equalsIgnoreCase(Constants.ABSTRACT_SUBSTITUTE_GLOBAL_TYPES_SERVICE_TEMPLATE);
+        return fileName.equalsIgnoreCase(Constants.GLOBAL_SUBSTITUTION_TYPES_SERVICE_TEMPLATE) || fileName
+            .equalsIgnoreCase(Constants.ABSTRACT_SUBSTITUTE_GLOBAL_TYPES_SERVICE_TEMPLATE);
     }
 
     @SuppressWarnings("unchecked")
-    private void setDerivedFrom(Map<String, NodeTypeInfo> nodeTypesInfo,
-                                List<Map.Entry<String, byte[]>> globalSubstitutes) {
+    private void setDerivedFrom(Map<String, NodeTypeInfo> nodeTypesInfo, List<Map.Entry<String, byte[]>> globalSubstitutes) {
         for (Map.Entry<String, byte[]> entry : globalSubstitutes) {
             String yamlFileContents = new String(entry.getValue());
             Map<String, Object> mappedToscaTemplate = (Map<String, Object>) new Yaml().load(yamlFileContents);
-            Either<Object, ResultStatusEnum> nodeTypesEither = findToscaElement(mappedToscaTemplate,
-                    TypeUtils.ToscaTagNamesEnum.NODE_TYPES, ToscaElementTypeEnum.MAP);
+            Either<Object, ResultStatusEnum> nodeTypesEither = findToscaElement(mappedToscaTemplate, TypeUtils.ToscaTagNamesEnum.NODE_TYPES,
+                ToscaElementTypeEnum.MAP);
             if (nodeTypesEither.isLeft()) {
                 Map<String, Object> nodeTypes = (Map<String, Object>) nodeTypesEither.left().value();
                 for (Map.Entry<String, Object> nodeType : nodeTypes.entrySet()) {
@@ -239,24 +259,16 @@ public class CsarInfo {
     }
 
     @SuppressWarnings("unchecked")
-    public static void markNestedVfc(Map<String, Object> mappedToscaTemplate, Map<String, NodeTypeInfo> nodeTypesInfo) {
-        findToscaElement(mappedToscaTemplate, TypeUtils.ToscaTagNamesEnum.NODE_TEMPLATES,
-                ToscaElementTypeEnum.MAP)
-                .right()
-                .on(nts-> processNodeTemplates((Map<String, Object>)nts, nodeTypesInfo));
-    }
-    
-    @SuppressWarnings("unchecked")
-    private void addGlobalSubstitutionsToNodeTypes(final List<Map.Entry<String, byte[]>> globalSubstitutes, final Set<String> nodeTypesUsedInNodeTemplates, final Map<String, NodeTypeInfo> nodeTypesInfo) {
+    private void addGlobalSubstitutionsToNodeTypes(final List<Map.Entry<String, byte[]>> globalSubstitutes,
+                                                   final Set<String> nodeTypesUsedInNodeTemplates, final Map<String, NodeTypeInfo> nodeTypesInfo) {
         for (Map.Entry<String, byte[]> entry : globalSubstitutes) {
             final String yamlFileContents = new String(entry.getValue());
             final Map<String, Object> mappedToscaTemplate = (Map<String, Object>) new Yaml().load(yamlFileContents);
-            final Either<Object, ResultStatusEnum> nodeTypesEither = findToscaElement(mappedToscaTemplate,
-                    TypeUtils.ToscaTagNamesEnum.NODE_TYPES, ToscaElementTypeEnum.MAP);
+            final Either<Object, ResultStatusEnum> nodeTypesEither = findToscaElement(mappedToscaTemplate, TypeUtils.ToscaTagNamesEnum.NODE_TYPES,
+                ToscaElementTypeEnum.MAP);
             if (nodeTypesEither.isLeft()) {
                 final Map<String, Object> nodeTypes = (Map<String, Object>) nodeTypesEither.left().value();
                 for (final Map.Entry<String, Object> nodeType : nodeTypes.entrySet()) {
-                    
                     if (!nodeTypesInfo.containsKey(nodeType.getKey()) && nodeTypesUsedInNodeTemplates.contains(nodeType.getKey())) {
                         nodeTypesInfo.put(nodeType.getKey(), buildNodeTypeInfo(nodeType, entry.getKey(), mappedToscaTemplate));
                     }
@@ -266,56 +278,35 @@ public class CsarInfo {
     }
 
     @SuppressWarnings("unchecked")
-    private static ResultStatusEnum processNodeTemplates( Map<String, Object> nodeTemplates, Map<String, NodeTypeInfo> nodeTypesInfo) {
-        nodeTemplates.values().forEach(nt->processNodeTemplate(nodeTypesInfo, (Map<String, Object>) nt));
-        return ResultStatusEnum.OK;
-    }
-    
-    @SuppressWarnings("unchecked")
-    private NodeTypeInfo buildNodeTypeInfo(final Map.Entry<String, Object> nodeType, final String templateFileName, final Map<String, Object> mappedToscaTemplate ) {
+    private NodeTypeInfo buildNodeTypeInfo(final Map.Entry<String, Object> nodeType, final String templateFileName,
+                                           final Map<String, Object> mappedToscaTemplate) {
         final NodeTypeInfo nodeTypeInfo = new NodeTypeInfo();
         nodeTypeInfo.setSubstitutionMapping(false);
         nodeTypeInfo.setNested(true);
         nodeTypeInfo.setType(nodeType.getKey());
         nodeTypeInfo.setTemplateFileName(templateFileName);
         nodeTypeInfo.setMappedToscaTemplate(buildToscaTemplateForNode(nodeType.getKey(), mappedToscaTemplate));
-        
         final Map<String, Object> nodeTypeMap = (Map<String, Object>) nodeType.getValue();
         final List<String> derivedFrom = new ArrayList<>();
         derivedFrom.add((String) nodeTypeMap.get(TypeUtils.ToscaTagNamesEnum.DERIVED_FROM.getElementName()));
         nodeTypeInfo.setDerivedFrom(derivedFrom);
-        
         return nodeTypeInfo;
     }
-    
+
     @SuppressWarnings("unchecked")
     private Map<String, Object> buildToscaTemplateForNode(final String nodeTypeName, final Map<String, Object> mappedToscaTemplate) {
         final Map<String, Object> mappedToscaTemplateforNode = new HashMap<>(mappedToscaTemplate);
-        
-        final Either<Object, ResultStatusEnum> nodeTypesEither = findToscaElement(mappedToscaTemplate,
-                TypeUtils.ToscaTagNamesEnum.NODE_TYPES, ToscaElementTypeEnum.MAP);
+        final Either<Object, ResultStatusEnum> nodeTypesEither = findToscaElement(mappedToscaTemplate, TypeUtils.ToscaTagNamesEnum.NODE_TYPES,
+            ToscaElementTypeEnum.MAP);
         final Map<String, Object> nodeTypes = new HashMap<>();
         if (nodeTypesEither.isLeft()) {
             final Map<String, Object> allNodeTypes = (Map<String, Object>) nodeTypesEither.left().value();
             nodeTypes.put(nodeTypeName, allNodeTypes.get(nodeTypeName));
         }
-
         mappedToscaTemplateforNode.put(TypeUtils.ToscaTagNamesEnum.NODE_TYPES.getElementName(), nodeTypes);
         return mappedToscaTemplateforNode;
     }
 
-    private static void processNodeTemplate(Map<String, NodeTypeInfo> nodeTypesInfo, Map<String, Object> nodeTemplate) {
-        if (nodeTemplate.containsKey(TypeUtils.ToscaTagNamesEnum.TYPE.getElementName())) {
-            String type = (String) nodeTemplate.get(TypeUtils.ToscaTagNamesEnum.TYPE.getElementName());
-            if (nodeTypesInfo.containsKey(type)) {
-                NodeTypeInfo nodeTypeInfo = nodeTypesInfo.get(type);
-                if (nodeTypeInfo.isSubstitutionMapping() && type.contains(Constants.USER_DEFINED_RESOURCE_NAMESPACE_PREFIX)) {
-                    nodeTypeInfo.setNested(true);
-                }
-            }
-        }
-    }
-
     /**
      * Gets the software information yaml path from the csar file map.
      *
@@ -325,10 +316,7 @@ public class CsarInfo {
         if (MapUtils.isEmpty(csar)) {
             return Optional.empty();
         }
-        final NonManoFolderType softwareInformationType =
-            nonManoConfiguration.getNonManoType(NonManoArtifactType.ONAP_SW_INFORMATION);
-        return csar.keySet().stream()
-            .filter(filePath -> filePath.startsWith(softwareInformationType.getPath()))
-            .findFirst();
+        final NonManoFolderType softwareInformationType = nonManoConfiguration.getNonManoType(NonManoArtifactType.ONAP_SW_INFORMATION);
+        return csar.keySet().stream().filter(filePath -> filePath.startsWith(softwareInformationType.getPath())).findFirst();
     }
 }
index 58f46bc..32e0918 100644 (file)
  */
 package org.openecomp.sdc.be.components.csar;
 
+import static java.util.stream.Collectors.toList;
+import static org.openecomp.sdc.be.components.impl.ImportUtils.ResultStatusEnum;
+import static org.openecomp.sdc.be.components.impl.ImportUtils.ToscaElementTypeEnum;
+import static org.openecomp.sdc.be.components.impl.ImportUtils.findFirstToscaListElement;
+import static org.openecomp.sdc.be.components.impl.ImportUtils.findFirstToscaMapElement;
+import static org.openecomp.sdc.be.components.impl.ImportUtils.findToscaElement;
+import static org.openecomp.sdc.be.components.impl.ImportUtils.loadYamlAsStrictMap;
+import static org.openecomp.sdc.be.utils.TypeUtils.ToscaTagNamesEnum.ARTIFACTS;
+import static org.openecomp.sdc.be.utils.TypeUtils.ToscaTagNamesEnum.CAPABILITIES;
+import static org.openecomp.sdc.be.utils.TypeUtils.ToscaTagNamesEnum.CAPABILITY;
+import static org.openecomp.sdc.be.utils.TypeUtils.ToscaTagNamesEnum.DEFAULT_VALUE;
+import static org.openecomp.sdc.be.utils.TypeUtils.ToscaTagNamesEnum.DESCRIPTION;
+import static org.openecomp.sdc.be.utils.TypeUtils.ToscaTagNamesEnum.FILE;
+import static org.openecomp.sdc.be.utils.TypeUtils.ToscaTagNamesEnum.GET_INPUT;
+import static org.openecomp.sdc.be.utils.TypeUtils.ToscaTagNamesEnum.GROUPS;
+import static org.openecomp.sdc.be.utils.TypeUtils.ToscaTagNamesEnum.IS_PASSWORD;
+import static org.openecomp.sdc.be.utils.TypeUtils.ToscaTagNamesEnum.MEMBERS;
+import static org.openecomp.sdc.be.utils.TypeUtils.ToscaTagNamesEnum.NODE;
+import static org.openecomp.sdc.be.utils.TypeUtils.ToscaTagNamesEnum.NODE_TEMPLATES;
+import static org.openecomp.sdc.be.utils.TypeUtils.ToscaTagNamesEnum.POLICIES;
+import static org.openecomp.sdc.be.utils.TypeUtils.ToscaTagNamesEnum.PROPERTIES;
+import static org.openecomp.sdc.be.utils.TypeUtils.ToscaTagNamesEnum.REQUIREMENTS;
+import static org.openecomp.sdc.be.utils.TypeUtils.ToscaTagNamesEnum.SUBSTITUTION_MAPPINGS;
+import static org.openecomp.sdc.be.utils.TypeUtils.ToscaTagNamesEnum.TARGETS;
+import static org.openecomp.sdc.be.utils.TypeUtils.ToscaTagNamesEnum.TOPOLOGY_TEMPLATE;
+import static org.openecomp.sdc.be.utils.TypeUtils.ToscaTagNamesEnum.TYPE;
+import static org.openecomp.sdc.be.utils.TypeUtils.ToscaTagNamesEnum.VALID_SOURCE_TYPES;
+
 import com.google.common.collect.Lists;
 import com.google.common.collect.Maps;
 import com.google.gson.Gson;
 import fj.data.Either;
+import java.util.ArrayList;
+import java.util.Collection;
 import java.util.Collections;
 import java.util.EnumMap;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
 import java.util.Objects;
+import java.util.Set;
+import java.util.regex.Pattern;
+import java.util.stream.Collectors;
 import org.apache.commons.collections.CollectionUtils;
 import org.apache.commons.collections.MapUtils;
 import org.apache.commons.lang.StringUtils;
@@ -66,43 +102,6 @@ import org.openecomp.sdc.common.log.wrappers.Logger;
 import org.springframework.stereotype.Component;
 import org.yaml.snakeyaml.parser.ParserException;
 
-import java.util.ArrayList;
-import java.util.Collection;
-import java.util.HashMap;
-import java.util.List;
-import java.util.Map;
-import java.util.Set;
-import java.util.regex.Pattern;
-import java.util.stream.Collectors;
-
-import static java.util.stream.Collectors.toList;
-import static org.openecomp.sdc.be.components.impl.ImportUtils.ResultStatusEnum;
-import static org.openecomp.sdc.be.components.impl.ImportUtils.ToscaElementTypeEnum;
-import static org.openecomp.sdc.be.components.impl.ImportUtils.findFirstToscaListElement;
-import static org.openecomp.sdc.be.components.impl.ImportUtils.findFirstToscaMapElement;
-import static org.openecomp.sdc.be.components.impl.ImportUtils.findToscaElement;
-import static org.openecomp.sdc.be.components.impl.ImportUtils.loadYamlAsStrictMap;
-import static org.openecomp.sdc.be.utils.TypeUtils.ToscaTagNamesEnum.ARTIFACTS;
-import static org.openecomp.sdc.be.utils.TypeUtils.ToscaTagNamesEnum.CAPABILITIES;
-import static org.openecomp.sdc.be.utils.TypeUtils.ToscaTagNamesEnum.CAPABILITY;
-import static org.openecomp.sdc.be.utils.TypeUtils.ToscaTagNamesEnum.DEFAULT_VALUE;
-import static org.openecomp.sdc.be.utils.TypeUtils.ToscaTagNamesEnum.DESCRIPTION;
-import static org.openecomp.sdc.be.utils.TypeUtils.ToscaTagNamesEnum.FILE;
-import static org.openecomp.sdc.be.utils.TypeUtils.ToscaTagNamesEnum.GET_INPUT;
-import static org.openecomp.sdc.be.utils.TypeUtils.ToscaTagNamesEnum.GROUPS;
-import static org.openecomp.sdc.be.utils.TypeUtils.ToscaTagNamesEnum.IS_PASSWORD;
-import static org.openecomp.sdc.be.utils.TypeUtils.ToscaTagNamesEnum.MEMBERS;
-import static org.openecomp.sdc.be.utils.TypeUtils.ToscaTagNamesEnum.NODE;
-import static org.openecomp.sdc.be.utils.TypeUtils.ToscaTagNamesEnum.NODE_TEMPLATES;
-import static org.openecomp.sdc.be.utils.TypeUtils.ToscaTagNamesEnum.POLICIES;
-import static org.openecomp.sdc.be.utils.TypeUtils.ToscaTagNamesEnum.PROPERTIES;
-import static org.openecomp.sdc.be.utils.TypeUtils.ToscaTagNamesEnum.REQUIREMENTS;
-import static org.openecomp.sdc.be.utils.TypeUtils.ToscaTagNamesEnum.SUBSTITUTION_MAPPINGS;
-import static org.openecomp.sdc.be.utils.TypeUtils.ToscaTagNamesEnum.TARGETS;
-import static org.openecomp.sdc.be.utils.TypeUtils.ToscaTagNamesEnum.TOPOLOGY_TEMPLATE;
-import static org.openecomp.sdc.be.utils.TypeUtils.ToscaTagNamesEnum.TYPE;
-import static org.openecomp.sdc.be.utils.TypeUtils.ToscaTagNamesEnum.VALID_SOURCE_TYPES;
-
 /**
  * A handler class designed to parse the YAML file of the service template for a JAVA object
  */
@@ -113,8 +112,6 @@ public class YamlTemplateParsingHandler {
     private static final int SUB_MAPPING_CAPABILITY_OWNER_NAME_IDX = 0;
     private static final int SUB_MAPPING_CAPABILITY_NAME_IDX = 1;
     private static final Logger log = Logger.getLogger(YamlTemplateParsingHandler.class);
-
-
     private Gson gson = new Gson();
     private JanusGraphDao janusGraphDao;
     private GroupTypeBusinessLogic groupTypeBusinessLogic;
@@ -122,7 +119,7 @@ public class YamlTemplateParsingHandler {
     private PolicyTypeBusinessLogic policyTypeBusinessLogic;
 
     public YamlTemplateParsingHandler(JanusGraphDao janusGraphDao, GroupTypeBusinessLogic groupTypeBusinessLogic,
-            AnnotationBusinessLogic annotationBusinessLogic, PolicyTypeBusinessLogic policyTypeBusinessLogic) {
+                                      AnnotationBusinessLogic annotationBusinessLogic, PolicyTypeBusinessLogic policyTypeBusinessLogic) {
         this.janusGraphDao = janusGraphDao;
         this.groupTypeBusinessLogic = groupTypeBusinessLogic;
         this.annotationBusinessLogic = annotationBusinessLogic;
@@ -130,25 +127,24 @@ public class YamlTemplateParsingHandler {
     }
 
     public ParsedToscaYamlInfo parseResourceInfoFromYAML(String fileName, String resourceYml, Map<String, String> createdNodesToscaResourceNames,
-                                                         Map<String, NodeTypeInfo> nodeTypesInfo, String nodeName, org.openecomp.sdc.be.model.Component component) {
+                                                         Map<String, NodeTypeInfo> nodeTypesInfo, String nodeName,
+                                                         org.openecomp.sdc.be.model.Component component) {
         log.debug("#parseResourceInfoFromYAML - Going to parse yaml {} ", fileName);
         Map<String, Object> mappedToscaTemplate = getMappedToscaTemplate(fileName, resourceYml, nodeTypesInfo, nodeName);
         ParsedToscaYamlInfo parsedToscaYamlInfo = new ParsedToscaYamlInfo();
-        findToscaElement(mappedToscaTemplate, TOPOLOGY_TEMPLATE, ToscaElementTypeEnum.ALL)
-                .left()
-                .on(err -> failIfNotTopologyTemplate(fileName));
-
+        findToscaElement(mappedToscaTemplate, TOPOLOGY_TEMPLATE, ToscaElementTypeEnum.ALL).left().on(err -> failIfNotTopologyTemplate(fileName));
         parsedToscaYamlInfo.setInputs(getInputs(mappedToscaTemplate));
         parsedToscaYamlInfo.setInstances(getInstances(fileName, mappedToscaTemplate, createdNodesToscaResourceNames));
         parsedToscaYamlInfo.setGroups(getGroups(fileName, mappedToscaTemplate));
-        if(component instanceof Resource){
+        if (component instanceof Resource) {
             parsedToscaYamlInfo.setPolicies(getPolicies(fileName, mappedToscaTemplate));
         }
         log.debug("#parseResourceInfoFromYAML - The yaml {} has been parsed ", fileName);
         return parsedToscaYamlInfo;
     }
 
-    private Map<String, Object> getMappedToscaTemplate(String fileName, String resourceYml, Map<String, NodeTypeInfo> nodeTypesInfo, String nodeName) {
+    private Map<String, Object> getMappedToscaTemplate(String fileName, String resourceYml, Map<String, NodeTypeInfo> nodeTypesInfo,
+                                                       String nodeName) {
         Map<String, Object> mappedToscaTemplate;
         if (isNodeExist(nodeTypesInfo, nodeName)) {
             mappedToscaTemplate = nodeTypesInfo.get(nodeName).getMappedToscaTemplate();
@@ -174,25 +170,16 @@ public class YamlTemplateParsingHandler {
     }
 
     private Map<String, InputDefinition> getInputs(Map<String, Object> toscaJson) {
-        Map<String, InputDefinition> inputs = ImportUtils.getInputs(toscaJson, annotationBusinessLogic.getAnnotationTypeOperations())
-                .left()
-                .on(err -> new HashMap<>());
+        Map<String, InputDefinition> inputs = ImportUtils.getInputs(toscaJson, annotationBusinessLogic.getAnnotationTypeOperations()).left()
+            .on(err -> new HashMap<>());
         annotationBusinessLogic.validateAndMergeAnnotationsAndAssignToInput(inputs);
         return inputs;
     }
 
     private Map<String, PolicyDefinition> getPolicies(String fileName, Map<String, Object> toscaJson) {
-
-        Map<String, Object> foundPolicies = findFirstToscaMapElement(toscaJson, POLICIES)
-                                                  .left()
-                                                  .on(err -> logPoliciesNotFound(fileName));
-
+        Map<String, Object> foundPolicies = findFirstToscaMapElement(toscaJson, POLICIES).left().on(err -> logPoliciesNotFound(fileName));
         if (MapUtils.isNotEmpty(foundPolicies)) {
-            return foundPolicies
-                           .entrySet()
-                           .stream()
-                           .map(this::createPolicy)
-                           .collect(Collectors.toMap(PolicyDefinition::getName, p -> p));
+            return foundPolicies.entrySet().stream().map(this::createPolicy).collect(Collectors.toMap(PolicyDefinition::getName, p -> p));
         }
         return Collections.emptyMap();
     }
@@ -222,7 +209,7 @@ public class YamlTemplateParsingHandler {
 
     private void validateAndFillPolicy(PolicyDefinition emptyPolicyDefinition, Map<String, Object> policyTemplateJsonMap) {
         String policyTypeName = (String) policyTemplateJsonMap.get(TYPE.getElementName());
-        if(StringUtils.isEmpty(policyTypeName)){
+        if (StringUtils.isEmpty(policyTypeName)) {
             log.debug("#validateAndFillPolicy - The 'type' member is not found under policy {}", emptyPolicyDefinition.getName());
             rollbackWithException(ActionStatus.POLICY_MISSING_POLICY_TYPE, emptyPolicyDefinition.getName());
         }
@@ -244,23 +231,18 @@ public class YamlTemplateParsingHandler {
     }
 
     private List<PropertyDataDefinition> validateFillPolicyProperties(PolicyTypeDefinition policyTypeDefinition,
-            Map<String, Object> policyTemplateJsonMap) {
+                                                                      Map<String, Object> policyTemplateJsonMap) {
         if (MapUtils.isEmpty(policyTemplateJsonMap) || Objects.isNull(policyTypeDefinition)) {
             return Collections.emptyList();
         }
         List<PropertyDataDefinition> propertyDataDefinitionList = new ArrayList<>();
-        Map<String, Object> propertiesMap =
-                (Map<String, Object>) policyTemplateJsonMap.get(PROPERTIES.getElementName());
+        Map<String, Object> propertiesMap = (Map<String, Object>) policyTemplateJsonMap.get(PROPERTIES.getElementName());
         if (MapUtils.isEmpty(propertiesMap)) {
             return Collections.emptyList();
         }
         if (CollectionUtils.isNotEmpty(policyTypeDefinition.getProperties())) {
-            propertyDataDefinitionList = policyTypeDefinition
-                                                 .getProperties()
-                                                 .stream()
-                                                 .map(propertyDefinition -> setPropertyValue(propertiesMap,
-                                                         propertyDefinition))
-                                                 .collect(Collectors.toList());
+            propertyDataDefinitionList = policyTypeDefinition.getProperties().stream()
+                .map(propertyDefinition -> setPropertyValue(propertiesMap, propertyDefinition)).collect(Collectors.toList());
         }
         return propertyDataDefinitionList;
     }
@@ -277,30 +259,26 @@ public class YamlTemplateParsingHandler {
 
     private Map<PolicyTargetType, List<String>> validateFillPolicyTargets(Map<String, Object> policyTemplateJson) {
         Map<PolicyTargetType, List<String>> targets = new EnumMap<>(PolicyTargetType.class);
-        if (policyTemplateJson.containsKey(TARGETS.getElementName())
-                    && policyTemplateJson.get(TARGETS.getElementName()) instanceof List ) {
+        if (policyTemplateJson.containsKey(TARGETS.getElementName()) && policyTemplateJson.get(TARGETS.getElementName()) instanceof List) {
             List<String> targetsElement = (List<String>) policyTemplateJson.get(TARGETS.getElementName());
             targets.put(PolicyTargetType.COMPONENT_INSTANCES, targetsElement);
         }
         return targets;
     }
 
-    private Map<String, UploadComponentInstanceInfo> getInstances(String yamlName, Map<String, Object> toscaJson, Map<String, String> createdNodesToscaResourceNames) {
-
-        Map<String, Object> nodeTemlates = findFirstToscaMapElement(toscaJson, NODE_TEMPLATES)
-                .left()
-                .on(err -> failIfNoNodeTemplates(yamlName));
-
+    private Map<String, UploadComponentInstanceInfo> getInstances(String yamlName, Map<String, Object> toscaJson,
+                                                                  Map<String, String> createdNodesToscaResourceNames) {
+        Map<String, Object> nodeTemlates = findFirstToscaMapElement(toscaJson, NODE_TEMPLATES).left().on(err -> failIfNoNodeTemplates(yamlName));
         return getInstances(toscaJson, createdNodesToscaResourceNames, nodeTemlates);
     }
 
-    private Map<String, UploadComponentInstanceInfo> getInstances(Map<String, Object> toscaJson, Map<String, String> createdNodesToscaResourceNames, Map<String, Object> nodeTemlates) {
+    private Map<String, UploadComponentInstanceInfo> getInstances(Map<String, Object> toscaJson, Map<String, String> createdNodesToscaResourceNames,
+                                                                  Map<String, Object> nodeTemlates) {
         Map<String, UploadComponentInstanceInfo> moduleComponentInstances;
         Map<String, Object> substitutionMappings = getSubstitutionMappings(toscaJson);
-        moduleComponentInstances = nodeTemlates.entrySet()
-                .stream()
-                .map(node -> buildModuleComponentInstanceInfo(node, substitutionMappings, createdNodesToscaResourceNames))
-                .collect(Collectors.toMap(UploadComponentInstanceInfo::getName, i -> i));
+        moduleComponentInstances = nodeTemlates.entrySet().stream()
+            .map(node -> buildModuleComponentInstanceInfo(node, substitutionMappings, createdNodesToscaResourceNames))
+            .collect(Collectors.toMap(UploadComponentInstanceInfo::getName, i -> i));
         return moduleComponentInstances;
     }
 
@@ -315,29 +293,22 @@ public class YamlTemplateParsingHandler {
 
     @SuppressWarnings("unchecked")
     private Map<String, GroupDefinition> getGroups(String fileName, Map<String, Object> toscaJson) {
-
-        Map<String, Object> foundGroups = findFirstToscaMapElement(toscaJson, GROUPS)
-                .left()
-                .on(err -> logGroupsNotFound(fileName));
-
+        Map<String, Object> foundGroups = findFirstToscaMapElement(toscaJson, GROUPS).left().on(err -> logGroupsNotFound(fileName));
         if (MapUtils.isNotEmpty(foundGroups) && matcheKey(foundGroups)) {
-            Map<String, GroupDefinition> groups = foundGroups
-                    .entrySet()
-                    .stream()
-                    .map(this::createGroup)
-                    .collect(Collectors.toMap(GroupDefinition::getName, g -> g));
+            Map<String, GroupDefinition> groups = foundGroups.entrySet().stream().map(this::createGroup)
+                .collect(Collectors.toMap(GroupDefinition::getName, g -> g));
             Map<String, Object> substitutionMappings = getSubstitutionMappings(toscaJson);
             if (capabilitiesSubstitutionMappingsExist(substitutionMappings)) {
-                groups.entrySet().forEach(entry -> updateCapabilitiesNames(entry.getValue(), getNamesToUpdate(entry.getKey(),
-                        (Map<String, List<String>>) substitutionMappings.get(CAPABILITIES.getElementName()))));
+                groups.entrySet().forEach(entry -> updateCapabilitiesNames(entry.getValue(),
+                    getNamesToUpdate(entry.getKey(), (Map<String, List<String>>) substitutionMappings.get(CAPABILITIES.getElementName()))));
             }
             return groups;
         }
         return new HashMap<>();
     }
 
-    private boolean matcheKey(Map<String, Object> foundGroups){
-        if (foundGroups!=null && !foundGroups.isEmpty()) {
+    private boolean matcheKey(Map<String, Object> foundGroups) {
+        if (foundGroups != null && !foundGroups.isEmpty()) {
             for (Map.Entry<String, Object> stringObjectEntry : foundGroups.entrySet()) {
                 String key = stringObjectEntry.getKey();
                 if (key.contains("group")) {
@@ -357,18 +328,14 @@ public class YamlTemplateParsingHandler {
 
     private void updateCapabilitiesNames(GroupDefinition group, Map<String, String> capabilityNames) {
         if (MapUtils.isNotEmpty(group.getCapabilities())) {
-            group.getCapabilities().values()
-                    .stream()
-                    .flatMap(Collection::stream)
-                    .filter(cap -> capabilityNames.containsKey(cap.getName()))
-                    .forEach(cap -> cap.setName(capabilityNames.get(cap.getName())));
+            group.getCapabilities().values().stream().flatMap(Collection::stream).filter(cap -> capabilityNames.containsKey(cap.getName()))
+                .forEach(cap -> cap.setName(capabilityNames.get(cap.getName())));
         }
     }
 
     private Map<String, String> getNamesToUpdate(String name, Map<String, List<String>> pair) {
-        return pair.entrySet().stream()
-                .filter(e -> e.getValue().get(SUB_MAPPING_CAPABILITY_OWNER_NAME_IDX).equalsIgnoreCase(name))
-                .collect(Collectors.toMap(e -> e.getValue().get(SUB_MAPPING_CAPABILITY_NAME_IDX), Map.Entry::getKey,  (n1 ,n2) -> n1));
+        return pair.entrySet().stream().filter(e -> e.getValue().get(SUB_MAPPING_CAPABILITY_OWNER_NAME_IDX).equalsIgnoreCase(name))
+            .collect(Collectors.toMap(e -> e.getValue().get(SUB_MAPPING_CAPABILITY_NAME_IDX), Map.Entry::getKey, (n1, n2) -> n1));
     }
 
     private boolean capabilitiesSubstitutionMappingsExist(Map<String, Object> substitutionMappings) {
@@ -420,30 +387,28 @@ public class YamlTemplateParsingHandler {
     }
 
     private void setMembersFromList(GroupDefinition groupInfo, List<?> membersAsList) {
-        groupInfo.setMembers(membersAsList
-                .stream()
-                .collect(Collectors.toMap(Object::toString, member -> "")));
+        groupInfo.setMembers(membersAsList.stream().collect(Collectors.toMap(Object::toString, member -> "")));
     }
 
     @SuppressWarnings("unchecked")
     private void validateUpdateGroupProperties(GroupDefinition groupInfo, Map<String, Object> groupTemplateJsonMap) {
         if (groupTemplateJsonMap.containsKey(PROPERTIES.getElementName())) {
             Object propertiesElement = groupTemplateJsonMap.get(PROPERTIES.getElementName());
-            if (propertiesElement instanceof Map){
+            if (propertiesElement instanceof Map) {
                 mergeGroupProperties(groupInfo, (Map<String, Object>) propertiesElement);
             }
         }
     }
 
     private void mergeGroupProperties(GroupDefinition groupInfo, Map<String, Object> parsedProperties) {
-        if(CollectionUtils.isNotEmpty(groupInfo.getProperties())){
+        if (CollectionUtils.isNotEmpty(groupInfo.getProperties())) {
             validateGroupProperties(parsedProperties, groupInfo);
             groupInfo.getProperties().forEach(p -> mergeGroupProperty(p, parsedProperties));
         }
     }
 
     private void mergeGroupProperty(PropertyDataDefinition property, Map<String, Object> parsedProperties) {
-        if(parsedProperties.containsKey(property.getName())){
+        if (parsedProperties.containsKey(property.getName())) {
             Object propValue = parsedProperties.get(property.getName());
             if (valueNotContainsPattern(propertyValuePattern, propValue)) {
                 setPropertyValueAndGetInputsValues(property, propValue);
@@ -452,7 +417,7 @@ public class YamlTemplateParsingHandler {
     }
 
     private void setPropertyValueAndGetInputsValues(PropertyDataDefinition property, Object propValue) {
-        if(propValue != null){
+        if (propValue != null) {
             UploadPropInfo uploadPropInfo = buildProperty(property.getName(), propValue);
             property.setValue(convertPropertyValue(ToscaPropertyType.isValidType(property.getType()), uploadPropInfo.getValue()));
             property.setGetInputValues(uploadPropInfo.getGet_input());
@@ -473,19 +438,18 @@ public class YamlTemplateParsingHandler {
 
     private void setDescription(GroupDefinition groupInfo, Map<String, Object> groupTemplateJsonMap) {
         if (groupTemplateJsonMap.containsKey(DESCRIPTION.getElementName())) {
-            groupInfo.setDescription(
-                    (String) groupTemplateJsonMap.get(DESCRIPTION.getElementName()));
+            groupInfo.setDescription((String) groupTemplateJsonMap.get(DESCRIPTION.getElementName()));
         }
     }
 
     private void validateAndFillGroup(GroupDefinition groupInfo, Map<String, Object> groupTemplateJsonMap) {
         String type = (String) groupTemplateJsonMap.get(TYPE.getElementName());
-        if(StringUtils.isEmpty(type)){
+        if (StringUtils.isEmpty(type)) {
             log.debug("#validateAndFillGroup - The 'type' member is not found under group {}", groupInfo.getName());
             rollbackWithException(ActionStatus.GROUP_MISSING_GROUP_TYPE, groupInfo.getName());
         }
         groupInfo.setType(type);
-        GroupTypeDefinition groupType =  groupTypeBusinessLogic.getLatestGroupTypeByType(type);
+        GroupTypeDefinition groupType = groupTypeBusinessLogic.getLatestGroupTypeByType(type);
         if (groupType == null) {
             log.debug("#validateAndFillGroup - The group type {} not found", groupInfo.getName());
             rollbackWithException(ActionStatus.GROUP_TYPE_IS_INVALID, type);
@@ -498,17 +462,14 @@ public class YamlTemplateParsingHandler {
 
     @SuppressWarnings("unchecked")
     private void validateUpdateGroupCapabilities(GroupDefinition groupInfo, Map<String, Object> groupTemplateJsonMap) {
-
         if (groupTemplateJsonMap.containsKey(CAPABILITIES.getElementName())) {
             Object capabilities = groupTemplateJsonMap.get(CAPABILITIES.getElementName());
             if (capabilities instanceof List) {
-                validateUpdateCapabilities(groupInfo, ((List<Object>) capabilities).stream()
-                        .map(o -> buildGroupCapability(groupInfo, o))
-                        .collect(Collectors.toMap(CapabilityDefinition::getType, this::addCapability, this::addCapabilities)));
+                validateUpdateCapabilities(groupInfo, ((List<Object>) capabilities).stream().map(o -> buildGroupCapability(groupInfo, o))
+                    .collect(Collectors.toMap(CapabilityDefinition::getType, this::addCapability, this::addCapabilities)));
             } else if (capabilities instanceof Map) {
-                validateUpdateCapabilities(groupInfo, ((Map<String, Object>) capabilities).entrySet()
-                        .stream()
-                        .map(e -> buildGroupCapability(groupInfo, e))
+                validateUpdateCapabilities(groupInfo,
+                    ((Map<String, Object>) capabilities).entrySet().stream().map(e -> buildGroupCapability(groupInfo, e))
                         .collect(Collectors.toMap(CapabilityDefinition::getType, this::addCapability, this::addCapabilities)));
             } else {
                 log.debug("#setCapabilities - Failed to import the capabilities of the group {}. ", groupInfo.getName());
@@ -527,7 +488,8 @@ public class YamlTemplateParsingHandler {
             if (MapUtils.isEmpty(group.getCapabilities())) {
                 failOnMissingCapabilityTypes(group, Lists.newArrayList(parsedCapabilities.keySet()));
             }
-            List<String> missingCapTypes = parsedCapabilities.keySet().stream().filter(ct -> !group.getCapabilities().containsKey(ct)).collect(toList());
+            List<String> missingCapTypes = parsedCapabilities.keySet().stream().filter(ct -> !group.getCapabilities().containsKey(ct))
+                .collect(toList());
             if (CollectionUtils.isNotEmpty(missingCapTypes)) {
                 failOnMissingCapabilityTypes(group, missingCapTypes);
             }
@@ -535,7 +497,8 @@ public class YamlTemplateParsingHandler {
         }
     }
 
-    private void validateCapabilities(GroupDefinition group, List<CapabilityDefinition> capabilities, Map<String, CapabilityDefinition> parsedCapabilities) {
+    private void validateCapabilities(GroupDefinition group, List<CapabilityDefinition> capabilities,
+                                      Map<String, CapabilityDefinition> parsedCapabilities) {
         List<String> allowedCapNames = capabilities.stream().map(CapabilityDefinition::getName).distinct().collect(toList());
         List<String> missingCapNames = parsedCapabilities.keySet().stream().filter(c -> !allowedCapNames.contains(c)).collect(toList());
         if (CollectionUtils.isNotEmpty(missingCapNames)) {
@@ -549,33 +512,30 @@ public class YamlTemplateParsingHandler {
     }
 
     private void validateCapabilityProperties(CapabilityDefinition capability, CapabilityDefinition parsedCapability) {
-        if(parsedCapability != null && parsedCapability.getProperties() != null){
-            List<String> parsedPropertiesNames = parsedCapability.getProperties()
-                .stream()
-                .map(ComponentInstanceProperty::getName).collect(toList());
-            validateProperties(capability.getProperties().stream().map(PropertyDataDefinition::getName).collect(toList()), parsedPropertiesNames, ActionStatus.PROPERTY_NOT_FOUND, capability.getName(), capability.getType());
+        if (parsedCapability != null && parsedCapability.getProperties() != null) {
+            List<String> parsedPropertiesNames = parsedCapability.getProperties().stream().map(ComponentInstanceProperty::getName).collect(toList());
+            validateProperties(capability.getProperties().stream().map(PropertyDataDefinition::getName).collect(toList()), parsedPropertiesNames,
+                ActionStatus.PROPERTY_NOT_FOUND, capability.getName(), capability.getType());
         }
     }
 
-    private void  validateGroupProperties(Map<String, Object> parsedProperties, GroupDefinition groupInfo) {
-        List<String> parsedPropertiesNames = parsedProperties.entrySet()
-                        .stream()
-                        .map(Map.Entry::getKey).collect(toList());
-        validateProperties(groupInfo.getProperties().stream().map(PropertyDataDefinition::getName).collect(toList()), parsedPropertiesNames, ActionStatus.GROUP_PROPERTY_NOT_FOUND, groupInfo.getName(), groupInfo.getType());
+    private void validateGroupProperties(Map<String, Object> parsedProperties, GroupDefinition groupInfo) {
+        List<String> parsedPropertiesNames = parsedProperties.entrySet().stream().map(Map.Entry::getKey).collect(toList());
+        validateProperties(groupInfo.getProperties().stream().map(PropertyDataDefinition::getName).collect(toList()), parsedPropertiesNames,
+            ActionStatus.GROUP_PROPERTY_NOT_FOUND, groupInfo.getName(), groupInfo.getType());
     }
 
-    private void validateProperties(List<String> validProperties, List<String> parsedProperties, ActionStatus actionStatus, String name, String type) {
+    private void validateProperties(List<String> validProperties, List<String> parsedProperties, ActionStatus actionStatus, String name,
+                                    String type) {
         if (CollectionUtils.isNotEmpty(parsedProperties)) {
-            verifyMissingProperties(actionStatus, name, type, parsedProperties
-                    .stream()
-                    .filter(n -> !validProperties.contains(n))
-                    .collect(toList()));
+            verifyMissingProperties(actionStatus, name, type, parsedProperties.stream().filter(n -> !validProperties.contains(n)).collect(toList()));
         }
     }
 
     private void verifyMissingProperties(ActionStatus actionStatus, String name, String type, List<String> missingProperties) {
         if (CollectionUtils.isNotEmpty(missingProperties)) {
-            log.debug("#validateProperties - Failed to validate properties. The properties {} are missing on {} of the type {}. ", missingProperties.toString(), name, type);
+            log.debug("#validateProperties - Failed to validate properties. The properties {} are missing on {} of the type {}. ",
+                missingProperties.toString(), name, type);
             rollbackWithException(actionStatus, missingProperties.toString(), missingProperties.toString(), name, type);
         }
     }
@@ -624,10 +584,9 @@ public class YamlTemplateParsingHandler {
     }
 
     @SuppressWarnings("unchecked")
-    private UploadComponentInstanceInfo buildModuleComponentInstanceInfo(
-            Map.Entry<String, Object> nodeTemplateJsonEntry, Map<String, Object> substitutionMappings,
-            Map<String, String> createdNodesToscaResourceNames) {
-
+    private UploadComponentInstanceInfo buildModuleComponentInstanceInfo(Map.Entry<String, Object> nodeTemplateJsonEntry,
+                                                                         Map<String, Object> substitutionMappings,
+                                                                         Map<String, String> createdNodesToscaResourceNames) {
         UploadComponentInstanceInfo nodeTemplateInfo = new UploadComponentInstanceInfo();
         nodeTemplateInfo.setName(nodeTemplateJsonEntry.getKey());
         try {
@@ -659,13 +618,12 @@ public class YamlTemplateParsingHandler {
     private void setSubstitutions(Map<String, Object> substitutionMappings, UploadComponentInstanceInfo nodeTemplateInfo) {
         if (substitutionMappings != null) {
             if (substitutionMappings.containsKey(CAPABILITIES.getElementName())) {
-                nodeTemplateInfo.setCapabilitiesNamesToUpdate(getNamesToUpdate(nodeTemplateInfo.getName(), (Map<String, List<String>>) substitutionMappings
-                        .get(CAPABILITIES.getElementName())));
+                nodeTemplateInfo.setCapabilitiesNamesToUpdate(getNamesToUpdate(nodeTemplateInfo.getName(),
+                    (Map<String, List<String>>) substitutionMappings.get(CAPABILITIES.getElementName())));
             }
             if (substitutionMappings.containsKey(REQUIREMENTS.getElementName())) {
-                nodeTemplateInfo.setRequirementsNamesToUpdate(getNamesToUpdate(
-                        nodeTemplateInfo.getName(), (Map<String, List<String>>) substitutionMappings
-                                .get(REQUIREMENTS.getElementName())));
+                nodeTemplateInfo.setRequirementsNamesToUpdate(getNamesToUpdate(nodeTemplateInfo.getName(),
+                    (Map<String, List<String>>) substitutionMappings.get(REQUIREMENTS.getElementName())));
             }
         }
     }
@@ -706,8 +664,8 @@ public class YamlTemplateParsingHandler {
         }
     }
 
-    private void setToscaResourceType(Map<String, String> createdNodesToscaResourceNames,
-                                      UploadComponentInstanceInfo nodeTemplateInfo, Map<String, Object> nodeTemplateJsonMap) {
+    private void setToscaResourceType(Map<String, String> createdNodesToscaResourceNames, UploadComponentInstanceInfo nodeTemplateInfo,
+                                      Map<String, Object> nodeTemplateJsonMap) {
         if (nodeTemplateJsonMap.containsKey(TYPE.getElementName())) {
             String toscaResourceType = (String) nodeTemplateJsonMap.get(TYPE.getElementName());
             if (createdNodesToscaResourceNames.containsKey(toscaResourceType)) {
@@ -717,28 +675,22 @@ public class YamlTemplateParsingHandler {
         }
     }
 
-    private void setDirectives(UploadComponentInstanceInfo nodeTemplateInfo,
-            Map<String, Object> nodeTemplateJsonMap) {
-        List<String> directives =
-                (List<String>) nodeTemplateJsonMap.get(TypeUtils.ToscaTagNamesEnum.DIRECTIVES.getElementName());
+    private void setDirectives(UploadComponentInstanceInfo nodeTemplateInfo, Map<String, Object> nodeTemplateJsonMap) {
+        List<String> directives = (List<String>) nodeTemplateJsonMap.get(TypeUtils.ToscaTagNamesEnum.DIRECTIVES.getElementName());
         nodeTemplateInfo.setDirectives(directives);
     }
 
-    private void setNodeFilter(UploadComponentInstanceInfo nodeTemplateInfo,
-            Map<String, Object> nodeTemplateJsonMap) {
+    private void setNodeFilter(UploadComponentInstanceInfo nodeTemplateInfo, Map<String, Object> nodeTemplateJsonMap) {
         if (nodeTemplateJsonMap.containsKey(TypeUtils.ToscaTagNamesEnum.NODE_FILTER.getElementName())) {
-            nodeTemplateInfo.setUploadNodeFilterInfo(
-                    new NodeFilterUploadCreator().createNodeFilterData(nodeTemplateJsonMap.get(
-                            TypeUtils.ToscaTagNamesEnum.NODE_FILTER.getElementName())));
+            nodeTemplateInfo.setUploadNodeFilterInfo(new NodeFilterUploadCreator()
+                .createNodeFilterData(nodeTemplateJsonMap.get(TypeUtils.ToscaTagNamesEnum.NODE_FILTER.getElementName())));
         }
     }
 
     @SuppressWarnings("unchecked")
     private Map<String, List<UploadReqInfo>> createReqModuleFromYaml(Map<String, Object> nodeTemplateJsonMap) {
         Map<String, List<UploadReqInfo>> moduleRequirements = new HashMap<>();
-        Either<List<Object>, ResultStatusEnum> requirementsListRes =
-                findFirstToscaListElement(nodeTemplateJsonMap, REQUIREMENTS);
-
+        Either<List<Object>, ResultStatusEnum> requirementsListRes = findFirstToscaListElement(nodeTemplateJsonMap, REQUIREMENTS);
         if (requirementsListRes.isLeft()) {
             for (Object jsonReqObj : requirementsListRes.left().value()) {
                 String reqName = ((Map<String, Object>) jsonReqObj).keySet().iterator().next();
@@ -746,8 +698,7 @@ public class YamlTemplateParsingHandler {
                 addModuleNodeTemplateReq(moduleRequirements, reqJson, reqName);
             }
         } else {
-            Either<Map<String, Object>, ResultStatusEnum> requirementsMapRes =
-                    findFirstToscaMapElement(nodeTemplateJsonMap, REQUIREMENTS);
+            Either<Map<String, Object>, ResultStatusEnum> requirementsMapRes = findFirstToscaMapElement(nodeTemplateJsonMap, REQUIREMENTS);
             if (requirementsMapRes.isLeft()) {
                 for (Map.Entry<String, Object> entry : requirementsMapRes.left().value().entrySet()) {
                     String reqName = entry.getKey();
@@ -760,7 +711,6 @@ public class YamlTemplateParsingHandler {
     }
 
     private void addModuleNodeTemplateReq(Map<String, List<UploadReqInfo>> moduleRequirements, Object requirementJson, String requirementName) {
-
         UploadReqInfo requirement = buildModuleNodeTemplateReg(requirementJson);
         requirement.setName(requirementName);
         if (moduleRequirements.containsKey(requirementName)) {
@@ -775,8 +725,7 @@ public class YamlTemplateParsingHandler {
     @SuppressWarnings("unchecked")
     private Map<String, Map<String, UploadArtifactInfo>> createArtifactsModuleFromYaml(Map<String, Object> nodeTemplateJsonMap) {
         Map<String, Map<String, UploadArtifactInfo>> moduleArtifacts = new HashMap<>();
-        Either<List<Object>, ResultStatusEnum> ArtifactsListRes =
-                findFirstToscaListElement(nodeTemplateJsonMap, ARTIFACTS);
+        Either<List<Object>, ResultStatusEnum> ArtifactsListRes = findFirstToscaListElement(nodeTemplateJsonMap, ARTIFACTS);
         if (ArtifactsListRes.isLeft()) {
             for (Object jsonArtifactObj : ArtifactsListRes.left().value()) {
                 String key = ((Map<String, Object>) jsonArtifactObj).keySet().iterator().next();
@@ -784,8 +733,7 @@ public class YamlTemplateParsingHandler {
                 addModuleNodeTemplateArtifacts(moduleArtifacts, artifactJson, key);
             }
         } else {
-            Either<Map<String, Map<String, Object>>, ResultStatusEnum> ArtifactsMapRes =
-                    findFirstToscaMapElement(nodeTemplateJsonMap, ARTIFACTS);
+            Either<Map<String, Map<String, Object>>, ResultStatusEnum> ArtifactsMapRes = findFirstToscaMapElement(nodeTemplateJsonMap, ARTIFACTS);
             if (ArtifactsMapRes.isLeft()) {
                 for (Map.Entry<String, Map<String, Object>> entry : ArtifactsMapRes.left().value().entrySet()) {
                     String artifactName = entry.getKey();
@@ -797,8 +745,8 @@ public class YamlTemplateParsingHandler {
         return moduleArtifacts;
     }
 
-    private void addModuleNodeTemplateArtifacts(Map<String, Map<String, UploadArtifactInfo>> moduleArtifacts, Object artifactJson, String artifactName) {
-
+    private void addModuleNodeTemplateArtifacts(Map<String, Map<String, UploadArtifactInfo>> moduleArtifacts, Object artifactJson,
+                                                String artifactName) {
         UploadArtifactInfo artifact = buildModuleNodeTemplateArtifact(artifactJson);
         artifact.setName(artifactName);
         if (moduleArtifacts.containsKey(ARTIFACTS.getElementName())) {
@@ -828,12 +776,10 @@ public class YamlTemplateParsingHandler {
         }
     }
 
-
     @SuppressWarnings("unchecked")
     private Map<String, List<UploadCapInfo>> createCapModuleFromYaml(Map<String, Object> nodeTemplateJsonMap) {
         Map<String, List<UploadCapInfo>> moduleCap = new HashMap<>();
-        Either<List<Object>, ResultStatusEnum> capabilitiesListRes =
-                findFirstToscaListElement(nodeTemplateJsonMap, CAPABILITIES);
+        Either<List<Object>, ResultStatusEnum> capabilitiesListRes = findFirstToscaListElement(nodeTemplateJsonMap, CAPABILITIES);
         if (capabilitiesListRes.isLeft()) {
             for (Object jsonCapObj : capabilitiesListRes.left().value()) {
                 String key = ((Map<String, Object>) jsonCapObj).keySet().iterator().next();
@@ -841,8 +787,7 @@ public class YamlTemplateParsingHandler {
                 addModuleNodeTemplateCap(moduleCap, capJson, key);
             }
         } else {
-            Either<Map<String, Object>, ResultStatusEnum> capabilitiesMapRes =
-                    findFirstToscaMapElement(nodeTemplateJsonMap, CAPABILITIES);
+            Either<Map<String, Object>, ResultStatusEnum> capabilitiesMapRes = findFirstToscaMapElement(nodeTemplateJsonMap, CAPABILITIES);
             if (capabilitiesMapRes.isLeft()) {
                 for (Map.Entry<String, Object> entry : capabilitiesMapRes.left().value().entrySet()) {
                     String capName = entry.getKey();
@@ -855,7 +800,6 @@ public class YamlTemplateParsingHandler {
     }
 
     private void addModuleNodeTemplateCap(Map<String, List<UploadCapInfo>> moduleCap, Object capJson, String key) {
-
         UploadCapInfo capabilityDef = buildModuleNodeTemplateCap(capJson);
         capabilityDef.setKey(key);
         if (moduleCap.containsKey(key)) {
@@ -870,7 +814,6 @@ public class YamlTemplateParsingHandler {
     @SuppressWarnings("unchecked")
     private UploadCapInfo buildModuleNodeTemplateCap(Object capObject) {
         UploadCapInfo capTemplateInfo = new UploadCapInfo();
-
         if (capObject instanceof String) {
             String nodeTemplateJsonString = (String) capObject;
             capTemplateInfo.setNode(nodeTemplateJsonString);
@@ -888,11 +831,9 @@ public class YamlTemplateParsingHandler {
             capTemplateInfo.setType((String) nodeTemplateJsonMap.get(TYPE.getElementName()));
         }
         if (nodeTemplateJsonMap.containsKey(VALID_SOURCE_TYPES.getElementName())) {
-            Either<List<Object>, ResultStatusEnum> validSourceTypesRes =
-                    findFirstToscaListElement(nodeTemplateJsonMap, VALID_SOURCE_TYPES);
+            Either<List<Object>, ResultStatusEnum> validSourceTypesRes = findFirstToscaListElement(nodeTemplateJsonMap, VALID_SOURCE_TYPES);
             if (validSourceTypesRes.isLeft()) {
-                capTemplateInfo.setValidSourceTypes(validSourceTypesRes.left().value().stream()
-                        .map(Object::toString).collect(toList()));
+                capTemplateInfo.setValidSourceTypes(validSourceTypesRes.left().value().stream().map(Object::toString).collect(toList()));
             }
         }
         if (nodeTemplateJsonMap.containsKey(PROPERTIES.getElementName())) {
@@ -906,7 +847,6 @@ public class YamlTemplateParsingHandler {
 
     @SuppressWarnings("unchecked")
     private UploadReqInfo buildModuleNodeTemplateReg(Object regObject) {
-
         UploadReqInfo regTemplateInfo = new UploadReqInfo();
         if (regObject instanceof String) {
             String nodeTemplateJsonString = (String) regObject;
@@ -917,18 +857,15 @@ public class YamlTemplateParsingHandler {
                 regTemplateInfo.setNode((String) nodeTemplateJsonMap.get(NODE.getElementName()));
             }
             if (nodeTemplateJsonMap.containsKey(CAPABILITY.getElementName())) {
-                regTemplateInfo.setCapabilityName(
-                        (String) nodeTemplateJsonMap.get(CAPABILITY.getElementName()));
+                regTemplateInfo.setCapabilityName((String) nodeTemplateJsonMap.get(CAPABILITY.getElementName()));
             }
         }
         return regTemplateInfo;
     }
 
     private Map<String, List<UploadPropInfo>> buildPropModuleFromYaml(Map<String, Object> nodeTemplateJsonMap) {
-
         Map<String, List<UploadPropInfo>> moduleProp = new HashMap<>();
-        Either<Map<String, Object>, ResultStatusEnum> toscaProperties =
-                findFirstToscaMapElement(nodeTemplateJsonMap, PROPERTIES);
+        Either<Map<String, Object>, ResultStatusEnum> toscaProperties = findFirstToscaMapElement(nodeTemplateJsonMap, PROPERTIES);
         if (toscaProperties.isLeft()) {
             Map<String, Object> jsonProperties = toscaProperties.left().value();
             for (Map.Entry<String, Object> jsonPropObj : jsonProperties.entrySet()) {
@@ -953,54 +890,43 @@ public class YamlTemplateParsingHandler {
 
     @SuppressWarnings("unchecked")
     private UploadPropInfo buildProperty(String propName, Object propValue) {
-
         UploadPropInfo propertyDef = new UploadPropInfo();
         propertyDef.setValue(propValue);
         propertyDef.setName(propName);
         if (propValue instanceof Map) {
             if (((Map<String, Object>) propValue).containsKey(TYPE.getElementName())) {
-                propertyDef.setType(((Map<String, Object>) propValue)
-                        .get(TYPE.getElementName()).toString());
+                propertyDef.setType(((Map<String, Object>) propValue).get(TYPE.getElementName()).toString());
             }
             if (containsGetInput(propValue)) {
                 fillInputRecursively(propName, (Map<String, Object>) propValue, propertyDef);
             }
-
             if (((Map<String, Object>) propValue).containsKey(DESCRIPTION.getElementName())) {
-                propertyDef.setDescription(((Map<String, Object>) propValue)
-                        .get(DESCRIPTION.getElementName()).toString());
+                propertyDef.setDescription(((Map<String, Object>) propValue).get(DESCRIPTION.getElementName()).toString());
             }
-            if (((Map<String, Object>) propValue)
-                    .containsKey(DEFAULT_VALUE.getElementName())) {
-                propertyDef.setValue(((Map<String, Object>) propValue)
-                        .get(DEFAULT_VALUE.getElementName()));
+            if (((Map<String, Object>) propValue).containsKey(DEFAULT_VALUE.getElementName())) {
+                propertyDef.setValue(((Map<String, Object>) propValue).get(DEFAULT_VALUE.getElementName()));
             }
             if (((Map<String, Object>) propValue).containsKey(IS_PASSWORD.getElementName())) {
-                propertyDef.setPassword(Boolean.getBoolean(((Map<String, Object>) propValue)
-                        .get(IS_PASSWORD.getElementName()).toString()));
+                propertyDef.setPassword(Boolean.getBoolean(((Map<String, Object>) propValue).get(IS_PASSWORD.getElementName()).toString()));
             } else {
                 propertyDef.setValue(propValue);
             }
         } else if (propValue instanceof List) {
             List<Object> propValueList = (List<Object>) propValue;
-
             fillInputsListRecursively(propertyDef, propValueList);
             propertyDef.setValue(propValue);
         }
-
         return propertyDef;
     }
 
     @SuppressWarnings("unchecked")
     private boolean containsGetInput(Object propValue) {
-        return ((Map<String, Object>) propValue).containsKey(GET_INPUT.getElementName())
-                || ImportUtils.containsGetInput(propValue);
+        return ((Map<String, Object>) propValue).containsKey(GET_INPUT.getElementName()) || ImportUtils.containsGetInput(propValue);
     }
 
     @SuppressWarnings("unchecked")
     private void fillInputsListRecursively(UploadPropInfo propertyDef, List<Object> propValueList) {
         for (Object objValue : propValueList) {
-
             if (objValue instanceof Map) {
                 Map<String, Object> objMap = (Map<String, Object>) objValue;
                 if (objMap.containsKey(GET_INPUT.getElementName())) {
@@ -1017,8 +943,7 @@ public class YamlTemplateParsingHandler {
     }
 
     @SuppressWarnings("unchecked")
-    private void findAndFillInputsListRecursively(UploadPropInfo propertyDef, Map<String, Object> objMap,
-                                                  Set<String> keys) {
+    private void findAndFillInputsListRecursively(UploadPropInfo propertyDef, Map<String, Object> objMap, Set<String> keys) {
         for (String key : keys) {
             Object value = objMap.get(key);
             if (value instanceof Map) {
@@ -1031,7 +956,6 @@ public class YamlTemplateParsingHandler {
     }
 
     private void fillInputRecursively(String propName, Map<String, Object> propValue, UploadPropInfo propertyDef) {
-
         if (propValue.containsKey(GET_INPUT.getElementName())) {
             Object getInput = propValue.get(GET_INPUT.getElementName());
             GetInputValueDataDefinition getInputInfo = new GetInputValueDataDefinition();
@@ -1040,10 +964,8 @@ public class YamlTemplateParsingHandler {
                 getInputs = new ArrayList<>();
             }
             if (getInput instanceof String) {
-
                 getInputInfo.setInputName((String) getInput);
                 getInputInfo.setPropName(propName);
-
             } else if (getInput instanceof List) {
                 fillInput(propName, getInput, getInputInfo);
             }
@@ -1061,7 +983,6 @@ public class YamlTemplateParsingHandler {
             Object value = propValue.get(propName);
             if (value instanceof Map) {
                 fillInputRecursively(propName, (Map<String, Object>) value, propertyDef);
-
             } else if (value instanceof List) {
                 fillInputsRecursively(propertyDef, propName, (List<Object>) value);
             }
@@ -1069,9 +990,7 @@ public class YamlTemplateParsingHandler {
     }
 
     private void fillInputsRecursively(UploadPropInfo propertyDef, String propName, List<Object> inputs) {
-        inputs.stream()
-                .filter(o -> o instanceof Map)
-                .forEach(o -> fillInputRecursively(propName, (Map<String, Object>)o, propertyDef));
+        inputs.stream().filter(o -> o instanceof Map).forEach(o -> fillInputRecursively(propName, (Map<String, Object>) o, propertyDef));
     }
 
     @SuppressWarnings("unchecked")
@@ -1086,10 +1005,8 @@ public class YamlTemplateParsingHandler {
             } else if (indexObj instanceof Float) {
                 int index = ((Float) indexObj).intValue();
                 getInputInfo.setIndexValue(index);
-            } else if (indexObj instanceof Map && ((Map<String, Object>) indexObj)
-                    .containsKey(GET_INPUT.getElementName())) {
-                Object index = ((Map<String, Object>) indexObj)
-                        .get(GET_INPUT.getElementName());
+            } else if (indexObj instanceof Map && ((Map<String, Object>) indexObj).containsKey(GET_INPUT.getElementName())) {
+                Object index = ((Map<String, Object>) indexObj).get(GET_INPUT.getElementName());
                 GetInputValueDataDefinition getInputInfoIndex = new GetInputValueDataDefinition();
                 getInputInfoIndex.setInputName((String) index);
                 getInputInfoIndex.setPropName(propName);
@@ -1119,15 +1036,19 @@ public class YamlTemplateParsingHandler {
     }
 
     private void failOnMissingCapabilityTypes(GroupDefinition groupDefinition, List<String> missingCapTypes) {
-        log.debug("#failOnMissingCapabilityTypes - Failed to validate the capabilities of the group {}. The capability types {} are missing on the group type {}. ", groupDefinition.getName(), missingCapTypes.toString(), groupDefinition.getType());
-        if(CollectionUtils.isNotEmpty(missingCapTypes)) {
+        log.debug(
+            "#failOnMissingCapabilityTypes - Failed to validate the capabilities of the group {}. The capability types {} are missing on the group type {}. ",
+            groupDefinition.getName(), missingCapTypes.toString(), groupDefinition.getType());
+        if (CollectionUtils.isNotEmpty(missingCapTypes)) {
             rollbackWithException(ActionStatus.MISSING_CAPABILITY_TYPE, missingCapTypes.toString());
         }
     }
 
     private void failOnMissingCapabilityNames(GroupDefinition groupDefinition, List<String> missingCapNames) {
-        log.debug("#failOnMissingCapabilityNames - Failed to validate the capabilities of the group {}. The capabilities with the names {} are missing on the group type {}. ", groupDefinition.getName(), missingCapNames.toString(), groupDefinition.getType());
-        rollbackWithException(ActionStatus.MISSING_CAPABILITIES, missingCapNames.toString(), CapabilityDataDefinition.OwnerType.GROUP.getValue(), groupDefinition.getName());
+        log.debug(
+            "#failOnMissingCapabilityNames - Failed to validate the capabilities of the group {}. The capabilities with the names {} are missing on the group type {}. ",
+            groupDefinition.getName(), missingCapNames.toString(), groupDefinition.getType());
+        rollbackWithException(ActionStatus.MISSING_CAPABILITIES, missingCapNames.toString(), CapabilityDataDefinition.OwnerType.GROUP.getValue(),
+            groupDefinition.getName());
     }
-
 }
index 52179b4..a69edfb 100644 (file)
@@ -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.
  * limitations under the License.
  * ============LICENSE_END=========================================================
  */
-
 package org.openecomp.sdc.be.components.distribution.engine;
 
+import java.net.ConnectException;
+import java.net.SocketTimeoutException;
+import java.util.Properties;
+import java.util.UUID;
+import javax.annotation.PostConstruct;
+import javax.ws.rs.core.HttpHeaders;
+import javax.ws.rs.core.MediaType;
 import org.apache.http.conn.ConnectTimeoutException;
 import org.openecomp.sdc.be.config.ConfigurationManager;
 import org.openecomp.sdc.common.api.Constants;
@@ -33,74 +39,53 @@ import org.openecomp.sdc.common.http.config.ExternalServiceConfig;
 import org.openecomp.sdc.common.log.wrappers.Logger;
 import org.springframework.stereotype.Component;
 
-import javax.annotation.PostConstruct;
-import javax.ws.rs.core.HttpHeaders;
-import javax.ws.rs.core.MediaType;
-import java.net.ConnectException;
-import java.net.SocketTimeoutException;
-import java.util.Properties;
-import java.util.UUID;
-
 @Component
 public class AaiRequestHandler {
 
-    private static final Logger logger = Logger.getLogger(AaiRequestHandler.class);
-    private ExternalServiceConfig aaiConfig;
-
     protected static final String OPERATIONAL_ENV_RESOURCE_CONFIG_PARAM = "operationalEnvironments";
     protected static final String OPERATIONAL_ENV_RESOURCE = "/operational-environment";
+    private static final Logger logger = Logger.getLogger(AaiRequestHandler.class);
+    private ExternalServiceConfig aaiConfig;
 
     @PostConstruct
     public void init() {
         logger.debug("AaiRequestHandler has been initialized.");
-
         aaiConfig = ConfigurationManager.getConfigurationManager().getDistributionEngineConfiguration().getAaiConfig();
         aaiConfig.getHttpClientConfig().setEnableMetricLogging(true);
         logger.debug("AaiRequestHandler Configuration={}", aaiConfig);
     }
 
-
     public HttpResponse<String> getOperationalEnvById(String id) {
         Properties headers = createHeaders();
-        String url = String.format("%s%s%s/%s",
-                aaiConfig.getHttpRequestConfig().getServerRootUrl(),
-                aaiConfig.getHttpRequestConfig().getResourceNamespaces().get(OPERATIONAL_ENV_RESOURCE_CONFIG_PARAM),
-                OPERATIONAL_ENV_RESOURCE, id);
-
+        String url = String.format("%s%s%s/%s", aaiConfig.getHttpRequestConfig().getServerRootUrl(),
+            aaiConfig.getHttpRequestConfig().getResourceNamespaces().get(OPERATIONAL_ENV_RESOURCE_CONFIG_PARAM), OPERATIONAL_ENV_RESOURCE, id);
         SupplierThrows<HttpResponse<String>, Exception> httpGet = () -> HttpRequest.get(url, headers, aaiConfig.getHttpClientConfig());
         long maxRetries = aaiConfig.getHttpClientConfig().getNumOfRetries();
         try {
             return FunctionalInterfaces.retryMethodOnException(httpGet, this::retryOnException, maxRetries);
-
         } catch (Exception e) {
             logger.debug("Request failed with exception {}", getCause(e).getMessage());
             return Responses.INTERNAL_SERVER_ERROR;
         }
     }
 
-
-    
-
     private boolean retryOnException(Exception e) {
         Throwable cause = getCause(e);
         return !(cause instanceof ConnectTimeoutException || cause instanceof ConnectException || cause instanceof SocketTimeoutException);
     }
 
-
     private Throwable getCause(Exception e) {
         if (e instanceof HttpExecuteException) {
             return e.getCause();
         }
         return e;
     }
-    
-    
+
     private Properties createHeaders() {
         Properties headers = new Properties();
         headers.put(HttpHeaders.ACCEPT, MediaType.APPLICATION_JSON);
         headers.put(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON);
         headers.put(Constants.X_TRANSACTION_ID_HEADER, UUID.randomUUID().toString());
-
         return headers;
     }
 }
index 98a8550..4106263 100644 (file)
@@ -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.
  * limitations under the License.
  * ============LICENSE_END=========================================================
  */
-
 package org.openecomp.sdc.be.components.distribution.engine;
 
+import java.util.ArrayList;
+import java.util.Collection;
+import java.util.List;
+import java.util.Map;
+import java.util.stream.Collectors;
 import lombok.Getter;
 import lombok.Setter;
 import org.openecomp.sdc.be.datatypes.elements.ArtifactDataDefinition;
@@ -27,12 +31,6 @@ import org.openecomp.sdc.be.model.ArtifactDefinition;
 import org.openecomp.sdc.be.model.ComponentInstance;
 import org.openecomp.sdc.be.model.Service;
 
-import java.util.ArrayList;
-import java.util.Collection;
-import java.util.List;
-import java.util.Map;
-import java.util.stream.Collectors;
-
 @Getter
 @Setter
 public class ArtifactInfoImpl implements IArtifactInfo {
@@ -63,7 +61,8 @@ public class ArtifactInfoImpl implements IArtifactInfo {
         this.generatedFromUUID = generatedFromUUID;
     }
 
-    public static List<ArtifactInfoImpl> convertToArtifactInfoImpl(Service service, ComponentInstance resourceInstance, Collection<ArtifactDefinition> list) {
+    public static List<ArtifactInfoImpl> convertToArtifactInfoImpl(Service service, ComponentInstance resourceInstance,
+                                                                   Collection<ArtifactDefinition> list) {
         List<ArtifactInfoImpl> ret = new ArrayList<>();
         Map<String, List<ArtifactDefinition>> artifactIdToDef = list.stream().collect(Collectors.groupingBy(ArtifactDefinition::getUniqueId));
         if (list != null) {
@@ -73,14 +72,15 @@ public class ArtifactInfoImpl implements IArtifactInfo {
                     ArtifactDefinition artifactFrom = artifactIdToDef.get(artifactDef.getGeneratedFromId()).get(0);
                     generatedFromUUID = artifactFrom.getArtifactUUID();
                 }
-                ArtifactInfoImpl artifactInfoImpl = new ArtifactInfoImpl(artifactDef, generatedFromUUID, getUpdatedRequiredArtifactsFromNamesToUuids(artifactDef, resourceInstance.getDeploymentArtifacts()));
-                String artifactURL = ServiceDistributionArtifactsBuilder.buildResourceInstanceArtifactUrl(service, resourceInstance, artifactDef.getArtifactName());
+                ArtifactInfoImpl artifactInfoImpl = new ArtifactInfoImpl(artifactDef, generatedFromUUID,
+                    getUpdatedRequiredArtifactsFromNamesToUuids(artifactDef, resourceInstance.getDeploymentArtifacts()));
+                String artifactURL = ServiceDistributionArtifactsBuilder
+                    .buildResourceInstanceArtifactUrl(service, resourceInstance, artifactDef.getArtifactName());
                 artifactInfoImpl.setArtifactURL(artifactURL);
                 ret.add(artifactInfoImpl);
             }
         }
         return ret;
-
     }
 
     public static List<ArtifactInfoImpl> convertServiceArtifactToArtifactInfoImpl(Service service, Collection<ArtifactDefinition> list) {
@@ -93,28 +93,32 @@ public class ArtifactInfoImpl implements IArtifactInfo {
                     ArtifactDefinition artifactFrom = artifactIdToDef.get(artifactDef.getGeneratedFromId()).get(0);
                     generatedFromUUID = artifactFrom.getArtifactUUID();
                 }
-                ArtifactInfoImpl artifactInfoImpl = new ArtifactInfoImpl(artifactDef, generatedFromUUID, getUpdatedRequiredArtifactsFromNamesToUuids(artifactDef, service.getDeploymentArtifacts()));
+                ArtifactInfoImpl artifactInfoImpl = new ArtifactInfoImpl(artifactDef, generatedFromUUID,
+                    getUpdatedRequiredArtifactsFromNamesToUuids(artifactDef, service.getDeploymentArtifacts()));
                 String artifactURL = ServiceDistributionArtifactsBuilder.buildServiceArtifactUrl(service, artifactDef.getArtifactName());
                 artifactInfoImpl.setArtifactURL(artifactURL);
                 ret.add(artifactInfoImpl);
             }
         }
         return ret;
-
     }
 
-    private static List<String> getUpdatedRequiredArtifactsFromNamesToUuids(ArtifactDefinition artifactDefinition, Map<String, ArtifactDefinition> artifacts) {
+    private static List<String> getUpdatedRequiredArtifactsFromNamesToUuids(ArtifactDefinition artifactDefinition,
+                                                                            Map<String, ArtifactDefinition> artifacts) {
         List<String> requiredArtifacts = null;
-        if (artifactDefinition != null && artifactDefinition.getRequiredArtifacts() != null && !artifactDefinition.getRequiredArtifacts().isEmpty() && artifacts != null && !artifacts.isEmpty()) {
-            requiredArtifacts = artifacts.values().stream().filter(art -> artifactDefinition.getRequiredArtifacts().contains(art.getArtifactName())).map(ArtifactDataDefinition::getArtifactUUID).collect(Collectors.toList());
+        if (artifactDefinition != null && artifactDefinition.getRequiredArtifacts() != null && !artifactDefinition.getRequiredArtifacts().isEmpty()
+            && artifacts != null && !artifacts.isEmpty()) {
+            requiredArtifacts = artifacts.values().stream().filter(art -> artifactDefinition.getRequiredArtifacts().contains(art.getArtifactName()))
+                .map(ArtifactDataDefinition::getArtifactUUID).collect(Collectors.toList());
         }
         return requiredArtifacts;
     }
 
     @Override
     public String toString() {
-        return "ArtifactInfoImpl [artifactName=" + artifactName + ", artifactType=" + artifactType + ", artifactURL=" + artifactURL + ", artifactChecksum=" + artifactChecksum + ", artifactDescription=" + artifactDescription + ", artifactTimeout="
-                + artifactTimeout + ", artifactUUID=" + artifactUUID + ", artifactVersion=" + artifactVersion + ", generatedFromUUID=" + generatedFromUUID + ", relatedArtifacts=" + relatedArtifacts + "]";
+        return "ArtifactInfoImpl [artifactName=" + artifactName + ", artifactType=" + artifactType + ", artifactURL=" + artifactURL
+            + ", artifactChecksum=" + artifactChecksum + ", artifactDescription=" + artifactDescription + ", artifactTimeout=" + artifactTimeout
+            + ", artifactUUID=" + artifactUUID + ", artifactVersion=" + artifactVersion + ", generatedFromUUID=" + generatedFromUUID
+            + ", relatedArtifacts=" + relatedArtifacts + "]";
     }
-
 }
index 1041e58..bebc286 100644 (file)
@@ -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.
  * limitations under the License.
  * ============LICENSE_END=========================================================
  */
-
 package org.openecomp.sdc.be.components.distribution.engine;
 
-import org.openecomp.sdc.be.distribution.api.client.CambriaOperationStatus;
-
 import java.util.ArrayList;
 import java.util.List;
+import org.openecomp.sdc.be.distribution.api.client.CambriaOperationStatus;
 
 public class CambriaErrorResponse {
 
     public static final int HTTP_OK = 200;
-
     public static final int HTTP_INTERNAL_SERVER_ERROR = 500;
-
     CambriaOperationStatus operationStatus;
     Integer httpCode;
     List<String> variables = new ArrayList<>();
@@ -82,5 +78,4 @@ public class CambriaErrorResponse {
     public String toString() {
         return "CambriaErrorResponse [operationStatus=" + operationStatus + ", httpCode=" + httpCode + ", variables=" + variables + "]";
     }
-
 }
index 3f8abcc..425b464 100644 (file)
  * limitations under the License.
  * ============LICENSE_END=========================================================
  */
-
 package org.openecomp.sdc.be.components.distribution.engine;
 
+import static java.util.concurrent.TimeUnit.SECONDS;
+
 import com.att.nsa.apiClient.credentials.ApiCredential;
 import com.att.nsa.apiClient.http.HttpException;
 import com.att.nsa.apiClient.http.HttpObjectNotFoundException;
@@ -39,13 +40,6 @@ import com.att.nsa.cambria.client.CambriaTopicManager;
 import com.google.common.annotations.VisibleForTesting;
 import com.google.gson.Gson;
 import fj.data.Either;
-import org.apache.http.HttpStatus;
-import org.openecomp.sdc.be.config.BeEcompErrorManager;
-import org.openecomp.sdc.be.config.ConfigurationManager;
-import org.openecomp.sdc.be.distribution.api.client.CambriaOperationStatus;
-import org.openecomp.sdc.common.log.wrappers.Logger;
-import org.springframework.stereotype.Component;
-
 import java.io.IOException;
 import java.net.MalformedURLException;
 import java.security.GeneralSecurityException;
@@ -55,25 +49,25 @@ import java.util.List;
 import java.util.Set;
 import java.util.regex.Matcher;
 import java.util.regex.Pattern;
-
-import static java.util.concurrent.TimeUnit.SECONDS;
+import org.apache.http.HttpStatus;
+import org.openecomp.sdc.be.config.BeEcompErrorManager;
+import org.openecomp.sdc.be.config.ConfigurationManager;
+import org.openecomp.sdc.be.distribution.api.client.CambriaOperationStatus;
+import org.openecomp.sdc.common.log.wrappers.Logger;
+import org.springframework.stereotype.Component;
 
 @Component("cambriaHandler")
-public class CambriaHandler implements ICambriaHandler{
+public class CambriaHandler implements ICambriaHandler {
 
     private static final Logger log = Logger.getLogger(CambriaHandler.class.getName());
     private static final String PARTITION_KEY = "asdc" + "aa";
     private static final String SEND_NOTIFICATION = "send notification";
-    private static final String CONSUMER_ID = ConfigurationManager.getConfigurationManager()
-                                                                  .getDistributionEngineConfiguration()
-                                                                  .getDistributionStatusTopic()
-                                                                  .getConsumerId();
-    private static final boolean USE_HTTPS_WITH_DMAAP = ConfigurationManager.getConfigurationManager()
-                                                                    .getDistributionEngineConfiguration()
-                                                                    .isUseHttpsWithDmaap();
+    private static final String CONSUMER_ID = ConfigurationManager.getConfigurationManager().getDistributionEngineConfiguration()
+        .getDistributionStatusTopic().getConsumerId();
+    private static final boolean USE_HTTPS_WITH_DMAAP = ConfigurationManager.getConfigurationManager().getDistributionEngineConfiguration()
+        .isUseHttpsWithDmaap();
     private final Gson gson = new Gson();
 
-
     /**
      * process the response error from Cambria client
      *
@@ -81,17 +75,13 @@ public class CambriaHandler implements ICambriaHandler{
      * @return
      */
     private Integer processMessageException(String message) {
-
         String[] patterns = {"(HTTP Status )(\\d\\d\\d)", "(HTTP/\\d.\\d )(\\d\\d\\d)"};
-
         Integer result = checkPattern(patterns[0], message, 2);
         if (result != null) {
             return result;
         }
         result = checkPattern(patterns[1], message, 2);
-
         return result;
-
     }
 
     /**
@@ -104,7 +94,6 @@ public class CambriaHandler implements ICambriaHandler{
      */
     private Integer checkPattern(String patternStr, String message, int groupIndex) {
         Integer result = null;
-
         Pattern pattern = Pattern.compile(patternStr);
         Matcher matcher = pattern.matcher(message);
         boolean find = matcher.find();
@@ -113,8 +102,7 @@ public class CambriaHandler implements ICambriaHandler{
             if (httpCode != null) {
                 try {
                     result = Integer.valueOf(httpCode);
-                }
-                catch (NumberFormatException e) {
+                } catch (NumberFormatException e) {
                     log.debug("Failed to parse http code {}", httpCode);
                 }
             }
@@ -130,36 +118,25 @@ public class CambriaHandler implements ICambriaHandler{
      */
     @Override
     public Either<Set<String>, CambriaErrorResponse> getTopics(List<String> hostSet) {
-
         CambriaTopicManager createTopicManager = null;
         try {
-
             createTopicManager = buildCambriaClient(createTopicManagerBuilder(hostSet));
-
             Set<String> topics = createTopicManager.getTopics();
-
             if (topics == null || topics.isEmpty()) {
                 CambriaErrorResponse cambriaErrorResponse = new CambriaErrorResponse(CambriaOperationStatus.NOT_FOUND, null);
                 return Either.right(cambriaErrorResponse);
             }
-
             return Either.left(topics);
-
-        }
-        catch (IOException | GeneralSecurityException e) {
-
+        } catch (IOException | GeneralSecurityException e) {
             CambriaErrorResponse cambriaErrorResponse = processError(e);
-
             log.debug("Failed to fetch topics from U-EB server", e);
             writeErrorToLog(cambriaErrorResponse, "getTopics", "get topics");
-
             return Either.right(cambriaErrorResponse);
         } finally {
             if (createTopicManager != null) {
                 createTopicManager.close();
             }
         }
-
     }
 
     /**
@@ -170,15 +147,11 @@ public class CambriaHandler implements ICambriaHandler{
      * @return
      */
     private CambriaErrorResponse processError(Exception e) {
-
         CambriaErrorResponse cambriaErrorResponse = new CambriaErrorResponse();
-
         Integer httpCode = processMessageException(e.getMessage());
-
         if (httpCode != null) {
             cambriaErrorResponse.setHttpCode(httpCode);
             switch (httpCode.intValue()) {
-
                 case 401:
                     cambriaErrorResponse.setOperationStatus(CambriaOperationStatus.AUTHENTICATION_ERROR);
                     break;
@@ -191,16 +164,12 @@ public class CambriaHandler implements ICambriaHandler{
                 default:
                     cambriaErrorResponse.setOperationStatus(CambriaOperationStatus.CONNNECTION_ERROR);
             }
-        }
-        else {
-
+        } else {
             boolean found = false;
             Throwable throwable = e.getCause();
             if (throwable != null) {
                 String message = throwable.getMessage();
-
                 Throwable cause = throwable.getCause();
-
                 if (cause != null) {
                     Class<?> clazz = cause.getClass();
                     String className = clazz.getName();
@@ -211,26 +180,23 @@ public class CambriaHandler implements ICambriaHandler{
                     }
                 }
             }
-
             if (!found) {
                 cambriaErrorResponse.setOperationStatus(CambriaOperationStatus.CONNNECTION_ERROR);
                 cambriaErrorResponse.setHttpCode(HttpStatus.SC_INTERNAL_SERVER_ERROR);
             }
         }
-
         return cambriaErrorResponse;
     }
 
     /**
      * write the error to the log
-     *  @param cambriaErrorResponse
+     *
+     * @param cambriaErrorResponse
      * @param methodName
      * @param operationDesc
      */
     private void writeErrorToLog(CambriaErrorResponse cambriaErrorResponse, String methodName, String operationDesc) {
-
         String httpCode = cambriaErrorResponse.getHttpCode() == null ? "" : String.valueOf(cambriaErrorResponse.getHttpCode());
-
         switch (cambriaErrorResponse.getOperationStatus()) {
             case UNKNOWN_HOST_ERROR:
                 BeEcompErrorManager.getInstance().logBeUebUnkownHostError(methodName, httpCode);
@@ -247,7 +213,6 @@ public class CambriaHandler implements ICambriaHandler{
             default:
                 break;
         }
-
     }
 
     /**
@@ -262,87 +227,66 @@ public class CambriaHandler implements ICambriaHandler{
      * @return
      */
     @Override
-    public CambriaErrorResponse createTopic(Collection<String> hostSet, String apiKey, String secretKey, String topicName, int partitionCount, int replicationCount) {
-
+    public CambriaErrorResponse createTopic(Collection<String> hostSet, String apiKey, String secretKey, String topicName, int partitionCount,
+                                            int replicationCount) {
         CambriaTopicManager createTopicManager = null;
         try {
-
             AbstractAuthenticatedManagerBuilder<CambriaTopicManager> clientBuilder = createTopicManagerBuilder(hostSet, apiKey, secretKey);
             createTopicManager = buildCambriaClient(clientBuilder);
-            
             createTopicManager.createTopic(topicName, "ASDC distribution notification topic", partitionCount, replicationCount);
-
-        }
-        catch (HttpException | IOException | GeneralSecurityException e) {
-
+        } catch (HttpException | IOException | GeneralSecurityException e) {
             log.debug("Failed to create topic {}", topicName, e);
-
             CambriaErrorResponse cambriaErrorResponse = processError(e);
-
             if (cambriaErrorResponse.getOperationStatus() != CambriaOperationStatus.TOPIC_ALREADY_EXIST) {
                 writeErrorToLog(cambriaErrorResponse, "createTopic", "create topic");
             }
-
             return cambriaErrorResponse;
-
         } finally {
             if (createTopicManager != null) {
                 createTopicManager.close();
             }
         }
         return new CambriaErrorResponse(CambriaOperationStatus.OK);
-
     }
+
     @Override
-    public CambriaErrorResponse unRegisterFromTopic(Collection<String> hostSet, String managerApiKey, String managerSecretKey, String subscriberApiKey, SubscriberTypeEnum subscriberTypeEnum, String topicName) {
+    public CambriaErrorResponse unRegisterFromTopic(Collection<String> hostSet, String managerApiKey, String managerSecretKey,
+                                                    String subscriberApiKey, SubscriberTypeEnum subscriberTypeEnum, String topicName) {
         String methodName = "unRegisterFromTopic";
         CambriaTopicManager createTopicManager = null;
         try {
-            AbstractAuthenticatedManagerBuilder<CambriaTopicManager> clientBuilder = createTopicManagerBuilder(hostSet, managerApiKey, managerSecretKey);
-            
+            AbstractAuthenticatedManagerBuilder<CambriaTopicManager> clientBuilder = createTopicManagerBuilder(hostSet, managerApiKey,
+                managerSecretKey);
             createTopicManager = buildCambriaClient(clientBuilder);
-
             if (subscriberTypeEnum == SubscriberTypeEnum.PRODUCER) {
                 createTopicManager.revokeProducer(topicName, subscriberApiKey);
-            }
-            else {
+            } else {
                 createTopicManager.revokeConsumer(topicName, subscriberApiKey);
             }
-
-        }
-        catch (HttpObjectNotFoundException e) {
-            log.debug("Failed to unregister {} from topic {} as {}", managerApiKey, topicName, subscriberTypeEnum.toString()
-                                                                                                                 .toLowerCase(), e);
+        } catch (HttpObjectNotFoundException e) {
+            log.debug("Failed to unregister {} from topic {} as {}", managerApiKey, topicName, subscriberTypeEnum.toString().toLowerCase(), e);
             BeEcompErrorManager.getInstance().logBeUebObjectNotFoundError(methodName, e.getMessage());
-
             return new CambriaErrorResponse(CambriaOperationStatus.OBJECT_NOT_FOUND, HttpStatus.SC_NOT_FOUND);
-
-        }
-        catch (HttpException | IOException | GeneralSecurityException e) {
+        } catch (HttpException | IOException | GeneralSecurityException e) {
             log.debug("Failed to unregister {} from topic {} as producer", managerApiKey, topicName, e);
             CambriaErrorResponse cambriaErrorResponse = processError(e);
-
-            writeErrorToLog(cambriaErrorResponse, methodName, "unregister from topic as " + subscriberTypeEnum
-                    .toString()
-                    .toLowerCase());
-
+            writeErrorToLog(cambriaErrorResponse, methodName, "unregister from topic as " + subscriberTypeEnum.toString().toLowerCase());
             return cambriaErrorResponse;
         } finally {
             if (createTopicManager != null) {
                 createTopicManager.close();
             }
         }
-
         return new CambriaErrorResponse(CambriaOperationStatus.OK, HttpStatus.SC_OK);
     }
 
-    private AbstractAuthenticatedManagerBuilder<CambriaTopicManager> createTopicManagerBuilder(Collection<String> hostSet, String managerApiKey, String managerSecretKey) {
+    private AbstractAuthenticatedManagerBuilder<CambriaTopicManager> createTopicManagerBuilder(Collection<String> hostSet, String managerApiKey,
+                                                                                               String managerSecretKey) {
         AbstractAuthenticatedManagerBuilder<CambriaTopicManager> clientBuilder = createTopicManagerBuilder(hostSet)
-                                                                         .authenticatedBy(managerApiKey, managerSecretKey);
+            .authenticatedBy(managerApiKey, managerSecretKey);
         if (USE_HTTPS_WITH_DMAAP) {
             clientBuilder = clientBuilder.usingHttps();
         }
-        
         return clientBuilder;
     }
 
@@ -362,47 +306,33 @@ public class CambriaHandler implements ICambriaHandler{
      * @return
      */
     @Override
-    public CambriaErrorResponse registerToTopic(Collection<String> hostSet, String managerApiKey, String managerSecretKey, String subscriberApiKey, SubscriberTypeEnum subscriberTypeEnum, String topicName) {
-
+    public CambriaErrorResponse registerToTopic(Collection<String> hostSet, String managerApiKey, String managerSecretKey, String subscriberApiKey,
+                                                SubscriberTypeEnum subscriberTypeEnum, String topicName) {
         String methodName = "registerToTopic";
         CambriaTopicManager createTopicManager = null;
         try {
-            AbstractAuthenticatedManagerBuilder<CambriaTopicManager> clientBuilder = createTopicManagerBuilder(hostSet, managerApiKey, managerSecretKey);
+            AbstractAuthenticatedManagerBuilder<CambriaTopicManager> clientBuilder = createTopicManagerBuilder(hostSet, managerApiKey,
+                managerSecretKey);
             createTopicManager = buildCambriaClient(clientBuilder);
-
             if (subscriberTypeEnum == SubscriberTypeEnum.PRODUCER) {
                 createTopicManager.allowProducer(topicName, subscriberApiKey);
-            }
-            else {
+            } else {
                 createTopicManager.allowConsumer(topicName, subscriberApiKey);
             }
-
-        }
-        catch (HttpObjectNotFoundException e) {
-            log.debug("Failed to register {} to topic {} as {}", managerApiKey, topicName, subscriberTypeEnum.toString()
-                                                                                                             .toLowerCase(), e);
-
+        } catch (HttpObjectNotFoundException e) {
+            log.debug("Failed to register {} to topic {} as {}", managerApiKey, topicName, subscriberTypeEnum.toString().toLowerCase(), e);
             BeEcompErrorManager.getInstance().logBeUebObjectNotFoundError(methodName, e.getMessage());
-
             return new CambriaErrorResponse(CambriaOperationStatus.OBJECT_NOT_FOUND, HttpStatus.SC_NOT_FOUND);
-
-        }
-        catch (HttpException | IOException | GeneralSecurityException e) {
-            log.debug("Failed to register {} to topic {} as {}", managerApiKey, topicName, subscriberTypeEnum.toString()
-                                                                                                             .toLowerCase(), e);
+        } catch (HttpException | IOException | GeneralSecurityException e) {
+            log.debug("Failed to register {} to topic {} as {}", managerApiKey, topicName, subscriberTypeEnum.toString().toLowerCase(), e);
             CambriaErrorResponse cambriaErrorResponse = processError(e);
-
-            writeErrorToLog(cambriaErrorResponse, methodName, "register to topic as " + subscriberTypeEnum
-                    .toString()
-                    .toLowerCase());
-
+            writeErrorToLog(cambriaErrorResponse, methodName, "register to topic as " + subscriberTypeEnum.toString().toLowerCase());
             return cambriaErrorResponse;
         } finally {
             if (createTopicManager != null) {
                 createTopicManager.close();
             }
         }
-
         return new CambriaErrorResponse(CambriaOperationStatus.OK, HttpStatus.SC_OK);
     }
 
@@ -420,24 +350,18 @@ public class CambriaHandler implements ICambriaHandler{
      * @throws Exception
      */
     @Override
-    public CambriaConsumer createConsumer(Collection<String> hostSet, String topicName, String apiKey, String secretKey, String consumerId, String consumerGroup, int timeoutMS) throws Exception {
-
-        CambriaConsumer consumer = new ConsumerBuilder().authenticatedBy(apiKey, secretKey)
-                                                        .knownAs(consumerGroup, consumerId)
-                                                        .onTopic(topicName)
-                                                        .usingHosts(hostSet)
-                                                        .waitAtServer(timeoutMS)
-                                                        .build();
+    public CambriaConsumer createConsumer(Collection<String> hostSet, String topicName, String apiKey, String secretKey, String consumerId,
+                                          String consumerGroup, int timeoutMS) throws Exception {
+        CambriaConsumer consumer = new ConsumerBuilder().authenticatedBy(apiKey, secretKey).knownAs(consumerGroup, consumerId).onTopic(topicName)
+            .usingHosts(hostSet).waitAtServer(timeoutMS).build();
         consumer.setApiCredentials(apiKey, secretKey);
         return consumer;
     }
 
     public void closeConsumer(CambriaConsumer consumer) {
-
         if (consumer != null) {
             consumer.close();
         }
-
     }
 
     /**
@@ -448,7 +372,6 @@ public class CambriaHandler implements ICambriaHandler{
      */
     @Override
     public Either<Iterable<String>, CambriaErrorResponse> fetchFromTopic(CambriaConsumer topicConsumer) {
-
         String methodName = "fetchFromTopic";
         try {
             Iterable<String> messages = topicConsumer.fetch();
@@ -456,19 +379,16 @@ public class CambriaHandler implements ICambriaHandler{
                 messages = new ArrayList<>();
             }
             return Either.left(messages);
-
-        }
-        catch (IOException e) {
+        } catch (IOException e) {
             CambriaErrorResponse cambriaErrorResponse = processError(e);
             log.debug("Failed to fetch from U-EB topic. error={}", e.getMessage());
             writeErrorToLog(cambriaErrorResponse, methodName, "get messages from topic");
             return Either.right(cambriaErrorResponse);
-
-        }
-        catch (Exception e) {
+        } catch (Exception e) {
             log.debug("Failed to fetch from U-EB topic", e);
             BeEcompErrorManager.getInstance().logBeDistributionEngineSystemError(methodName, e.getMessage());
-            CambriaErrorResponse cambriaErrorResponse = new CambriaErrorResponse(CambriaOperationStatus.INTERNAL_SERVER_ERROR, HttpStatus.SC_INTERNAL_SERVER_ERROR);
+            CambriaErrorResponse cambriaErrorResponse = new CambriaErrorResponse(CambriaOperationStatus.INTERNAL_SERVER_ERROR,
+                HttpStatus.SC_INTERNAL_SERVER_ERROR);
             return Either.right(cambriaErrorResponse);
         }
     }
@@ -484,42 +404,29 @@ public class CambriaHandler implements ICambriaHandler{
      * @return
      */
     @Override
-    public CambriaErrorResponse sendNotification(String topicName, String uebPublicKey, String uebSecretKey, List<String> uebServers, INotificationData data) {
-
+    public CambriaErrorResponse sendNotification(String topicName, String uebPublicKey, String uebSecretKey, List<String> uebServers,
+                                                 INotificationData data) {
         CambriaBatchingPublisher createSimplePublisher = null;
-
         try {
-
             String json = gson.toJson(data);
             log.trace("Before sending notification data {} to topic {}", json, topicName);
-
             createSimplePublisher = new PublisherBuilder().onTopic(topicName).usingHosts(uebServers).build();
             createSimplePublisher.setApiCredentials(uebPublicKey, uebSecretKey);
-
             int result = createSimplePublisher.send(PARTITION_KEY, json);
-
             try {
                 SECONDS.sleep(1L);
-            }
-            catch (InterruptedException e) {
+            } catch (InterruptedException e) {
                 log.debug("Failed during sleep after sending the message.", e);
                 Thread.currentThread().interrupt();
             }
-
             log.debug("After sending notification data to topic {}. result is {}", topicName, result);
-
             return new CambriaErrorResponse(CambriaOperationStatus.OK, 200);
-
         } catch (IOException | GeneralSecurityException e) {
             log.debug("Failed to send notification {} to topic {} ", data, topicName, e);
-
             CambriaErrorResponse cambriaErrorResponse = processError(e);
-
             writeErrorToLog(cambriaErrorResponse, "sendNotification", SEND_NOTIFICATION);
-
             return cambriaErrorResponse;
-        }
-        finally {
+        } finally {
             if (createSimplePublisher != null) {
                 log.debug("Before closing publisher");
                 createSimplePublisher.close();
@@ -527,44 +434,32 @@ public class CambriaHandler implements ICambriaHandler{
             }
         }
     }
+
     @Override
-    public CambriaErrorResponse sendNotificationAndClose(String topicName, String uebPublicKey, String uebSecretKey, List<String> uebServers, INotificationData data, long waitBeforeCloseTimeout) {
+    public CambriaErrorResponse sendNotificationAndClose(String topicName, String uebPublicKey, String uebSecretKey, List<String> uebServers,
+                                                         INotificationData data, long waitBeforeCloseTimeout) {
         String methodName = "sendNotificationAndClose";
         CambriaBatchingPublisher createSimplePublisher;
         CambriaErrorResponse response;
         try {
-
             String json = gson.toJson(data);
             log.debug("Before sending notification data {} to topic {}", json, topicName);
-
             createSimplePublisher = new PublisherBuilder().onTopic(topicName).usingHosts(uebServers).build();
             createSimplePublisher.setApiCredentials(uebPublicKey, uebSecretKey);
-
             int result = createSimplePublisher.send(PARTITION_KEY, json);
-
             try {
                 Thread.sleep(1000);
-            }
-            catch (InterruptedException e) {
+            } catch (InterruptedException e) {
                 log.debug("Failed during sleep after sending the message.", e);
                 Thread.currentThread().interrupt();
             }
-
             log.debug("After sending notification data to topic {}. result is {}", topicName, result);
-
-        }
-        catch (IOException | GeneralSecurityException  e) {
+        } catch (IOException | GeneralSecurityException e) {
             log.debug("Failed to send notification {} to topic {} ", data, topicName, e);
-
-
             response = processError(e);
-
             writeErrorToLog(response, methodName, SEND_NOTIFICATION);
-
             return response;
-
         }
-
         log.debug("Before closing publisher. Maximum timeout is {} seconds", waitBeforeCloseTimeout);
         try {
             List<message> messagesInQ = createSimplePublisher.close(waitBeforeCloseTimeout, SECONDS);
@@ -572,75 +467,59 @@ public class CambriaHandler implements ICambriaHandler{
                 log.debug("Cambria client returned {} non sent messages.", messagesInQ.size());
                 response = new CambriaErrorResponse(CambriaOperationStatus.INTERNAL_SERVER_ERROR, 500);
                 writeErrorToLog(response, methodName, SEND_NOTIFICATION);
-            }
-            else {
+            } else {
                 log.debug("No message left in the queue after closing cambria publisher");
                 response = new CambriaErrorResponse(CambriaOperationStatus.OK, 200);
             }
-        }
-        catch (InterruptedException e) {
+        } catch (InterruptedException e) {
             log.debug("InterruptedException while closing cambria publisher", e);
             Thread.currentThread().interrupt();
             response = new CambriaErrorResponse(CambriaOperationStatus.INTERNAL_SERVER_ERROR, 500);
             writeErrorToLog(response, methodName, SEND_NOTIFICATION);
-        }
-        catch (IOException e) {
+        } catch (IOException e) {
             log.debug("Failed to close cambria publisher", e);
             response = new CambriaErrorResponse(CambriaOperationStatus.INTERNAL_SERVER_ERROR, 500);
             writeErrorToLog(response, methodName, SEND_NOTIFICATION);
         }
         log.debug("After closing publisher");
-
         return response;
-
     }
+
     @Override
     public CambriaErrorResponse getApiKey(String server, String apiKey) {
-
         CambriaErrorResponse response;
         List<String> hostSet = new ArrayList<>();
         hostSet.add(server);
         try {
             CambriaIdentityManager createIdentityManager = buildCambriaClient(new IdentityManagerBuilder().usingHosts(hostSet));
             createIdentityManager.getApiKey(apiKey);
-
             response = new CambriaErrorResponse(CambriaOperationStatus.OK, 200);
-
-        }
-        catch (HttpException | IOException | CambriaApiException | GeneralSecurityException e) {
+        } catch (HttpException | IOException | CambriaApiException | GeneralSecurityException e) {
             log.debug("Failed to fetch api key {} from server {}", apiKey, server, e);
-
             response = processError(e);
-
         }
-
         return response;
     }
+
     @Override
     public Either<ApiCredential, CambriaErrorResponse> createUebKeys(List<String> hostSet) {
         Either<ApiCredential, CambriaErrorResponse> result;
-
         try {
             CambriaIdentityManager createIdentityManager = buildCambriaClient(new IdentityManagerBuilder().usingHosts(hostSet));
-
             String description = String.format("ASDC Key for %s", CONSUMER_ID);
             ApiCredential credential = createIdentityManager.createApiKey("", description);
             createIdentityManager.setApiCredentials(credential.getApiKey(), credential.getApiSecret());
             result = Either.left(credential);
-
-        }
-        catch (Exception e) {
+        } catch (Exception e) {
             log.debug("Failed to create ueb keys for servers {}", hostSet, e);
-
             result = Either.right(processError(e));
-
         }
-
         return result;
     }
 
     @VisibleForTesting
-    <T extends CambriaClient> T buildCambriaClient(CambriaClientBuilders.AbstractAuthenticatedManagerBuilder<T> client) throws MalformedURLException, GeneralSecurityException {
+    <T extends CambriaClient> T buildCambriaClient(CambriaClientBuilders.AbstractAuthenticatedManagerBuilder<T> client)
+        throws MalformedURLException, GeneralSecurityException {
         return client.build();
     }
 }
index 630815d..dd201d9 100644 (file)
@@ -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.
@@ -17,7 +17,6 @@
  * limitations under the License.
  * ============LICENSE_END=========================================================
  */
-
 package org.openecomp.sdc.be.components.distribution.engine;
 
 import com.att.aft.dme2.api.DME2Exception;
index 2fa6190..cb14ebe 100644 (file)
@@ -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.
  * limitations under the License.
  * ============LICENSE_END=========================================================
  */
-
 package org.openecomp.sdc.be.components.distribution.engine;
 
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+import java.util.Optional;
+import java.util.concurrent.atomic.AtomicBoolean;
+import java.util.regex.Matcher;
+import java.util.regex.Pattern;
+import javax.annotation.PostConstruct;
+import javax.annotation.PreDestroy;
+import javax.annotation.Resource;
 import org.apache.commons.collections.CollectionUtils;
 import org.apache.commons.lang3.StringUtils;
 import org.openecomp.sdc.be.components.validation.ServiceDistributionValidation;
@@ -35,48 +44,32 @@ import org.openecomp.sdc.common.log.wrappers.Logger;
 import org.springframework.beans.factory.annotation.Autowired;
 import org.springframework.stereotype.Component;
 
-import javax.annotation.PostConstruct;
-import javax.annotation.PreDestroy;
-import javax.annotation.Resource;
-import java.util.HashMap;
-import java.util.List;
-import java.util.Map;
-import java.util.Optional;
-import java.util.concurrent.atomic.AtomicBoolean;
-import java.util.regex.Matcher;
-import java.util.regex.Pattern;
 @Component("distributionEngine")
 public class DistributionEngine implements IDistributionEngine {
 
     private static final Logger logger = Logger.getLogger(DistributionEngine.class.getName());
-    private static final Pattern FQDN_PATTERN = Pattern.compile("^([a-zA-Z0-9]|[a-zA-Z0-9][a-zA-Z0-9\\-]{0,61}[a-zA-Z0-9])(\\.([a-zA-Z0-9]|[a-zA-Z0-9][a-zA-Z0-9\\-]{0,61}[a-zA-Z0-9]))*(:[0-9]{2,4})*$", Pattern.CASE_INSENSITIVE);
-
+    private static final Pattern FQDN_PATTERN = Pattern.compile(
+        "^([a-zA-Z0-9]|[a-zA-Z0-9][a-zA-Z0-9\\-]{0,61}[a-zA-Z0-9])(\\.([a-zA-Z0-9]|[a-zA-Z0-9][a-zA-Z0-9\\-]{0,61}[a-zA-Z0-9]))*(:[0-9]{2,4})*$",
+        Pattern.CASE_INSENSITIVE);
     @Autowired
     private EnvironmentsEngine environmentsEngine;
-
     @Resource
     private DistributionNotificationSender distributionNotificationSender;
-
     @Resource
     private ServiceDistributionArtifactsBuilder serviceDistributionArtifactsBuilder;
-
     @Resource
     private DistributionEngineClusterHealth distributionEngineClusterHealth;
-
     @Resource
     private ServiceDistributionValidation serviceDistributionValidation;
-
     private Map<String, DistributionEngineInitTask> envNamePerInitTask = new HashMap<>();
     private Map<String, DistributionEnginePollingTask> envNamePerPollingTask = new HashMap<>();
     private Map<String, AtomicBoolean> envNamePerStatus = new HashMap<>();
 
     @Override
     public boolean isActive() {
-
         if (envNamePerInitTask.isEmpty()) {
             return false;
         }
-
         for (DistributionEngineInitTask task : envNamePerInitTask.values()) {
             boolean active = task.isActive();
             if (!active) {
@@ -89,40 +82,31 @@ public class DistributionEngine implements IDistributionEngine {
     @PostConstruct
     private void init() {
         logger.trace("Enter init method of DistributionEngine");
-
-        DistributionEngineConfiguration distributionEngineConfiguration = ConfigurationManager.getConfigurationManager().getDistributionEngineConfiguration();
-
+        DistributionEngineConfiguration distributionEngineConfiguration = ConfigurationManager.getConfigurationManager()
+            .getDistributionEngineConfiguration();
         boolean startDistributionEngine = distributionEngineConfiguration.isStartDistributionEngine();
         logger.debug("Distribution engine activation parameter is {}", startDistributionEngine);
         if (!startDistributionEngine) {
             logger.info("The distribution engine is disabled");
-
             this.distributionEngineClusterHealth.setHealthCheckUebIsDisabled();
-
             return;
         }
-
         boolean isValidConfig = validateConfiguration(distributionEngineConfiguration);
-
         if (!isValidConfig) {
-            BeEcompErrorManager.getInstance().logBeUebSystemError(DistributionEngineInitTask.INIT_DISTRIBUTION_ENGINE_FLOW, "validate distribution configuration in init phase");
-
+            BeEcompErrorManager.getInstance()
+                .logBeUebSystemError(DistributionEngineInitTask.INIT_DISTRIBUTION_ENGINE_FLOW, "validate distribution configuration in init phase");
             this.distributionEngineClusterHealth.setHealthCheckUebConfigurationError();
             return;
         }
-
         List<String> environments = distributionEngineConfiguration.getEnvironments();
-
         for (String envName : environments) {
             logger.debug("init task for environment {}", envName);
             AtomicBoolean status = new AtomicBoolean(false);
             envNamePerStatus.put(envName, status);
             environmentsEngine.connectUebTopicForDistributionConfTopic(envName, status, envNamePerInitTask, envNamePerPollingTask);
         }
-
         logger.debug("init UEB health check");
         distributionEngineClusterHealth.startHealthCheckTask(envNamePerStatus);
-
         logger.trace("Exit init method of DistributionEngine");
     }
 
@@ -139,18 +123,16 @@ public class DistributionEngine implements IDistributionEngine {
                 task.destroy();
             }
         }
-
     }
 
     /**
      * validate mandatory configuration parameters received
+     *
      * @param deConfiguration: distribution engine configuration
      * @return boolean result: true of false
      */
     protected boolean validateConfiguration(DistributionEngineConfiguration deConfiguration) {
-
         String methodName = "validateConfiguration";
-
         boolean result = isValidServers(deConfiguration.getUebServers(), methodName, "uebServers");
         result = isValidParam(deConfiguration.getEnvironments(), methodName, "environments") && result;
         result = isValidParam(deConfiguration.getUebPublicKey(), methodName, "uebPublicKey") && result;
@@ -165,38 +147,31 @@ public class DistributionEngine implements IDistributionEngine {
         result = isValidParam(deConfiguration.getDistributionStatusTopic().getConsumerGroup(), methodName, "consumerGroup") && result;
         result = isValidObject(deConfiguration.getDistributionStatusTopic().getFetchTimeSec(), methodName, "fetchTimeSec") && result;
         result = isValidObject(deConfiguration.getDistributionStatusTopic().getPollingIntervalSec(), methodName, "pollingIntervalSec") && result;
-
         return result;
     }
 
     private boolean isValidServers(List<String> uebServers, String methodName, String paramName) {
-
         if (uebServers == null || uebServers.isEmpty()) {
             BeEcompErrorManager.getInstance().logBeMissingConfigurationError(methodName, paramName);
             return false;
         }
-
         if (uebServers.size() < 2) {
             BeEcompErrorManager.getInstance().logBeConfigurationInvalidListSizeError(methodName, paramName, 2);
             return false;
         }
-
         for (String serverFqdn : uebServers) {
             if (!isValidFqdn(serverFqdn)) {
                 BeEcompErrorManager.getInstance().logBeInvalidConfigurationError(methodName, paramName, serverFqdn);
                 return false;
             }
         }
-
         return true;
     }
 
     private boolean isValidFqdn(String serverFqdn) {
-
         try {
             Matcher matcher = FQDN_PATTERN.matcher(serverFqdn);
             return matcher.matches();
-
         } catch (Exception e) {
             logger.debug("Failed to match value of address {}", serverFqdn, e);
             return false;
@@ -204,7 +179,6 @@ public class DistributionEngine implements IDistributionEngine {
     }
 
     private boolean isValidParam(String paramValue, String methodName, String paramName) {
-
         if (StringUtils.isEmpty(paramValue)) {
             BeEcompErrorManager.getInstance().logBeMissingConfigurationError(methodName, paramName);
             return false;
@@ -213,7 +187,6 @@ public class DistributionEngine implements IDistributionEngine {
     }
 
     private boolean isValidParam(List<String> paramValue, String methodName, String paramName) {
-
         if (CollectionUtils.isEmpty(paramValue)) {
             BeEcompErrorManager.getInstance().logBeMissingConfigurationError(methodName, paramName);
             return false;
@@ -222,42 +195,35 @@ public class DistributionEngine implements IDistributionEngine {
     }
 
     private boolean isValidObject(Object paramValue, String methodName, String paramName) {
-
         if (paramValue == null) {
             BeEcompErrorManager.getInstance().logBeMissingConfigurationError(methodName, paramName);
             return false;
         }
         return true;
-
     }
 
     private String getEnvironmentErrorDescription(StorageOperationStatus status) {
-
         switch (status) {
-        case DISTR_ENVIRONMENT_NOT_AVAILABLE:
-            return "environment is unavailable";
-        case DISTR_ENVIRONMENT_NOT_FOUND:
-            return "environment is not configured in our system";
-        case DISTR_ENVIRONMENT_SENT_IS_INVALID:
-            return "environment name is invalid";
-        default:
-            return "unkhown";
+            case DISTR_ENVIRONMENT_NOT_AVAILABLE:
+                return "environment is unavailable";
+            case DISTR_ENVIRONMENT_NOT_FOUND:
+                return "environment is not configured in our system";
+            case DISTR_ENVIRONMENT_SENT_IS_INVALID:
+                return "environment name is invalid";
+            default:
+                return "unkhown";
         }
     }
 
     @Override
     public StorageOperationStatus isEnvironmentAvailable(String envName) {
-
         if (envName == null || envName.isEmpty()) {
-
             return StorageOperationStatus.DISTR_ENVIRONMENT_SENT_IS_INVALID;
         }
-
         AtomicBoolean status = envNamePerStatus.get(envName);
         if (status == null) {
             return StorageOperationStatus.DISTR_ENVIRONMENT_NOT_FOUND;
         }
-
         if (!status.get()) {
             return StorageOperationStatus.DISTR_ENVIRONMENT_NOT_AVAILABLE;
         }
@@ -266,9 +232,7 @@ public class DistributionEngine implements IDistributionEngine {
 
     @Override
     public StorageOperationStatus isEnvironmentAvailable() {
-
         String envName = ConfigurationManager.getConfigurationManager().getDistributionEngineConfiguration().getEnvironments().get(0);
-
         return isEnvironmentAvailable(envName);
     }
 
@@ -284,13 +248,16 @@ public class DistributionEngine implements IDistributionEngine {
     }
 
     @Override
-    public ActionStatus notifyService(String distributionId, Service service, INotificationData notificationData, String envId, String envName, User modifier) {
-        logger.debug("Received notify service request. distributionId = {}, serviceUuid = {} serviceUid = {}, envName = {}, userId = {}, modifierName {}", distributionId, service.getUUID(), service.getUniqueId(), envName, service.getLastUpdaterUserId(), modifier);
+    public ActionStatus notifyService(String distributionId, Service service, INotificationData notificationData, String envId, String envName,
+                                      User modifier) {
+        logger.debug(
+            "Received notify service request. distributionId = {}, serviceUuid = {} serviceUid = {}, envName = {}, userId = {}, modifierName {}",
+            distributionId, service.getUUID(), service.getUniqueId(), envName, service.getLastUpdaterUserId(), modifier);
         String topicName = buildTopicName(envName);
-        ActionStatus notifyServiceStatus = Optional.ofNullable(environmentsEngine.getEnvironmentById(envId))
-                .map(EnvironmentMessageBusData::new)
-                .map(messageBusData -> distributionNotificationSender.sendNotification(topicName, distributionId, messageBusData, notificationData, service, modifier))
-                .orElse(ActionStatus.DISTRIBUTION_ENVIRONMENT_NOT_AVAILABLE);
+        ActionStatus notifyServiceStatus = Optional.ofNullable(environmentsEngine.getEnvironmentById(envId)).map(EnvironmentMessageBusData::new).map(
+            messageBusData -> distributionNotificationSender
+                .sendNotification(topicName, distributionId, messageBusData, notificationData, service, modifier))
+            .orElse(ActionStatus.DISTRIBUTION_ENVIRONMENT_NOT_AVAILABLE);
         logger.debug("Finish notifyService. status is {}", notifyServiceStatus);
         return notifyServiceStatus;
     }
@@ -306,7 +273,8 @@ public class DistributionEngine implements IDistributionEngine {
         StorageOperationStatus status = isEnvironmentAvailable(envName);
         if (status != StorageOperationStatus.OK) {
             String envErrorDec = getEnvironmentErrorDescription(status);
-            BeEcompErrorManager.getInstance().logBeDistributionEngineSystemError(DistributionNotificationSender.DISTRIBUTION_NOTIFICATION_SENDING, "Environment name " + envName + " is not available. Reason : " + envErrorDec);
+            BeEcompErrorManager.getInstance().logBeDistributionEngineSystemError(DistributionNotificationSender.DISTRIBUTION_NOTIFICATION_SENDING,
+                "Environment name " + envName + " is not available. Reason : " + envErrorDec);
         }
         return status;
     }
@@ -327,5 +295,4 @@ public class DistributionEngine implements IDistributionEngine {
         value = serviceDistributionArtifactsBuilder.buildServiceForDistribution(value, service);
         return value;
     }
-
 }
index ec58cad..1e9899b 100644 (file)
@@ -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.
  * limitations under the License.
  * ============LICENSE_END=========================================================
  */
-
 package org.openecomp.sdc.be.components.distribution.engine;
 
-import org.openecomp.sdc.be.config.BeEcompErrorManager;
-import org.openecomp.sdc.be.config.ConfigurationManager;
-import org.openecomp.sdc.be.config.DistributionEngineConfiguration;
-import org.openecomp.sdc.common.api.Constants;
-import org.openecomp.sdc.common.api.HealthCheckInfo;
-import org.openecomp.sdc.common.api.HealthCheckInfo.HealthCheckStatus;
-import org.openecomp.sdc.common.log.wrappers.Logger;
-import org.springframework.stereotype.Component;
-
-import javax.annotation.PostConstruct;
-import javax.annotation.PreDestroy;
 import java.util.ArrayList;
 import java.util.Collection;
 import java.util.List;
@@ -43,69 +31,155 @@ import java.util.concurrent.ScheduledFuture;
 import java.util.concurrent.ThreadFactory;
 import java.util.concurrent.TimeUnit;
 import java.util.concurrent.atomic.AtomicBoolean;
+import javax.annotation.PostConstruct;
+import javax.annotation.PreDestroy;
+import org.openecomp.sdc.be.config.BeEcompErrorManager;
+import org.openecomp.sdc.be.config.ConfigurationManager;
+import org.openecomp.sdc.be.config.DistributionEngineConfiguration;
+import org.openecomp.sdc.common.api.Constants;
+import org.openecomp.sdc.common.api.HealthCheckInfo;
+import org.openecomp.sdc.common.api.HealthCheckInfo.HealthCheckStatus;
+import org.openecomp.sdc.common.log.wrappers.Logger;
+import org.springframework.stereotype.Component;
+
 @Component("distribution-engine-cluster-health")
 public class DistributionEngineClusterHealth {
 
+    private static final String UEB_HEALTH_CHECK_STR = "uebHealthCheck";
+    private static final Logger logger = Logger.getLogger(DistributionEngineClusterHealth.class.getName());
     protected static String UEB_HEALTH_LOG_CONTEXT = "ueb.healthcheck";
-
     //TODO use LoggerMetric instead
     private static final Logger healthLogger = Logger.getLogger(UEB_HEALTH_LOG_CONTEXT);
-
-    private static final String UEB_HEALTH_CHECK_STR = "uebHealthCheck";
-
     boolean lastHealthState = false;
-
     Object lockOject = new Object();
-
+    ScheduledExecutorService healthCheckScheduler = Executors.newSingleThreadScheduledExecutor(new ThreadFactory() {
+        @Override
+        public Thread newThread(Runnable r) {
+            return new Thread(r, "UEB-Health-Check-Task");
+        }
+    });
+    HealthCheckScheduledTask healthCheckScheduledTask = null;
     private long reconnectInterval = 5;
-
     private long healthCheckReadTimeout = 20;
-
-    private static final Logger logger = Logger.getLogger(DistributionEngineClusterHealth.class.getName());
-
     private List<String> uebServers = null;
-
     private String publicApiKey = null;
+    private HealthCheckInfo healthCheckInfo = HealthCheckInfoResult.UNKNOWN.getHealthCheckInfo();
+    private Map<String, AtomicBoolean> envNamePerStatus = null;
+    private ScheduledFuture<?> scheduledFuture = null;
 
-    public enum HealthCheckInfoResult {
-
-        OK(new HealthCheckInfo(Constants.HC_COMPONENT_DISTRIBUTION_ENGINE, HealthCheckStatus.UP, null, ClusterStatusDescription.OK.getDescription())),
-        UNAVAILABLE(new HealthCheckInfo(Constants.HC_COMPONENT_DISTRIBUTION_ENGINE, HealthCheckStatus.DOWN, null, ClusterStatusDescription.UNAVAILABLE.getDescription())),
-        NOT_CONFIGURED(new HealthCheckInfo(Constants.HC_COMPONENT_DISTRIBUTION_ENGINE, HealthCheckStatus.DOWN, null, ClusterStatusDescription.NOT_CONFIGURED.getDescription())),
-        DISABLED(new HealthCheckInfo(Constants.HC_COMPONENT_DISTRIBUTION_ENGINE, HealthCheckStatus.DOWN, null, ClusterStatusDescription.DISABLED.getDescription())),
-        UNKNOWN(new HealthCheckInfo(Constants.HC_COMPONENT_DISTRIBUTION_ENGINE, HealthCheckStatus.UNKNOWN, null, ClusterStatusDescription.UNKNOWN.getDescription()));
-
-        private HealthCheckInfo healthCheckInfo;
+    @PostConstruct
+    protected void init() {
+        logger.trace("Enter init method of DistributionEngineClusterHealth");
+        Long reconnectIntervalConfig = ConfigurationManager.getConfigurationManager().getConfiguration()
+            .getUebHealthCheckReconnectIntervalInSeconds();
+        if (reconnectIntervalConfig != null) {
+            reconnectInterval = reconnectIntervalConfig.longValue();
+        }
+        Long healthCheckReadTimeoutConfig = ConfigurationManager.getConfigurationManager().getConfiguration().getUebHealthCheckReadTimeout();
+        if (healthCheckReadTimeoutConfig != null) {
+            healthCheckReadTimeout = healthCheckReadTimeoutConfig.longValue();
+        }
+        DistributionEngineConfiguration distributionEngineConfiguration = ConfigurationManager.getConfigurationManager()
+            .getDistributionEngineConfiguration();
+        this.uebServers = distributionEngineConfiguration.getUebServers();
+        this.publicApiKey = distributionEngineConfiguration.getUebPublicKey();
+        this.healthCheckScheduledTask = new HealthCheckScheduledTask(this.uebServers);
+        logger.trace("Exit init method of DistributionEngineClusterHealth");
+    }
 
-        HealthCheckInfoResult(HealthCheckInfo healthCheckInfo) {
-            this.healthCheckInfo = healthCheckInfo;
+    @PreDestroy
+    protected void destroy() {
+        if (scheduledFuture != null) {
+            scheduledFuture.cancel(true);
+            scheduledFuture = null;
         }
+        if (healthCheckScheduler != null) {
+            healthCheckScheduler.shutdown();
+        }
+    }
 
-        public HealthCheckInfo getHealthCheckInfo() {
-            return healthCheckInfo;
+    /**
+     * Start health check task.
+     *
+     * @param envNamePerStatus
+     * @param startTask
+     */
+    public void startHealthCheckTask(Map<String, AtomicBoolean> envNamePerStatus, boolean startTask) {
+        this.envNamePerStatus = envNamePerStatus;
+        if (startTask && this.scheduledFuture == null) {
+            this.scheduledFuture = this.healthCheckScheduler.scheduleAtFixedRate(healthCheckScheduledTask, 0, reconnectInterval, TimeUnit.SECONDS);
         }
+    }
 
+    public void startHealthCheckTask(Map<String, AtomicBoolean> envNamePerStatus) {
+        startHealthCheckTask(envNamePerStatus, true);
     }
 
-    private HealthCheckInfo healthCheckInfo = HealthCheckInfoResult.UNKNOWN.getHealthCheckInfo();
+    private void logAlarm(boolean lastHealthState) {
+        if (lastHealthState) {
+            BeEcompErrorManager.getInstance().logBeHealthCheckUebClusterRecovery(UEB_HEALTH_CHECK_STR);
+        } else {
+            BeEcompErrorManager.getInstance().logBeHealthCheckUebClusterError(UEB_HEALTH_CHECK_STR);
+        }
+    }
 
-    private Map<String, AtomicBoolean> envNamePerStatus = null;
+    public HealthCheckInfo getHealthCheckInfo() {
+        return healthCheckInfo;
+    }
 
-    private ScheduledFuture<?> scheduledFuture = null;
+    /**
+     * change the health check to DISABLE
+     */
+    public void setHealthCheckUebIsDisabled() {
+        healthCheckInfo = HealthCheckInfoResult.DISABLED.getHealthCheckInfo();
+    }
 
-    ScheduledExecutorService healthCheckScheduler = Executors.newSingleThreadScheduledExecutor(new ThreadFactory() {
-        @Override
-        public Thread newThread(Runnable r) {
-            return new Thread(r, "UEB-Health-Check-Task");
+    /**
+     * change the health check to NOT CONFGIURED
+     */
+    public void setHealthCheckUebConfigurationError() {
+        healthCheckInfo = HealthCheckInfoResult.NOT_CONFIGURED.getHealthCheckInfo();
+    }
+
+    public void setHealthCheckOkAndReportInCaseLastStateIsDown() {
+        if (lastHealthState) {
+            return;
         }
-    });
+        synchronized (lockOject) {
+            if (!lastHealthState) {
+                logger.debug("Going to update health check state to available");
+                lastHealthState = true;
+                healthCheckInfo = HealthCheckInfoResult.OK.getHealthCheckInfo();
+                logAlarm(lastHealthState);
+            }
+        }
+    }
 
-    HealthCheckScheduledTask healthCheckScheduledTask = null;
+    public enum HealthCheckInfoResult {
+        OK(new HealthCheckInfo(Constants.HC_COMPONENT_DISTRIBUTION_ENGINE, HealthCheckStatus.UP, null,
+            ClusterStatusDescription.OK.getDescription())), UNAVAILABLE(
+            new HealthCheckInfo(Constants.HC_COMPONENT_DISTRIBUTION_ENGINE, HealthCheckStatus.DOWN, null,
+                ClusterStatusDescription.UNAVAILABLE.getDescription())), NOT_CONFIGURED(
+            new HealthCheckInfo(Constants.HC_COMPONENT_DISTRIBUTION_ENGINE, HealthCheckStatus.DOWN, null,
+                ClusterStatusDescription.NOT_CONFIGURED.getDescription())), DISABLED(
+            new HealthCheckInfo(Constants.HC_COMPONENT_DISTRIBUTION_ENGINE, HealthCheckStatus.DOWN, null,
+                ClusterStatusDescription.DISABLED.getDescription())), UNKNOWN(
+            new HealthCheckInfo(Constants.HC_COMPONENT_DISTRIBUTION_ENGINE, HealthCheckStatus.UNKNOWN, null,
+                ClusterStatusDescription.UNKNOWN.getDescription()));
+        private HealthCheckInfo healthCheckInfo;
 
-    public enum ClusterStatusDescription {
+        HealthCheckInfoResult(HealthCheckInfo healthCheckInfo) {
+            this.healthCheckInfo = healthCheckInfo;
+        }
 
-        OK("OK"), UNAVAILABLE("U-EB cluster is not available"), NOT_CONFIGURED("U-EB cluster is not configured"), DISABLED("DE is disabled in configuration"), UNKNOWN("U-EB cluster is currently unknown (try again in few minutes)");
+        public HealthCheckInfo getHealthCheckInfo() {
+            return healthCheckInfo;
+        }
+    }
 
+    public enum ClusterStatusDescription {
+        OK("OK"), UNAVAILABLE("U-EB cluster is not available"), NOT_CONFIGURED("U-EB cluster is not configured"), DISABLED(
+            "DE is disabled in configuration"), UNKNOWN("U-EB cluster is currently unknown (try again in few minutes)");
         private String desc;
 
         ClusterStatusDescription(String desc) {
@@ -115,24 +189,30 @@ public class DistributionEngineClusterHealth {
         public String getDescription() {
             return desc;
         }
-
     }
 
     /**
      * Health Check Task Scheduler.
-     *
-     * It schedules a task which send a apiKey get query towards the UEB servers. In case a query to the first UEB server is failed, then a second query is sent to the next UEB server.
-     *
+     * <p>
+     * It schedules a task which send a apiKey get query towards the UEB servers. In case a query to the first UEB server is failed, then a second
+     * query is sent to the next UEB server.
      *
      * @author esofer
-     *
      */
     public class HealthCheckScheduledTask implements Runnable {
 
         List<UebHealthCheckCall> healthCheckCalls = new ArrayList<>();
+        /**
+         * executor for the query itself
+         */
+        ExecutorService healthCheckExecutor = Executors.newSingleThreadExecutor(new ThreadFactory() {
+            @Override
+            public Thread newThread(Runnable r) {
+                return new Thread(r, "UEB-Health-Check-Thread");
+            }
+        });
 
         public HealthCheckScheduledTask(List<String> uebServers) {
-
             logger.debug("Create health check calls for servers {}", uebServers);
             if (uebServers != null) {
                 for (String server : uebServers) {
@@ -143,17 +223,13 @@ public class DistributionEngineClusterHealth {
 
         @Override
         public void run() {
-
             healthLogger.trace("Executing UEB Health Check Task - Start");
-
             boolean healthStatus = verifyAtLeastOneEnvIsUp();
-
             if (healthStatus) {
                 boolean queryUebStatus = queryUeb();
                 if (queryUebStatus == lastHealthState) {
                     return;
                 }
-
                 synchronized (lockOject) {
                     if (queryUebStatus != lastHealthState) {
                         logger.trace("UEB Health State Changed to {}. Issuing alarm / recovery alarm...", healthStatus);
@@ -169,17 +245,13 @@ public class DistributionEngineClusterHealth {
             } else {
                 healthLogger.trace("Not all UEB Environments are up");
             }
-
         }
 
         /**
          * verify that at least one environment is up.
-         *
          */
         private boolean verifyAtLeastOneEnvIsUp() {
-
             boolean healthStatus = false;
-
             if (envNamePerStatus != null) {
                 Collection<AtomicBoolean> values = envNamePerStatus.values();
                 if (values != null) {
@@ -191,163 +263,45 @@ public class DistributionEngineClusterHealth {
                     }
                 }
             }
-
             return healthStatus;
         }
 
-        /**
-         * executor for the query itself
-         */
-        ExecutorService healthCheckExecutor = Executors.newSingleThreadExecutor(new ThreadFactory() {
-            @Override
-            public Thread newThread(Runnable r) {
-                return new Thread(r, "UEB-Health-Check-Thread");
-            }
-        });
-
         /**
          * go all UEB servers and send a get apiKeys query. In case a query is succeed, no query is sent to the rest of UEB servers.
          *
-         *
          * @return
          */
         private boolean queryUeb() {
-
             Boolean result = false;
             int retryNumber = 1;
             for (UebHealthCheckCall healthCheckCall : healthCheckCalls) {
                 try {
-
-                    healthLogger.debug("Before running Health Check retry query number {} towards UEB server {}", retryNumber, healthCheckCall.getServer());
-
+                    healthLogger
+                        .debug("Before running Health Check retry query number {} towards UEB server {}", retryNumber, healthCheckCall.getServer());
                     Future<Boolean> future = healthCheckExecutor.submit(healthCheckCall);
                     result = future.get(healthCheckReadTimeout, TimeUnit.SECONDS);
-
-                    healthLogger.debug("After running Health Check retry query number {} towards UEB server {}. Result is {}", retryNumber, healthCheckCall.getServer(), result);
-
+                    healthLogger.debug("After running Health Check retry query number {} towards UEB server {}. Result is {}", retryNumber,
+                        healthCheckCall.getServer(), result);
                     if (result != null && result.booleanValue()) {
                         break;
                     }
-
                 } catch (Exception e) {
                     String message = e.getMessage();
                     if (message == null) {
                         message = e.getClass().getName();
                     }
-                    healthLogger.debug("Error occured during running Health Check retry query towards UEB server {}. Result is {}", healthCheckCall.getServer(), message);
-                    healthLogger.trace("Error occured during running Health Check retry query towards UEB server {}. Result is {}", healthCheckCall.getServer(), message, e);
+                    healthLogger.debug("Error occured during running Health Check retry query towards UEB server {}. Result is {}",
+                        healthCheckCall.getServer(), message);
+                    healthLogger.trace("Error occured during running Health Check retry query towards UEB server {}. Result is {}",
+                        healthCheckCall.getServer(), message, e);
                 }
                 retryNumber++;
-
             }
-
             return result;
-
         }
 
         public List<UebHealthCheckCall> getHealthCheckCalls() {
             return healthCheckCalls;
         }
-
-    }
-
-    @PostConstruct
-    protected void init() {
-
-        logger.trace("Enter init method of DistributionEngineClusterHealth");
-
-        Long reconnectIntervalConfig = ConfigurationManager.getConfigurationManager().getConfiguration().getUebHealthCheckReconnectIntervalInSeconds();
-        if (reconnectIntervalConfig != null) {
-            reconnectInterval = reconnectIntervalConfig.longValue();
-        }
-        Long healthCheckReadTimeoutConfig = ConfigurationManager.getConfigurationManager().getConfiguration().getUebHealthCheckReadTimeout();
-        if (healthCheckReadTimeoutConfig != null) {
-            healthCheckReadTimeout = healthCheckReadTimeoutConfig.longValue();
-        }
-
-        DistributionEngineConfiguration distributionEngineConfiguration = ConfigurationManager.getConfigurationManager().getDistributionEngineConfiguration();
-
-        this.uebServers = distributionEngineConfiguration.getUebServers();
-        this.publicApiKey = distributionEngineConfiguration.getUebPublicKey();
-
-        this.healthCheckScheduledTask = new HealthCheckScheduledTask(this.uebServers);
-
-        logger.trace("Exit init method of DistributionEngineClusterHealth");
-
-    }
-
-    @PreDestroy
-    protected void destroy() {
-
-        if (scheduledFuture != null) {
-            scheduledFuture.cancel(true);
-            scheduledFuture = null;
-        }
-
-        if (healthCheckScheduler != null) {
-            healthCheckScheduler.shutdown();
-        }
-
-    }
-
-    /**
-     * Start health check task.
-     *
-     * @param envNamePerStatus
-     * @param startTask
-     */
-    public void startHealthCheckTask(Map<String, AtomicBoolean> envNamePerStatus, boolean startTask) {
-        this.envNamePerStatus = envNamePerStatus;
-
-        if (startTask && this.scheduledFuture == null) {
-            this.scheduledFuture = this.healthCheckScheduler.scheduleAtFixedRate(healthCheckScheduledTask, 0, reconnectInterval, TimeUnit.SECONDS);
-        }
-    }
-
-    public void startHealthCheckTask(Map<String, AtomicBoolean> envNamePerStatus) {
-        startHealthCheckTask(envNamePerStatus, true);
-    }
-
-    private void logAlarm(boolean lastHealthState) {
-        if (lastHealthState) {
-            BeEcompErrorManager.getInstance().logBeHealthCheckUebClusterRecovery(UEB_HEALTH_CHECK_STR);
-        } else {
-            BeEcompErrorManager.getInstance().logBeHealthCheckUebClusterError(UEB_HEALTH_CHECK_STR);
-        }
-    }
-
-    public HealthCheckInfo getHealthCheckInfo() {
-        return healthCheckInfo;
-    }
-
-    /**
-     * change the health check to DISABLE
-     */
-    public void setHealthCheckUebIsDisabled() {
-        healthCheckInfo = HealthCheckInfoResult.DISABLED.getHealthCheckInfo();
-    }
-
-    /**
-     * change the health check to NOT CONFGIURED
-     */
-    public void setHealthCheckUebConfigurationError() {
-        healthCheckInfo = HealthCheckInfoResult.NOT_CONFIGURED.getHealthCheckInfo();
-    }
-
-    public void setHealthCheckOkAndReportInCaseLastStateIsDown() {
-
-        if (lastHealthState) {
-            return;
-        }
-        synchronized (lockOject) {
-            if (!lastHealthState) {
-                logger.debug("Going to update health check state to available");
-                lastHealthState = true;
-                healthCheckInfo = HealthCheckInfoResult.OK.getHealthCheckInfo();
-                logAlarm(lastHealthState);
-            }
-        }
-
     }
-
 }
index 52b1967..6207cd2 100644 (file)
@@ -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.
  * limitations under the License.
  * ============LICENSE_END=========================================================
  */
-
 package org.openecomp.sdc.be.components.distribution.engine;
 
 import fj.data.Either;
-import org.openecomp.sdc.be.config.BeEcompErrorManager;
-import org.openecomp.sdc.be.config.DistributionEngineConfiguration;
-import org.openecomp.sdc.be.distribution.api.client.CambriaOperationStatus;
-import org.openecomp.sdc.be.impl.ComponentsUtils;
-import org.openecomp.sdc.be.resources.data.OperationalEnvironmentEntry;
-import org.openecomp.sdc.be.resources.data.auditing.AuditingActionEnum;
-import org.openecomp.sdc.be.resources.data.auditing.model.DistributionTopicData;
-import org.openecomp.sdc.common.log.wrappers.Logger;
-
 import java.util.HashSet;
 import java.util.Set;
 import java.util.concurrent.Executors;
@@ -38,6 +28,14 @@ import java.util.concurrent.ScheduledFuture;
 import java.util.concurrent.TimeUnit;
 import java.util.concurrent.atomic.AtomicBoolean;
 import java.util.stream.Collectors;
+import org.openecomp.sdc.be.config.BeEcompErrorManager;
+import org.openecomp.sdc.be.config.DistributionEngineConfiguration;
+import org.openecomp.sdc.be.distribution.api.client.CambriaOperationStatus;
+import org.openecomp.sdc.be.impl.ComponentsUtils;
+import org.openecomp.sdc.be.resources.data.OperationalEnvironmentEntry;
+import org.openecomp.sdc.be.resources.data.auditing.AuditingActionEnum;
+import org.openecomp.sdc.be.resources.data.auditing.model.DistributionTopicData;
+import org.openecomp.sdc.common.log.wrappers.Logger;
 
 public class DistributionEngineInitTask implements Runnable {
 
@@ -48,26 +46,25 @@ public class DistributionEngineInitTask implements Runnable {
     public static final String CREATED = "CREATED";
     public static final String FAILED = "FAILED";
     public static final Integer HTTP_OK = 200;
-
+    private static final Logger logger = Logger.getLogger(DistributionEngineInitTask.class.getName());
+    boolean maximumRetryInterval = false;
+    ComponentsUtils componentsUtils = null;
+    DistributionEnginePollingTask distributionEnginePollingTask = null;
+    ScheduledFuture<?> scheduledFuture = null;
     private Long delayBeforeStartFlow = 0l;
     private DistributionEngineConfiguration deConfiguration;
     private String envName;
     private long retryInterval;
     private long currentRetryInterval;
     private long maxInterval;
-    boolean maximumRetryInterval = false;
     private AtomicBoolean status = null;
-    ComponentsUtils componentsUtils = null;
-    DistributionEnginePollingTask distributionEnginePollingTask = null;
     private OperationalEnvironmentEntry environmentEntry;
-
     private CambriaHandler cambriaHandler = new CambriaHandler();
-
     private ScheduledExecutorService scheduledExecutorService = Executors.newScheduledThreadPool(1);
-    private static final Logger logger = Logger.getLogger(DistributionEngineInitTask.class.getName());
-    ScheduledFuture<?> scheduledFuture = null;
-    
-    public DistributionEngineInitTask(Long delayBeforeStartFlow, DistributionEngineConfiguration deConfiguration, String envName, AtomicBoolean status, ComponentsUtils componentsUtils, DistributionEnginePollingTask distributionEnginePollingTask, OperationalEnvironmentEntry environmentEntry) {
+
+    public DistributionEngineInitTask(Long delayBeforeStartFlow, DistributionEngineConfiguration deConfiguration, String envName,
+                                      AtomicBoolean status, ComponentsUtils componentsUtils,
+                                      DistributionEnginePollingTask distributionEnginePollingTask, OperationalEnvironmentEntry environmentEntry) {
         super();
         this.delayBeforeStartFlow = delayBeforeStartFlow;
         this.deConfiguration = deConfiguration;
@@ -81,26 +78,25 @@ public class DistributionEngineInitTask implements Runnable {
         this.environmentEntry = environmentEntry;
     }
 
+    public static String buildTopicName(String topicName, String environment) {
+        return topicName + "-" + environment.toUpperCase();
+    }
+
     public void startTask() {
         if (scheduledExecutorService != null) {
             Integer retryInterval = deConfiguration.getInitRetryIntervalSec();
-            logger.debug("Start Distribution Engine init task. retry interval {} seconds, delay before first run {} seconds", retryInterval, delayBeforeStartFlow);
+            logger.debug("Start Distribution Engine init task. retry interval {} seconds, delay before first run {} seconds", retryInterval,
+                delayBeforeStartFlow);
             this.scheduledFuture = scheduledExecutorService.scheduleAtFixedRate(this, delayBeforeStartFlow, retryInterval, TimeUnit.SECONDS);
-
         }
     }
 
     public void restartTask() {
-
         this.stopTask();
-
         logger.debug("Start Distribution Engine init task. next run in {} seconds", this.currentRetryInterval);
-
         long lastCurrentInterval = currentRetryInterval;
         incrementRetryInterval();
-
         this.scheduledFuture = scheduledExecutorService.scheduleAtFixedRate(this, lastCurrentInterval, this.currentRetryInterval, TimeUnit.SECONDS);
-
     }
 
     protected void incrementRetryInterval() {
@@ -140,10 +136,8 @@ public class DistributionEngineInitTask implements Runnable {
 
     @Override
     public void run() {
-
         boolean result = false;
         result = initFlow();
-
         if (result) {
             this.stopTask();
             this.status.set(true);
@@ -165,12 +159,9 @@ public class DistributionEngineInitTask implements Runnable {
      * @return
      */
     public boolean initFlow() {
-
         logger.trace("Start init flow for environment {}", this.envName);
-
         Set<String> topicsList = null;
         Either<Set<String>, CambriaErrorResponse> getTopicsRes = null;
-
         getTopicsRes = cambriaHandler.getTopics(environmentEntry.getDmaapUebAddress().stream().collect(Collectors.toList()));
         if (getTopicsRes.isRight()) {
             CambriaErrorResponse status = getTopicsRes.right().value();
@@ -183,35 +174,29 @@ public class DistributionEngineInitTask implements Runnable {
         } else {
             topicsList = getTopicsRes.left().value();
         }
-
         String notificationTopic = buildTopicName(deConfiguration.getDistributionNotifTopicName(), this.envName);
         logger.debug("Going to handle topic {}", notificationTopic);
         if (!createNotificationTopicIfNotExists(topicsList, notificationTopic)) {
             return false;
         }
-
         CambriaErrorResponse registerProducerStatus = registerToTopic(notificationTopic, SubscriberTypeEnum.PRODUCER);
-
         CambriaOperationStatus createStatus = registerProducerStatus.getOperationStatus();
-
         if (createStatus != CambriaOperationStatus.OK) {
             return false;
         }
-
         String statusTopic = buildTopicName(deConfiguration.getDistributionStatusTopicName(), this.envName);
         logger.debug("Going to handle topic {}", statusTopic);
         if (!createStatusTopicIfNotExists(topicsList, statusTopic)) {
             return false;
         }
-
         CambriaErrorResponse registerConcumerStatus = registerToTopic(statusTopic, SubscriberTypeEnum.CONSUMER);
-
         return registerConcumerStatus.getOperationStatus() == CambriaOperationStatus.OK;
     }
 
     private CambriaErrorResponse registerToTopic(String topicName, SubscriberTypeEnum subscriberType) {
-        CambriaErrorResponse registerStatus = cambriaHandler.registerToTopic(environmentEntry.getDmaapUebAddress(), environmentEntry.getUebApikey(), environmentEntry.getUebSecretKey(), environmentEntry.getUebApikey(), subscriberType, topicName);
-
+        CambriaErrorResponse registerStatus = cambriaHandler
+            .registerToTopic(environmentEntry.getDmaapUebAddress(), environmentEntry.getUebApikey(), environmentEntry.getUebSecretKey(),
+                environmentEntry.getUebApikey(), subscriberType, topicName);
         String role = CONSUMER;
         if (subscriberType == SubscriberTypeEnum.PRODUCER) {
             role = PRODUCER;
@@ -225,56 +210,50 @@ public class DistributionEngineInitTask implements Runnable {
             Integer httpCode = registerProducerStatus.getHttpCode();
             String httpCodeStr = String.valueOf(httpCode);
             this.componentsUtils.auditDistributionEngine(AuditingActionEnum.ADD_KEY_TO_TOPIC_ACL, this.envName,
-                    DistributionTopicData.newBuilder()
-                            .notificationTopic(notificationTopic)
-                            .build(),
-                    role, environmentEntry.getUebApikey(), httpCodeStr);
+                DistributionTopicData.newBuilder().notificationTopic(notificationTopic).build(), role, environmentEntry.getUebApikey(), httpCodeStr);
         }
     }
 
     private boolean createStatusTopicIfNotExists(Set<String> topicsList, String topicName) {
-        DistributionTopicData distributionTopicData = DistributionTopicData.newBuilder()
-                .statusTopic(topicName)
-                .build();
+        DistributionTopicData distributionTopicData = DistributionTopicData.newBuilder().statusTopic(topicName).build();
         return createDistributionTopic(topicsList, topicName, distributionTopicData);
     }
 
     private boolean createNotificationTopicIfNotExists(Set<String> topicsList, String topicName) {
-
-        DistributionTopicData distributionTopicData = DistributionTopicData.newBuilder()
-                .notificationTopic(topicName)
-                .build();
+        DistributionTopicData distributionTopicData = DistributionTopicData.newBuilder().notificationTopic(topicName).build();
         return createDistributionTopic(topicsList, topicName, distributionTopicData);
     }
 
     private boolean createDistributionTopic(Set<String> topicsList, String topicName, DistributionTopicData distributionTopicData) {
-
         boolean isSucceeded = true;
-
         if (topicsList.contains(topicName)) {
             if (componentsUtils != null) {
-                componentsUtils.auditDistributionEngine(AuditingActionEnum.CREATE_DISTRIBUTION_TOPIC, this.envName, distributionTopicData, ALREADY_EXISTS);
+                componentsUtils
+                    .auditDistributionEngine(AuditingActionEnum.CREATE_DISTRIBUTION_TOPIC, this.envName, distributionTopicData, ALREADY_EXISTS);
             }
             return isSucceeded;
         }
-        CambriaErrorResponse createDistribTopicStatus = cambriaHandler.createTopic(environmentEntry.getDmaapUebAddress(), environmentEntry.getUebApikey(), environmentEntry.getUebSecretKey(), topicName, deConfiguration.getCreateTopic().getPartitionCount(),
-                deConfiguration.getCreateTopic().getReplicationCount());
-
+        CambriaErrorResponse createDistribTopicStatus = cambriaHandler
+            .createTopic(environmentEntry.getDmaapUebAddress(), environmentEntry.getUebApikey(), environmentEntry.getUebSecretKey(), topicName,
+                deConfiguration.getCreateTopic().getPartitionCount(), deConfiguration.getCreateTopic().getReplicationCount());
         CambriaOperationStatus status = createDistribTopicStatus.getOperationStatus();
         switch (status) {
             case OK:
                 if (componentsUtils != null) {
-                    componentsUtils.auditDistributionEngine(AuditingActionEnum.CREATE_DISTRIBUTION_TOPIC, this.envName, distributionTopicData, CREATED);
+                    componentsUtils
+                        .auditDistributionEngine(AuditingActionEnum.CREATE_DISTRIBUTION_TOPIC, this.envName, distributionTopicData, CREATED);
                 }
                 break;
             case TOPIC_ALREADY_EXIST:
                 if (componentsUtils != null) {
-                    componentsUtils.auditDistributionEngine(AuditingActionEnum.CREATE_DISTRIBUTION_TOPIC, this.envName, distributionTopicData, ALREADY_EXISTS);
+                    componentsUtils
+                        .auditDistributionEngine(AuditingActionEnum.CREATE_DISTRIBUTION_TOPIC, this.envName, distributionTopicData, ALREADY_EXISTS);
                 }
                 break;
             default:
                 if (componentsUtils != null) {
-                    componentsUtils.auditDistributionEngine(AuditingActionEnum.CREATE_DISTRIBUTION_TOPIC, this.envName, distributionTopicData, FAILED);
+                    componentsUtils
+                        .auditDistributionEngine(AuditingActionEnum.CREATE_DISTRIBUTION_TOPIC, this.envName, distributionTopicData, FAILED);
                 }
                 BeEcompErrorManager.getInstance().logBeUebSystemError(INIT_DISTRIBUTION_ENGINE_FLOW, "try to create topic " + topicName);
                 isSucceeded = false;
@@ -283,10 +262,6 @@ public class DistributionEngineInitTask implements Runnable {
         return isSucceeded;
     }
 
-    public static String buildTopicName(String topicName, String environment) {
-        return topicName + "-" + environment.toUpperCase();
-    }
-
     public boolean isActive() {
         return this.status.get();
     }
index 933d3ef..1246710 100644 (file)
@@ -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.
  * limitations under the License.
  * ============LICENSE_END=========================================================
  */
-
 package org.openecomp.sdc.be.components.distribution.engine;
 
 import com.att.nsa.cambria.client.CambriaConsumer;
 import com.google.gson.Gson;
 import com.google.gson.GsonBuilder;
 import fj.data.Either;
+import java.util.concurrent.Executors;
+import java.util.concurrent.ScheduledExecutorService;
+import java.util.concurrent.ScheduledFuture;
+import java.util.concurrent.TimeUnit;
 import org.apache.commons.lang3.concurrent.BasicThreadFactory;
 import org.openecomp.sdc.be.components.distribution.engine.report.DistributionCompleteReporter;
 import org.openecomp.sdc.be.config.BeEcompErrorManager;
@@ -34,41 +37,32 @@ import org.openecomp.sdc.be.resources.data.OperationalEnvironmentEntry;
 import org.openecomp.sdc.common.log.wrappers.Logger;
 import org.openecomp.sdc.common.log.wrappers.LoggerSdcAudit;
 
-import java.util.concurrent.Executors;
-import java.util.concurrent.ScheduledExecutorService;
-import java.util.concurrent.ScheduledFuture;
-import java.util.concurrent.TimeUnit;
-
 public class DistributionEnginePollingTask implements Runnable {
 
     public static final String DISTRIBUTION_STATUS_POLLING = "distributionEngineStatusPolling";
     private static final String PARTNER_NAME = "UNKNOWN";
-
+    private static final Logger logger = Logger.getLogger(DistributionEnginePollingTask.class.getName());
+    private static LoggerSdcAudit audit = new LoggerSdcAudit(DistributionEnginePollingTask.class);
+    ScheduledFuture<?> scheduledFuture = null;
     private String topicName;
     private ComponentsUtils componentUtils;
     private int fetchTimeoutInSec = 15;
     private int pollingIntervalInSec;
     private String consumerId;
     private String consumerGroup;
-
     private CambriaHandler cambriaHandler = new CambriaHandler();
     private Gson gson = new GsonBuilder().setPrettyPrinting().create();
     private DistributionCompleteReporter distributionCompleteReporter;
-
-    private ScheduledExecutorService scheduledPollingService = Executors.newScheduledThreadPool(1, new BasicThreadFactory.Builder().namingPattern("TopicPollingThread-%d").build());
-
-    private static final Logger logger = Logger.getLogger(DistributionEnginePollingTask.class.getName());
-    private static LoggerSdcAudit audit = new LoggerSdcAudit(DistributionEnginePollingTask.class);
-
-    ScheduledFuture<?> scheduledFuture = null;
+    private ScheduledExecutorService scheduledPollingService = Executors
+        .newScheduledThreadPool(1, new BasicThreadFactory.Builder().namingPattern("TopicPollingThread-%d").build());
     private CambriaConsumer cambriaConsumer = null;
-
     private DistributionEngineClusterHealth distributionEngineClusterHealth = null;
-
     private OperationalEnvironmentEntry environmentEntry;
 
-    public DistributionEnginePollingTask(DistributionEngineConfiguration distributionEngineConfiguration, DistributionCompleteReporter distributionCompleteReporter, ComponentsUtils componentUtils, DistributionEngineClusterHealth distributionEngineClusterHealth, OperationalEnvironmentEntry environmentEntry) {
-
+    public DistributionEnginePollingTask(DistributionEngineConfiguration distributionEngineConfiguration,
+                                         DistributionCompleteReporter distributionCompleteReporter, ComponentsUtils componentUtils,
+                                         DistributionEngineClusterHealth distributionEngineClusterHealth,
+                                         OperationalEnvironmentEntry environmentEntry) {
         this.componentUtils = componentUtils;
         DistributionStatusTopicConfig statusConfig = distributionEngineConfiguration.getDistributionStatusTopic();
         this.pollingIntervalInSec = statusConfig.getPollingIntervalSec();
@@ -81,7 +75,6 @@ public class DistributionEnginePollingTask implements Runnable {
     }
 
     public void startTask(String topicName) {
-
         this.topicName = topicName;
         logger.debug("start task for polling topic {}", topicName);
         if (fetchTimeoutInSec < 15) {
@@ -89,13 +82,12 @@ public class DistributionEnginePollingTask implements Runnable {
             fetchTimeoutInSec = 15;
         }
         try {
-            cambriaConsumer = cambriaHandler.createConsumer(environmentEntry.getDmaapUebAddress(), topicName, environmentEntry.getUebApikey(), environmentEntry.getUebSecretKey(), consumerId, consumerGroup,
-                    fetchTimeoutInSec * 1000);
-
+            cambriaConsumer = cambriaHandler
+                .createConsumer(environmentEntry.getDmaapUebAddress(), topicName, environmentEntry.getUebApikey(), environmentEntry.getUebSecretKey(),
+                    consumerId, consumerGroup, fetchTimeoutInSec * 1000);
             if (scheduledPollingService != null) {
                 logger.debug("Start Distribution Engine polling task. polling interval {} seconds", pollingIntervalInSec);
                 scheduledFuture = scheduledPollingService.scheduleAtFixedRate(this, 0, pollingIntervalInSec, TimeUnit.SECONDS);
-
             }
         } catch (Exception e) {
             logger.debug("unexpected error occured", e);
@@ -117,7 +109,6 @@ public class DistributionEnginePollingTask implements Runnable {
             logger.debug("close consumer");
             cambriaHandler.closeConsumer(cambriaConsumer);
         }
-
     }
 
     public void destroy() {
@@ -128,7 +119,6 @@ public class DistributionEnginePollingTask implements Runnable {
     @Override
     public void run() {
         logger.trace("run() method. polling queue {}", topicName);
-
         try {
             // init error
             if (cambriaConsumer == null) {
@@ -136,19 +126,19 @@ public class DistributionEnginePollingTask implements Runnable {
                 stopTask();
                 return;
             }
-
             Either<Iterable<String>, CambriaErrorResponse> fetchResult = cambriaHandler.fetchFromTopic(cambriaConsumer);
             // fetch error
             if (fetchResult.isRight()) {
                 CambriaErrorResponse errorResponse = fetchResult.right().value();
-                BeEcompErrorManager.getInstance().logBeUebSystemError(DISTRIBUTION_STATUS_POLLING, "failed to fetch messages from topic " + topicName + " error: " + errorResponse);
-
+                BeEcompErrorManager.getInstance().logBeUebSystemError(DISTRIBUTION_STATUS_POLLING,
+                    "failed to fetch messages from topic " + topicName + " error: " + errorResponse);
                 // TODO: if status== internal error (connection problem) change
+
                 // state to inactive
+
                 // in next try, if succeed - change to active
                 return;
             }
-
             // success
             Iterable<String> messages = fetchResult.left().value();
             for (String message : messages) {
@@ -160,42 +150,44 @@ public class DistributionEnginePollingTask implements Runnable {
                     distributionEngineClusterHealth.setHealthCheckOkAndReportInCaseLastStateIsDown();
                 } catch (Exception e) {
                     logger.debug("failed to convert message to object", e);
-                    BeEcompErrorManager.getInstance().logBeUebSystemError(DISTRIBUTION_STATUS_POLLING, "failed to parse message " + message + " from topic " + topicName + " error: " + fetchResult.right().value());
+                    BeEcompErrorManager.getInstance().logBeUebSystemError(DISTRIBUTION_STATUS_POLLING,
+                        "failed to parse message " + message + " from topic " + topicName + " error: " + fetchResult.right().value());
                 }
-
             }
         } catch (Exception e) {
             logger.debug("unexpected error occurred", e);
             String methodName = Object.class.getEnclosingMethod().getName();
             BeEcompErrorManager.getInstance().logBeDistributionEngineSystemError(methodName, e.getMessage());
         }
-
     }
 
     private void handleDistributionNotificationMsg(DistributionStatusNotification notification, LoggerSdcAudit audit) {
-        componentUtils.auditDistributionStatusNotification(notification.getDistributionID(),
-                notification.getConsumerID(), topicName, notification.getArtifactURL(),
-                String.valueOf(notification.getTimestamp()), notification.getStatus().name(),
-                notification.getErrorReason(), audit);
+        componentUtils.auditDistributionStatusNotification(notification.getDistributionID(), notification.getConsumerID(), topicName,
+            notification.getArtifactURL(), String.valueOf(notification.getTimestamp()), notification.getStatus().name(),
+            notification.getErrorReason(), audit);
         if (notification.isDistributionCompleteNotification()) {
             distributionCompleteReporter.reportDistributionComplete(notification);
         }
     }
 
     private void shutdownExecutor() {
-        if (scheduledPollingService == null)
+        if (scheduledPollingService == null) {
             return;
-
+        }
         scheduledPollingService.shutdown(); // Disable new tasks from being
+
         // submitted
         try {
             // Wait a while for existing tasks to terminate
             if (!scheduledPollingService.awaitTermination(60, TimeUnit.SECONDS)) {
                 scheduledPollingService.shutdownNow(); // Cancel currently
+
                 // executing tasks
+
                 // Wait a while for tasks to respond to being cancelled
-                if (!scheduledPollingService.awaitTermination(60, TimeUnit.SECONDS))
+                if (!scheduledPollingService.awaitTermination(60, TimeUnit.SECONDS)) {
                     logger.debug("Pool did not terminate");
+                }
             }
         } catch (InterruptedException ie) {
             // (Re-)Cancel if current thread also interrupted
@@ -204,5 +196,4 @@ public class DistributionEnginePollingTask implements Runnable {
             Thread.currentThread().interrupt();
         }
     }
-
 }
index 1c6afe5..0098eac 100644 (file)
@@ -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.
@@ -17,7 +17,6 @@
  * limitations under the License.
  * ============LICENSE_END=========================================================
  */
-
 package org.openecomp.sdc.be.components.distribution.engine;
 
 import org.openecomp.sdc.be.config.ConfigurationManager;
@@ -34,39 +33,28 @@ import org.springframework.stereotype.Component;
 public class DistributionNotificationSender {
 
     protected static final String DISTRIBUTION_NOTIFICATION_SENDING = "distributionNotificationSending";
-
     private static final Logger logger = Logger.getLogger(DistributionNotificationSender.class.getName());
-
     @javax.annotation.Resource
     protected ComponentsUtils componentUtils;
     private CambriaHandler cambriaHandler = new CambriaHandler();
-    private DistributionEngineConfiguration deConfiguration =
-            ConfigurationManager.getConfigurationManager().getDistributionEngineConfiguration();
+    private DistributionEngineConfiguration deConfiguration = ConfigurationManager.getConfigurationManager().getDistributionEngineConfiguration();
 
-    public ActionStatus sendNotification(String topicName, String distributionId,
-            EnvironmentMessageBusData messageBusData, INotificationData notificationData, Service service,
-            User modifier) {
+    public ActionStatus sendNotification(String topicName, String distributionId, EnvironmentMessageBusData messageBusData,
+                                         INotificationData notificationData, Service service, User modifier) {
         long startTime = System.currentTimeMillis();
-        CambriaErrorResponse status =
-                cambriaHandler.sendNotificationAndClose(topicName, messageBusData.getUebPublicKey(),
-                        messageBusData.getUebPrivateKey(), messageBusData.getDmaaPuebEndpoints(), notificationData,
-                        deConfiguration.getDistributionNotificationTopic().getMaxWaitingAfterSendingSeconds());
-
-        logger.info("After publishing service {} of version {}. Status is {}", service.getName(), service.getVersion(),
-                status.getHttpCode());
-
-        auditDistributionNotification(new AuditDistributionNotificationBuilder().setTopicName(topicName)
-                .setDistributionId(distributionId).setStatus(status).setService(service)
-                .setEnvId(messageBusData.getEnvId()).setModifier(modifier)
-                .setWorkloadContext(notificationData.getWorkloadContext()).setTenant(messageBusData.getTenant()));
-
+        CambriaErrorResponse status = cambriaHandler
+            .sendNotificationAndClose(topicName, messageBusData.getUebPublicKey(), messageBusData.getUebPrivateKey(),
+                messageBusData.getDmaaPuebEndpoints(), notificationData,
+                deConfiguration.getDistributionNotificationTopic().getMaxWaitingAfterSendingSeconds());
+        logger.info("After publishing service {} of version {}. Status is {}", service.getName(), service.getVersion(), status.getHttpCode());
+        auditDistributionNotification(
+            new AuditDistributionNotificationBuilder().setTopicName(topicName).setDistributionId(distributionId).setStatus(status).setService(service)
+                .setEnvId(messageBusData.getEnvId()).setModifier(modifier).setWorkloadContext(notificationData.getWorkloadContext())
+                .setTenant(messageBusData.getTenant()));
         long endTime = System.currentTimeMillis();
-
         if (logger.isDebugEnabled()) {
-            logger.debug("After building and publishing artifacts object. Total took {} milliseconds",
-                    endTime - startTime);
+            logger.debug("After building and publishing artifacts object. Total took {} milliseconds", endTime - startTime);
         }
-
         return convertCambriaResponse(status);
     }
 
@@ -74,20 +62,15 @@ public class DistributionNotificationSender {
         if (this.componentUtils != null) {
             Integer httpCode = builder.getStatus().getHttpCode();
             String httpCodeStr = String.valueOf(httpCode);
-
             String desc = getDescriptionFromErrorResponse(builder.getStatus());
-
-            this.componentUtils.auditDistributionNotification(builder.getService().getUUID(),
-                    builder.getService().getName(), "Service", builder.getService().getVersion(), builder.getModifier(),
-                    builder.getEnvId(), builder.getService().getLifecycleState().name(), builder.getTopicName(),
-                    builder.getDistributionId(), desc, httpCodeStr, builder.getWorkloadContext(), builder.getTenant());
+            this.componentUtils.auditDistributionNotification(builder.getService().getUUID(), builder.getService().getName(), "Service",
+                builder.getService().getVersion(), builder.getModifier(), builder.getEnvId(), builder.getService().getLifecycleState().name(),
+                builder.getTopicName(), builder.getDistributionId(), desc, httpCodeStr, builder.getWorkloadContext(), builder.getTenant());
         }
     }
 
     private String getDescriptionFromErrorResponse(CambriaErrorResponse status) {
-
         CambriaOperationStatus operationStatus = status.getOperationStatus();
-
         switch (operationStatus) {
             case OK:
                 return "OK";
@@ -103,14 +86,11 @@ public class DistributionNotificationSender {
                 return "Error: object not found in U-EB server";
             default:
                 return "Error: Internal Cambria server problem";
-
         }
-
     }
 
     private ActionStatus convertCambriaResponse(CambriaErrorResponse status) {
         CambriaOperationStatus operationStatus = status.getOperationStatus();
-
         switch (operationStatus) {
             case OK:
                 return ActionStatus.OK;
@@ -126,9 +106,6 @@ public class DistributionNotificationSender {
                 return ActionStatus.OBJECT_NOT_FOUND;
             default:
                 return ActionStatus.GENERAL_ERROR;
-
         }
     }
-
-
 }
index 430b8be..f05cc76 100644 (file)
@@ -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.
@@ -17,7 +17,6 @@
  * limitations under the License.
  * ============LICENSE_END=========================================================
  */
-
 package org.openecomp.sdc.be.components.distribution.engine;
 
 public class DistributionStatusNotification {
@@ -78,11 +77,13 @@ public class DistributionStatusNotification {
     }
 
     public boolean isDistributionCompleteNotification() {
-        return DistributionStatusNotificationEnum.DISTRIBUTION_COMPLETE_OK == status || DistributionStatusNotificationEnum.DISTRIBUTION_COMPLETE_ERROR == status;
+        return DistributionStatusNotificationEnum.DISTRIBUTION_COMPLETE_OK == status
+            || DistributionStatusNotificationEnum.DISTRIBUTION_COMPLETE_ERROR == status;
     }
 
     @Override
     public String toString() {
-        return "DistributionStatusNotification [distributionId=" + distributionID + ", consumerId=" + consumerID + ", timestamp=" + timestamp + ", artifactURL=" + artifactURL + ", status=" + status + ", errorReason=" + errorReason + "]";
+        return "DistributionStatusNotification [distributionId=" + distributionID + ", consumerId=" + consumerID + ", timestamp=" + timestamp
+            + ", artifactURL=" + artifactURL + ", status=" + status + ", errorReason=" + errorReason + "]";
     }
 }
index 65aa18e..64c1963 100644 (file)
@@ -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.
  * limitations under the License.
  * ============LICENSE_END=========================================================
  */
-
 package org.openecomp.sdc.be.components.distribution.engine;
 
 public enum DistributionStatusNotificationEnum {
-
     DOWNLOAD_OK, DOWNLOAD_ERROR, ALREADY_DOWNLOADED, DEPLOY_OK, DEPLOY_ERROR, ALREADY_DEPLOYED, NOTIFIED, NOT_NOTIFIED, COMPONENT_DONE_ERROR, COMPONENT_DONE_OK, DISTRIBUTION_COMPLETE_OK, DISTRIBUTION_COMPLETE_ERROR
 }
index 4fb4122..0f4836e 100644 (file)
@@ -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.
  * limitations under the License.
  * ============LICENSE_END=========================================================
  */
-
 package org.openecomp.sdc.be.components.distribution.engine;
 
 import com.att.nsa.mr.client.MRBatchingPublisher;
 import com.att.nsa.mr.client.MRClientFactory;
 import com.att.nsa.mr.client.MRConsumer;
 import fj.data.Either;
+import java.io.File;
+import java.io.IOException;
+import java.security.GeneralSecurityException;
+import java.util.Properties;
 import org.onap.sdc.security.SecurityUtil;
 import org.openecomp.sdc.be.config.DmaapConsumerConfiguration;
 import org.openecomp.sdc.be.config.DmaapProducerConfiguration;
 import org.openecomp.sdc.common.log.wrappers.Logger;
 import org.springframework.stereotype.Component;
 
-import java.io.File;
-import java.io.IOException;
-import java.security.GeneralSecurityException;
-import java.util.Properties;
-
 /**
  * Allows to create DMAAP client of type MRConsumer according received configuration parameters
  */
 @Component("dmaapClientFactory")
 public class DmaapClientFactory {
+
     private static final Logger logger = Logger.getLogger(DmaapClientFactory.class.getName());
 
     /**
      * Creates DMAAP consumer according to received parameters
+     *
      * @param parameters
      * @return an instance object of type MRConsumer
      * @throws IOException
@@ -53,9 +53,10 @@ public class DmaapClientFactory {
         logger.info("MRConsumer created for topic {}", parameters.getTopic());
         return consumer;
     }
-    
+
     /**
      * Creates DMAAP consumer according to received parameters
+     *
      * @param parameters
      * @return an instance object of type MRConsumer
      * @throws IOException
@@ -69,8 +70,8 @@ public class DmaapClientFactory {
 
     private Properties buildProperties(DmaapConsumerConfiguration parameters) throws GeneralSecurityException, IOException {
         Properties props = new Properties();
-        Either<String,String> passkey = SecurityUtil.INSTANCE.decrypt(parameters.getCredential().getPassword() );
-        if (passkey.isRight()){
+        Either<String, String> passkey = SecurityUtil.INSTANCE.decrypt(parameters.getCredential().getPassword());
+        if (passkey.isRight()) {
             throw new GeneralSecurityException("invalid password, cannot build properties");
         }
         props.setProperty("Latitude", Double.toString(parameters.getLatitude()));
@@ -79,34 +80,30 @@ public class DmaapClientFactory {
         props.setProperty("ServiceName", parameters.getServiceName());
         props.setProperty("Environment", parameters.getEnvironment());
         props.setProperty("Partner", parameters.getPartner());
-        props.setProperty("routeOffer", parameters.getRouteOffer());        
-        props.setProperty("Protocol", parameters.getProtocol());        
+        props.setProperty("routeOffer", parameters.getRouteOffer());
+        props.setProperty("Protocol", parameters.getProtocol());
         props.setProperty("username", parameters.getCredential().getUsername());
-        props.setProperty("password", passkey.left().value() );
-        props.setProperty("contenttype", parameters.getContenttype());        
+        props.setProperty("password", passkey.left().value());
+        props.setProperty("contenttype", parameters.getContenttype());
         props.setProperty("host", parameters.getHosts());
         props.setProperty("topic", parameters.getTopic());
         props.setProperty("group", parameters.getConsumerGroup());
         props.setProperty("id", parameters.getConsumerId());
         props.setProperty("timeout", Integer.toString(parameters.getTimeoutMs()));
-        props.setProperty("limit", Integer.toString(parameters.getLimit()));        
+        props.setProperty("limit", Integer.toString(parameters.getLimit()));
         props.setProperty("AFT_DME2_REQ_TRACE_ON", Boolean.toString(parameters.isDme2TraceOn()));
         props.setProperty("AFT_ENVIRONMENT", parameters.getAftEnvironment());
         props.setProperty("AFT_DME2_EP_CONN_TIMEOUT", Integer.toString(parameters.getAftDme2ConnectionTimeoutMs()));
         props.setProperty("AFT_DME2_ROUNDTRIP_TIMEOUT_MS", Integer.toString(parameters.getAftDme2RoundtripTimeoutMs()));
         props.setProperty("AFT_DME2_EP_READ_TIMEOUT_MS", Integer.toString(parameters.getAftDme2ReadTimeoutMs()));
-
         props.setProperty("AFT_DME2_SSL_ENABLE", Boolean.toString(parameters.isAftDme2SslEnable()));
         props.setProperty("AFT_DME2_CLIENT_IGNORE_SSL_CONFIG", Boolean.toString(parameters.isAftDme2ClientIgnoreSslConfig()));
         props.setProperty("AFT_DME2_CLIENT_KEYSTORE", parameters.getAftDme2ClientKeystore());
         props.setProperty("AFT_DME2_CLIENT_KEYSTORE_PASSWORD", parameters.getAftDme2ClientKeystorePassword());
         props.setProperty("AFT_DME2_CLIENT_SSL_CERT_ALIAS", parameters.getAftDme2ClientSslCertAlias());
-
-        
         String dme2PreferredRouterFilePath = parameters.getDme2preferredRouterFilePath();
         ensureFileExists(dme2PreferredRouterFilePath);
         props.setProperty("DME2preferredRouterFilePath", dme2PreferredRouterFilePath);
-        
         props.setProperty("TransportType", "DME2");
         props.setProperty("SubContextPath", "/");
         props.setProperty("MethodType", "GET");
@@ -116,15 +113,14 @@ public class DmaapClientFactory {
         props.setProperty("AFT_DME2_EXCHANGE_REQUEST_HANDLERS", "");
         props.setProperty("AFT_DME2_EXCHANGE_REPLY_HANDLERS", "");
         props.setProperty("sessionstickinessrequired", "no");
-
         return props;
     }
 
-    private Properties buildProducerProperties(DmaapProducerConfiguration parameters) throws GeneralSecurityException, IOException { 
+    private Properties buildProducerProperties(DmaapProducerConfiguration parameters) throws GeneralSecurityException, IOException {
         logger.info("The DmaapProducerConfiguration is {} ", parameters);
         Properties props = new Properties();
-        Either<String,String> passkey = SecurityUtil.INSTANCE.decrypt(parameters.getCredential().getPassword() );
-        if (passkey.isRight()){
+        Either<String, String> passkey = SecurityUtil.INSTANCE.decrypt(parameters.getCredential().getPassword());
+        if (passkey.isRight()) {
             throw new GeneralSecurityException("invalid password, cannot build properties");
         }
         props.setProperty("Latitude", Double.toString(parameters.getLatitude()));
@@ -136,7 +132,7 @@ public class DmaapClientFactory {
         props.setProperty("routeOffer", parameters.getRouteOffer());
         props.setProperty("Protocol", parameters.getProtocol());
         props.setProperty("username", parameters.getCredential().getUsername());
-        props.setProperty("password", passkey.left().value() );
+        props.setProperty("password", passkey.left().value());
         props.setProperty("contenttype", parameters.getContenttype());
         props.setProperty("host", parameters.getHosts());
         props.setProperty("topic", parameters.getTopic());
@@ -147,13 +143,11 @@ public class DmaapClientFactory {
         props.setProperty("AFT_DME2_EP_CONN_TIMEOUT", Integer.toString(parameters.getAftDme2ConnectionTimeoutMs()));
         props.setProperty("AFT_DME2_ROUNDTRIP_TIMEOUT_MS", Integer.toString(parameters.getAftDme2RoundtripTimeoutMs()));
         props.setProperty("AFT_DME2_EP_READ_TIMEOUT_MS", Integer.toString(parameters.getAftDme2ReadTimeoutMs()));
-        
         props.setProperty("AFT_DME2_SSL_ENABLE", Boolean.toString(parameters.isAftDme2SslEnable()));
         props.setProperty("AFT_DME2_CLIENT_IGNORE_SSL_CONFIG", Boolean.toString(parameters.isAftDme2ClientIgnoreSslConfig()));
         props.setProperty("AFT_DME2_CLIENT_KEYSTORE", parameters.getAftDme2ClientKeystore());
         props.setProperty("AFT_DME2_CLIENT_KEYSTORE_PASSWORD", parameters.getAftDme2ClientKeystorePassword());
         props.setProperty("AFT_DME2_CLIENT_SSL_CERT_ALIAS", parameters.getAftDme2ClientSslCertAlias());
-
         String dme2PreferredRouterFilePath = parameters.getDme2preferredRouterFilePath();
         ensureFileExists(dme2PreferredRouterFilePath);
         props.setProperty("DME2preferredRouterFilePath", dme2PreferredRouterFilePath);
@@ -165,22 +159,19 @@ public class DmaapClientFactory {
         props.setProperty("AFT_DME2_EXCHANGE_REQUEST_HANDLERS", "");
         props.setProperty("AFT_DME2_EXCHANGE_REPLY_HANDLERS", "");
         props.setProperty("sessionstickinessrequired", "no");
-
-        props.setProperty("maxBatchSize","1");
-        props.setProperty("maxAgeMs","250");
-        props.setProperty("partition","1");
-        props.setProperty("MessageSentThreadOccurance","10");
-        props.setProperty("Authorization","Basic bTEzMzMxQGNjZC5hdHQuY29tOkFhMTIzNDU2");
-
+        props.setProperty("maxBatchSize", "1");
+        props.setProperty("maxAgeMs", "250");
+        props.setProperty("partition", "1");
+        props.setProperty("MessageSentThreadOccurance", "10");
+        props.setProperty("Authorization", "Basic bTEzMzMxQGNjZC5hdHQuY29tOkFhMTIzNDU2");
         return props;
     }
 
     private void ensureFileExists(String filePath) throws IOException {
         File file = new File(filePath);
-        if(file.createNewFile()) {
+        if (file.createNewFile()) {
             logger.info("The file {} has been created on the disk", file.getAbsolutePath());
-        }
-        else{
+        } else {
             logger.info("The file {} already exists", file.getAbsolutePath());
         }
     }
index 681b302..81fa3dd 100644 (file)
@@ -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.
  * limitations under the License.
  * ============LICENSE_END=========================================================
  */
-
 package org.openecomp.sdc.be.components.distribution.engine;
 
 import com.att.nsa.mr.client.MRConsumer;
+import java.lang.Thread.UncaughtExceptionHandler;
+import java.util.concurrent.ExecutorService;
+import java.util.concurrent.ScheduledExecutorService;
+import java.util.concurrent.TimeUnit;
+import java.util.function.Consumer;
 import org.openecomp.sdc.be.config.ConfigurationManager;
 import org.openecomp.sdc.be.config.DmaapConsumerConfiguration;
 import org.openecomp.sdc.common.log.elements.LogFieldsMdcHandler;
@@ -28,33 +32,28 @@ import org.openecomp.sdc.common.log.wrappers.Logger;
 import org.springframework.beans.factory.annotation.Autowired;
 import org.springframework.stereotype.Service;
 
-import java.lang.Thread.UncaughtExceptionHandler;
-import java.util.concurrent.ExecutorService;
-import java.util.concurrent.ScheduledExecutorService;
-import java.util.concurrent.TimeUnit;
-import java.util.function.Consumer;
-
 /**
- * Allows consuming DMAAP topic according to received consumer parameters
- * Allows processing received messages.
+ * Allows consuming DMAAP topic according to received consumer parameters Allows processing received messages.
  */
 @Service
 public class DmaapConsumer {
+
     private static final String LOG_PARTNER_NAME = "SDC.BE";
     private static final Logger logger = Logger.getLogger(DmaapClientFactory.class.getName());
+    private static LogFieldsMdcHandler mdcFieldsHandler = new LogFieldsMdcHandler();
     private final ExecutorFactory executorFactory;
     private final DmaapClientFactory dmaapClientFactory;
     private final DmaapHealth dmaapHealth;
-    private static LogFieldsMdcHandler mdcFieldsHandler = new LogFieldsMdcHandler();
+
     /**
      * Allows to create an object of type DmaapConsumer
+     *
      * @param executorFactory
      * @param dmaapClientFactory
      * @param dmaapHealth
      */
     @Autowired
-    public DmaapConsumer(ExecutorFactory executorFactory, DmaapClientFactory dmaapClientFactory,
-        DmaapHealth dmaapHealth) {
+    public DmaapConsumer(ExecutorFactory executorFactory, DmaapClientFactory dmaapClientFactory, DmaapHealth dmaapHealth) {
         this.executorFactory = executorFactory;
         this.dmaapClientFactory = dmaapClientFactory;
         this.dmaapHealth = dmaapHealth;
@@ -62,26 +61,26 @@ public class DmaapConsumer {
 
     /**
      * Allows consuming DMAAP topic according to received consumer parameters
+     *
      * @param notificationReceived
      * @param exceptionHandler
      * @throws Exception
      */
     public void consumeDmaapTopic(Consumer<String> notificationReceived, UncaughtExceptionHandler exceptionHandler) throws Exception {
-
-        DmaapConsumerConfiguration dmaapConsumerParams = ConfigurationManager.getConfigurationManager().getConfiguration().getDmaapConsumerConfiguration();
+        DmaapConsumerConfiguration dmaapConsumerParams = ConfigurationManager.getConfigurationManager().getConfiguration()
+            .getDmaapConsumerConfiguration();
         String topic = dmaapConsumerParams.getTopic();
         logger.info("Starting to consume topic {} for DMAAP consumer with the next parameters {}. ", topic, dmaapConsumerParams);
         MRConsumer consumer = dmaapClientFactory.create(dmaapConsumerParams);
         ScheduledExecutorService pollExecutor = executorFactory.createScheduled(topic + "Client");
         ExecutorService notificationExecutor = executorFactory.create(topic + "Consumer", exceptionHandler);
-
         pollExecutor.scheduleWithFixedDelay(() -> {
             logger.info("Trying to fetch messages from topic: {}", topic);
             boolean isTopicAvailable = false;
             mdcFieldsHandler.addInfoForErrorAndDebugLogging(LOG_PARTNER_NAME);
             try {
                 Iterable<String> messages = consumer.fetch();
-                isTopicAvailable = true ;
+                isTopicAvailable = true;
                 if (messages != null) {
                     for (String msg : messages) {
                         logger.info("The DMAAP message {} received. The topic is {}.", msg, topic);
@@ -89,12 +88,10 @@ public class DmaapConsumer {
                     }
                 }
                 //successfully fetched
-            }
-            catch (Exception e) {
+            } catch (Exception e) {
                 logger.error("The exception occurred upon fetching DMAAP message", e);
             }
-            dmaapHealth.report( isTopicAvailable );
+            dmaapHealth.report(isTopicAvailable);
         }, 0L, dmaapConsumerParams.getPollingInterval(), TimeUnit.SECONDS);
     }
-
 }
index 0515b08..96ac070 100644 (file)
@@ -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.
  * limitations under the License.
  * ============LICENSE_END=========================================================
  */
-
 package org.openecomp.sdc.be.components.distribution.engine;
 
-import org.apache.commons.validator.routines.UrlValidator;
-import org.apache.http.client.utils.URIUtils;
-import org.openecomp.sdc.be.config.BeEcompErrorManager;
-import org.openecomp.sdc.be.config.ConfigurationManager;
-import org.openecomp.sdc.be.config.DmaapConsumerConfiguration;
-import org.openecomp.sdc.common.api.HealthCheckInfo;
-import org.openecomp.sdc.common.log.wrappers.Logger;
-import org.springframework.stereotype.Component;
+import static org.apache.commons.lang3.StringUtils.countMatches;
+import static org.apache.commons.lang3.StringUtils.isNotBlank;
+import static org.openecomp.sdc.common.api.Constants.HC_COMPONENT_DMAAP_ENGINE;
 
-import javax.annotation.PostConstruct;
-import javax.annotation.PreDestroy;
 import java.io.IOException;
 import java.net.InetAddress;
 import java.net.URI;
@@ -40,76 +32,78 @@ import java.util.concurrent.ScheduledExecutorService;
 import java.util.concurrent.ScheduledFuture;
 import java.util.concurrent.TimeUnit;
 import java.util.concurrent.atomic.AtomicBoolean;
-
-import static org.apache.commons.lang3.StringUtils.countMatches;
-import static org.apache.commons.lang3.StringUtils.isNotBlank;
-import static org.openecomp.sdc.common.api.Constants.HC_COMPONENT_DMAAP_ENGINE;
+import javax.annotation.PostConstruct;
+import javax.annotation.PreDestroy;
+import org.apache.commons.validator.routines.UrlValidator;
+import org.apache.http.client.utils.URIUtils;
+import org.openecomp.sdc.be.config.BeEcompErrorManager;
+import org.openecomp.sdc.be.config.ConfigurationManager;
+import org.openecomp.sdc.be.config.DmaapConsumerConfiguration;
+import org.openecomp.sdc.common.api.HealthCheckInfo;
+import org.openecomp.sdc.common.log.wrappers.Logger;
+import org.springframework.stereotype.Component;
 
 @Component("dmaapHealth")
 public class DmaapHealth {
 
-
     private static final String DMAAP_HEALTH_LOG_CONTEXT = "dmaap.healthcheck";
     private static final String DMAAP_HEALTH_CHECK_STR = "dmaapHealthCheck";
     private static final Logger log = Logger.getLogger(DmaapHealth.class.getName());
     private static final Logger logHealth = Logger.getLogger(DMAAP_HEALTH_LOG_CONTEXT);
+    private final ScheduledExecutorService scheduler = Executors.newScheduledThreadPool(1);
     private HealthCheckInfo healthCheckInfo = DmaapHealth.HealthCheckInfoResult.UNAVAILABLE.getHealthCheckInfo();
     private long healthCheckReadTimeout = 20;
     private long reconnectInterval = 5;
-    private HealthCheckScheduledTask healthCheckScheduledTask = null ;
-    private final ScheduledExecutorService scheduler = Executors.newScheduledThreadPool(1);
+    private HealthCheckScheduledTask healthCheckScheduledTask = null;
     private ScheduledFuture<?> scheduledFuture = null;
-    private DmaapConsumerConfiguration configuration = null ;
-
+    private DmaapConsumerConfiguration configuration = null;
     private volatile AtomicBoolean lastHealthState = new AtomicBoolean(false);
     private volatile AtomicBoolean reportedHealthState = null;
 
-    public enum HealthCheckInfoResult {
-        OK(new HealthCheckInfo(HC_COMPONENT_DMAAP_ENGINE, HealthCheckInfo.HealthCheckStatus.UP, null, DmaapStatusDescription.OK.getDescription())),
-        UNAVAILABLE(new HealthCheckInfo(HC_COMPONENT_DMAAP_ENGINE, HealthCheckInfo.HealthCheckStatus.DOWN, null, DmaapStatusDescription.UNAVAILABLE.getDescription())),
-        DOWN(new HealthCheckInfo(HC_COMPONENT_DMAAP_ENGINE, HealthCheckInfo.HealthCheckStatus.DOWN, null, DmaapStatusDescription.DOWN.getDescription()));
-
-        private HealthCheckInfo healthCheckInfo;
-        HealthCheckInfoResult(HealthCheckInfo healthCheckInfo) {
-            this.healthCheckInfo = healthCheckInfo;
-        }
-        public HealthCheckInfo getHealthCheckInfo() {
-            return healthCheckInfo;
+    public static String getUrlHost(String qualifiedHost) throws URISyntaxException {
+        //region - parse complex format ex. <http://URL:PORT>
+        try {
+            UrlValidator validator = new UrlValidator();
+            if (validator.isValid(qualifiedHost)) {
+                return URIUtils.extractHost(new URI(qualifiedHost)).getHostName();
+            } else {
+                log.debug("{} - invalid url format, continuing ", DMAAP_HEALTH_CHECK_STR);
+            }
+        } catch (URISyntaxException e) {
+            log.debug("{} - invalid url format, continuing {} ", DMAAP_HEALTH_CHECK_STR, e);
         }
-    }
-
-    public enum DmaapStatusDescription {
-        OK("OK"), UNAVAILABLE("Dmaap is not available"),DOWN("DOWN"), NOT_CONFIGURED("Dmaap configuration is missing/wrong ");
+        //endregion
 
-        private String desc;
-        DmaapStatusDescription(String desc) {
-            this.desc = desc;
-        }
-        public String getDescription() {
-            return desc;
+        //region - try shortcut format <URL> or <URL:PORT>
+        if (countMatches(qualifiedHost, ":") <= 1) {
+            String[] address = qualifiedHost.split(":");
+            if (address.length > 0 && isNotBlank(address[0])) {
+                return address[0];
+            }
         }
-
+        //endregion
+        throw new URISyntaxException(qualifiedHost,
+            "invalid hostname, expecting a single <host:port> ,  (valid ex. www.google.com:80 | www.google.com | http:\\\\www.google.com:8181)");
     }
 
     @PostConstruct
     public DmaapHealth init() {
-        if(!ConfigurationManager.getConfigurationManager().getConfiguration().getDmaapConsumerConfiguration().isActive()){
+        if (!ConfigurationManager.getConfigurationManager().getConfiguration().getDmaapConsumerConfiguration().isActive()) {
             log.debug("Dmaap health check task disabled");
             return this;
         }
         log.trace("Enter init method of Dmaap health");
-        synchronized (DmaapHealth.class){
+        synchronized (DmaapHealth.class) {
             this.configuration = ConfigurationManager.getConfigurationManager().getConfiguration().getDmaapConsumerConfiguration();
-
             Integer pollingInterval = configuration.getPollingInterval();
-            if (pollingInterval != null && pollingInterval!=0) {
+            if (pollingInterval != null && pollingInterval != 0) {
                 reconnectInterval = pollingInterval;
             }
             Integer healthCheckReadTimeoutConfig = configuration.getTimeoutMs();
             if (healthCheckReadTimeoutConfig != null) {
                 this.healthCheckReadTimeout = healthCheckReadTimeoutConfig;
             }
-            this.healthCheckScheduledTask = new HealthCheckScheduledTask( configuration ); //what is the representation? csv? delimiter? json or other
+            this.healthCheckScheduledTask = new HealthCheckScheduledTask(configuration); //what is the representation? csv? delimiter? json or other
             startHealthCheckTask(true);
         }
         log.trace("Exit init method of DistributionEngineClusterHealth");
@@ -133,110 +127,122 @@ public class DmaapHealth {
      * @param startTask
      */
     private void startHealthCheckTask(boolean startTask) {
-        synchronized (DmaapHealth.class){
+        synchronized (DmaapHealth.class) {
             if (startTask && this.scheduledFuture == null) {
-                this.scheduledFuture = this.scheduler.scheduleAtFixedRate(this.healthCheckScheduledTask , 0, reconnectInterval, TimeUnit.SECONDS);
+                this.scheduledFuture = this.scheduler.scheduleAtFixedRate(this.healthCheckScheduledTask, 0, reconnectInterval, TimeUnit.SECONDS);
             }
         }
     }
 
-    void report(Boolean isUp){
-        if (reportedHealthState == null)
+    void report(Boolean isUp) {
+        if (reportedHealthState == null) {
             reportedHealthState = new AtomicBoolean(isUp);
+        }
         reportedHealthState.set(isUp);
     }
 
-
     public HealthCheckInfo getHealthCheckInfo() {
         return healthCheckInfo;
     }
 
+    public enum HealthCheckInfoResult {
+        // @formatter:off
+        OK(new HealthCheckInfo(HC_COMPONENT_DMAAP_ENGINE, HealthCheckInfo.HealthCheckStatus.UP, null, DmaapStatusDescription.OK.getDescription())),
+        UNAVAILABLE(new HealthCheckInfo(HC_COMPONENT_DMAAP_ENGINE, HealthCheckInfo.HealthCheckStatus.DOWN, null, DmaapStatusDescription.UNAVAILABLE.getDescription())),
+        DOWN(new HealthCheckInfo(HC_COMPONENT_DMAAP_ENGINE, HealthCheckInfo.HealthCheckStatus.DOWN, null, DmaapStatusDescription.DOWN.getDescription()));
+        // @formatter:on
+
+        private HealthCheckInfo healthCheckInfo;
+
+        HealthCheckInfoResult(HealthCheckInfo healthCheckInfo) {
+            this.healthCheckInfo = healthCheckInfo;
+        }
+
+        public HealthCheckInfo getHealthCheckInfo() {
+            return healthCheckInfo;
+        }
+    }
+
+    public enum DmaapStatusDescription {
+        // @formatter:off
+        OK("OK"),
+        UNAVAILABLE("Dmaap is not available"),
+        DOWN("DOWN"),
+        NOT_CONFIGURED("Dmaap configuration is missing/wrong ");
+        // @formatter:on
+
+        private String desc;
+
+        DmaapStatusDescription(String desc) {
+            this.desc = desc;
+        }
+
+        public String getDescription() {
+            return desc;
+        }
+
+    }
+
     /**
      * Health Check Task Scheduler - infinite check.
      */
     public class HealthCheckScheduledTask implements Runnable {
-        private final DmaapConsumerConfiguration config;
+
         private static final int TIMEOUT = 8192;
+        private final DmaapConsumerConfiguration config;
 
-        HealthCheckScheduledTask(final DmaapConsumerConfiguration config){
+        HealthCheckScheduledTask(final DmaapConsumerConfiguration config) {
             this.config = config;
         }
+
         @Override
         public void run() {
             logHealth.trace("Executing Dmaap Health Check Task - Start");
             boolean prevIsReachable;
             boolean reachable;
             //first try simple ping
-            try{
-                if ( reportedHealthState != null ){
+            try {
+                if (reportedHealthState != null) {
                     reachable = reportedHealthState.get();
+                } else {
+                    reachable = false;
                 }
-                else{
-                    reachable =  false;
-                }
-                prevIsReachable = lastHealthState.getAndSet( reachable );
+                prevIsReachable = lastHealthState.getAndSet(reachable);
                 healthCheckInfo = reachable ? HealthCheckInfoResult.OK.healthCheckInfo : HealthCheckInfoResult.DOWN.healthCheckInfo;
-            }
-            catch( Exception e ){
-                log.debug("{} - cannot check connectivity -> {}",DMAAP_HEALTH_CHECK_STR, e );
+            } catch (Exception e) {
+                log.debug("{} - cannot check connectivity -> {}", DMAAP_HEALTH_CHECK_STR, e);
                 prevIsReachable = lastHealthState.getAndSet(false);
                 healthCheckInfo = HealthCheckInfoResult.UNAVAILABLE.healthCheckInfo;
             }
-            if (prevIsReachable != lastHealthState.get())
-                logAlarm( lastHealthState.get() );
+            if (prevIsReachable != lastHealthState.get()) {
+                logAlarm(lastHealthState.get());
+            }
         }
 
-
         /**
          * @deprecated (health is reported outside from EnvironmentEngine consumer fetch)
          */
         @Deprecated
-        public boolean isICMPReachable( ) throws IOException{
-            try{
+        public boolean isICMPReachable() throws IOException {
+            try {
                 String hostname = getUrlHost(config.getHosts());
-                return InetAddress.getByName( hostname ).isReachable(TIMEOUT);
-            }catch( URISyntaxException e ){
-                log.debug("{} - malformed host configuration -> ",DMAAP_HEALTH_CHECK_STR , e);
+                return InetAddress.getByName(hostname).isReachable(TIMEOUT);
+            } catch (URISyntaxException e) {
+                log.debug("{} - malformed host configuration -> ", DMAAP_HEALTH_CHECK_STR, e);
             }
             return false;
         }
 
         private void logAlarm(boolean lastHealthState) {
-            try{
-                if ( lastHealthState ) {
-                    BeEcompErrorManager.getInstance().logDmaapHealthCheckRecovery( DMAAP_HEALTH_CHECK_STR );
+            try {
+                if (lastHealthState) {
+                    BeEcompErrorManager.getInstance().logDmaapHealthCheckRecovery(DMAAP_HEALTH_CHECK_STR);
                 } else {
-                    BeEcompErrorManager.getInstance().logDmaapHealthCheckError( DMAAP_HEALTH_CHECK_STR );
+                    BeEcompErrorManager.getInstance().logDmaapHealthCheckError(DMAAP_HEALTH_CHECK_STR);
                 }
-            }catch( Exception e ){
-                log.debug("cannot logAlarm -> {}" ,e );
-            }
-        }
-
-    }
-
-    public static String getUrlHost(String qualifiedHost) throws URISyntaxException{
-        //region - parse complex format ex. <http://URL:PORT>
-        try{
-            UrlValidator validator = new UrlValidator();
-            if (validator.isValid(qualifiedHost)){
-                return URIUtils.extractHost(new URI(qualifiedHost)).getHostName();
-            }else{
-                log.debug("{} - invalid url format, continuing ", DMAAP_HEALTH_CHECK_STR );
+            } catch (Exception e) {
+                log.debug("cannot logAlarm -> {}", e);
             }
-        }catch(URISyntaxException e){
-            log.debug("{} - invalid url format, continuing {} ", DMAAP_HEALTH_CHECK_STR , e);
         }
-        //endregion
-
-        //region - try shortcut format <URL> or <URL:PORT>
-        if ( countMatches( qualifiedHost , ":") <= 1){
-            String[] address = qualifiedHost.split(":");
-            if ( address.length>0 && isNotBlank(address[0]) ){
-                return address[0];
-            }
-        }
-        //endregion
-        throw new URISyntaxException( qualifiedHost , "invalid hostname, expecting a single <host:port> ,  (valid ex. www.google.com:80 | www.google.com | http:\\\\www.google.com:8181)");
     }
 }
index 208fb84..b4934f7 100644 (file)
@@ -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.
@@ -17,7 +17,6 @@
  * limitations under the License.
  * ============LICENSE_END=========================================================
  */
-
 package org.openecomp.sdc.be.components.distribution.engine;
 
 /**
@@ -62,6 +61,4 @@ public class DmaapNotificationDataImpl implements IDmaapNotificationData, IDmaap
     public String getTenantContext() {
         return tenantContext;
     }
-
-
 }
index 5bb579e..e68a486 100644 (file)
@@ -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.
  * limitations under the License.
  * ============LICENSE_END=========================================================
  */
-
 package org.openecomp.sdc.be.components.distribution.engine;
 
-import org.openecomp.sdc.be.resources.data.OperationalEnvironmentEntry;
-
 import java.util.ArrayList;
 import java.util.List;
+import org.openecomp.sdc.be.resources.data.OperationalEnvironmentEntry;
 
 /**
  * a pojo which holds all the necessary data to communicate with the message bus
@@ -32,13 +30,9 @@ import java.util.List;
 public class EnvironmentMessageBusData {
 
     private List<String> dmaaPuebEndpoints;
-
     private String uebPublicKey;
-
     private String uebPrivateKey;
-
     private String envId;
-
     private String tenant;
 
     public EnvironmentMessageBusData() {
@@ -91,5 +85,4 @@ public class EnvironmentMessageBusData {
     public void setEnvId(String envId) {
         this.envId = envId;
     }
-
 }
index 97d2440..315ba1d 100644 (file)
@@ -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.
  * limitations under the License.
  * ============LICENSE_END=========================================================
  */
-
 package org.openecomp.sdc.be.components.distribution.engine;
 
+import static org.apache.commons.lang3.StringUtils.isEmpty;
+import static org.glassfish.jersey.internal.guava.Predicates.not;
+import static org.openecomp.sdc.common.datastructure.FunctionalInterfaces.runMethodWithTimeOut;
+
 import com.att.aft.dme2.api.DME2Exception;
 import com.att.aft.dme2.iterator.DME2EndpointIterator;
 import com.att.aft.dme2.iterator.domain.DME2EndpointReference;
@@ -29,6 +32,18 @@ import com.google.common.annotations.VisibleForTesting;
 import com.google.gson.Gson;
 import com.google.gson.GsonBuilder;
 import fj.data.Either;
+import java.util.Date;
+import java.util.HashMap;
+import java.util.HashSet;
+import java.util.LinkedList;
+import java.util.List;
+import java.util.Map;
+import java.util.Set;
+import java.util.concurrent.atomic.AtomicBoolean;
+import java.util.function.Function;
+import java.util.function.Supplier;
+import java.util.stream.Collectors;
+import javax.annotation.PostConstruct;
 import org.apache.commons.lang3.StringUtils;
 import org.apache.http.HttpStatus;
 import org.openecomp.sdc.be.components.distribution.engine.IDmaapNotificationData.DmaapActionEnum;
@@ -52,23 +67,6 @@ import org.openecomp.sdc.common.log.elements.LogFieldsMdcHandler;
 import org.openecomp.sdc.common.log.wrappers.Logger;
 import org.springframework.stereotype.Service;
 
-import javax.annotation.PostConstruct;
-import java.util.Date;
-import java.util.HashMap;
-import java.util.HashSet;
-import java.util.LinkedList;
-import java.util.List;
-import java.util.Map;
-import java.util.Set;
-import java.util.concurrent.atomic.AtomicBoolean;
-import java.util.function.Function;
-import java.util.function.Supplier;
-import java.util.stream.Collectors;
-
-import static org.apache.commons.lang3.StringUtils.isEmpty;
-import static org.glassfish.jersey.internal.guava.Predicates.not;
-import static org.openecomp.sdc.common.datastructure.FunctionalInterfaces.runMethodWithTimeOut;
-
 /**
  * Allows to consume DMAAP topic and handle received notifications
  */
@@ -79,13 +77,7 @@ public class EnvironmentsEngine implements INotificationHandler {
     private static final String UNKNOWN = "Unknown";
     private static final Logger log = Logger.getLogger(EnvironmentsEngine.class.getName());
     private static final String LOG_PARTNER_NAME = "SDC.BE";
-    private ConfigurationManager configurationManager = ConfigurationManager.getConfigurationManager();
-
-    private Map<String, OperationalEnvironmentEntry> environments = new HashMap<>();
-    private Map<String, AtomicBoolean> envNamePerStatus = new HashMap<>();
-    private Map<String, DistributionEnginePollingTask> envNamePerPollingTask = new HashMap<>();
-    private Map<String, DistributionEngineInitTask> envNamePerInitTask = new HashMap<>();
-
+    private static LogFieldsMdcHandler mdcFieldsHandler = new LogFieldsMdcHandler();
     private final DmaapConsumer dmaapConsumer;
     private final OperationalEnvironmentDao operationalEnvironmentDao;
     private final DME2EndpointIteratorCreator epIterCreator;
@@ -94,9 +86,16 @@ public class EnvironmentsEngine implements INotificationHandler {
     private final CambriaHandler cambriaHandler;
     private final DistributionEngineClusterHealth distributionEngineClusterHealth;
     private final DistributionCompleteReporter distributionCompleteReporter;
-    private static LogFieldsMdcHandler mdcFieldsHandler = new LogFieldsMdcHandler();
+    private ConfigurationManager configurationManager = ConfigurationManager.getConfigurationManager();
+    private Map<String, OperationalEnvironmentEntry> environments = new HashMap<>();
+    private Map<String, AtomicBoolean> envNamePerStatus = new HashMap<>();
+    private Map<String, DistributionEnginePollingTask> envNamePerPollingTask = new HashMap<>();
+    private Map<String, DistributionEngineInitTask> envNamePerInitTask = new HashMap<>();
 
-    public EnvironmentsEngine(DmaapConsumer dmaapConsumer, OperationalEnvironmentDao operationalEnvironmentDao, DME2EndpointIteratorCreator epIterCreator, AaiRequestHandler aaiRequestHandler, ComponentsUtils componentUtils, CambriaHandler cambriaHandler, DistributionEngineClusterHealth distributionEngineClusterHealth, DistributionCompleteReporter distributionCompleteReporter) {
+    public EnvironmentsEngine(DmaapConsumer dmaapConsumer, OperationalEnvironmentDao operationalEnvironmentDao,
+                              DME2EndpointIteratorCreator epIterCreator, AaiRequestHandler aaiRequestHandler, ComponentsUtils componentUtils,
+                              CambriaHandler cambriaHandler, DistributionEngineClusterHealth distributionEngineClusterHealth,
+                              DistributionCompleteReporter distributionCompleteReporter) {
         this.dmaapConsumer = dmaapConsumer;
         this.operationalEnvironmentDao = operationalEnvironmentDao;
         this.epIterCreator = epIterCreator;
@@ -115,12 +114,12 @@ public class EnvironmentsEngine implements INotificationHandler {
             environments = populateEnvironments();
             createUebTopicsForEnvironments();
             initDmeGlobalConfig();
-            if(!configurationManager.getConfiguration().getDmaapConsumerConfiguration().isActive()){
+            if (!configurationManager.getConfiguration().getDmaapConsumerConfiguration().isActive()) {
                 log.info("Environments engine is disabled");
                 return;
             }
-            dmaapConsumer.consumeDmaapTopic(this::handleMessage,
-                (t, e) -> log.error("An error occurred upon consuming topic by Dmaap consumer client: ", e));
+            dmaapConsumer
+                .consumeDmaapTopic(this::handleMessage, (t, e) -> log.error("An error occurred upon consuming topic by Dmaap consumer client: ", e));
             log.info("Environments engine has been initialized.");
         } catch (Exception e) {
             log.error("An error occurred upon consuming topic by Dmaap consumer client.", e);
@@ -128,28 +127,31 @@ public class EnvironmentsEngine implements INotificationHandler {
     }
 
     private void initDmeGlobalConfig() {
-        DmaapConsumerConfiguration dmaapConsumerParams = ConfigurationManager.getConfigurationManager().getConfiguration().getDmaapConsumerConfiguration();
+        DmaapConsumerConfiguration dmaapConsumerParams = ConfigurationManager.getConfigurationManager().getConfiguration()
+            .getDmaapConsumerConfiguration();
         if (dmaapConsumerParams == null) {
             log.warn("cannot read dmaap configuration file,DME might not be initialized properly");
             return;
         }
         System.setProperty("AFT_ENVIRONMENT", dmaapConsumerParams.getAftEnvironment()); // AFTPRD for production
-        System.setProperty("AFT_LATITUDE", dmaapConsumerParams.getLatitude() != null ? dmaapConsumerParams.getLatitude().toString() : "1.0"); // Replace with actual latitude
-        System.setProperty("AFT_LONGITUDE", dmaapConsumerParams.getLongitude() != null ? dmaapConsumerParams.getLongitude().toString() : "1.0"); // Replace with actual longitude
+
+        System.setProperty("AFT_LATITUDE",
+            dmaapConsumerParams.getLatitude() != null ? dmaapConsumerParams.getLatitude().toString() : "1.0"); // Replace with actual latitude
+
+        System.setProperty("AFT_LONGITUDE",
+            dmaapConsumerParams.getLongitude() != null ? dmaapConsumerParams.getLongitude().toString() : "1.0"); // Replace with actual longitude
     }
 
-    public void connectUebTopicTenantIsolation(OperationalEnvironmentEntry opEnvEntry,
-                                               AtomicBoolean status,
-                                               Map<String, DistributionEngineInitTask> envNamePerInitTask, Map<String, DistributionEnginePollingTask> envNamePerPollingTask) {
+    public void connectUebTopicTenantIsolation(OperationalEnvironmentEntry opEnvEntry, AtomicBoolean status,
+                                               Map<String, DistributionEngineInitTask> envNamePerInitTask,
+                                               Map<String, DistributionEnginePollingTask> envNamePerPollingTask) {
         connectUebTopic(opEnvEntry, status, envNamePerInitTask, envNamePerPollingTask);
-
     }
 
-    public void connectUebTopicForDistributionConfTopic(String envName,
-                                                        AtomicBoolean status,
-                                                        Map<String, DistributionEngineInitTask> envNamePerInitTask, Map<String, DistributionEnginePollingTask> envNamePerPollingTask) {
+    public void connectUebTopicForDistributionConfTopic(String envName, AtomicBoolean status,
+                                                        Map<String, DistributionEngineInitTask> envNamePerInitTask,
+                                                        Map<String, DistributionEnginePollingTask> envNamePerPollingTask) {
         connectUebTopic(environments.get(envName), status, envNamePerInitTask, envNamePerPollingTask);
-
     }
 
     /**
@@ -163,33 +165,26 @@ public class EnvironmentsEngine implements INotificationHandler {
     private void connectUebTopic(OperationalEnvironmentEntry opEnvEntry, AtomicBoolean status,
                                  Map<String, DistributionEngineInitTask> envNamePerInitTask,
                                  Map<String, DistributionEnginePollingTask> envNamePerPollingTask) {
-
         String envId = opEnvEntry.getEnvironmentId();
-
         DistributionEngineConfiguration distributionEngineConfiguration = ConfigurationManager.getConfigurationManager()
-                .getDistributionEngineConfiguration();
-        DistributionEnginePollingTask distributionEnginePollingTask = new DistributionEnginePollingTask(
-                distributionEngineConfiguration, distributionCompleteReporter, componentUtils, distributionEngineClusterHealth,
-                opEnvEntry);
+            .getDistributionEngineConfiguration();
+        DistributionEnginePollingTask distributionEnginePollingTask = new DistributionEnginePollingTask(distributionEngineConfiguration,
+            distributionCompleteReporter, componentUtils, distributionEngineClusterHealth, opEnvEntry);
         String envName = configurationManager.getDistributionEngineConfiguration().getEnvironments().get(0);
-        DistributionEngineInitTask distributionEngineInitTask = new DistributionEngineInitTask(0l,
-                distributionEngineConfiguration, envName, status, componentUtils, distributionEnginePollingTask,
-                opEnvEntry);
+        DistributionEngineInitTask distributionEngineInitTask = new DistributionEngineInitTask(0l, distributionEngineConfiguration, envName, status,
+            componentUtils, distributionEnginePollingTask, opEnvEntry);
         distributionEngineInitTask.startTask();
         envNamePerInitTask.put(envId, distributionEngineInitTask);
         envNamePerPollingTask.put(envId, distributionEnginePollingTask);
-
         log.debug("Environment envId = {} has been connected to the UEB topic", envId);
     }
 
     @Override
     public boolean handleMessage(String notification) {
-        DmaapConsumerConfiguration dmaapConsumerParams = ConfigurationManager.getConfigurationManager()
-                .getConfiguration().getDmaapConsumerConfiguration();
+        DmaapConsumerConfiguration dmaapConsumerParams = ConfigurationManager.getConfigurationManager().getConfiguration()
+            .getDmaapConsumerConfiguration();
         Supplier<Boolean> supplier = () -> handleMessageLogic(notification);
-        Either<Boolean, Boolean> eitherTimeOut = runMethodWithTimeOut(supplier,
-                dmaapConsumerParams.getTimeLimitForNotificationHandleMs());
-
+        Either<Boolean, Boolean> eitherTimeOut = runMethodWithTimeOut(supplier, dmaapConsumerParams.getTimeLimitForNotificationHandleMs());
         boolean result;
         if (eitherTimeOut.isRight()) {
             result = false;
@@ -203,15 +198,10 @@ public class EnvironmentsEngine implements INotificationHandler {
         Wrapper<Boolean> errorWrapper = new Wrapper<>();
         Wrapper<OperationalEnvironmentEntry> opEnvEntryWrapper = new Wrapper<>();
         try {
-
             log.debug("handle message - for operational environment notification received: {}", notification);
             Gson gsonObj = new GsonBuilder().create();
-
-            IDmaapNotificationData notificationData = gsonObj.fromJson(notification,
-                    DmaapNotificationDataImpl.class);
-            IDmaapAuditNotificationData auditNotificationData = gsonObj.fromJson(notification,
-                    DmaapNotificationDataImpl.class);
-
+            IDmaapNotificationData notificationData = gsonObj.fromJson(notification, DmaapNotificationDataImpl.class);
+            IDmaapAuditNotificationData auditNotificationData = gsonObj.fromJson(notification, DmaapNotificationDataImpl.class);
             AuditingActionEnum actionEnum;
             switch (notificationData.getAction()) {
                 case CREATE:
@@ -227,11 +217,9 @@ public class EnvironmentsEngine implements INotificationHandler {
                     actionEnum = AuditingActionEnum.UNKNOWN_ENVIRONMENT_NOTIFICATION;
                     break;
             }
-            componentUtils.auditEnvironmentEngine(actionEnum,
-                    notificationData.getOperationalEnvironmentId(), notificationData.getOperationalEnvironmentType().getEventTypenName(),
-                    notificationData.getAction().getActionName(), auditNotificationData.getOperationalEnvironmentName(),
-                    auditNotificationData.getTenantContext());
-
+            componentUtils.auditEnvironmentEngine(actionEnum, notificationData.getOperationalEnvironmentId(),
+                notificationData.getOperationalEnvironmentType().getEventTypenName(), notificationData.getAction().getActionName(),
+                auditNotificationData.getOperationalEnvironmentName(), auditNotificationData.getTenantContext());
             if (errorWrapper.isEmpty()) {
                 validateNotification(errorWrapper, notificationData, auditNotificationData);
             }
@@ -239,16 +227,12 @@ public class EnvironmentsEngine implements INotificationHandler {
             if (errorWrapper.isEmpty()) {
                 saveEntryWithInProgressStatus(errorWrapper, opEnvEntryWrapper, notificationData);
             }
-
             if (errorWrapper.isEmpty()) {
                 buildOpEnv(errorWrapper, opEnvEntryWrapper.getInnerElement());
             }
-
         } catch (Exception e) {
-            log.debug("handle message for operational environment failed for notification: {} with error :{}",
-                    notification, e.getMessage(), e);
+            log.debug("handle message for operational environment failed for notification: {} with error :{}", notification, e.getMessage(), e);
             errorWrapper.setInnerElement(false);
-
         }
         return errorWrapper.isEmpty();
     }
@@ -274,28 +258,23 @@ public class EnvironmentsEngine implements INotificationHandler {
         if (errorWrapper.isEmpty()) {
             retrieveOpEnvInfoFromAAI(errorWrapper, opEnvEntry);
         }
-
         if (errorWrapper.isEmpty()) {
             // Get List Of UEB Addresses From AFT_DME
             retrieveUebAddressesFromAftDme(errorWrapper, opEnvEntry);
         }
-
         // Create UEB keys and set them on EnvEntry
         if (errorWrapper.isEmpty()) {
             createUebKeys(errorWrapper, opEnvEntry);
         }
-
         // Create Topics
         if (errorWrapper.isEmpty()) {
             log.debug("handle message - Create Topics");
             createUebTopicsForEnvironment(opEnvEntry);
         }
-
         // Save Status Complete and Add to Map
         if (errorWrapper.isEmpty()) {
             saveEntryWithCompleteStatus(errorWrapper, opEnvEntry);
         }
-
         // Update Environments Map
         if (errorWrapper.isEmpty()) {
             environments.put(opEnvEntry.getEnvironmentId(), opEnvEntry);
@@ -314,24 +293,24 @@ public class EnvironmentsEngine implements INotificationHandler {
         log.debug("handle message - save OperationalEnvironment Complete Dao");
         opEnvEntry.setStatus(EnvironmentStatusEnum.COMPLETED);
         saveOpEnvEntry(errorWrapper, opEnvEntry);
-
     }
 
     void retrieveUebAddressesFromAftDme(Wrapper<Boolean> errorWrapper, OperationalEnvironmentEntry opEnvEntry) {
         log.debug("handle message - Get List Of UEB Addresses From AFT_DME");
-        log.invoke(opEnvEntry.getEnvironmentId(), "retrieveUebAddressesFromAftDme", opEnvEntry.getStatus(), EnvironmentsEngine.class.getName(), errorWrapper.toString() );
+        log.invoke(opEnvEntry.getEnvironmentId(), "retrieveUebAddressesFromAftDme", opEnvEntry.getStatus(), EnvironmentsEngine.class.getName(),
+            errorWrapper.toString());
         try {
             boolean isKeyFieldsValid = !isEmpty(opEnvEntry.getTenant()) && !isEmpty(opEnvEntry.getEcompWorkloadContext());
             if (isKeyFieldsValid) {
                 String opEnvKey = map2OpEnvKey(opEnvEntry);
                 List<String> uebHosts = discoverUebHosts(opEnvKey);
                 opEnvEntry.setDmaapUebAddress(uebHosts.stream().collect(Collectors.toSet()));
-                log.invokeReturn(opEnvEntry.getEnvironmentId(), "retrieveUebAddressesFromAftDme", opEnvEntry.getStatus(), "SDC-BE", errorWrapper.toString() );
+                log.invokeReturn(opEnvEntry.getEnvironmentId(), "retrieveUebAddressesFromAftDme", opEnvEntry.getStatus(), "SDC-BE",
+                    errorWrapper.toString());
             } else {
                 errorWrapper.setInnerElement(false);
                 log.debug("Can Not Build AFT DME Key from workLoad & Tenant Fields.");
             }
-
         } catch (Exception e) {
             errorWrapper.setInnerElement(false);
             log.error("Failed to retrieve Ueb Addresses From DME. ", e);
@@ -340,10 +319,8 @@ public class EnvironmentsEngine implements INotificationHandler {
 
     void createUebKeys(Wrapper<Boolean> errorWrapper, OperationalEnvironmentEntry opEnvEntry) {
         log.debug("handle message - Create UEB keys");
-        List<String> discoverEndPoints = opEnvEntry.getDmaapUebAddress().stream()
-                .collect(Collectors.toList());
-        Either<ApiCredential, CambriaErrorResponse> eitherCreateUebKeys = cambriaHandler
-                .createUebKeys(discoverEndPoints);
+        List<String> discoverEndPoints = opEnvEntry.getDmaapUebAddress().stream().collect(Collectors.toList());
+        Either<ApiCredential, CambriaErrorResponse> eitherCreateUebKeys = cambriaHandler.createUebKeys(discoverEndPoints);
         if (eitherCreateUebKeys.isRight()) {
             errorWrapper.setInnerElement(false);
             log.debug("handle message - failed to create UEB Keys");
@@ -356,8 +333,7 @@ public class EnvironmentsEngine implements INotificationHandler {
 
     void retrieveOpEnvInfoFromAAI(Wrapper<Boolean> errorWrapper, OperationalEnvironmentEntry opEnvEntry) {
         log.debug("handle message - Get Env Info From A&AI");
-        Either<OperationalEnvInfo, Integer> eitherOperationalEnvInfo = getOperationalEnvById(
-                opEnvEntry.getEnvironmentId());
+        Either<OperationalEnvInfo, Integer> eitherOperationalEnvInfo = getOperationalEnvById(opEnvEntry.getEnvironmentId());
         if (eitherOperationalEnvInfo.isRight()) {
             errorWrapper.setInnerElement(false);
             log.debug("handle message - failed to retrieve details from A&AI");
@@ -368,7 +344,8 @@ public class EnvironmentsEngine implements INotificationHandler {
         }
     }
 
-    void saveEntryWithInProgressStatus(Wrapper<Boolean> errorWrapper, Wrapper<OperationalEnvironmentEntry> opEnvEntryWrapper, IDmaapNotificationData notificationData) {
+    void saveEntryWithInProgressStatus(Wrapper<Boolean> errorWrapper, Wrapper<OperationalEnvironmentEntry> opEnvEntryWrapper,
+                                       IDmaapNotificationData notificationData) {
         log.debug("handle message - save OperationalEnvironment In-Progress Dao");
         OperationalEnvironmentEntry opEnvEntry = new OperationalEnvironmentEntry();
         // Entry Environment ID holds actually the environment NAME
@@ -377,16 +354,12 @@ public class EnvironmentsEngine implements INotificationHandler {
         opEnvEntry.setIsProduction(false);
         saveOpEnvEntry(errorWrapper, opEnvEntry);
         opEnvEntryWrapper.setInnerElement(opEnvEntry);
-
     }
 
-
     void validateState(Wrapper<Boolean> errorWrapper, IDmaapNotificationData notificationData) {
         log.debug("handle message - verify OperationalEnvironment not In-Progress");
         String opEnvId = notificationData.getOperationalEnvironmentId();
-
-        Either<OperationalEnvironmentEntry, CassandraOperationStatus> eitherOpEnv = operationalEnvironmentDao
-                .get(opEnvId);
+        Either<OperationalEnvironmentEntry, CassandraOperationStatus> eitherOpEnv = operationalEnvironmentDao.get(opEnvId);
         if (eitherOpEnv.isLeft()) {
             final OperationalEnvironmentEntry opEnvEntry = eitherOpEnv.left().value();
             if (StringUtils.equals(opEnvEntry.getStatus(), EnvironmentStatusEnum.IN_PROGRESS.getName())) {
@@ -397,11 +370,9 @@ public class EnvironmentsEngine implements INotificationHandler {
             CassandraOperationStatus operationStatus = eitherOpEnv.right().value();
             if (operationStatus != CassandraOperationStatus.NOT_FOUND) {
                 errorWrapper.setInnerElement(false);
-                log.debug("failed to retrieve operationa environment with id:{} cassandra error was :{}", opEnvId,
-                        operationStatus);
+                log.debug("failed to retrieve operationa environment with id:{} cassandra error was :{}", opEnvId, operationStatus);
             }
         }
-
     }
 
     void validateActionType(Wrapper<Boolean> errorWrapper, IDmaapNotificationData notificationData) {
@@ -420,21 +391,18 @@ public class EnvironmentsEngine implements INotificationHandler {
         if (envType != OperationaEnvironmentTypeEnum.ECOMP) {
             errorWrapper.setInnerElement(false);
             log.debug("handle message - validate Environment Type Failed With Environment Type: {} Flow Stopped!", envType);
-            componentUtils.auditEnvironmentEngine(AuditingActionEnum.UNSUPPORTED_ENVIRONMENT_TYPE,
-                    notificationData.getOperationalEnvironmentId(), notificationData.getOperationalEnvironmentType().getEventTypenName(),
-                    notificationData.getAction().getActionName(), auditNotificationData.getOperationalEnvironmentName(),
-                    auditNotificationData.getTenantContext());
+            componentUtils.auditEnvironmentEngine(AuditingActionEnum.UNSUPPORTED_ENVIRONMENT_TYPE, notificationData.getOperationalEnvironmentId(),
+                notificationData.getOperationalEnvironmentType().getEventTypenName(), notificationData.getAction().getActionName(),
+                auditNotificationData.getOperationalEnvironmentName(), auditNotificationData.getTenantContext());
         }
     }
 
-
     private void saveOpEnvEntry(Wrapper<Boolean> errorWrapper, OperationalEnvironmentEntry entry) {
         entry.setLastModified(new Date(System.currentTimeMillis()));
         CassandraOperationStatus saveStaus = operationalEnvironmentDao.save(entry);
         if (saveStaus != CassandraOperationStatus.OK) {
             errorWrapper.setInnerElement(false);
-            log.debug("handle message saving  operational environmet failed for id :{} with error : {}",
-                    entry.getEnvironmentId(), saveStaus);
+            log.debug("handle message saving  operational environmet failed for id :{} with error : {}", entry.getEnvironmentId(), saveStaus);
         }
     }
 
@@ -443,7 +411,6 @@ public class EnvironmentsEngine implements INotificationHandler {
         String environment = configurationManager.getConfiguration().getDmaapConsumerConfiguration().getEnvironment();
         String lookupURI = String.format(lookupUriFormat, opEnvKey, environment);
         log.debug("DME2 GRM URI: {}", lookupURI);
-
         List<String> uebHosts = new LinkedList<>();
         DME2EndpointIterator iterator = epIterCreator.create(lookupURI);
         // Beginning iteration
@@ -453,7 +420,6 @@ public class EnvironmentsEngine implements INotificationHandler {
             log.debug("DME returns EP with UEB host {}, UEB port: {}", dmeEndpoint.getHost(), dmeEndpoint.getPort());
             uebHosts.add(dmeEndpoint.getHost());
         }
-
         return uebHosts;
     }
 
@@ -470,34 +436,28 @@ public class EnvironmentsEngine implements INotificationHandler {
 
     private OperationalEnvironmentEntry readEnvFromConfig() {
         OperationalEnvironmentEntry entry = new OperationalEnvironmentEntry();
-        DistributionEngineConfiguration distributionEngineConfiguration = configurationManager
-                .getDistributionEngineConfiguration();
+        DistributionEngineConfiguration distributionEngineConfiguration = configurationManager.getDistributionEngineConfiguration();
         entry.setUebApikey(distributionEngineConfiguration.getUebPublicKey());
         entry.setUebSecretKey(distributionEngineConfiguration.getUebSecretKey());
-
         Set<String> puebEndpoints = new HashSet<>();
         puebEndpoints.addAll(distributionEngineConfiguration.getUebServers());
         entry.setDmaapUebAddress(puebEndpoints);
-
-        String envName = distributionEngineConfiguration.getEnvironments().size() == 1
-                ? distributionEngineConfiguration.getEnvironments().get(0) : UNKNOWN;
+        String envName =
+            distributionEngineConfiguration.getEnvironments().size() == 1 ? distributionEngineConfiguration.getEnvironments().get(0) : UNKNOWN;
         entry.setEnvironmentId(envName);
         entry.setIsProduction(true);
-
         if (log.isDebugEnabled()) {
             log.debug("Enviroment read from configuration: {}", entry);
         }
-
         return entry;
     }
 
     private Map<String, OperationalEnvironmentEntry> getEnvironmentsFromDb() {
         Either<List<OperationalEnvironmentEntry>, CassandraOperationStatus> opEnvResult = operationalEnvironmentDao
-                .getByEnvironmentsStatus(EnvironmentStatusEnum.COMPLETED);
-
+            .getByEnvironmentsStatus(EnvironmentStatusEnum.COMPLETED);
         if (opEnvResult.isLeft()) {
             Map<String, OperationalEnvironmentEntry> resultMap = opEnvResult.left().value().stream()
-                    .collect(Collectors.toMap(OperationalEnvironmentEntry::getEnvironmentId, Function.identity()));
+                .collect(Collectors.toMap(OperationalEnvironmentEntry::getEnvironmentId, Function.identity()));
             resultMap.forEach((key, value) -> log.debug("Enviroment loaded from DB: {}", value));
             return resultMap;
         } else {
@@ -508,9 +468,7 @@ public class EnvironmentsEngine implements INotificationHandler {
     }
 
     void createUebTopicsForEnvironments() {
-        environments.values().stream()
-                .filter(not(OperationalEnvironmentEntry::getIsProduction))
-                .forEach(this::createUebTopicsForEnvironment);
+        environments.values().stream().filter(not(OperationalEnvironmentEntry::getIsProduction)).forEach(this::createUebTopicsForEnvironment);
     }
 
     public void createUebTopicsForEnvironment(OperationalEnvironmentEntry opEnvEntry) {
@@ -518,7 +476,6 @@ public class EnvironmentsEngine implements INotificationHandler {
         log.debug("Create Environment {} on UEB Topic.", envId);
         AtomicBoolean status = new AtomicBoolean(false);
         envNamePerStatus.put(envId, status);
-
         connectUebTopicTenantIsolation(opEnvEntry, status, envNamePerInitTask, envNamePerPollingTask);
     }
 
@@ -532,21 +489,16 @@ public class EnvironmentsEngine implements INotificationHandler {
     }
 
     public OperationalEnvironmentEntry getEnvironmentByDmaapUebAddress(List<String> dmaapUebAddress) {
-        return environments.values().stream()
-                .filter(e -> e.getDmaapUebAddress().stream()
-                    .filter(dmaapUebAddress::contains).findAny().isPresent())
-                .findFirst()
-                .orElseThrow(() -> new ByActionStatusComponentException(ActionStatus.DISTRIBUTION_ENV_DOES_NOT_EXIST,dmaapUebAddress.toString()));
+        return environments.values().stream().filter(e -> e.getDmaapUebAddress().stream().filter(dmaapUebAddress::contains).findAny().isPresent())
+            .findFirst()
+            .orElseThrow(() -> new ByActionStatusComponentException(ActionStatus.DISTRIBUTION_ENV_DOES_NOT_EXIST, dmaapUebAddress.toString()));
     }
 
-
-
     public Either<OperationalEnvInfo, Integer> getOperationalEnvById(String id) {
         HttpResponse<String> resp = aaiRequestHandler.getOperationalEnvById(id);
         if (resp.getStatusCode() == HttpStatus.SC_OK) {
             try {
                 OperationalEnvInfo operationalEnvInfo = OperationalEnvInfo.createFromJson(resp.getResponse());
-
                 log.debug("Get \"{}\" operational environment. {}", id, operationalEnvInfo);
                 return Either.left(operationalEnvInfo);
             } catch (Exception e) {
@@ -554,8 +506,8 @@ public class EnvironmentsEngine implements INotificationHandler {
                 return Either.right(HttpStatus.SC_INTERNAL_SERVER_ERROR);
             }
         } else {
-            log.debug("Get \"{}\" operational environment failed with statusCode: {}, description: {}", id,
-                    resp.getStatusCode(), resp.getDescription());
+            log.debug("Get \"{}\" operational environment failed with statusCode: {}, description: {}", id, resp.getStatusCode(),
+                resp.getDescription());
             return Either.right(resp.getStatusCode());
         }
     }
@@ -574,6 +526,5 @@ public class EnvironmentsEngine implements INotificationHandler {
 
     public void addToMap(OperationalEnvironmentEntry opEnvEntry) {
         environments.put(opEnvEntry.getEnvironmentId(), opEnvEntry);
-
     }
 }
index d0c1edc..ee718f1 100644 (file)
@@ -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.
  * limitations under the License.
  * ============LICENSE_END=========================================================
  */
-
 package org.openecomp.sdc.be.components.distribution.engine;
 
 import com.google.common.util.concurrent.ThreadFactoryBuilder;
-import org.openecomp.sdc.common.log.wrappers.Logger;
-import org.slf4j.LoggerFactory;
-import org.springframework.stereotype.Component;
-
 import java.lang.Thread.UncaughtExceptionHandler;
 import java.util.concurrent.ExecutorService;
 import java.util.concurrent.Executors;
 import java.util.concurrent.ScheduledExecutorService;
 import java.util.concurrent.ThreadFactory;
+import org.openecomp.sdc.common.log.wrappers.Logger;
+import org.slf4j.LoggerFactory;
+import org.springframework.stereotype.Component;
+
 @Component("executorFactory")
 /**
  * Allows to create next kinds of single thread executors: SingleThreadExecutor and SingleThreadScheduledExecutor
@@ -38,26 +37,22 @@ public class ExecutorFactory {
 
     private static final Logger logger = Logger.getLogger(EnvironmentsEngine.class.getName());
 
-    public ExecutorService create(String name, UncaughtExceptionHandler exceptionHandler){
+    public ExecutorService create(String name, UncaughtExceptionHandler exceptionHandler) {
         logger.info("Going to create single thread executor. ");
         ThreadFactory threadFactory = createThreadFactory(name, exceptionHandler);
         return Executors.newSingleThreadExecutor(threadFactory);
     }
 
-    public ScheduledExecutorService createScheduled(String name){
+    public ScheduledExecutorService createScheduled(String name) {
         logger.info("Going to create single thread scheduled executor. ");
         ThreadFactory threadFactory = createThreadFactory(name,
-                (t, e) -> LoggerFactory.getLogger(UncaughtExceptionHandler.class).error("An error occurred: ", e));
+            (t, e) -> LoggerFactory.getLogger(UncaughtExceptionHandler.class).error("An error occurred: ", e));
         return Executors.newSingleThreadScheduledExecutor(threadFactory);
     }
 
     private ThreadFactory createThreadFactory(String name, UncaughtExceptionHandler exceptionHandler) {
         String nameFormat = name + "-%d";
-        return new ThreadFactoryBuilder()
-                .setThreadFactory(Executors.defaultThreadFactory())
-                .setNameFormat(nameFormat)
-                .setUncaughtExceptionHandler(exceptionHandler)
-                .setDaemon(true)
-                .build();
+        return new ThreadFactoryBuilder().setThreadFactory(Executors.defaultThreadFactory()).setNameFormat(nameFormat)
+            .setUncaughtExceptionHandler(exceptionHandler).setDaemon(true).build();
     }
 }
index b4919df..ba51ba6 100644 (file)
@@ -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.
  * limitations under the License.
  * ============LICENSE_END=========================================================
  */
-
 package org.openecomp.sdc.be.components.distribution.engine;
 
 public interface IArtifactInfo {
 
-    /** Artifact File name */
+    /**
+     * Artifact File name
+     */
     String getArtifactName();
 
     /**
@@ -33,12 +34,9 @@ public interface IArtifactInfo {
     String getArtifactType();
 
     /**
-     * Relative artifact's URL. Should be used in REST GET API to download the artifact's payload.<br>
-     * The full artifact URL will be in the following format :<br>
-     * https://{serverBaseURL}/{resourcePath}<br>
-     * serverBaseURL - Hostname ( ASDC LB FQDN) + optional port <br>
-     * resourcePath - "artifactURL" <br>
-     * Ex : https://asdc.sdc.com/v1/catalog/services/srv1/2.0/resources/aaa/1.0/artifacts/aaa.yml
+     * Relative artifact's URL. Should be used in REST GET API to download the artifact's payload.<br> The full artifact URL will be in the following
+     * format :<br> https://{serverBaseURL}/{resourcePath}<br> serverBaseURL - Hostname ( ASDC LB FQDN) + optional port <br> resourcePath -
+     * "artifactURL" <br> Ex : https://asdc.sdc.com/v1/catalog/services/srv1/2.0/resources/aaa/1.0/artifacts/aaa.yml
      */
     String getArtifactURL();
 
@@ -57,5 +55,4 @@ public interface IArtifactInfo {
      * Artifact description
      */
     String getArtifactDescription();
-
 }
index 60ab20d..b887e7f 100644 (file)
  * limitations under the License.
  * ============LICENSE_END=========================================================
  */
-
 package org.openecomp.sdc.be.components.distribution.engine;
 
 import com.att.nsa.apiClient.credentials.ApiCredential;
 import com.att.nsa.cambria.client.CambriaConsumer;
 import fj.data.Either;
-
 import java.util.Collection;
 import java.util.List;
 import java.util.Set;
@@ -31,15 +29,28 @@ import java.util.Set;
 public interface ICambriaHandler {
 
     Either<Set<String>, CambriaErrorResponse> getTopics(List<String> hostSet);
-    CambriaErrorResponse createTopic(Collection<String> hostSet, String apiKey, String secretKey, String topicName, int partitionCount, int replicationCount);
-    CambriaErrorResponse unRegisterFromTopic(Collection<String> hostSet, String managerApiKey, String managerSecretKey, String subscriberApiKey, SubscriberTypeEnum subscriberTypeEnum, String topicName);
-    CambriaErrorResponse registerToTopic(Collection<String> hostSet, String managerApiKey, String managerSecretKey, String subscriberApiKey, SubscriberTypeEnum subscriberTypeEnum, String topicName);
-    CambriaConsumer createConsumer(Collection<String> hostSet, String topicName, String apiKey, String secretKey, String consumerId, String consumerGroup, int timeoutMS) throws Exception;
+
+    CambriaErrorResponse createTopic(Collection<String> hostSet, String apiKey, String secretKey, String topicName, int partitionCount,
+                                     int replicationCount);
+
+    CambriaErrorResponse unRegisterFromTopic(Collection<String> hostSet, String managerApiKey, String managerSecretKey, String subscriberApiKey,
+                                             SubscriberTypeEnum subscriberTypeEnum, String topicName);
+
+    CambriaErrorResponse registerToTopic(Collection<String> hostSet, String managerApiKey, String managerSecretKey, String subscriberApiKey,
+                                         SubscriberTypeEnum subscriberTypeEnum, String topicName);
+
+    CambriaConsumer createConsumer(Collection<String> hostSet, String topicName, String apiKey, String secretKey, String consumerId,
+                                   String consumerGroup, int timeoutMS) throws Exception;
+
     Either<Iterable<String>, CambriaErrorResponse> fetchFromTopic(CambriaConsumer topicConsumer);
-    CambriaErrorResponse sendNotification(String topicName, String uebPublicKey, String uebSecretKey, List<String> uebServers, INotificationData data);
-    CambriaErrorResponse sendNotificationAndClose(String topicName, String uebPublicKey, String uebSecretKey, List<String> uebServers, INotificationData data, long waitBeforeCloseTimeout);
-    CambriaErrorResponse getApiKey(String server, String apiKey);
-    Either<ApiCredential, CambriaErrorResponse> createUebKeys(List<String> hostSet);
 
+    CambriaErrorResponse sendNotification(String topicName, String uebPublicKey, String uebSecretKey, List<String> uebServers,
+                                          INotificationData data);
+
+    CambriaErrorResponse sendNotificationAndClose(String topicName, String uebPublicKey, String uebSecretKey, List<String> uebServers,
+                                                  INotificationData data, long waitBeforeCloseTimeout);
 
+    CambriaErrorResponse getApiKey(String server, String apiKey);
+
+    Either<ApiCredential, CambriaErrorResponse> createUebKeys(List<String> hostSet);
 }
index 2136463..f08043c 100644 (file)
@@ -17,7 +17,6 @@
  * limitations under the License.
  * ============LICENSE_END=========================================================
  */
-
 package org.openecomp.sdc.be.components.distribution.engine;
 
 import java.util.List;
index 23bccac..f41055c 100644 (file)
@@ -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.
  * limitations under the License.
  * ============LICENSE_END=========================================================
  */
-
 package org.openecomp.sdc.be.components.distribution.engine;
 
 public interface IDmaapAuditNotificationData {
+
     String getOperationalEnvironmentName();
+
     String getTenantContext();
 }
index ee90867..bc0ffbb 100644 (file)
@@ -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.
  * limitations under the License.
  * ============LICENSE_END=========================================================
  */
-
 package org.openecomp.sdc.be.components.distribution.engine;
 
 import static org.openecomp.sdc.common.datastructure.FunctionalInterfaces.getEnumValueByFieldValue;
 
 public interface IDmaapNotificationData {
+
     String getOperationalEnvironmentId();
 
     OperationaEnvironmentTypeEnum getOperationalEnvironmentType();
@@ -30,12 +30,13 @@ public interface IDmaapNotificationData {
     DmaapActionEnum getAction();
 
     enum DmaapActionEnum {
+        // @formatter:off
         DELETE("Delete"),
         CREATE("Create"),
         UPDATE("Update"),
-        UNKONW("UNKONW")
+        UNKONW("UNKONW");
+        // @formatter:on
 
-        ;
         private String actionName;
 
         private DmaapActionEnum(String actionName) {
@@ -46,15 +47,17 @@ public interface IDmaapNotificationData {
             return actionName;
         }
 
-        public static DmaapActionEnum findByName(String actionName){
+        public static DmaapActionEnum findByName(String actionName) {
             return getEnumValueByFieldValue(actionName, DmaapActionEnum.values(), DmaapActionEnum::getActionName, UNKONW, false);
         }
     }
 
     enum OperationaEnvironmentTypeEnum {
+        // @formatter:off
         ECOMP("ECOMP"),
-        UNKONW("UNKONW")
-        ;
+        UNKONW("UNKONW");
+        // @formatter:on
+
         private String eventTypenName;
 
         private OperationaEnvironmentTypeEnum(String eventTypenName) {
@@ -65,8 +68,9 @@ public interface IDmaapNotificationData {
             return eventTypenName;
         }
 
-        public static OperationaEnvironmentTypeEnum findByName(String operationalEnvironmentTypeName){
-            return getEnumValueByFieldValue(operationalEnvironmentTypeName, OperationaEnvironmentTypeEnum.values(), OperationaEnvironmentTypeEnum::getEventTypenName, UNKONW, false);
+        public static OperationaEnvironmentTypeEnum findByName(String operationalEnvironmentTypeName) {
+            return getEnumValueByFieldValue(operationalEnvironmentTypeName, OperationaEnvironmentTypeEnum.values(),
+                OperationaEnvironmentTypeEnum::getEventTypenName, UNKONW, false);
         }
     }
 }
index d66f8f9..a1f2299 100644 (file)
@@ -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.
  * limitations under the License.
  * ============LICENSE_END=========================================================
  */
-
 package org.openecomp.sdc.be.components.distribution.engine;
 
 import java.util.List;
 
 public interface INotificationData {
+
     /**
      * Global Distribution Identifier: UUID generated by ASDC per each distribution activation.<br>
      * Generated UUID is compliant with RFC 4122.<br>
@@ -31,76 +31,81 @@ public interface INotificationData {
      */
     String getDistributionID();
 
-    /** Logical Service Name. */
-    String getServiceName();
+    void setDistributionID(String distributionId);
 
     /**
-     * Service Version.<br>
-     * Two dot (".") separated digit blocks.<br>
-     * Ex. : "2.0"
+     * Logical Service Name.
      */
-    String getServiceVersion();
+    String getServiceName();
 
     /**
-     * Global UUID generated by ASDC per each service version. Generated UUID is compliant with RFC 4122.<br>
-     * It is a 128-bit value formatted into blocks of hexadecimal digits separated by a hyphen ("-").<br>
-     * Ex. : AA97B177-9383-4934-8543-0F91A7A02836
+     * Logical Service Name.
      */
-    String getServiceUUID();
+    void setServiceName(String serviceName);
 
     /**
-     * Service description
+     * Service Version.<br> Two dot (".") separated digit blocks.<br> Ex. : "2.0"
      */
-    String getServiceDescription();
+    String getServiceVersion();
 
     /**
-     * ServiceInvariant UUID
+     * Service Version.<br> Two dot (".") separated digit blocks.<br> Ex. : "2.0"
      */
-    String getServiceInvariantUUID();
-
-    /** List of the resource instances */
-    List<JsonContainerResourceInstance> getResources();
-
-    /** List of the artifacts */
-    List<ArtifactInfoImpl> getServiceArtifacts();
-
-    String getWorkloadContext();
-
-    void setDistributionID(String distributionId);
-
-    /** Logical Service Name. */
-    void setServiceName(String serviceName);
+    void setServiceVersion(String serviceVersion);
 
     /**
-     * Service Version.<br>
-     * Two dot (".") separated digit blocks.<br>
-     * Ex. : "2.0"
+     * Global UUID generated by ASDC per each service version. Generated UUID is compliant with RFC 4122.<br> It is a 128-bit value formatted into
+     * blocks of hexadecimal digits separated by a hyphen ("-").<br> Ex. : AA97B177-9383-4934-8543-0F91A7A02836
      */
-    void setServiceVersion(String serviceVersion);
+    String getServiceUUID();
 
     /**
-     * Global UUID generated by ASDC per each service version. Generated UUID is compliant with RFC 4122.<br>
-     * It is a 128-bit value formatted into blocks of hexadecimal digits separated by a hyphen ("-").<br>
-     * Ex. : AA97B177-9383-4934-8543-0F91A7A02836
+     * Global UUID generated by ASDC per each service version. Generated UUID is compliant with RFC 4122.<br> It is a 128-bit value formatted into
+     * blocks of hexadecimal digits separated by a hyphen ("-").<br> Ex. : AA97B177-9383-4934-8543-0F91A7A02836
      */
     void setServiceUUID(String serviceUUID);
 
+    /**
+     * Service description
+     */
+    String getServiceDescription();
+
     /**
      * Service Description
      */
     void setServiceDescription(String serviceDescription);
 
+    /**
+     * ServiceInvariant UUID
+     */
+    String getServiceInvariantUUID();
+
     /**
      * ServiceInvariant UUID
      */
     void setServiceInvariantUUID(String serviceInvariantUuid);
 
-    /** List of the Resource Instances */
+    /**
+     * List of the resource instances
+     */
+    List<JsonContainerResourceInstance> getResources();
+
+    /**
+     * List of the Resource Instances
+     */
     void setResources(List<JsonContainerResourceInstance> resource);
 
-    /** List of the Resource Instances */
+    /**
+     * List of the artifacts
+     */
+    List<ArtifactInfoImpl> getServiceArtifacts();
+
+    /**
+     * List of the Resource Instances
+     */
     void setServiceArtifacts(List<ArtifactInfoImpl> artifacts);
 
-    void setWorkloadContext(String workloadContext);
+    String getWorkloadContext();
 
+    void setWorkloadContext(String workloadContext);
 }
index 49f4084..46a6d25 100644 (file)
@@ -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.
  * limitations under the License.
  * ============LICENSE_END=========================================================
  */
-
 package org.openecomp.sdc.be.components.distribution.engine;
 
 public interface INotificationHandler {
+
     /**
      * Allows to handle received topic message
+     *
      * @param notification
      * @return true if finished successfully otherwise false
      */
     public boolean handleMessage(String notification);
-
 }
index deac875..d731b74 100644 (file)
@@ -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.
  * limitations under the License.
  * ============LICENSE_END=========================================================
  */
-
 package org.openecomp.sdc.be.components.distribution.engine;
 
 public interface IResourceArtifactInfo extends IArtifactInfo {
 
-    /** resource name */
+    /**
+     * resource name
+     */
     String getResourceName();
 
-    /** resource version */
+    /**
+     * resource version
+     */
     String getResourceVersion();
 
     /**
@@ -35,5 +38,4 @@ public interface IResourceArtifactInfo extends IArtifactInfo {
      * Ex.: AA97B177-9383-4934-8543-0F91A7A02836
      */
     String getResourceUUID();
-
 }
index e102f74..910cff7 100644 (file)
@@ -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.
@@ -17,7 +17,6 @@
  * limitations under the License.
  * ============LICENSE_END=========================================================
  */
-
 package org.openecomp.sdc.be.components.distribution.engine;
 
 public interface IServiceArtifactInfo extends IArtifactInfo {
index 9c478e7..c4b51ff 100644 (file)
@@ -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.
  * limitations under the License.
  * ============LICENSE_END=========================================================
  */
-
 package org.openecomp.sdc.be.components.distribution.engine;
 
-import org.openecomp.sdc.be.model.ComponentInstance;
-
 import java.util.List;
+import org.openecomp.sdc.be.model.ComponentInstance;
 
 public class JsonContainerResourceInstance {
+
     private String resourceInstanceName;
     private String resourceName;
     private String resourceVersion;
@@ -46,14 +45,15 @@ public class JsonContainerResourceInstance {
         this.artifacts = artifacts;
         this.resourceCustomizationUUID = resourceInstance.getCustomizationUUID();
     }
-    
+
     public JsonContainerResourceInstance(ComponentInstance resourceInstance, List<ArtifactInfoImpl> artifacts) {
         super();
         this.resourceInstanceName = resourceInstance.getName();
         this.resourceName = resourceInstance.getComponentName();
         this.resourceVersion = resourceInstance.getComponentVersion();
-        if(resourceInstance.getOriginType() != null)
+        if (resourceInstance.getOriginType() != null) {
             this.resoucreType = resourceInstance.getOriginType().getValue();
+        }
         this.resourceUUID = resourceInstance.getComponentUid();
         this.artifacts = artifacts;
         this.resourceCustomizationUUID = resourceInstance.getCustomizationUUID();
@@ -141,8 +141,9 @@ public class JsonContainerResourceInstance {
 
     @Override
     public String toString() {
-        return "JsonContainerResourceInstance [resourceInstanceName=" + resourceInstanceName + ", resourceName=" + resourceName + ", resourceVersion=" + resourceVersion + ", resoucreType=" + resoucreType + ", resourceUUID=" + resourceUUID
-                + ", resourceInvariantUUID=" + resourceInvariantUUID + ", resourceCustomizationUUID=" + resourceCustomizationUUID + ", category=" + category + ", subcategory=" + subcategory + ", artifacts=" + artifacts + "]";
+        return "JsonContainerResourceInstance [resourceInstanceName=" + resourceInstanceName + ", resourceName=" + resourceName + ", resourceVersion="
+            + resourceVersion + ", resoucreType=" + resoucreType + ", resourceUUID=" + resourceUUID + ", resourceInvariantUUID="
+            + resourceInvariantUUID + ", resourceCustomizationUUID=" + resourceCustomizationUUID + ", category=" + category + ", subcategory="
+            + subcategory + ", artifacts=" + artifacts + "]";
     }
-
 }
index 1db67a9..21738b1 100644 (file)
@@ -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.
@@ -17,7 +17,6 @@
  * limitations under the License.
  * ============LICENSE_END=========================================================
  */
-
 package org.openecomp.sdc.be.components.distribution.engine;
 
 import java.util.List;
@@ -39,33 +38,33 @@ public class NotificationDataImpl implements INotificationData {
         return distributionID;
     }
 
+    public void setDistributionID(String distributionID) {
+        this.distributionID = distributionID;
+    }
+
     @Override
     public String getServiceName() {
         return serviceName;
     }
 
+    public void setServiceName(String serviceName) {
+        this.serviceName = serviceName;
+    }
+
     @Override
     public String getServiceVersion() {
         return serviceVersion;
     }
 
+    public void setServiceVersion(String serviceVersion) {
+        this.serviceVersion = serviceVersion;
+    }
+
     @Override
     public String getServiceUUID() {
         return serviceUUID;
     }
 
-    public void setDistributionID(String distributionID) {
-        this.distributionID = distributionID;
-    }
-
-    public void setServiceName(String serviceName) {
-        this.serviceName = serviceName;
-    }
-
-    public void setServiceVersion(String serviceVersion) {
-        this.serviceVersion = serviceVersion;
-    }
-
     public void setServiceUUID(String serviceUUID) {
         this.serviceUUID = serviceUUID;
     }
@@ -77,25 +76,23 @@ public class NotificationDataImpl implements INotificationData {
     public void setServiceDescription(String serviceDescription) {
         this.serviceDescription = serviceDescription;
     }
+
     @Override
-    public String getWorkloadContext() { return workloadContext; }
+    public String getWorkloadContext() {
+        return workloadContext;
+    }
 
     @Override
-    public void setWorkloadContext(String workloadContext) { this.workloadContext = workloadContext;    }
+    public void setWorkloadContext(String workloadContext) {
+        this.workloadContext = workloadContext;
+    }
 
     @Override
     public String toString() {
-        return "NotificationDataImpl{" +
-                "distributionID='" + distributionID + '\'' +
-                ", serviceName='" + serviceName + '\'' +
-                ", serviceVersion='" + serviceVersion + '\'' +
-                ", serviceUUID='" + serviceUUID + '\'' +
-                ", serviceDescription='" + serviceDescription + '\'' +
-                ", serviceInvariantUUID='" + serviceInvariantUUID + '\'' +
-                ", resources=" + resources +
-                ", serviceArtifacts=" + serviceArtifacts +
-                ", workloadContext='" + workloadContext + '\'' +
-                '}';
+        return "NotificationDataImpl{" + "distributionID='" + distributionID + '\'' + ", serviceName='" + serviceName + '\'' + ", serviceVersion='"
+            + serviceVersion + '\'' + ", serviceUUID='" + serviceUUID + '\'' + ", serviceDescription='" + serviceDescription + '\''
+            + ", serviceInvariantUUID='" + serviceInvariantUUID + '\'' + ", resources=" + resources + ", serviceArtifacts=" + serviceArtifacts
+            + ", workloadContext='" + workloadContext + '\'' + '}';
     }
 
     @Override
@@ -106,7 +103,6 @@ public class NotificationDataImpl implements INotificationData {
     @Override
     public void setResources(List<JsonContainerResourceInstance> resources) {
         this.resources = resources;
-
     }
 
     @Override
@@ -118,7 +114,6 @@ public class NotificationDataImpl implements INotificationData {
     @Override
     public void setServiceArtifacts(List<ArtifactInfoImpl> serviceArtifacts) {
         this.serviceArtifacts = serviceArtifacts;
-
     }
 
     @Override
@@ -130,5 +125,4 @@ public class NotificationDataImpl implements INotificationData {
     public void setServiceInvariantUUID(String serviceInvariantUUID) {
         this.serviceInvariantUUID = serviceInvariantUUID;
     }
-
 }
index 4a12cec..48b4d0c 100644 (file)
@@ -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.
  * limitations under the License.
  * ============LICENSE_END=========================================================
  */
-
 package org.openecomp.sdc.be.components.distribution.engine;
 
 import com.google.common.util.concurrent.ThreadFactoryBuilder;
-import org.openecomp.sdc.be.config.DistributionEngineConfiguration.DistributionNotificationTopicConfig;
-import org.openecomp.sdc.common.log.wrappers.Logger;
-
 import java.util.concurrent.ExecutorService;
 import java.util.concurrent.SynchronousQueue;
 import java.util.concurrent.ThreadFactory;
 import java.util.concurrent.ThreadPoolExecutor;
 import java.util.concurrent.TimeUnit;
+import org.openecomp.sdc.be.config.DistributionEngineConfiguration.DistributionNotificationTopicConfig;
+import org.openecomp.sdc.common.log.wrappers.Logger;
 
 public class NotificationExecutorService {
 
     private static final Logger logger = Logger.getLogger(NotificationExecutorService.class.getName());
 
     public ExecutorService createExcecutorService(DistributionNotificationTopicConfig distributionNotificationTopic) {
-
         Integer minThreadPoolSize = distributionNotificationTopic.getMinThreadPoolSize();
         if (minThreadPoolSize == null) {
             minThreadPoolSize = 0;
         }
-
         Integer maxThreadPoolSize = distributionNotificationTopic.getMaxThreadPoolSize();
         if (maxThreadPoolSize == null) {
             maxThreadPoolSize = 10;
         }
-
         ThreadFactoryBuilder threadFactoryBuilder = new ThreadFactoryBuilder();
         threadFactoryBuilder.setNameFormat("distribution-notification-thread-%d");
         ThreadFactory threadFactory = threadFactoryBuilder.build();
-
         return new ThreadPoolExecutor(minThreadPoolSize, maxThreadPoolSize, 60L, TimeUnit.SECONDS, new SynchronousQueue<>(), threadFactory);
     }
 
     public void shutdownAndAwaitTermination(ExecutorService pool, long maxTimeToWait) {
-
         logger.debug("shutdown NotificationExecutorService");
         pool.shutdown(); // Disable new tasks from being submitted
         try {
             // Wait a while for existing tasks to terminate
             if (!pool.awaitTermination(maxTimeToWait, TimeUnit.SECONDS)) {
                 pool.shutdownNow(); // Cancel currently executing tasks
+
                 // Wait a while for tasks to respond to being cancelled
                 if (!pool.awaitTermination(maxTimeToWait, TimeUnit.SECONDS)) {
                     logger.debug("Failed to close executor service");
@@ -73,5 +67,4 @@ public class NotificationExecutorService {
             Thread.currentThread().interrupt();
         }
     }
-
 }
index 19a857a..86090e4 100644 (file)
@@ -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.
@@ -17,7 +17,6 @@
  * limitations under the License.
  * ============LICENSE_END=========================================================
  */
-
 package org.openecomp.sdc.be.components.distribution.engine;
 
 public class ResourceArtifactInfoImpl extends ArtifactInfoImpl implements IResourceArtifactInfo {
@@ -52,7 +51,7 @@ public class ResourceArtifactInfoImpl extends ArtifactInfoImpl implements IResou
 
     @Override
     public String toString() {
-        return "ResourceArtifactInfoImpl [resourceName=" + resourceName + ", resourceVersion=" + resourceVersion + ", resourceUUID=" + resourceUUID + super.toString() + "]";
+        return "ResourceArtifactInfoImpl [resourceName=" + resourceName + ", resourceVersion=" + resourceVersion + ", resourceUUID=" + resourceUUID
+            + super.toString() + "]";
     }
-
 }
index 1d62680..c9503ac 100644 (file)
@@ -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.
@@ -17,7 +17,6 @@
  * limitations under the License.
  * ============LICENSE_END=========================================================
  */
-
 package org.openecomp.sdc.be.components.distribution.engine;
 
 public class ServiceArtifactInfoImpl extends ArtifactInfoImpl implements IServiceArtifactInfo {
@@ -26,5 +25,4 @@ public class ServiceArtifactInfoImpl extends ArtifactInfoImpl implements IServic
     public String toString() {
         return "ServiceArtifactInfoImpl [" + super.toString() + "]";
     }
-
 }
index ef43c43..2d43e9f 100644 (file)
@@ -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.
  * limitations under the License.
  * ============LICENSE_END=========================================================
  */
-
 package org.openecomp.sdc.be.components.distribution.engine;
 
 import fj.data.Either;
+import java.util.ArrayList;
+import java.util.List;
+import java.util.Map;
+import java.util.Optional;
+import java.util.stream.Collectors;
 import org.apache.commons.collections.CollectionUtils;
 import org.apache.commons.collections.MapUtils;
 import org.openecomp.sdc.be.config.ConfigurationManager;
@@ -39,34 +43,53 @@ import org.openecomp.sdc.common.log.wrappers.Logger;
 import org.springframework.beans.factory.annotation.Autowired;
 import org.springframework.stereotype.Component;
 
-import java.util.ArrayList;
-import java.util.List;
-import java.util.Map;
-import java.util.Optional;
-import java.util.stream.Collectors;
-
 @Component("serviceDistributionArtifactsBuilder")
 public class ServiceDistributionArtifactsBuilder {
 
     private static final Logger logger = Logger.getLogger(ServiceDistributionArtifactsBuilder.class.getName());
-
     private static final String BASE_ARTIFACT_URL = "/sdc/v1/catalog/services/%s/%s/";
     private static final String SERVICE_ARTIFACT_URL = BASE_ARTIFACT_URL + "artifacts/%s";
     private static final String RESOURCE_INSTANCE_ARTIFACT_URL = BASE_ARTIFACT_URL + "resourceInstances/%s/artifacts/%s";
-
+    private final ToscaOperationFacade toscaOperationFacade;
     @javax.annotation.Resource
     InterfaceLifecycleOperation interfaceLifecycleOperation;
-
     @javax.annotation.Resource
     ArtifactOperation artifactOperation;
 
-    private final ToscaOperationFacade toscaOperationFacade;
-
     @Autowired
     public ServiceDistributionArtifactsBuilder(ToscaOperationFacade toscaOperationFacade) {
         this.toscaOperationFacade = toscaOperationFacade;
     }
 
+    /**
+     * build the URL for resource instance artifact
+     *
+     * @param service
+     * @param resourceInstance
+     * @param artifactName
+     * @return URL string
+     */
+    public static String buildResourceInstanceArtifactUrl(Service service, ComponentInstance resourceInstance, String artifactName) {
+        String url = String
+            .format(RESOURCE_INSTANCE_ARTIFACT_URL, service.getSystemName(), service.getVersion(), resourceInstance.getNormalizedName(),
+                artifactName);
+        logger.debug("After building artifact url {}", url);
+        return url;
+    }
+
+    /**
+     * build the URL for resource instance artifact
+     *
+     * @param service
+     * @param artifactName
+     * @return URL string
+     */
+    public static String buildServiceArtifactUrl(Service service, String artifactName) {
+        String url = String.format(SERVICE_ARTIFACT_URL, service.getSystemName(), service.getVersion(), artifactName);
+        logger.debug("After building artifact url {}", url);
+        return url;
+    }
+
     public InterfaceLifecycleOperation getInterfaceLifecycleOperation() {
         return interfaceLifecycleOperation;
     }
@@ -76,13 +99,11 @@ public class ServiceDistributionArtifactsBuilder {
     }
 
     private String resolveWorkloadContext(String workloadContext) {
-        return workloadContext != null ? workloadContext :
-                ConfigurationManager.getConfigurationManager().getConfiguration().getWorkloadContext();
+        return workloadContext != null ? workloadContext : ConfigurationManager.getConfigurationManager().getConfiguration().getWorkloadContext();
     }
 
     public INotificationData buildResourceInstanceForDistribution(Service service, String distributionId, String workloadContext) {
         INotificationData notificationData = new NotificationDataImpl();
-
         notificationData.setResources(convertRIsToJsonContanier(service));
         notificationData.setServiceName(service.getName());
         notificationData.setServiceVersion(service.getVersion());
@@ -91,70 +112,62 @@ public class ServiceDistributionArtifactsBuilder {
         notificationData.setServiceDescription(service.getDescription());
         notificationData.setServiceInvariantUUID(service.getInvariantUUID());
         workloadContext = resolveWorkloadContext(workloadContext);
-        if (workloadContext!=null){
+        if (workloadContext != null) {
             notificationData.setWorkloadContext(workloadContext);
         }
         logger.debug("Before returning notification data object {}", notificationData);
-
         return notificationData;
     }
 
     public INotificationData buildServiceForDistribution(INotificationData notificationData, Service service) {
-
         notificationData.setServiceArtifacts(convertServiceArtifactsToArtifactInfo(service));
-
         logger.debug("Before returning notification data object {}", notificationData);
-
         return notificationData;
     }
 
     private List<ArtifactInfoImpl> convertServiceArtifactsToArtifactInfo(Service service) {
-
         Map<String, ArtifactDefinition> serviceArtifactsMap = service.getDeploymentArtifacts();
         List<ArtifactDefinition> extractedServiceArtifacts = serviceArtifactsMap.values().stream()
-                //filters all artifacts with existing EsId
-                .filter(ArtifactDefinition::checkEsIdExist)
-                //collects all filtered artifacts with existing EsId to List
-                .collect(Collectors.toList());
-
+            //filters all artifacts with existing EsId
+            .filter(ArtifactDefinition::checkEsIdExist)
+            //collects all filtered artifacts with existing EsId to List
+            .collect(Collectors.toList());
         Optional<ArtifactDefinition> toscaTemplateArtifactOptl = exrtactToscaTemplateArtifact(service);
-        if(toscaTemplateArtifactOptl.isPresent()){
+        if (toscaTemplateArtifactOptl.isPresent()) {
             extractedServiceArtifacts.add(toscaTemplateArtifactOptl.get());
         }
-
         Optional<ArtifactDefinition> toscaCsarArtifactOptl = exrtactToscaCsarArtifact(service);
-        if(toscaCsarArtifactOptl.isPresent()){
+        if (toscaCsarArtifactOptl.isPresent()) {
             extractedServiceArtifacts.add(toscaCsarArtifactOptl.get());
         }
-
         return ArtifactInfoImpl.convertServiceArtifactToArtifactInfoImpl(service, extractedServiceArtifacts);
     }
 
     private Optional<ArtifactDefinition> exrtactToscaTemplateArtifact(Service service) {
         return service.getToscaArtifacts().values().stream()
-                //filters TOSCA_TEMPLATE artifact
-                .filter(e -> e.getArtifactType().equals(ArtifactTypeEnum.TOSCA_TEMPLATE.getType())).findAny();
+            //filters TOSCA_TEMPLATE artifact
+            .filter(e -> e.getArtifactType().equals(ArtifactTypeEnum.TOSCA_TEMPLATE.getType())).findAny();
     }
 
     private Optional<ArtifactDefinition> exrtactToscaCsarArtifact(Service service) {
         return service.getToscaArtifacts().values().stream()
-                //filters TOSCA_CSAR artifact
-                .filter(e -> e.getArtifactType().equals(ArtifactTypeEnum.TOSCA_CSAR.getType())).findAny();
+            //filters TOSCA_CSAR artifact
+            .filter(e -> e.getArtifactType().equals(ArtifactTypeEnum.TOSCA_CSAR.getType())).findAny();
     }
 
     private List<JsonContainerResourceInstance> convertRIsToJsonContanier(Service service) {
         List<JsonContainerResourceInstance> ret = new ArrayList<>();
         if (service.getComponentInstances() != null) {
             for (ComponentInstance instance : service.getComponentInstances()) {
-                JsonContainerResourceInstance jsonContainer = new JsonContainerResourceInstance(instance, convertToArtifactsInfoImpl(service, instance));
+                JsonContainerResourceInstance jsonContainer = new JsonContainerResourceInstance(instance,
+                    convertToArtifactsInfoImpl(service, instance));
                 ComponentParametersView filter = new ComponentParametersView();
                 filter.disableAll();
                 filter.setIgnoreCategories(false);
-                toscaOperationFacade.getToscaElement(instance.getComponentUid(), filter)
-                    .left()
-                    .bind(r->{fillJsonContainer(jsonContainer, (Resource) r); return Either.left(r);})
-                    .right()
-                    .forEach(r->logger.debug("Resource {} Invariant UUID & Categories retrieving failed", instance.getComponentUid()));
+                toscaOperationFacade.getToscaElement(instance.getComponentUid(), filter).left().bind(r -> {
+                    fillJsonContainer(jsonContainer, (Resource) r);
+                    return Either.left(r);
+                }).right().forEach(r -> logger.debug("Resource {} Invariant UUID & Categories retrieving failed", instance.getComponentUid()));
                 ret.add(jsonContainer);
             }
         }
@@ -167,20 +180,19 @@ public class ServiceDistributionArtifactsBuilder {
     }
 
     private List<ArtifactInfoImpl> convertToArtifactsInfoImpl(Service service, ComponentInstance resourceInstance) {
-        List<ArtifactInfoImpl> artifacts = ArtifactInfoImpl.convertToArtifactInfoImpl(service, resourceInstance, getArtifactsWithPayload(resourceInstance));
+        List<ArtifactInfoImpl> artifacts = ArtifactInfoImpl
+            .convertToArtifactInfoImpl(service, resourceInstance, getArtifactsWithPayload(resourceInstance));
         return artifacts;
     }
 
     private void setCategories(JsonContainerResourceInstance jsonContainer, List<CategoryDefinition> categories) {
         if (categories != null) {
             CategoryDefinition categoryDefinition = categories.get(0);
-
             if (categoryDefinition != null) {
                 jsonContainer.setCategory(categoryDefinition.getName());
                 List<SubCategoryDefinition> subcategories = categoryDefinition.getSubcategories();
                 if (null != subcategories) {
                     SubCategoryDefinition subCategoryDefinition = subcategories.get(0);
-
                     if (subCategoryDefinition != null) {
                         jsonContainer.setSubcategory(subCategoryDefinition.getName());
                     }
@@ -191,62 +203,23 @@ public class ServiceDistributionArtifactsBuilder {
 
     private List<ArtifactDefinition> getArtifactsWithPayload(ComponentInstance resourceInstance) {
         List<ArtifactDefinition> ret = new ArrayList<>();
-
         List<ArtifactDefinition> deployableArtifacts = new ArrayList<>();
         if (resourceInstance.getDeploymentArtifacts() != null) {
             deployableArtifacts.addAll(resourceInstance.getDeploymentArtifacts().values());
         }
-
         for (ArtifactDefinition artifactDef : deployableArtifacts) {
             if (artifactDef.checkEsIdExist()) {
                 ret.add(artifactDef);
             }
         }
-
         return ret;
     }
 
-    /**
-     * build the URL for resource instance artifact
-     *
-     * @param    service
-     * @param    resourceInstance
-     * @param    artifactName
-     * @return    URL string
-     */
-    public static String buildResourceInstanceArtifactUrl(Service service, ComponentInstance resourceInstance,
-            String artifactName) {
-
-        String url = String.format(RESOURCE_INSTANCE_ARTIFACT_URL, service.getSystemName(), service.getVersion(),
-                resourceInstance.getNormalizedName(), artifactName);
-
-        logger.debug("After building artifact url {}", url);
-
-        return url;
-    }
-
-    /**
-     * build the URL for resource instance artifact
-     *
-     * @param    service
-     * @param    artifactName
-     * @return    URL string
-     */
-    public static String buildServiceArtifactUrl(Service service, String artifactName) {
-
-        String url = String.format(SERVICE_ARTIFACT_URL, service.getSystemName(), service.getVersion(), artifactName);
-
-        logger.debug("After building artifact url {}", url);
-
-        return url;
-
-    }
-
     /**
      * Verifies that the service or at least one of its instance contains deployment artifacts
      *
-     * @param    the service
-     * @return    boolean
+     * @param the service
+     * @return boolean
      */
     public boolean verifyServiceContainsDeploymentArtifacts(Service service) {
         if (MapUtils.isNotEmpty(service.getDeploymentArtifacts())) {
@@ -261,7 +234,6 @@ public class ServiceDistributionArtifactsBuilder {
     }
 
     private boolean isContainsPayload(Map<String, ArtifactDefinition> deploymentArtifacts) {
-       return deploymentArtifacts != null && deploymentArtifacts.values().stream().anyMatch(ArtifactDefinition::checkEsIdExist);
+        return deploymentArtifacts != null && deploymentArtifacts.values().stream().anyMatch(ArtifactDefinition::checkEsIdExist);
     }
-
 }
index 3477648..0de3d3e 100644 (file)
@@ -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.
  * limitations under the License.
  * ============LICENSE_END=========================================================
  */
-
 package org.openecomp.sdc.be.components.distribution.engine;
 
 public enum SubscriberTypeEnum {
-
     CONSUMER, PRODUCER;
 }
index bed0aae..d28592d 100644 (file)
@@ -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.
  * limitations under the License.
  * ============LICENSE_END=========================================================
  */
-
 package org.openecomp.sdc.be.components.distribution.engine;
 
-import org.openecomp.sdc.common.log.wrappers.Logger;
-
 import java.util.concurrent.Callable;
+import org.openecomp.sdc.common.log.wrappers.Logger;
 
 public class UebHealthCheckCall implements Callable<Boolean> {
 
+    private static final Logger healthLogger = Logger.getLogger(DistributionEngineClusterHealth.UEB_HEALTH_LOG_CONTEXT);
+    private static final Logger logger = Logger.getLogger(UebHealthCheckCall.class.getName());
     CambriaHandler cambriaHandler = new CambriaHandler();
-
     String server;
     String publicApiKey;
 
-    private static final Logger healthLogger = Logger.getLogger(DistributionEngineClusterHealth.UEB_HEALTH_LOG_CONTEXT);
-
-    private static final Logger logger = Logger.getLogger(UebHealthCheckCall.class.getName());
-
     public UebHealthCheckCall(String server, String publicApiKey) {
         super();
         this.server = server;
@@ -43,24 +38,20 @@ public class UebHealthCheckCall implements Callable<Boolean> {
 
     @Override
     public Boolean call() {
-
         healthLogger.trace("Going to run health check towards ueb server {}", server);
-
         boolean result = false;
         CambriaErrorResponse cambriaErrorResponse = cambriaHandler.getApiKey(server, publicApiKey);
-
         logger.debug("After running Health check towards ueb server {}. Result is {}", server, cambriaErrorResponse);
-
         if (cambriaErrorResponse.httpCode < CambriaErrorResponse.HTTP_INTERNAL_SERVER_ERROR) {
-            logger.debug("After running Health check towards ueb server {}. Error code is {}. Set result to true", server, cambriaErrorResponse.httpCode);
+            logger.debug("After running Health check towards ueb server {}. Error code is {}. Set result to true", server,
+                cambriaErrorResponse.httpCode);
             result = true;
+        } else {
+            logger.debug("After running Health check towards ueb server {}. Error code is {}. Set result to false", server,
+                cambriaErrorResponse.httpCode);
         }
-        else {
-            logger.debug("After running Health check towards ueb server {}. Error code is {}. Set result to false", server, cambriaErrorResponse.httpCode);
-        }
-
-        healthLogger.trace("Result after running health check towards ueb server {} is {}. Returned result is {} ", server, cambriaErrorResponse, result);
-
+        healthLogger
+            .trace("Result after running health check towards ueb server {} is {}. Returned result is {} ", server, cambriaErrorResponse, result);
         return result;
     }
 
@@ -75,5 +66,4 @@ public class UebHealthCheckCall implements Callable<Boolean> {
     public void setCambriaHandler(CambriaHandler cambriaHandler) {
         this.cambriaHandler = cambriaHandler;
     }
-
 }
index c566c1c..9222da0 100644 (file)
@@ -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.
  * limitations under the License.
  * ============LICENSE_END=========================================================
  */
-
 package org.openecomp.sdc.be.components.distribution.engine;
 
-import org.openecomp.sdc.be.datatypes.elements.PropertyDataDefinition;
-import org.openecomp.sdc.be.model.GroupDefinition;
-import org.openecomp.sdc.be.model.GroupInstance;
-import org.openecomp.sdc.be.model.GroupInstanceProperty;
-import org.openecomp.sdc.be.model.GroupProperty;
-import org.openecomp.sdc.common.api.Constants;
-
 import java.util.ArrayList;
 import java.util.LinkedList;
 import java.util.List;
 import java.util.Map;
 import java.util.Optional;
 import java.util.stream.Collectors;
+import org.openecomp.sdc.be.datatypes.elements.PropertyDataDefinition;
+import org.openecomp.sdc.be.model.GroupDefinition;
+import org.openecomp.sdc.be.model.GroupInstance;
+import org.openecomp.sdc.be.model.GroupInstanceProperty;
+import org.openecomp.sdc.be.model.GroupProperty;
+import org.openecomp.sdc.common.api.Constants;
 
 public class VfModuleArtifactPayload {
 
     private String vfModuleModelName, vfModuleModelInvariantUUID, vfModuleModelVersion, vfModuleModelUUID, vfModuleModelCustomizationUUID, vfModuleModelDescription;
     private Boolean isBase;
     private List<String> artifacts;
-    private Map< String, Object> properties;
+    private Map<String, Object> properties;
 
     public VfModuleArtifactPayload(GroupDefinition group) {
         vfModuleModelName = group.getName();
@@ -47,11 +45,9 @@ public class VfModuleArtifactPayload {
         vfModuleModelVersion = group.getVersion();
         vfModuleModelUUID = group.getGroupUUID();
         vfModuleModelDescription = group.getDescription();
-
         artifacts = group.getArtifactsUuid();
         // Base Value is set from properties
         setBaseValue(group);
-
     }
 
     public VfModuleArtifactPayload(GroupInstance group) {
@@ -61,38 +57,41 @@ public class VfModuleArtifactPayload {
         vfModuleModelUUID = group.getGroupUUID();
         vfModuleModelCustomizationUUID = group.getCustomizationUUID();
         vfModuleModelDescription = group.getDescription();
-
         artifacts = new ArrayList<>(group.getArtifactsUuid() != null ? group.getArtifactsUuid() : new LinkedList<>());
         artifacts.addAll(group.getGroupInstanceArtifactsUuid() != null ? group.getGroupInstanceArtifactsUuid() : new LinkedList<>());
-
         // Base Value is set from properties
         setBaseValue(group);
-
-        if(group.convertToGroupInstancesProperties() != null)
+        if (group.convertToGroupInstancesProperties() != null) {
             setProperties(group.convertToGroupInstancesProperties());
+        }
+    }
+
+    public static int compareByGroupName(VfModuleArtifactPayload art1, VfModuleArtifactPayload art2) {
+        Float thisCounter = Float.parseFloat(art1.vfModuleModelName.split(Constants.MODULE_NAME_DELIMITER)[1].replace(' ', '.'));
+        Float otherCounter = Float.parseFloat(art2.vfModuleModelName.split(Constants.MODULE_NAME_DELIMITER)[1].replace(' ', '.'));
+        return thisCounter.compareTo(otherCounter);
     }
 
     private void setBaseValue(GroupInstance group) {
         if (group.convertToGroupInstancesProperties() != null) {
-            Optional<GroupInstanceProperty> findBaseProperty = group.convertToGroupInstancesProperties().stream().filter(p -> p.getName().equals(Constants.IS_BASE)).findAny();
+            Optional<GroupInstanceProperty> findBaseProperty = group.convertToGroupInstancesProperties().stream()
+                .filter(p -> p.getName().equals(Constants.IS_BASE)).findAny();
             if (findBaseProperty.isPresent()) {
                 isBase = Boolean.valueOf(findBaseProperty.get().getValue());
             }
-
         }
     }
+
     private void setBaseValue(GroupDefinition group) {
         if (group.getProperties() != null) {
-            Optional<GroupProperty> findBaseProperty = group.convertToGroupProperties().stream().filter(p -> p.getName().equals(Constants.IS_BASE)).findAny();
+            Optional<GroupProperty> findBaseProperty = group.convertToGroupProperties().stream().filter(p -> p.getName().equals(Constants.IS_BASE))
+                .findAny();
             if (findBaseProperty.isPresent()) {
                 isBase = Boolean.valueOf(findBaseProperty.get().getValue());
             }
-
         }
     }
 
-
-
     public List<String> getArtifacts() {
         return artifacts;
     }
@@ -101,21 +100,12 @@ public class VfModuleArtifactPayload {
         this.artifacts = artifacts;
     }
 
-
-
     public Map<String, Object> getProperties() {
         return properties;
     }
 
-
     public void setProperties(List<GroupInstanceProperty> properties) {
-        this.properties  = properties.stream().filter(p -> !p.getName().equals(Constants.IS_BASE)).collect(
-                    Collectors.toMap(PropertyDataDefinition::getName, x -> x.getValue() == null? "":x.getValue() ));
-    }
-
-    public static int compareByGroupName(VfModuleArtifactPayload art1, VfModuleArtifactPayload art2) {
-        Float thisCounter = Float.parseFloat(art1.vfModuleModelName.split(Constants.MODULE_NAME_DELIMITER)[1].replace(' ', '.'));
-        Float otherCounter = Float.parseFloat(art2.vfModuleModelName.split(Constants.MODULE_NAME_DELIMITER)[1].replace(' ', '.'));
-        return thisCounter.compareTo(otherCounter);
+        this.properties = properties.stream().filter(p -> !p.getName().equals(Constants.IS_BASE))
+            .collect(Collectors.toMap(PropertyDataDefinition::getName, x -> x.getValue() == null ? "" : x.getValue()));
     }
 }
index f5b5e2f..1276031 100644 (file)
@@ -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.
  * limitations under the License.
  * ============LICENSE_END=========================================================
  */
-
 package org.openecomp.sdc.be.components.distribution.engine.config;
 
 import org.springframework.context.annotation.ComponentScan;
 import org.springframework.context.annotation.Configuration;
 
 @Configuration
-@ComponentScan({"org.openecomp.sdc.be.components.distribution.engine",
-        })
+@ComponentScan({"org.openecomp.sdc.be.components.distribution.engine",})
 public class DistributionEngineSpringConfig {
 
 }
index 7e6a4d8..4ef627f 100644 (file)
@@ -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.
@@ -17,7 +17,6 @@
  * limitations under the License.
  * ============LICENSE_END=========================================================
  */
-
 package org.openecomp.sdc.be.components.distribution.engine.report;
 
 import org.openecomp.sdc.be.components.distribution.engine.DistributionStatusNotification;
@@ -25,5 +24,4 @@ import org.openecomp.sdc.be.components.distribution.engine.DistributionStatusNot
 public interface DistributionCompleteReporter {
 
     void reportDistributionComplete(DistributionStatusNotification distributionStatusNotification);
-
 }
index 5cb8a26..d753e64 100644 (file)
@@ -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.
  * limitations under the License.
  * ============LICENSE_END=========================================================
  */
-
 package org.openecomp.sdc.be.components.distribution.engine.report;
 
+import javax.annotation.Resource;
 import org.openecomp.sdc.be.components.distribution.engine.DistributionStatusNotification;
 import org.openecomp.sdc.be.components.distribution.engine.rest.MSORestClient;
 import org.springframework.stereotype.Component;
 
-import javax.annotation.Resource;
-
 @Component
 public class MsoDistributionCompleteReporter implements DistributionCompleteReporter {
 
@@ -34,6 +32,7 @@ public class MsoDistributionCompleteReporter implements DistributionCompleteRepo
 
     @Override
     public void reportDistributionComplete(DistributionStatusNotification distributionStatusNotification) {
-        msoClient.notifyDistributionComplete(distributionStatusNotification.getDistributionID(), distributionStatusNotification.getStatus(), distributionStatusNotification.getErrorReason());
+        msoClient.notifyDistributionComplete(distributionStatusNotification.getDistributionID(), distributionStatusNotification.getStatus(),
+            distributionStatusNotification.getErrorReason());
     }
 }
index 391c6c6..dd23e2d 100644 (file)
@@ -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.
@@ -17,7 +17,6 @@
  * limitations under the License.
  * ============LICENSE_END=========================================================
  */
-
 package org.openecomp.sdc.be.components.distribution.engine.rest;
 
 /**
index fb0310b..92ece13 100644 (file)
@@ -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.
  * limitations under the License.
  * ============LICENSE_END=========================================================
  */
-
 package org.openecomp.sdc.be.components.distribution.engine.rest;
 
 import com.google.common.annotations.VisibleForTesting;
 import com.google.gson.Gson;
+import java.util.Properties;
 import org.apache.http.entity.ContentType;
 import org.apache.http.entity.StringEntity;
 import org.eclipse.jetty.util.URIUtil;
@@ -39,40 +39,40 @@ import org.openecomp.sdc.common.http.config.HttpClientConfig;
 import org.openecomp.sdc.common.log.wrappers.Logger;
 import org.springframework.stereotype.Component;
 
-import java.util.Properties;
-
 @Component
 public class MSORestClient {
 
-    private static final Logger logger = Logger.getLogger(MSORestClient.class.getName());
-    private static final Gson gson = new Gson();
     @VisibleForTesting
     static final String DISTRIBUTIONS_RESOURCE_CONFIG_PARAM = "distributions";
-
+    private static final Logger logger = Logger.getLogger(MSORestClient.class.getName());
+    private static final Gson gson = new Gson();
     private ExternalServiceConfig serviceConfig = ConfigurationManager.getConfigurationManager().getDistributionEngineConfiguration().getMsoConfig();
 
     public MSORestClient() {
         HttpClientConfig httpClientConfig = serviceConfig.getHttpClientConfig();
-        int numOfRetries = httpClientConfig.getNumOfRetries(); 
-        if ( numOfRetries > 0 ) {
+        int numOfRetries = httpClientConfig.getNumOfRetries();
+        if (numOfRetries > 0) {
             httpClientConfig.setRetryHandler(RetryHandlers.getDefault(numOfRetries));
         }
         serviceConfig.getHttpClientConfig().setEnableMetricLogging(true);
     }
 
-    public HttpResponse<String> notifyDistributionComplete(String distributionId, DistributionStatusNotificationEnum distributionStatusEnum, String errReason) {
+    public HttpResponse<String> notifyDistributionComplete(String distributionId, DistributionStatusNotificationEnum distributionStatusEnum,
+                                                           String errReason) {
         try {
             return doNotifyDistributionComplete(distributionId, distributionStatusEnum, errReason);
-        }
-        catch(HttpExecuteException e) {
+        } catch (HttpExecuteException e) {
             logger.debug("The request to mso failed with exception ", e);
             return Responses.INTERNAL_SERVER_ERROR;
         }
     }
 
-    private HttpResponse<String> doNotifyDistributionComplete(String distributionId, DistributionStatusNotificationEnum distributionStatusEnum, String errReason) throws HttpExecuteException {
-        StringEntity entity = new StringEntity(gson.toJson(new DistributionStatusRequest(distributionStatusEnum.name(), errReason)), ContentType.APPLICATION_JSON);
-        HttpResponse<String> response = HttpRequest.patch(buildMsoDistributionUrl(distributionId), buildReqHeader(), entity, serviceConfig.getHttpClientConfig());
+    private HttpResponse<String> doNotifyDistributionComplete(String distributionId, DistributionStatusNotificationEnum distributionStatusEnum,
+                                                              String errReason) throws HttpExecuteException {
+        StringEntity entity = new StringEntity(gson.toJson(new DistributionStatusRequest(distributionStatusEnum.name(), errReason)),
+            ContentType.APPLICATION_JSON);
+        HttpResponse<String> response = HttpRequest
+            .patch(buildMsoDistributionUrl(distributionId), buildReqHeader(), entity, serviceConfig.getHttpClientConfig());
         return response;
     }
 
@@ -89,5 +89,4 @@ public class MSORestClient {
         String distributionsApiPath = distributionsPath + URIUtil.SLASH + distributionId;
         return msoBaseUrl + distributionsApiPath;
     }
-
 }
index c532ee9..a90ebf9 100644 (file)
  * limitations under the License.
  * ============LICENSE_END=========================================================
  */
-
 package org.openecomp.sdc.be.components.health;
 
+import static java.lang.String.format;
+import static java.util.concurrent.Executors.newSingleThreadScheduledExecutor;
+import static org.apache.http.HttpStatus.SC_INTERNAL_SERVER_ERROR;
+import static org.apache.http.HttpStatus.SC_OK;
+import static org.openecomp.sdc.common.api.Constants.HC_COMPONENT_BE;
+import static org.openecomp.sdc.common.api.Constants.HC_COMPONENT_CASSANDRA;
+import static org.openecomp.sdc.common.api.Constants.HC_COMPONENT_DMAAP_PRODUCER;
+import static org.openecomp.sdc.common.api.Constants.HC_COMPONENT_ECOMP_PORTAL;
+import static org.openecomp.sdc.common.api.Constants.HC_COMPONENT_JANUSGRAPH;
+import static org.openecomp.sdc.common.api.Constants.HC_COMPONENT_ON_BOARDING;
+import static org.openecomp.sdc.common.api.HealthCheckInfo.HealthCheckStatus.DOWN;
+import static org.openecomp.sdc.common.api.HealthCheckInfo.HealthCheckStatus.UP;
+import static org.openecomp.sdc.common.impl.ExternalConfiguration.getAppVersion;
+
 import com.fasterxml.jackson.core.type.TypeReference;
 import com.fasterxml.jackson.databind.ObjectMapper;
 import com.google.common.annotations.VisibleForTesting;
+import java.util.ArrayList;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+import java.util.Map.Entry;
+import java.util.concurrent.ScheduledExecutorService;
+import java.util.concurrent.ScheduledFuture;
+import java.util.concurrent.TimeUnit;
+import java.util.stream.Collectors;
+import javax.annotation.PostConstruct;
+import javax.annotation.PreDestroy;
+import javax.annotation.Resource;
 import org.apache.commons.lang3.tuple.ImmutablePair;
 import org.apache.commons.lang3.tuple.Pair;
 import org.openecomp.sdc.be.catalog.impl.DmaapProducerHealth;
@@ -47,34 +72,6 @@ import org.openecomp.sdc.common.util.HealthCheckUtil;
 import org.springframework.beans.factory.annotation.Autowired;
 import org.springframework.stereotype.Component;
 
-import javax.annotation.PostConstruct;
-import javax.annotation.PreDestroy;
-import javax.annotation.Resource;
-import java.util.ArrayList;
-import java.util.HashMap;
-import java.util.List;
-import java.util.Map;
-import java.util.Map.Entry;
-import java.util.concurrent.ScheduledExecutorService;
-import java.util.concurrent.ScheduledFuture;
-import java.util.concurrent.TimeUnit;
-import java.util.stream.Collectors;
-
-import static java.lang.String.format;
-import static java.util.concurrent.Executors.newSingleThreadScheduledExecutor;
-import static org.apache.http.HttpStatus.SC_INTERNAL_SERVER_ERROR;
-import static org.apache.http.HttpStatus.SC_OK;
-import static org.openecomp.sdc.common.api.Constants.HC_COMPONENT_BE;
-import static org.openecomp.sdc.common.api.Constants.HC_COMPONENT_CASSANDRA;
-import static org.openecomp.sdc.common.api.Constants.HC_COMPONENT_DMAAP_PRODUCER;
-import static org.openecomp.sdc.common.api.Constants.HC_COMPONENT_ECOMP_PORTAL;
-import static org.openecomp.sdc.common.api.Constants.HC_COMPONENT_JANUSGRAPH;
-import static org.openecomp.sdc.common.api.Constants.HC_COMPONENT_ON_BOARDING;
-import static org.openecomp.sdc.common.api.HealthCheckInfo.HealthCheckStatus.DOWN;
-import static org.openecomp.sdc.common.api.HealthCheckInfo.HealthCheckStatus.UP;
-import static org.openecomp.sdc.common.impl.ExternalConfiguration.getAppVersion;
-
-
 @Component("healthCheckBusinessLogic")
 public class HealthCheckBusinessLogic {
 
@@ -84,10 +81,10 @@ public class HealthCheckBusinessLogic {
     private static final String COMPONENT_CHANGED_MESSAGE = "BE Component %s state changed from %s to %s";
     private static final Logger log = Logger.getLogger(HealthCheckBusinessLogic.class.getName());
     private static final HealthCheckUtil healthCheckUtil = new HealthCheckUtil();
-    private final ScheduledExecutorService healthCheckScheduler = newSingleThreadScheduledExecutor((Runnable r) -> new Thread(r, "BE-Health-Check-Task"));
+    private final ScheduledExecutorService healthCheckScheduler = newSingleThreadScheduledExecutor(
+        (Runnable r) -> new Thread(r, "BE-Health-Check-Task"));
     private HealthCheckScheduledTask healthCheckScheduledTask = null;
     private static LogFieldsMdcHandler mdcFieldsHandler = new LogFieldsMdcHandler();
-
     @Resource
     private JanusGraphGenericDao janusGraphGenericDao;
     @Resource
@@ -100,7 +97,6 @@ public class HealthCheckBusinessLogic {
     private CassandraHealthCheck cassandraHealthCheck;
     @Resource
     private PortalHealthCheckBuilder portalHealthCheck;
-
     @Autowired
     private SwitchoverDetector switchoverDetector;
     private volatile List<HealthCheckInfo> prevBeHealthCheckInfos = null;
@@ -108,77 +104,60 @@ public class HealthCheckBusinessLogic {
 
     @PostConstruct
     public void init() {
-
         prevBeHealthCheckInfos = getBeHealthCheckInfos();
-
         log.debug("After initializing prevBeHealthCheckInfos: {}", prevBeHealthCheckInfos);
-
         healthCheckScheduledTask = new HealthCheckScheduledTask();
-
         if (this.scheduledFuture == null) {
             this.scheduledFuture = this.healthCheckScheduler.scheduleAtFixedRate(healthCheckScheduledTask, 0, 3, TimeUnit.SECONDS);
         }
-
     }
 
     public boolean isDistributionEngineUp() {
-
         HealthCheckInfo healthCheckInfo = distributionEngineClusterHealth.getHealthCheckInfo();
         return healthCheckInfo.getHealthCheckStatus() != DOWN;
     }
 
     public Pair<Boolean, List<HealthCheckInfo>> getBeHealthCheckInfosStatus() {
         Configuration config = ConfigurationManager.getConfigurationManager().getConfiguration();
-        return new ImmutablePair<>(healthCheckUtil.getAggregateStatus(prevBeHealthCheckInfos, config.getHealthStatusExclude()), prevBeHealthCheckInfos);
+        return new ImmutablePair<>(healthCheckUtil.getAggregateStatus(prevBeHealthCheckInfos, config.getHealthStatusExclude()),
+            prevBeHealthCheckInfos);
     }
 
     private List<HealthCheckInfo> getBeHealthCheckInfos() {
-
         log.trace("In getBeHealthCheckInfos");
-
         List<HealthCheckInfo> healthCheckInfos = new ArrayList<>();
-
         //Dmaap
         HealthCheckInfo info;
         if ((info = getDmaapHealthCheck()) != null) {
             healthCheckInfos.add(info);
         }
-
         //DmaapProducer
         healthCheckInfos.add(getDmaapProducerHealthCheck());
-
         // BE
         healthCheckInfos.add(new HealthCheckInfo(HC_COMPONENT_BE, UP, getAppVersion(), "OK"));
-
         // JanusGraph
         healthCheckInfos.add(getJanusGraphHealthCheck());
-
         // Distribution Engine
         healthCheckInfos.add(distributionEngineClusterHealth.getHealthCheckInfo());
-
         //Cassandra
         healthCheckInfos.add(getCassandraHealthCheck());
-
         // Amdocs
         healthCheckInfos.add(getHostedComponentsBeHealthCheck(HC_COMPONENT_ON_BOARDING, buildOnBoardingHealthCheckUrl()));
-
-         //ECOMP Portal
+        //ECOMP Portal
         healthCheckInfos.add(portalHealthCheck.getHealthCheckInfo());
-
         //CADI
         healthCheckInfos.add(CADIHealthCheck.getCADIHealthCheckInstance().getCADIStatus());
-
         return healthCheckInfos;
     }
 
     private HealthCheckInfo getDmaapHealthCheck() {
         HealthCheckInfo healthCheckInfo = null;
-        if(ConfigurationManager.getConfigurationManager().getConfiguration().getDmaapConsumerConfiguration().isActive()){
+        if (ConfigurationManager.getConfigurationManager().getConfiguration().getDmaapConsumerConfiguration().isActive()) {
             String appVersion = getAppVersion();
             dmaapHealth.getHealthCheckInfo().setVersion(appVersion);
             healthCheckInfo = dmaapHealth.getHealthCheckInfo();
         } else {
-          log.debug("Dmaap health check disabled");
+            log.debug("Dmaap health check disabled");
         }
         return healthCheckInfo;
     }
@@ -200,7 +179,6 @@ public class HealthCheckBusinessLogic {
         String description;
         boolean isJanusGraphUp;
         HealthCheckInfo healthCheckInfo = new HealthCheckInfo(HC_COMPONENT_JANUSGRAPH, DOWN, null, null);
-
         try {
             isJanusGraphUp = janusGraphGenericDao.isGraphOpen();
         } catch (Exception e) {
@@ -213,7 +191,6 @@ public class HealthCheckBusinessLogic {
             description = "OK";
             healthCheckInfo.setDescription(description);
             healthCheckInfo.setHealthCheckStatus(HealthCheckInfo.HealthCheckStatus.UP);
-
         } else {
             description = "JanusGraph graph is down";
             healthCheckInfo.setDescription(description);
@@ -222,11 +199,9 @@ public class HealthCheckBusinessLogic {
     }
 
     private HealthCheckInfo getCassandraHealthCheck() {
-
         String description;
         boolean isCassandraUp = false;
         HealthCheckInfo healthCheckInfo = new HealthCheckInfo(HC_COMPONENT_CASSANDRA, DOWN, null, null);
-
         try {
             isCassandraUp = cassandraHealthCheck.getCassandraStatus();
         } catch (Exception e) {
@@ -252,13 +227,11 @@ public class HealthCheckBusinessLogic {
         String version = null;
         List<HealthCheckInfo> componentsInfo = new ArrayList<>();
         final int timeout = 3000;
-
         if (healthCheckUrl != null) {
             try {
                 HttpResponse<String> httpResponse = HttpRequest.get(healthCheckUrl, new HttpClientConfig(new Timeouts(timeout, timeout)));
                 int statusCode = httpResponse.getStatusCode();
                 String aggDescription = "";
-
                 if ((statusCode == SC_OK || statusCode == SC_INTERNAL_SERVER_ERROR) && !componentName.equals(HC_COMPONENT_ECOMP_PORTAL)) {
                     String response = httpResponse.getResponse();
                     log.trace("{} Health Check response: {}", componentName, response);
@@ -274,7 +247,6 @@ public class HealthCheckBusinessLogic {
                 } else {
                     log.trace("{} Health Check Response code: {}", componentName, statusCode);
                 }
-
                 if (statusCode != SC_OK) {
                     healthCheckStatus = DOWN;
                     description = getDescription(componentName, aggDescription);
@@ -283,7 +255,6 @@ public class HealthCheckBusinessLogic {
                     healthCheckStatus = UP;
                     description = "OK";
                 }
-
             } catch (Exception e) {
                 log.error("{} unexpected response: ", componentName, e);
                 healthCheckStatus = DOWN;
@@ -312,9 +283,8 @@ public class HealthCheckBusinessLogic {
 
     private String getDescription(String componentName, String aggDescription) {
         String description;
-        description = aggDescription.length() > 0
-                ? aggDescription
-                : componentName + " is Down, specific reason unknown";//No inner component returned DOWN, but the status of HC is still DOWN.
+        description = aggDescription.length() > 0 ? aggDescription
+            : componentName + " is Down, specific reason unknown";//No inner component returned DOWN, but the status of HC is still DOWN.
         return description;
     }
 
@@ -333,16 +303,13 @@ public class HealthCheckBusinessLogic {
 
     @PreDestroy
     protected void destroy() {
-
         if (scheduledFuture != null) {
             scheduledFuture.cancel(true);
             scheduledFuture = null;
         }
-
         if (healthCheckScheduler != null) {
             healthCheckScheduler.shutdown();
         }
-
     }
 
     private void logAlarm(String componentChangedMsg) {
@@ -354,18 +321,15 @@ public class HealthCheckBusinessLogic {
     }
 
     public boolean anyStatusChanged(List<HealthCheckInfo> beHealthCheckInfos, List<HealthCheckInfo> prevBeHealthCheckInfos) {
-
         boolean result = false;
-
         if (beHealthCheckInfos != null && prevBeHealthCheckInfos != null) {
-
-            Map<String, HealthCheckStatus> currentValues = beHealthCheckInfos.stream().collect(Collectors.toMap(HealthCheckInfo::getHealthCheckComponent, HealthCheckInfo::getHealthCheckStatus));
-            Map<String, HealthCheckStatus> prevValues = prevBeHealthCheckInfos.stream().collect(Collectors.toMap(HealthCheckInfo::getHealthCheckComponent, HealthCheckInfo::getHealthCheckStatus));
-
+            Map<String, HealthCheckStatus> currentValues = beHealthCheckInfos.stream()
+                .collect(Collectors.toMap(HealthCheckInfo::getHealthCheckComponent, HealthCheckInfo::getHealthCheckStatus));
+            Map<String, HealthCheckStatus> prevValues = prevBeHealthCheckInfos.stream()
+                .collect(Collectors.toMap(HealthCheckInfo::getHealthCheckComponent, HealthCheckInfo::getHealthCheckStatus));
             if (currentValues != null && prevValues != null) {
                 int currentSize = currentValues.size();
                 int prevSize = prevValues.size();
-
                 if (currentSize != prevSize) {
                     result = true; //extra/missing component
                     updateHealthCheckStatusMap(currentValues, prevValues);
@@ -373,34 +337,30 @@ public class HealthCheckBusinessLogic {
                     result = isHealthStatusChanged(result, currentValues, prevValues);
                 }
             }
-
         } else if (beHealthCheckInfos == null && prevBeHealthCheckInfos == null) {
             result = false;
         } else {
             writeLogAlarm(prevBeHealthCheckInfos);
             result = true;
         }
-
         return result;
     }
 
     private void writeLogAlarm(List<HealthCheckInfo> prevBeHealthCheckInfos) {
-        logAlarm(format(COMPONENT_CHANGED_MESSAGE, "", prevBeHealthCheckInfos == null ? "null" : "true", prevBeHealthCheckInfos == null ? "true" : "null"));
+        logAlarm(format(COMPONENT_CHANGED_MESSAGE, "", prevBeHealthCheckInfos == null ? "null" : "true",
+            prevBeHealthCheckInfos == null ? "true" : "null"));
     }
 
     private boolean isHealthStatusChanged(boolean result, Map<String, HealthCheckStatus> currentValues, Map<String, HealthCheckStatus> prevValues) {
         for (Entry<String, HealthCheckStatus> entry : currentValues.entrySet()) {
             String key = entry.getKey();
             HealthCheckStatus value = entry.getValue();
-
             if (!prevValues.containsKey(key)) {
                 result = true; //component missing
                 logAlarm(format(COMPONENT_CHANGED_MESSAGE, key, prevValues.get(key), currentValues.get(key)));
                 break;
             }
-
             HealthCheckStatus prevHealthCheckStatus = prevValues.get(key);
-
             if (value != prevHealthCheckStatus) {
                 result = true; //component status changed
                 logAlarm(format(COMPONENT_CHANGED_MESSAGE, key, prevValues.get(key), currentValues.get(key)));
@@ -419,40 +379,35 @@ public class HealthCheckBusinessLogic {
             notPresent = new HashMap<>(prevValues);
             notPresent.keySet().removeAll(currentValues.keySet());
         }
-
         for (String component : notPresent.keySet()) {
             logAlarm(format(COMPONENT_CHANGED_MESSAGE, component, prevValues.get(component), currentValues.get(component)));
         }
     }
+
     @VisibleForTesting
     String buildOnBoardingHealthCheckUrl() {
-
         Configuration.OnboardingConfig onboardingConfig = ConfigurationManager.getConfigurationManager().getConfiguration().getOnboarding();
         if (onboardingConfig != null) {
-            return String.format(hcUrl, onboardingConfig.getProtocol(), onboardingConfig.getHost(),
-                    onboardingConfig.getPort(),onboardingConfig.getHealthCheckUri());
+            return String.format(hcUrl, onboardingConfig.getProtocol(), onboardingConfig.getHost(), onboardingConfig.getPort(),
+                onboardingConfig.getHealthCheckUri());
         }
         log.error("Onboarding health check configuration is missing.");
         return null;
     }
 
     public class HealthCheckScheduledTask implements Runnable {
+
         @Override
         public void run() {
             mdcFieldsHandler.addInfoForErrorAndDebugLogging(LOG_PARTNER_NAME);
             Configuration config = ConfigurationManager.getConfigurationManager().getConfiguration();
             log.trace("Executing BE Health Check Task");
-
             List<HealthCheckInfo> currentBeHealthCheckInfos = getBeHealthCheckInfos();
             boolean healthStatus = healthCheckUtil.getAggregateStatus(currentBeHealthCheckInfos, config.getHealthStatusExclude());
-
             boolean prevHealthStatus = healthCheckUtil.getAggregateStatus(prevBeHealthCheckInfos, config.getHealthStatusExclude());
-
             boolean anyStatusChanged = anyStatusChanged(currentBeHealthCheckInfos, prevBeHealthCheckInfos);
-
             if (prevHealthStatus != healthStatus || anyStatusChanged) {
                 log.trace("BE Health State Changed to {}. Issuing alarm / recovery alarm...", healthStatus);
-
                 prevBeHealthCheckInfos = currentBeHealthCheckInfos;
                 logAlarm(healthStatus);
             }
@@ -465,8 +420,5 @@ public class HealthCheckBusinessLogic {
                 BeEcompErrorManager.getInstance().logBeHealthCheckError(BE_HEALTH_CHECK_STR);
             }
         }
-
-
     }
-
 }
index f9281e1..732bfbf 100644 (file)
  * limitations under the License.
  * ============LICENSE_END=========================================================
  */
-
 package org.openecomp.sdc.be.components.health;
 
+import static org.apache.http.HttpStatus.SC_OK;
+import static org.onap.portalsdk.core.onboarding.util.CipherUtil.decryptPKC;
+import static org.openecomp.sdc.common.api.Constants.HC_COMPONENT_ECOMP_PORTAL;
+import static org.openecomp.sdc.common.api.HealthCheckInfo.HealthCheckStatus.DOWN;
+import static org.openecomp.sdc.common.api.HealthCheckInfo.HealthCheckStatus.UP;
+
 import com.google.common.annotations.VisibleForTesting;
+import java.security.InvalidParameterException;
+import java.util.Base64;
+import java.util.Properties;
+import java.util.UUID;
+import java.util.concurrent.Executors;
+import java.util.concurrent.ScheduledExecutorService;
+import java.util.concurrent.ScheduledFuture;
+import java.util.concurrent.TimeUnit;
+import javax.annotation.PostConstruct;
+import javax.annotation.PreDestroy;
+import javax.ws.rs.core.HttpHeaders;
+import javax.ws.rs.core.MediaType;
 import org.apache.commons.lang.StringUtils;
 import org.onap.portalsdk.core.onboarding.exception.CipherUtilException;
 import org.onap.portalsdk.core.onboarding.util.PortalApiProperties;
@@ -39,25 +56,6 @@ import org.openecomp.sdc.common.http.config.Timeouts;
 import org.openecomp.sdc.common.log.wrappers.Logger;
 import org.springframework.stereotype.Component;
 
-import javax.annotation.PostConstruct;
-import javax.annotation.PreDestroy;
-import javax.ws.rs.core.HttpHeaders;
-import javax.ws.rs.core.MediaType;
-import java.security.InvalidParameterException;
-import java.util.Base64;
-import java.util.Properties;
-import java.util.UUID;
-import java.util.concurrent.Executors;
-import java.util.concurrent.ScheduledExecutorService;
-import java.util.concurrent.ScheduledFuture;
-import java.util.concurrent.TimeUnit;
-
-import static org.apache.http.HttpStatus.SC_OK;
-import static org.onap.portalsdk.core.onboarding.util.CipherUtil.decryptPKC;
-import static org.openecomp.sdc.common.api.Constants.HC_COMPONENT_ECOMP_PORTAL;
-import static org.openecomp.sdc.common.api.HealthCheckInfo.HealthCheckStatus.DOWN;
-import static org.openecomp.sdc.common.api.HealthCheckInfo.HealthCheckStatus.UP;
-
 @Component("portalHealthCheckBusinessLogic")
 public class PortalHealthCheckBuilder {
 
@@ -68,23 +66,20 @@ public class PortalHealthCheckBuilder {
     private static final String PORTAL_ERROR = HC_COMPONENT_ECOMP_PORTAL + " responded with %s status code";
     private String decryptedPortalUser;
     private String decryptedPortalPass;
-    private EcompPortalConfig configuration = null ;
+    private EcompPortalConfig configuration = null;
     private long healthCheckReadTimeout = 20;
     private long reconnectInterval = 5;
-    private HealthCheckScheduledTask healthCheckScheduledTask = null ;
+    private HealthCheckScheduledTask healthCheckScheduledTask = null;
     private final ScheduledExecutorService scheduler = Executors.newScheduledThreadPool(1);
     private ScheduledFuture<?> scheduledFuture = null;
-    private HealthCheckInfo healthCheckInfo = new HealthCheckInfo
-            (HC_COMPONENT_ECOMP_PORTAL, HealthCheckStatus.DOWN, null, CONFIG_IS_MISSING, null);
+    private HealthCheckInfo healthCheckInfo = new HealthCheckInfo(HC_COMPONENT_ECOMP_PORTAL, HealthCheckStatus.DOWN, null, CONFIG_IS_MISSING, null);
 
     @VisibleForTesting
     PortalHealthCheckBuilder init(EcompPortalConfig configuration) throws CipherUtilException {
         log.trace("Enter init method of Portal healthcheck");
-        decryptedPortalUser = decryptPKC
-                (getPortalProperty(PortalPropertiesEnum.USER.value()));
-        decryptedPortalPass = decryptPKC
-                (getPortalProperty(PortalPropertiesEnum.PASSWORD.value()));
-        synchronized (PortalHealthCheckBuilder.class){
+        decryptedPortalUser = decryptPKC(getPortalProperty(PortalPropertiesEnum.USER.value()));
+        decryptedPortalPass = decryptPKC(getPortalProperty(PortalPropertiesEnum.PASSWORD.value()));
+        synchronized (PortalHealthCheckBuilder.class) {
             if (configuration != null) {
                 Integer pollingInterval = configuration.getPollingInterval();
                 if (pollingInterval != null && pollingInterval != 0) {
@@ -96,8 +91,7 @@ public class PortalHealthCheckBuilder {
                 }
                 this.healthCheckScheduledTask = new HealthCheckScheduledTask(configuration);
                 startHealthCheckTask(true);
-            }
-            else {
+            } else {
                 log.error("ECOMP Portal health check configuration is missing.");
             }
         }
@@ -110,7 +104,6 @@ public class PortalHealthCheckBuilder {
         return init(ConfigurationManager.getConfigurationManager().getConfiguration().getEcompPortal());
     }
 
-
     @PreDestroy
     protected void destroy() {
         if (scheduledFuture != null) {
@@ -128,9 +121,9 @@ public class PortalHealthCheckBuilder {
      * @param startTask
      */
     private void startHealthCheckTask(boolean startTask) {
-        synchronized (PortalHealthCheckBuilder.class){
+        synchronized (PortalHealthCheckBuilder.class) {
             if (startTask && this.scheduledFuture == null) {
-                this.scheduledFuture = this.scheduler.scheduleAtFixedRate(this.healthCheckScheduledTask , 0, reconnectInterval, TimeUnit.SECONDS);
+                this.scheduledFuture = this.scheduler.scheduleAtFixedRate(this.healthCheckScheduledTask, 0, reconnectInterval, TimeUnit.SECONDS);
             }
         }
     }
@@ -148,6 +141,7 @@ public class PortalHealthCheckBuilder {
      * Health Check Task Scheduler - infinite check.
      */
     public class HealthCheckScheduledTask implements Runnable {
+
         private final EcompPortalConfig config;
         String healthCheckUrl = buildPortalHealthCheckUrl();
         HealthCheckStatus healthCheckStatus = DOWN;
@@ -155,9 +149,10 @@ public class PortalHealthCheckBuilder {
         String description;
         final int timeout = 3000;
 
-        HealthCheckScheduledTask(final EcompPortalConfig config){
+        HealthCheckScheduledTask(final EcompPortalConfig config) {
             this.config = config;
         }
+
         @Override
         public void run() {
             if (healthCheckUrl != null) {
@@ -177,7 +172,6 @@ public class PortalHealthCheckBuilder {
             } else {
                 description = CONFIG_IS_MISSING;
             }
-
             healthCheckInfo.setHealthCheckStatus(healthCheckStatus);
             healthCheckInfo.setDescription(description);
         }
@@ -195,19 +189,16 @@ public class PortalHealthCheckBuilder {
         final String hcUrl = "%s://%s:%s%s";
         Configuration.EcompPortalConfig configuration = ConfigurationManager.getConfigurationManager().getConfiguration().getEcompPortal();
         if (configuration != null) {
-            return String.format(hcUrl, configuration.getProtocol(), configuration.getHost(),
-                    configuration.getPort(), configuration.getHealthCheckUri());
+            return String
+                .format(hcUrl, configuration.getProtocol(), configuration.getHost(), configuration.getPort(), configuration.getHealthCheckUri());
         }
         log.error("ECOMP Portal health check configuration is missing.");
         return null;
     }
 
-    private Properties createHeaders(){
+    private Properties createHeaders() {
         Properties headers = new Properties();
-        String encodedBasicAuthCred = Base64.getEncoder()
-                .encodeToString((decryptedPortalUser + ":" +
-                        decryptedPortalPass)
-                        .getBytes());
+        String encodedBasicAuthCred = Base64.getEncoder().encodeToString((decryptedPortalUser + ":" + decryptedPortalPass).getBytes());
         headers.put(HttpHeaders.ACCEPT, MediaType.APPLICATION_JSON);
         headers.put(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON);
         headers.put(Constants.X_TRANSACTION_ID_HEADER, UUID.randomUUID().toString());
@@ -226,5 +217,4 @@ public class PortalHealthCheckBuilder {
     public EcompPortalConfig getConfiguration() {
         return ConfigurationManager.getConfigurationManager().getConfiguration().getEcompPortal();
     }
-
 }
index 9206dcb..2fbcabe 100644 (file)
 package org.openecomp.sdc.be.components.impl;
 
 import fj.data.Either;
+import java.util.ArrayList;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
 import lombok.Getter;
 import lombok.Setter;
 import org.apache.commons.lang3.tuple.ImmutablePair;
 import org.openecomp.sdc.be.components.validation.ServiceDistributionValidation;
 import org.openecomp.sdc.be.externalapi.servlet.representation.AbstractResourceInfo;
 import org.openecomp.sdc.be.externalapi.servlet.representation.AbstractTemplateInfo;
-import org.openecomp.sdc.be.model.*;
+import org.openecomp.sdc.be.model.Component;
+import org.openecomp.sdc.be.model.ComponentInstance;
+import org.openecomp.sdc.be.model.RequirementCapabilityRelDef;
+import org.openecomp.sdc.be.model.Resource;
+import org.openecomp.sdc.be.model.Service;
 import org.openecomp.sdc.be.model.category.CategoryDefinition;
 import org.openecomp.sdc.be.model.category.SubCategoryDefinition;
 import org.openecomp.sdc.be.model.jsonjanusgraph.operations.ArtifactsOperations;
 import org.openecomp.sdc.be.model.jsonjanusgraph.operations.InterfaceOperation;
-import org.openecomp.sdc.be.model.operations.api.*;
+import org.openecomp.sdc.be.model.operations.api.IElementOperation;
+import org.openecomp.sdc.be.model.operations.api.IGroupInstanceOperation;
+import org.openecomp.sdc.be.model.operations.api.IGroupOperation;
+import org.openecomp.sdc.be.model.operations.api.IGroupTypeOperation;
+import org.openecomp.sdc.be.model.operations.api.StorageOperationStatus;
 import org.openecomp.sdc.be.model.operations.impl.InterfaceLifecycleOperation;
 import org.openecomp.sdc.common.log.wrappers.Logger;
 import org.openecomp.sdc.exception.ResponseFormat;
 import org.springframework.beans.factory.annotation.Autowired;
 
-import java.util.ArrayList;
-import java.util.HashMap;
-import java.util.List;
-import java.util.Map;
-
 @Getter
 @Setter
 @org.springframework.stereotype.Component("abstractTemplateBusinessLogic")
 public class AbstractTemplateBusinessLogic extends BaseBusinessLogic {
 
     private static final String INITIAL_VERSION = "0.1";
-
     private static final Logger log = Logger.getLogger(AbstractTemplateBusinessLogic.class);
-
-    @Autowired
-    ServiceDistributionValidation serviceDistributionValidation;
-
     @Autowired
     protected ServiceImportManager serviceImportManager;
-
     @Autowired
     protected ServiceBusinessLogic serviceBusinessLogic;
+    @Autowired
+    ServiceDistributionValidation serviceDistributionValidation;
 
     @Autowired
-    public AbstractTemplateBusinessLogic(IElementOperation elementDao, IGroupOperation groupOperation,
-                                         IGroupInstanceOperation groupInstanceOperation, IGroupTypeOperation groupTypeOperation,
-                                         InterfaceOperation interfaceOperation,
+    public AbstractTemplateBusinessLogic(IElementOperation elementDao, IGroupOperation groupOperation, IGroupInstanceOperation groupInstanceOperation,
+                                         IGroupTypeOperation groupTypeOperation, InterfaceOperation interfaceOperation,
                                          InterfaceLifecycleOperation interfaceLifecycleTypeOperation, ArtifactsOperations artifactToscaOperation) {
-        super(elementDao, groupOperation, groupInstanceOperation, groupTypeOperation,
-                interfaceOperation, interfaceLifecycleTypeOperation, artifactToscaOperation);
+        super(elementDao, groupOperation, groupInstanceOperation, groupTypeOperation, interfaceOperation, interfaceLifecycleTypeOperation,
+            artifactToscaOperation);
     }
 
     public Either<AbstractTemplateInfo, ResponseFormat> getServiceAbstractStatus(List<? extends Component> componentList) {
@@ -70,48 +72,45 @@ public class AbstractTemplateBusinessLogic extends BaseBusinessLogic {
         if (componentList == null || componentList.isEmpty()) {
             return Either.left(abstractTemplateInfo);
         }
-
         for (Component curr : componentList) {
             Service service = (Service) curr;
             List<ComponentInstance> componentInstances = service.getComponentInstances();
             List<RequirementCapabilityRelDef> componentInstancesRelations = service.getComponentInstancesRelations();
             abstractTemplateInfo.setServiceUniqueId(service.getUniqueId());
             String serviceUniqueId = abstractTemplateInfo.getServiceUniqueId();
-            Either<Boolean, ResponseFormat> isAbstractResourceData = getEveryServiceAbstractStatus(componentInstances, abstractTemplateInfo, componentInstancesRelations, serviceUniqueId);
+            Either<Boolean, ResponseFormat> isAbstractResourceData = getEveryServiceAbstractStatus(componentInstances, abstractTemplateInfo,
+                componentInstancesRelations, serviceUniqueId);
             if (isAbstractResourceData.isRight()) {
                 return Either.right(isAbstractResourceData.right().value());
             }
         }
-
         return Either.left(abstractTemplateInfo);
     }
 
-    private Either<Boolean, ResponseFormat> getEveryServiceAbstractStatus(List<ComponentInstance> componentInstances, AbstractTemplateInfo abstractTemplateInfo,
-                                                                          List<RequirementCapabilityRelDef> componentInstancesRelations, String serviceUniqueId) {
+    private Either<Boolean, ResponseFormat> getEveryServiceAbstractStatus(List<ComponentInstance> componentInstances,
+                                                                          AbstractTemplateInfo abstractTemplateInfo,
+                                                                          List<RequirementCapabilityRelDef> componentInstancesRelations,
+                                                                          String serviceUniqueId) {
         Map<String, ImmutablePair<String, String>> uuidDuplicatesMap = new HashMap<>();
         List<AbstractResourceInfo> abstractResourceInfoList = new ArrayList<>();
         Boolean isContainAbstractResource = false;
-
         for (ComponentInstance componentInstance : componentInstances) {
             String componentUid = componentInstance.getComponentUid();
             String invariantUUID, resourceUUID;
             if (!uuidDuplicatesMap.containsKey(componentUid)) {
-                Either<Resource, StorageOperationStatus> eitherResource = toscaOperationFacade
-                        .getToscaElement(componentInstance.getComponentUid());
+                Either<Resource, StorageOperationStatus> eitherResource = toscaOperationFacade.getToscaElement(componentInstance.getComponentUid());
                 if (eitherResource.isRight()) {
-                    log.debug("getEveryServiceAbstractStatus: Failed getting resource with UUid: {}",
-                            componentInstance.getComponentUid());
+                    log.debug("getEveryServiceAbstractStatus: Failed getting resource with UUid: {}", componentInstance.getComponentUid());
                     ResponseFormat responseFormat = componentsUtils.getResponseFormat(eitherResource.right().value());
                     return Either.right(responseFormat);
                 } else {
                     final Resource resource = eitherResource.left().value();
                     invariantUUID = resource.getInvariantUUID();
                     resourceUUID = resource.getUUID();
-                    ImmutablePair<String, String> uuidInvariantUUIDPair = new ImmutablePair<>(resourceUUID,
-                            invariantUUID);
+                    ImmutablePair<String, String> uuidInvariantUUIDPair = new ImmutablePair<>(resourceUUID, invariantUUID);
                     uuidDuplicatesMap.put(componentUid, uuidInvariantUUIDPair);
-
-                    isContainAbstractResource = getResourceAbstractStatus(resource, isContainAbstractResource, componentInstancesRelations, serviceUniqueId,abstractResourceInfoList);
+                    isContainAbstractResource = getResourceAbstractStatus(resource, isContainAbstractResource, componentInstancesRelations,
+                        serviceUniqueId, abstractResourceInfoList);
                 }
             }
         }
@@ -120,40 +119,41 @@ public class AbstractTemplateBusinessLogic extends BaseBusinessLogic {
         return Either.left(isContainAbstractResource);
     }
 
-    private boolean getResourceAbstractStatus(Resource resource,Boolean isContainAbstractResource, List<RequirementCapabilityRelDef> componentInstancesRelations,
-                                              String serviceUniqueId,List<AbstractResourceInfo> abstractResourceInfoList) {
+    private boolean getResourceAbstractStatus(Resource resource, Boolean isContainAbstractResource,
+                                              List<RequirementCapabilityRelDef> componentInstancesRelations, String serviceUniqueId,
+                                              List<AbstractResourceInfo> abstractResourceInfoList) {
         boolean isAbstract = getIsAbstract(resource.getCategories());
         log.debug("before if isAbstract,get resource:{}", resource);
         if (isAbstract) {
-            log.debug("getResourceAbstractStatus: resource {} with id {} ,NormalizedName:{},isAbstract{} is abstract resource",
-                    resource.getName(), resource.getUUID(), resource.getNormalizedName(), true);
+            log.debug("getResourceAbstractStatus: resource {} with id {} ,NormalizedName:{},isAbstract{} is abstract resource", resource.getName(),
+                resource.getUUID(), resource.getNormalizedName(), true);
             isContainAbstractResource = true;
             AbstractResourceInfo abstractResourceInfo = getAbstractResourceInfo(resource, componentInstancesRelations, serviceUniqueId);
             abstractResourceInfoList.add(abstractResourceInfo);
         } else {
-            log.debug("getResourceAbstractStatus:resource {} ,with id {} isAbstract{} is missing the isAbstract parameter",
-                    resource.getName(), resource.getUUID(),false);
+            log.debug("getResourceAbstractStatus:resource {} ,with id {} isAbstract{} is missing the isAbstract parameter", resource.getName(),
+                resource.getUUID(), false);
         }
         return isContainAbstractResource;
     }
 
-    private AbstractResourceInfo getAbstractResourceInfo(Resource resource,List<RequirementCapabilityRelDef> componentInstancesRelations,String serviceUniqueId){
+    private AbstractResourceInfo getAbstractResourceInfo(Resource resource, List<RequirementCapabilityRelDef> componentInstancesRelations,
+                                                         String serviceUniqueId) {
         AbstractResourceInfo abstractResourceInfo = new AbstractResourceInfo();
         abstractResourceInfo.setAbstractResourceUUid(resource.getUUID());
         abstractResourceInfo.setAbstractResourceName(resource.getName());
         abstractResourceInfo.setAbstractResourceUniqueId(resource.getUniqueId());
         String uniqueId = serviceUniqueId + "." + resource.getUniqueId() + "." + resource.getNormalizedName();
-
         List<RequirementCapabilityRelDef> resourceComponentInstancesRelations = new ArrayList<>();
-        log.debug("get serviceUniqueId:{},get UniqueId:{},get NormalizedName:{}",
-                serviceUniqueId, resource.getUniqueId(), resource.getNormalizedName());
+        log.debug("get serviceUniqueId:{},get UniqueId:{},get NormalizedName:{}", serviceUniqueId, resource.getUniqueId(),
+            resource.getNormalizedName());
         log.debug("get is Abstract,componentInstancesRelations:{}", componentInstancesRelations);
         for (RequirementCapabilityRelDef componentInstancesRelation : componentInstancesRelations) {
             log.debug("for componentInstancesRelation,get componentInstancesRelation:{}", componentInstancesRelation);
             String toNode = componentInstancesRelation.getToNode();
             String fromNode = componentInstancesRelation.getFromNode();
-            log.debug("for componentInstancesRelation,get fromNode:{},uniqueId:{},ToNode:{},Relationships:{}",
-                    fromNode,uniqueId,toNode,componentInstancesRelation.getRelationships());
+            log.debug("for componentInstancesRelation,get fromNode:{},uniqueId:{},ToNode:{},Relationships:{}", fromNode, uniqueId, toNode,
+                componentInstancesRelation.getRelationships());
             if (toNode.toUpperCase().contains(uniqueId.toUpperCase()) || fromNode.toUpperCase().contains(uniqueId.toUpperCase())) {
                 RequirementCapabilityRelDef resourceComponentInstancesRelation = new RequirementCapabilityRelDef();
                 log.debug("fromNode contains name,get componentInstancesRelation:{}", componentInstancesRelation);
@@ -173,8 +173,7 @@ public class AbstractTemplateBusinessLogic extends BaseBusinessLogic {
         boolean anAbstract = false;
         if (categories != null && !categories.isEmpty()) {
             CategoryDefinition categoryDef = categories.get(0);
-            if (categoryDef != null && categoryDef.getName() != null && categoryDef.getName()
-                    .equals(ImportUtils.Constants.ABSTRACT_CATEGORY_NAME)) {
+            if (categoryDef != null && categoryDef.getName() != null && categoryDef.getName().equals(ImportUtils.Constants.ABSTRACT_CATEGORY_NAME)) {
                 SubCategoryDefinition subCategoryDef = categoryDef.getSubcategories().get(0);
                 if (subCategoryDef != null && subCategoryDef.getName().equals(ImportUtils.Constants.ABSTRACT_SUBCATEGORY)) {
                     anAbstract = true;
index 70ec37c..87ef16f 100644 (file)
@@ -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.
@@ -17,7 +17,6 @@
  * limitations under the License.
  * ============LICENSE_END=========================================================
  */
-
 package org.openecomp.sdc.be.components.impl;
 
 import org.openecomp.sdc.be.model.Service;
@@ -26,6 +25,7 @@ import org.openecomp.sdc.be.model.Service;
  * Created by chaya on 10/22/2017.
  */
 public class ActivationRequestInformation {
+
     private Service serviceToActivate;
     private String workloadContext;
     private String tenant;
index ee6878e..c3efa61 100644 (file)
@@ -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.
  * limitations under the License.
  * ============LICENSE_END=========================================================
  */
-
 package org.openecomp.sdc.be.components.impl;
 
 import fj.data.Either;
+import java.util.List;
 import org.openecomp.sdc.be.config.BeEcompErrorManager;
 import org.openecomp.sdc.be.config.ConfigurationManager;
 import org.openecomp.sdc.be.dao.api.ActionStatus;
@@ -48,57 +48,47 @@ import org.openecomp.sdc.exception.ResponseFormat;
 import org.springframework.beans.factory.annotation.Autowired;
 import org.springframework.stereotype.Component;
 
-import java.util.List;
-
 @Component("additionalInformationBusinessLogic")
 public class AdditionalInformationBusinessLogic extends BaseBusinessLogic {
 
     private static final String CREATE_ADDITIONAL_INFORMATION = "CreateAdditionalInformation";
-
     private static final String UPDATE_ADDITIONAL_INFORMATION = "UpdateAdditionalInformation";
-
     private static final String DELETE_ADDITIONAL_INFORMATION = "DeleteAdditionalInformation";
-
     private static final String GET_ADDITIONAL_INFORMATION = "GetAdditionalInformation";
-
     private static final Logger log = Logger.getLogger(AdditionalInformationBusinessLogic.class.getName());
     private static final String FAILED_TO_LOCK_COMPONENT_ERROR = "Failed to lock component {} error - {}";
-
     private final AdditionalInformationOperation additionalInformationOperation;
 
     @Autowired
-    public AdditionalInformationBusinessLogic(IElementOperation elementDao,
-        IGroupOperation groupOperation,
-        IGroupInstanceOperation groupInstanceOperation,
-        IGroupTypeOperation groupTypeOperation,
-        InterfaceOperation interfaceOperation,
-        InterfaceLifecycleOperation interfaceLifecycleTypeOperation,
-        AdditionalInformationOperation additionalInformationOperation,
-        ArtifactsOperations artifactToscaOperation) {
-        super(elementDao, groupOperation, groupInstanceOperation, groupTypeOperation,
-            interfaceOperation, interfaceLifecycleTypeOperation, artifactToscaOperation);
+    public AdditionalInformationBusinessLogic(IElementOperation elementDao, IGroupOperation groupOperation,
+                                              IGroupInstanceOperation groupInstanceOperation, IGroupTypeOperation groupTypeOperation,
+                                              InterfaceOperation interfaceOperation, InterfaceLifecycleOperation interfaceLifecycleTypeOperation,
+                                              AdditionalInformationOperation additionalInformationOperation,
+                                              ArtifactsOperations artifactToscaOperation) {
+        super(elementDao, groupOperation, groupInstanceOperation, groupTypeOperation, interfaceOperation, interfaceLifecycleTypeOperation,
+            artifactToscaOperation);
         this.additionalInformationOperation = additionalInformationOperation;
     }
 
     /**
      * Create new additional information on resource/service on graph
+     *
      * @param nodeType
      * @param resourceId
      * @param additionalInfoParameterInfo
      * @param userId
      * @return Either<AdditionalInfoParameterInfo, ResponseFormat>
      */
-    public Either<AdditionalInfoParameterInfo, ResponseFormat> createAdditionalInformation(NodeTypeEnum nodeType, String resourceId, AdditionalInfoParameterInfo additionalInfoParameterInfo, String userId) {
-
+    public Either<AdditionalInfoParameterInfo, ResponseFormat> createAdditionalInformation(NodeTypeEnum nodeType, String resourceId,
+                                                                                           AdditionalInfoParameterInfo additionalInfoParameterInfo,
+                                                                                           String userId) {
         validateUserExists(userId);
         Either<AdditionalInfoParameterInfo, ResponseFormat> result = null;
-
         ResponseFormat responseFormat = verifyCanWorkOnComponent(nodeType, resourceId, userId);
         if (responseFormat != null) {
             result = Either.right(responseFormat);
             return result;
         }
-
         // lock component
         StorageOperationStatus lockResult = graphLockOperation.lockComponent(resourceId, nodeType);
         if (lockResult != StorageOperationStatus.OK) {
@@ -113,45 +103,40 @@ public class AdditionalInformationBusinessLogic extends BaseBusinessLogic {
                 result = Either.right(responseFormat);
                 return result;
             }
-
             // validate label
             responseFormat = validateAndConvertKey(additionalInfoParameterInfo, CREATE_ADDITIONAL_INFORMATION);
             if (responseFormat != null) {
                 result = Either.right(responseFormat);
                 return result;
             }
-
             // validate value
             responseFormat = validateAndConvertValue(additionalInfoParameterInfo, CREATE_ADDITIONAL_INFORMATION);
             if (responseFormat != null) {
                 result = Either.right(responseFormat);
                 return result;
             }
-
-            Either<AdditionalInformationDefinition, StorageOperationStatus> addResult = additionalInformationOperation.createAdditionalInformationParameter(nodeType, resourceId, additionalInfoParameterInfo.getKey(),
+            Either<AdditionalInformationDefinition, StorageOperationStatus> addResult = additionalInformationOperation
+                .createAdditionalInformationParameter(nodeType, resourceId, additionalInfoParameterInfo.getKey(),
                     additionalInfoParameterInfo.getValue(), true);
-
             if (addResult.isRight()) {
                 StorageOperationStatus status = addResult.right().value();
                 BeEcompErrorManager.getInstance().logBeSystemError(CREATE_ADDITIONAL_INFORMATION);
                 ActionStatus actionStatus = componentsUtils.convertFromStorageResponseForAdditionalInformation(status);
-                result = Either.right(componentsUtils.getResponseFormatAdditionalProperty(actionStatus, additionalInfoParameterInfo, nodeType, AdditionalInformationEnum.Label));
+                result = Either.right(componentsUtils
+                    .getResponseFormatAdditionalProperty(actionStatus, additionalInfoParameterInfo, nodeType, AdditionalInformationEnum.Label));
                 return result;
-
             } else {
                 AdditionalInformationDefinition informationDefinition = addResult.left().value();
-
-                AdditionalInfoParameterInfo createdAI = findAdditionInformationKey(informationDefinition.getParameters(), additionalInfoParameterInfo.getKey());
+                AdditionalInfoParameterInfo createdAI = findAdditionInformationKey(informationDefinition.getParameters(),
+                    additionalInfoParameterInfo.getKey());
                 result = Either.left(createdAI);
                 return result;
             }
-
         } finally {
             commitOrRollback(result);
             // unlock component
             graphLockOperation.unlockComponent(resourceId, nodeType);
         }
-
     }
 
     /**
@@ -162,13 +147,12 @@ public class AdditionalInformationBusinessLogic extends BaseBusinessLogic {
      */
     private ResponseFormat validateAndConvertValue(AdditionalInfoParameterInfo additionalInfoParameterInfo, String context) {
         ResponseFormat result = null;
-
         String value = additionalInfoParameterInfo.getValue();
         log.debug("Going to validate additional information value {}", value);
-
         Either<String, ResponseFormat> valueValidRes = validateValue(value);
         if (valueValidRes.isRight()) {
-            BeEcompErrorManager.getInstance().logBeInvalidValueError(context, additionalInfoParameterInfo.getValue(), "additional information value", "string");
+            BeEcompErrorManager.getInstance()
+                .logBeInvalidValueError(context, additionalInfoParameterInfo.getValue(), "additional information value", "string");
             result = valueValidRes.right().value();
         } else {
             String newValue = valueValidRes.left().value();
@@ -187,21 +171,18 @@ public class AdditionalInformationBusinessLogic extends BaseBusinessLogic {
      * @return
      */
     private ResponseFormat validateAndConvertKey(AdditionalInfoParameterInfo additionalInfoParameterInfo, String context) {
-
         String key = additionalInfoParameterInfo.getKey();
         log.debug("Going to validate additional information key {}", key);
-
         ResponseFormat result = null;
         ResponseFormat responseFormat;
         Either<String, ResponseFormat> validateKeyRes = validateAndNormalizeKey(key);
         if (validateKeyRes.isRight()) {
             responseFormat = validateKeyRes.right().value();
-            BeEcompErrorManager.getInstance().logBeInvalidValueError(context, additionalInfoParameterInfo.getKey(), "additional information label", "string");
+            BeEcompErrorManager.getInstance()
+                .logBeInvalidValueError(context, additionalInfoParameterInfo.getKey(), "additional information label", "string");
             result = responseFormat;
-
         } else {
             String convertedKey = validateKeyRes.left().value();
-
             if (log.isTraceEnabled() && key != null && !key.equals(convertedKey)) {
                 log.trace("The additional information key {} was normalized to {}", key, convertedKey);
             }
@@ -218,26 +199,29 @@ public class AdditionalInformationBusinessLogic extends BaseBusinessLogic {
      * @param additionalInfoParameterInfo
      * @return response format in case the maximal number has been reached.
      */
-    private ResponseFormat validateMaxSizeNotReached(NodeTypeEnum nodeType, String componentId, AdditionalInfoParameterInfo additionalInfoParameterInfo) {
-
+    private ResponseFormat validateMaxSizeNotReached(NodeTypeEnum nodeType, String componentId,
+                                                     AdditionalInfoParameterInfo additionalInfoParameterInfo) {
         ResponseFormat result;
-        Integer additionalInformationMaxNumberOfKeys = ConfigurationManager.getConfigurationManager().getConfiguration().getAdditionalInformationMaxNumberOfKeys();
-
-        Either<Integer, StorageOperationStatus> checkRes = additionalInformationOperation.getNumberOfAdditionalInformationParameters(nodeType, componentId, true);
+        Integer additionalInformationMaxNumberOfKeys = ConfigurationManager.getConfigurationManager().getConfiguration()
+            .getAdditionalInformationMaxNumberOfKeys();
+        Either<Integer, StorageOperationStatus> checkRes = additionalInformationOperation
+            .getNumberOfAdditionalInformationParameters(nodeType, componentId, true);
         if (checkRes.isRight()) {
             StorageOperationStatus status = checkRes.right().value();
-
             ActionStatus actionStatus = componentsUtils.convertFromStorageResponseForAdditionalInformation(status);
-            result = componentsUtils.getResponseFormatAdditionalProperty(actionStatus, additionalInfoParameterInfo, nodeType, AdditionalInformationEnum.None);
+            result = componentsUtils
+                .getResponseFormatAdditionalProperty(actionStatus, additionalInfoParameterInfo, nodeType, AdditionalInformationEnum.None);
             return result;
         }
         Integer currentNumberOfProperties = checkRes.left().value();
         if (currentNumberOfProperties >= additionalInformationMaxNumberOfKeys) {
-            log.info("The current number of additional information properties is {}. The maximum allowed additional information properties is {}", currentNumberOfProperties, currentNumberOfProperties);
-            result = componentsUtils.getResponseFormatAdditionalProperty(ActionStatus.ADDITIONAL_INFORMATION_MAX_NUMBER_REACHED, additionalInfoParameterInfo, nodeType, AdditionalInformationEnum.None);
+            log.info("The current number of additional information properties is {}. The maximum allowed additional information properties is {}",
+                currentNumberOfProperties, currentNumberOfProperties);
+            result = componentsUtils
+                .getResponseFormatAdditionalProperty(ActionStatus.ADDITIONAL_INFORMATION_MAX_NUMBER_REACHED, additionalInfoParameterInfo, nodeType,
+                    AdditionalInformationEnum.None);
             return result;
         }
-
         return null;
     }
 
@@ -248,24 +232,20 @@ public class AdditionalInformationBusinessLogic extends BaseBusinessLogic {
      * @return
      */
     private Either<String, ResponseFormat> validateValue(String value) {
-
         boolean isNonEmptyString = ValidationUtils.validateStringNotEmpty(value);
         if (!isNonEmptyString) {
             return Either.right(componentsUtils.getResponseFormatAdditionalProperty(ActionStatus.ADDITIONAL_INFORMATION_EMPTY_STRING_NOT_ALLOWED));
         }
-
         boolean valid = StringValidator.getInstance().isValid(value, null);
         if (!valid) {
-            return Either.right(componentsUtils.getResponseFormatAdditionalProperty(ActionStatus.ADDITIONAL_INFORMATION_VALUE_NOT_ALLOWED_CHARACTERS, new AdditionalInfoParameterInfo(null, value), null, AdditionalInformationEnum.Value));
+            return Either.right(componentsUtils.getResponseFormatAdditionalProperty(ActionStatus.ADDITIONAL_INFORMATION_VALUE_NOT_ALLOWED_CHARACTERS,
+                new AdditionalInfoParameterInfo(null, value), null, AdditionalInformationEnum.Value));
         }
-
         String converted = StringConvertor.getInstance().convert(value, null, null);
-
         return Either.left(converted);
     }
 
     private AdditionalInfoParameterInfo findAdditionInformationKey(List<AdditionalInfoParameterInfo> parameters, String key) {
-
         for (AdditionalInfoParameterInfo infoParameterInfo : parameters) {
             if (infoParameterInfo.getKey().equals(key)) {
                 return infoParameterInfo;
@@ -276,27 +256,31 @@ public class AdditionalInformationBusinessLogic extends BaseBusinessLogic {
 
     /**
      * validate and normalize the key
+     *
      * @param key
      * @return Either<String, ResponseFormat>
      */
     private Either<String, ResponseFormat> validateAndNormalizeKey(String key) {
-
         AdditionalInfoParameterInfo additionalInfoParameterInfo = new AdditionalInfoParameterInfo();
         additionalInfoParameterInfo.setKey(key);
-
         String normKey = ValidationUtils.normalizeAdditionalInformation(key);
         boolean isNonEmptyString = ValidationUtils.validateStringNotEmpty(normKey);
         if (!isNonEmptyString) {
-            return Either.right(componentsUtils.getResponseFormatAdditionalProperty(ActionStatus.ADDITIONAL_INFORMATION_EMPTY_STRING_NOT_ALLOWED, null, null, AdditionalInformationEnum.Label));
+            return Either.right(componentsUtils
+                .getResponseFormatAdditionalProperty(ActionStatus.ADDITIONAL_INFORMATION_EMPTY_STRING_NOT_ALLOWED, null, null,
+                    AdditionalInformationEnum.Label));
         }
         boolean isValidString = ValidationUtils.validateAdditionalInformationKeyName(normKey);
         if (!isValidString) {
             if (!ValidationUtils.validateLength(normKey, ValidationUtils.ADDITIONAL_INFORMATION_KEY_MAX_LENGTH)) {
-                return Either.right(componentsUtils.getResponseFormatAdditionalProperty(ActionStatus.ADDITIONAL_INFORMATION_EXCEEDS_LIMIT, additionalInfoParameterInfo, null, AdditionalInformationEnum.Label));
+                return Either.right(componentsUtils
+                    .getResponseFormatAdditionalProperty(ActionStatus.ADDITIONAL_INFORMATION_EXCEEDS_LIMIT, additionalInfoParameterInfo, null,
+                        AdditionalInformationEnum.Label));
             }
-            return Either.right(componentsUtils.getResponseFormatAdditionalProperty(ActionStatus.ADDITIONAL_INFORMATION_KEY_NOT_ALLOWED_CHARACTERS, additionalInfoParameterInfo, null, AdditionalInformationEnum.Label));
+            return Either.right(componentsUtils
+                .getResponseFormatAdditionalProperty(ActionStatus.ADDITIONAL_INFORMATION_KEY_NOT_ALLOWED_CHARACTERS, additionalInfoParameterInfo,
+                    null, AdditionalInformationEnum.Label));
         }
-
         return Either.left(normKey);
     }
 
@@ -309,11 +293,11 @@ public class AdditionalInformationBusinessLogic extends BaseBusinessLogic {
      * @param userId
      * @return
      */
-    public Either<AdditionalInfoParameterInfo, ResponseFormat> updateAdditionalInformation(NodeTypeEnum nodeType, String resourceId, AdditionalInfoParameterInfo additionalInfoParameterInfo, String userId) {
-
+    public Either<AdditionalInfoParameterInfo, ResponseFormat> updateAdditionalInformation(NodeTypeEnum nodeType, String resourceId,
+                                                                                           AdditionalInfoParameterInfo additionalInfoParameterInfo,
+                                                                                           String userId) {
         validateUserExists(userId);
         Either<AdditionalInfoParameterInfo, ResponseFormat> result = null;
-
         ResponseFormat responseFormat = verifyCanWorkOnComponent(nodeType, resourceId, userId);
         if (responseFormat != null) {
             result = Either.right(responseFormat);
@@ -328,42 +312,39 @@ public class AdditionalInformationBusinessLogic extends BaseBusinessLogic {
             return result;
         }
         try {
-
             // validate input
             responseFormat = validateAndConvertKey(additionalInfoParameterInfo, UPDATE_ADDITIONAL_INFORMATION);
             if (responseFormat != null) {
                 result = Either.right(responseFormat);
                 return result;
             }
-
             responseFormat = validateAndConvertValue(additionalInfoParameterInfo, UPDATE_ADDITIONAL_INFORMATION);
             if (responseFormat != null) {
                 result = Either.right(responseFormat);
                 return result;
             }
-
-            Either<AdditionalInformationDefinition, StorageOperationStatus> addResult = additionalInformationOperation.updateAdditionalInformationParameter(nodeType, resourceId, additionalInfoParameterInfo.getUniqueId(),
+            Either<AdditionalInformationDefinition, StorageOperationStatus> addResult = additionalInformationOperation
+                .updateAdditionalInformationParameter(nodeType, resourceId, additionalInfoParameterInfo.getUniqueId(),
                     additionalInfoParameterInfo.getKey(), additionalInfoParameterInfo.getValue(), true);
-
             if (addResult.isRight()) {
                 StorageOperationStatus status = addResult.right().value();
                 BeEcompErrorManager.getInstance().logBeSystemError(UPDATE_ADDITIONAL_INFORMATION);
                 ActionStatus actionStatus = componentsUtils.convertFromStorageResponseForAdditionalInformation(status);
-                result = Either.right(componentsUtils.getResponseFormatAdditionalProperty(actionStatus, additionalInfoParameterInfo, nodeType, AdditionalInformationEnum.None));
+                result = Either.right(componentsUtils
+                    .getResponseFormatAdditionalProperty(actionStatus, additionalInfoParameterInfo, nodeType, AdditionalInformationEnum.None));
                 return result;
             } else {
                 AdditionalInformationDefinition informationDefinition = addResult.left().value();
-                AdditionalInfoParameterInfo parameterInfo = findAdditionInformationKey(informationDefinition.getParameters(), additionalInfoParameterInfo.getKey());
+                AdditionalInfoParameterInfo parameterInfo = findAdditionInformationKey(informationDefinition.getParameters(),
+                    additionalInfoParameterInfo.getKey());
                 result = Either.left(parameterInfo);
                 return result;
             }
-
         } finally {
             commitOrRollback(result);
             // unlock component
             graphLockOperation.unlockComponent(resourceId, nodeType);
         }
-
     }
 
     /**
@@ -375,11 +356,11 @@ public class AdditionalInformationBusinessLogic extends BaseBusinessLogic {
      * @param userId
      * @return
      */
-    public Either<AdditionalInfoParameterInfo, ResponseFormat> deleteAdditionalInformation(NodeTypeEnum nodeType, String resourceId, AdditionalInfoParameterInfo additionalInfoParameterInfo, String userId) {
-
+    public Either<AdditionalInfoParameterInfo, ResponseFormat> deleteAdditionalInformation(NodeTypeEnum nodeType, String resourceId,
+                                                                                           AdditionalInfoParameterInfo additionalInfoParameterInfo,
+                                                                                           String userId) {
         validateUserExists(userId);
         Either<AdditionalInfoParameterInfo, ResponseFormat> result = null;
-
         ResponseFormat responseFormat = verifyCanWorkOnComponent(nodeType, resourceId, userId);
         if (responseFormat != null) {
             return Either.right(responseFormat);
@@ -392,41 +373,38 @@ public class AdditionalInformationBusinessLogic extends BaseBusinessLogic {
             result = Either.right(componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR));
             return result;
         }
-
         try {
-
-            Either<AdditionalInfoParameterInfo, StorageOperationStatus> findIdRes = additionalInformationOperation.getAdditionalInformationParameter(nodeType, resourceId, additionalInfoParameterInfo.getUniqueId(), true);
+            Either<AdditionalInfoParameterInfo, StorageOperationStatus> findIdRes = additionalInformationOperation
+                .getAdditionalInformationParameter(nodeType, resourceId, additionalInfoParameterInfo.getUniqueId(), true);
             if (findIdRes.isRight()) {
                 StorageOperationStatus status = findIdRes.right().value();
                 if (status != StorageOperationStatus.NOT_FOUND) {
                     BeEcompErrorManager.getInstance().logBeSystemError(GET_ADDITIONAL_INFORMATION);
                 }
                 ActionStatus actionStatus = componentsUtils.convertFromStorageResponseForAdditionalInformation(status);
-                result = Either.right(componentsUtils.getResponseFormatAdditionalProperty(actionStatus, additionalInfoParameterInfo, nodeType, AdditionalInformationEnum.None));
+                result = Either.right(componentsUtils
+                    .getResponseFormatAdditionalProperty(actionStatus, additionalInfoParameterInfo, nodeType, AdditionalInformationEnum.None));
                 return result;
             }
-
             AdditionalInfoParameterInfo foundAdditionalInfo = findIdRes.left().value();
-
-            Either<AdditionalInformationDefinition, StorageOperationStatus> addResult = additionalInformationOperation.deleteAdditionalInformationParameter(nodeType, resourceId, additionalInfoParameterInfo.getUniqueId(), true);
-
+            Either<AdditionalInformationDefinition, StorageOperationStatus> addResult = additionalInformationOperation
+                .deleteAdditionalInformationParameter(nodeType, resourceId, additionalInfoParameterInfo.getUniqueId(), true);
             if (addResult.isRight()) {
                 StorageOperationStatus status = addResult.right().value();
                 BeEcompErrorManager.getInstance().logBeDaoSystemError(DELETE_ADDITIONAL_INFORMATION);
                 ActionStatus actionStatus = componentsUtils.convertFromStorageResponseForAdditionalInformation(status);
-                result = Either.right(componentsUtils.getResponseFormatAdditionalProperty(actionStatus, additionalInfoParameterInfo, nodeType, AdditionalInformationEnum.None));
+                result = Either.right(componentsUtils
+                    .getResponseFormatAdditionalProperty(actionStatus, additionalInfoParameterInfo, nodeType, AdditionalInformationEnum.None));
                 return result;
             } else {
                 result = Either.left(foundAdditionalInfo);
                 return result;
             }
-
         } finally {
             commitOrRollback(result);
             // unlock component
             graphLockOperation.unlockComponent(resourceId, nodeType);
         }
-
     }
 
     /**
@@ -436,31 +414,26 @@ public class AdditionalInformationBusinessLogic extends BaseBusinessLogic {
      * @param userId
      * @return
      */
-    public Either<AdditionalInfoParameterInfo, ResponseFormat> getAdditionalInformation(NodeTypeEnum nodeType, String resourceId, AdditionalInfoParameterInfo additionalInfoParameterInfo, String userId) {
-
+    public Either<AdditionalInfoParameterInfo, ResponseFormat> getAdditionalInformation(NodeTypeEnum nodeType, String resourceId,
+                                                                                        AdditionalInfoParameterInfo additionalInfoParameterInfo,
+                                                                                        String userId) {
         validateUserExists(userId);
         Either<AdditionalInfoParameterInfo, ResponseFormat> result = null;
-
         try {
-
-            Either<AdditionalInfoParameterInfo, StorageOperationStatus> findIdRes = additionalInformationOperation.getAdditionalInformationParameter(nodeType, resourceId, additionalInfoParameterInfo.getUniqueId(), true);
-
+            Either<AdditionalInfoParameterInfo, StorageOperationStatus> findIdRes = additionalInformationOperation
+                .getAdditionalInformationParameter(nodeType, resourceId, additionalInfoParameterInfo.getUniqueId(), true);
             if (findIdRes.isRight()) {
                 StorageOperationStatus status = findIdRes.right().value();
                 ActionStatus actionStatus = componentsUtils.convertFromStorageResponseForAdditionalInformation(status);
-                result = Either.right(componentsUtils.getResponseFormatAdditionalProperty(actionStatus, additionalInfoParameterInfo, nodeType, AdditionalInformationEnum.None));
+                result = Either.right(componentsUtils
+                    .getResponseFormatAdditionalProperty(actionStatus, additionalInfoParameterInfo, nodeType, AdditionalInformationEnum.None));
             }
-
             AdditionalInfoParameterInfo foundAdditionalInfo = findIdRes.left().value();
-
             result = Either.left(foundAdditionalInfo);
-
             return result;
-
         } finally {
             commitOrRollback(result);
         }
-
     }
 
     /**
@@ -471,15 +444,13 @@ public class AdditionalInformationBusinessLogic extends BaseBusinessLogic {
      * @param userId
      * @return
      */
-    public Either<AdditionalInformationDefinition, ResponseFormat> getAllAdditionalInformation(NodeTypeEnum nodeType, String resourceId, String userId) {
-
+    public Either<AdditionalInformationDefinition, ResponseFormat> getAllAdditionalInformation(NodeTypeEnum nodeType, String resourceId,
+                                                                                               String userId) {
         validateUserExists(userId);
-
         Either<AdditionalInformationDefinition, ResponseFormat> result = null;
-
         try {
-
-            Either<AdditionalInformationDefinition, JanusGraphOperationStatus> findIdRes = additionalInformationOperation.getAllAdditionalInformationParameters(nodeType, resourceId, false);
+            Either<AdditionalInformationDefinition, JanusGraphOperationStatus> findIdRes = additionalInformationOperation
+                .getAllAdditionalInformationParameters(nodeType, resourceId, false);
             if (findIdRes.isRight()) {
                 StorageOperationStatus status = DaoStatusConverter.convertJanusGraphStatusToStorageStatus(findIdRes.right().value());
                 ActionStatus actionStatus = componentsUtils.convertFromStorageResponseForAdditionalInformation(status);
@@ -488,39 +459,33 @@ public class AdditionalInformationBusinessLogic extends BaseBusinessLogic {
                 AdditionalInformationDefinition informationDefinition = findIdRes.left().value();
                 result = Either.left(informationDefinition);
             }
-
             return result;
-
         } finally {
             commitOrRollback(result);
         }
-
     }
 
     private ResponseFormat verifyCanWorkOnComponent(NodeTypeEnum nodeType, String resourceId, String userId) {
-
         switch (nodeType) {
-        case Resource:
+            case Resource:
+                // verify that resource is checked-out and the user is the last
 
-            // verify that resource is checked-out and the user is the last
-            // updater
-            if (!ComponentValidationUtils.canWorkOnComponent(resourceId, toscaOperationFacade, userId)) {
-                return componentsUtils.getResponseFormat(ActionStatus.RESTRICTED_OPERATION);
-            }
-            break;
-        case Service:
+                // updater
+                if (!ComponentValidationUtils.canWorkOnComponent(resourceId, toscaOperationFacade, userId)) {
+                    return componentsUtils.getResponseFormat(ActionStatus.RESTRICTED_OPERATION);
+                }
+                break;
+            case Service:
+                // verify that resource is checked-out and the user is the last
 
-            // verify that resource is checked-out and the user is the last
-            // updater
-            if (!ComponentValidationUtils.canWorkOnComponent(resourceId, toscaOperationFacade, userId)) {
-                return componentsUtils.getResponseFormat(ActionStatus.RESTRICTED_OPERATION);
-            }
-            break;
-        default:
-            return componentsUtils.getResponseFormat(ActionStatus.INVALID_CONTENT, nodeType.getName());
+                // updater
+                if (!ComponentValidationUtils.canWorkOnComponent(resourceId, toscaOperationFacade, userId)) {
+                    return componentsUtils.getResponseFormat(ActionStatus.RESTRICTED_OPERATION);
+                }
+                break;
+            default:
+                return componentsUtils.getResponseFormat(ActionStatus.INVALID_CONTENT, nodeType.getName());
         }
-
         return null;
     }
-
 }
index b0af789..f8d4871 100644 (file)
@@ -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.
  * limitations under the License.
  * ============LICENSE_END=========================================================
  */
-
 package org.openecomp.sdc.be.components.impl;
 
+import static org.apache.commons.collections.CollectionUtils.isNotEmpty;
+
+import java.util.ArrayList;
+import java.util.HashSet;
+import java.util.List;
+import java.util.Map;
+import java.util.Set;
 import org.openecomp.sdc.be.components.validation.AnnotationValidator;
 import org.openecomp.sdc.be.dao.utils.MapUtil;
 import org.openecomp.sdc.be.datatypes.elements.Annotation;
@@ -30,29 +36,19 @@ import org.openecomp.sdc.be.model.PropertyDefinition;
 import org.openecomp.sdc.be.model.operations.impl.AnnotationTypeOperations;
 import org.springframework.stereotype.Component;
 
-import java.util.ArrayList;
-import java.util.HashSet;
-import java.util.List;
-import java.util.Map;
-import java.util.Set;
-
-import static org.apache.commons.collections.CollectionUtils.isNotEmpty;
-
 @Component
 public class AnnotationBusinessLogic {
 
     private final AnnotationTypeOperations annotationTypeOperations;
-
     private final AnnotationValidator annotationValidator;
 
-    public AnnotationBusinessLogic(AnnotationTypeOperations annotationTypeOperations,
-                                   AnnotationValidator annotationValidator){
+    public AnnotationBusinessLogic(AnnotationTypeOperations annotationTypeOperations, AnnotationValidator annotationValidator) {
         this.annotationTypeOperations = annotationTypeOperations;
         this.annotationValidator = annotationValidator;
     }
 
     public void validateAndMergeAnnotationsAndAssignToInput(Map<String, InputDefinition> inputs) {
-        if (!inputs.isEmpty()){
+        if (!inputs.isEmpty()) {
             for (InputDefinition input : inputs.values()) {
                 List<Annotation> inputAnnotationList = input.getAnnotations();
                 if (isNotEmpty(inputAnnotationList)) {
@@ -72,11 +68,13 @@ public class AnnotationBusinessLogic {
 
     private void validateMergeAndSetAnnoProps(Annotation annotation, AnnotationTypeDefinition dbAnnotationTypeDefinition) {
         annotationValidator.validateAnnotationsProperties(annotation, dbAnnotationTypeDefinition);
-        List<PropertyDataDefinition> mergedPropertiesList = mergePropsOfAnnoDataTypeWithParsedAnnoProps(annotation.getProperties(), dbAnnotationTypeDefinition.getProperties());
+        List<PropertyDataDefinition> mergedPropertiesList = mergePropsOfAnnoDataTypeWithParsedAnnoProps(annotation.getProperties(),
+            dbAnnotationTypeDefinition.getProperties());
         annotation.setProperties(mergedPropertiesList);
     }
 
-    private List<PropertyDataDefinition> mergePropsOfAnnoDataTypeWithParsedAnnoProps(List<PropertyDataDefinition> annoProperties, List<PropertyDefinition> typePropertiesList) {
+    private List<PropertyDataDefinition> mergePropsOfAnnoDataTypeWithParsedAnnoProps(List<PropertyDataDefinition> annoProperties,
+                                                                                     List<PropertyDefinition> typePropertiesList) {
         Set<PropertyDataDefinition> mergedPropertiesSet = new HashSet<>(typePropertiesList);
         Map<String, PropertyDefinition> typePropsMap = MapUtil.toMap(typePropertiesList, PropertyDefinition::getName);
         for (PropertyDataDefinition propertyDataDefinitionObject : annoProperties) {
@@ -88,5 +86,4 @@ public class AnnotationBusinessLogic {
         }
         return new ArrayList<>(mergedPropertiesSet);
     }
-
 }
index 15e9a77..34b01c7 100644 (file)
  */
 package org.openecomp.sdc.be.components.impl;
 
+import static org.openecomp.sdc.common.datastructure.FunctionalInterfaces.wrapWithTryCatch;
+
 import com.google.common.annotations.VisibleForTesting;
 import fj.data.Either;
+import java.util.HashMap;
+import java.util.HashSet;
+import java.util.LinkedList;
+import java.util.List;
+import java.util.Map;
+import java.util.stream.Collectors;
 import org.openecomp.sdc.be.catalog.enums.ChangeTypeEnum;
 import org.openecomp.sdc.be.components.impl.exceptions.ByActionStatusComponentException;
 import org.openecomp.sdc.be.components.validation.AccessValidations;
@@ -44,108 +52,88 @@ import org.openecomp.sdc.common.log.enums.EcompLoggerErrorCode;
 import org.openecomp.sdc.common.log.wrappers.Logger;
 import org.openecomp.sdc.exception.ResponseFormat;
 
-import java.util.HashMap;
-import java.util.HashSet;
-import java.util.LinkedList;
-import java.util.List;
-import java.util.Map;
-import java.util.stream.Collectors;
-
-import static org.openecomp.sdc.common.datastructure.FunctionalInterfaces.wrapWithTryCatch;
-
-
 @org.springframework.stereotype.Component
 public class ArchiveBusinessLogic {
 
     private static final Logger log = Logger.getLogger(ArchiveBusinessLogic.class.getName());
-
     private final JanusGraphDao janusGraphDao;
     private final AccessValidations accessValidations;
     private final ArchiveOperation archiveOperation;
     private final ToscaOperationFacade toscaOperationFacade;
     private final ComponentsUtils componentUtils;
-       private final CatalogOperation catalogOperations;
+    private final CatalogOperation catalogOperations;
 
-    public ArchiveBusinessLogic(JanusGraphDao janusGraphDao, AccessValidations accessValidations, ArchiveOperation archiveOperation, ToscaOperationFacade tof, ComponentsUtils componentsUtils,
-       CatalogOperation catalogOperations) {
+    public ArchiveBusinessLogic(JanusGraphDao janusGraphDao, AccessValidations accessValidations, ArchiveOperation archiveOperation,
+                                ToscaOperationFacade tof, ComponentsUtils componentsUtils, CatalogOperation catalogOperations) {
         this.janusGraphDao = janusGraphDao;
         this.accessValidations = accessValidations;
         this.archiveOperation = archiveOperation;
         this.toscaOperationFacade = tof;
         this.componentUtils = componentsUtils;
-               this.catalogOperations = catalogOperations;
+        this.catalogOperations = catalogOperations;
     }
 
     public void archiveComponent(String containerComponentType, String userId, String componentId) {
         User user = accessValidations.userIsAdminOrDesigner(userId, containerComponentType + "_ARCHIVE");
         Either<List<String>, ActionStatus> result = this.archiveOperation.archiveComponent(componentId);
-
-        if (result.isRight()){
+        if (result.isRight()) {
             throw new ByActionStatusComponentException(result.right().value(), componentId);
         }
         this.auditAction(ArchiveOperation.Action.ARCHIVE, result.left().value(), user, containerComponentType);
-               // Send Archive Notification To Facade
-               wrapWithTryCatch(() -> sendNotificationToFacade(componentId, ChangeTypeEnum.ARCHIVE));
+        // Send Archive Notification To Facade
+        wrapWithTryCatch(() -> sendNotificationToFacade(componentId, ChangeTypeEnum.ARCHIVE));
     }
 
     public void restoreComponent(String containerComponentType, String userId, String componentId) {
         User user = accessValidations.userIsAdminOrDesigner(userId, containerComponentType + "_RESTORE");
         Either<List<String>, ActionStatus> result = this.archiveOperation.restoreComponent(componentId);
-        if (result.isRight()){
+        if (result.isRight()) {
             throw new ByActionStatusComponentException(result.right().value(), componentId);
         }
         this.auditAction(ArchiveOperation.Action.RESTORE, result.left().value(), user, containerComponentType);
-               // Send Archive Notification To Facade
-               wrapWithTryCatch(() -> sendNotificationToFacade(componentId, ChangeTypeEnum.RESTORE));
+        // Send Archive Notification To Facade
+        wrapWithTryCatch(() -> sendNotificationToFacade(componentId, ChangeTypeEnum.RESTORE));
     }
 
-    public List<String> onVspArchive(String userId, List<String> csarUuids){
+    public List<String> onVspArchive(String userId, List<String> csarUuids) {
         return this.onVspArchiveOrRestore(userId, csarUuids, ArchiveOperation.Action.ARCHIVE);
     }
 
-    public List<String> onVspRestore(String userId, List<String> csarUuids){
+    public List<String> onVspRestore(String userId, List<String> csarUuids) {
         return this.onVspArchiveOrRestore(userId, csarUuids, ArchiveOperation.Action.RESTORE);
     }
 
     private List<String> onVspArchiveOrRestore(String userId, List<String> csarUuids, ArchiveOperation.Action action) {
-
         accessValidations.userIsAdminOrDesigner(userId, action.name() + "_VSP");
-
         ActionStatus actionStatus;
         List<String> failedCsarIDs = new LinkedList<>();
-
         for (String csarUuid : csarUuids) {
             try {
-
                 if (action == ArchiveOperation.Action.ARCHIVE) {
                     actionStatus = this.archiveOperation.onVspArchived(csarUuid);
                 } else {
                     actionStatus = this.archiveOperation.onVspRestored(csarUuid);
                 }
-
                 //If not found VFs with this CSAR ID we still want a success (nothing is actually done)
                 if (actionStatus == ActionStatus.RESOURCE_NOT_FOUND) {
                     actionStatus = ActionStatus.OK;
                 }
-
                 if (actionStatus != ActionStatus.OK) {
                     failedCsarIDs.add(csarUuid);
                 }
-
             } catch (Exception e) {
                 log.error("Failed to handle notification: {} on VSP for csarUuid: {}", action.name(), csarUuid);
                 log.error("Exception Thrown:", e);
                 failedCsarIDs.add(csarUuid);
             }
         }
-
         return failedCsarIDs;
     }
 
     public Map<String, List<CatalogComponent>> getArchiveComponents(String userId, List<OriginTypeEnum> excludeTypes) {
         try {
-
-            Either<List<CatalogComponent>, StorageOperationStatus> components = toscaOperationFacade.getCatalogOrArchiveComponents(false, excludeTypes);
+            Either<List<CatalogComponent>, StorageOperationStatus> components = toscaOperationFacade
+                .getCatalogOrArchiveComponents(false, excludeTypes);
             if (components.isLeft()) {
                 List<CatalogComponent> comps = components.left().value();
                 return comps.stream().collect(Collectors.groupingBy(cmpt -> ComponentTypeEnum.findParamByType(cmpt.getComponentType())));
@@ -153,52 +141,54 @@ public class ArchiveBusinessLogic {
                 log.info("No components found");
                 return new HashMap();
             }
-        } catch (Exception e){
+        } catch (Exception e) {
             log.error("Error fetching archived elements", e);
             throw e;
-        }
-        finally {
+        } finally {
             janusGraphDao.commit();
         }
     }
 
-
     @VisibleForTesting
     void auditAction(ArchiveOperation.Action action, List<String> affectedCompIds, User user, String containerComponentType) {
         String comment = String.format("All versions of this component were %s", action == ArchiveOperation.Action.ARCHIVE ? "archived" : "restored");
         HashSet<String> auditDoneUUIDs = new HashSet<>();
-        for (String componentId : affectedCompIds){
+        for (String componentId : affectedCompIds) {
             Either<Component, StorageOperationStatus> result = toscaOperationFacade.getToscaElement(componentId, new ComponentParametersView());
             if (result.isRight()) {
-                log.error(EcompLoggerErrorCode.DATA_ERROR, null, "GetToscaElement",
-                        result.right().value().name() + "for component with id {}", componentId);
+                log.error(EcompLoggerErrorCode.DATA_ERROR, null, "GetToscaElement", result.right().value().name() + "for component with id {}",
+                    componentId);
                 continue;
             }
             if (auditDoneUUIDs.add(result.left().value().getUUID())) {
                 //a component with this UUID is not added to audit DB/log for current archive/restore operation yet - add to audit DB now
-                AuditingActionEnum auditAction = action == ArchiveOperation.Action.ARCHIVE ? AuditingActionEnum.ARCHIVE_COMPONENT : AuditingActionEnum.RESTORE_COMPONENT; //The audit Action
-                result.left().foreachDoEffect(
-                    c -> {
-                        // The archive/restore records have been retrieved from Cassandra using the separate queries.
-                        // Setting current version as null allows to avoid appearing same records in ActivityLog twice:
-                        // - first time as per current version query
-                        //- second type as per archive/restore query
-                        c.setVersion(null);
-                        componentUtils.auditComponentAdmin(componentUtils.getResponseFormat(ActionStatus.OK), user, c, auditAction, ComponentTypeEnum.findByParamName(containerComponentType), comment);
-                    });
+
+                AuditingActionEnum auditAction = action == ArchiveOperation.Action.ARCHIVE ? AuditingActionEnum.ARCHIVE_COMPONENT
+                    : AuditingActionEnum.RESTORE_COMPONENT; //The audit Action
+                result.left().foreachDoEffect(c -> {
+                    // The archive/restore records have been retrieved from Cassandra using the separate queries.
+
+                    // Setting current version as null allows to avoid appearing same records in ActivityLog twice:
+
+                    // - first time as per current version query
+
+                    //- second type as per archive/restore query
+                    c.setVersion(null);
+                    componentUtils.auditComponentAdmin(componentUtils.getResponseFormat(ActionStatus.OK), user, c, auditAction,
+                        ComponentTypeEnum.findByParamName(containerComponentType), comment);
+                });
             }
         }
     }
-       protected Either<Component, ResponseFormat> sendNotificationToFacade(String componentId,
-                       ChangeTypeEnum changeStatus) {
-               log.debug("build {} notification for facade start", changeStatus.name());
-               Either<Component, StorageOperationStatus> toscaElement = toscaOperationFacade.getToscaElement(componentId);
-               Component component = toscaElement.left()
-                               .value();
-               ActionStatus status = catalogOperations.updateCatalog(changeStatus, component);
-               if (status != ActionStatus.OK) {
-                       return Either.right(componentUtils.getResponseFormat(status));
-               }
-               return Either.left(component);
-       }
+
+    protected Either<Component, ResponseFormat> sendNotificationToFacade(String componentId, ChangeTypeEnum changeStatus) {
+        log.debug("build {} notification for facade start", changeStatus.name());
+        Either<Component, StorageOperationStatus> toscaElement = toscaOperationFacade.getToscaElement(componentId);
+        Component component = toscaElement.left().value();
+        ActionStatus status = catalogOperations.updateCatalog(changeStatus, component);
+        if (status != ActionStatus.OK) {
+            return Either.right(componentUtils.getResponseFormat(status));
+        }
+        return Either.left(component);
+    }
 }
index 66dce60..19eda82 100644 (file)
@@ -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.
  * limitations under the License.
  * ============LICENSE_END=========================================================
  */
-
 package org.openecomp.sdc.be.components.impl;
 
-import org.apache.commons.collections.MapUtils;
-import org.openecomp.sdc.be.components.ArtifactsResolver;
-import org.openecomp.sdc.be.datatypes.enums.ComponentTypeEnum;
-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.model.InterfaceDefinition;
-import org.openecomp.sdc.be.model.Service;
-
 import java.util.ArrayList;
 import java.util.Arrays;
 import java.util.Collections;
@@ -37,6 +27,14 @@ import java.util.Map;
 import java.util.Objects;
 import java.util.Optional;
 import java.util.stream.Collectors;
+import org.apache.commons.collections.MapUtils;
+import org.openecomp.sdc.be.components.ArtifactsResolver;
+import org.openecomp.sdc.be.datatypes.enums.ComponentTypeEnum;
+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.model.InterfaceDefinition;
+import org.openecomp.sdc.be.model.Service;
 
 @org.springframework.stereotype.Component("artifact-resolver")
 public class ArtifactResolverImpl implements ArtifactsResolver {
@@ -45,7 +43,6 @@ public class ArtifactResolverImpl implements ArtifactsResolver {
     public ArtifactDefinition findArtifactOnComponent(Component component, ComponentTypeEnum componentType, String artifactId) {
         List<ArtifactDefinition> allComponentsArtifacts = getAllComponentsArtifacts(component, componentType);
         return findById(allComponentsArtifacts, artifactId);
-
     }
 
     @Override
@@ -55,29 +52,23 @@ public class ArtifactResolverImpl implements ArtifactsResolver {
     }
 
     private ArtifactDefinition findById(List<ArtifactDefinition> artifacts, String artifactId) {
-        return artifacts.stream()
-                        .filter(artifact -> artifact.getUniqueId().equals(artifactId))
-                        .findFirst().orElse(null);
+        return artifacts.stream().filter(artifact -> artifact.getUniqueId().equals(artifactId)).findFirst().orElse(null);
     }
 
     private List<ArtifactDefinition> getAllComponentsArtifacts(Component component, ComponentTypeEnum componentType) {
         Map<String, ArtifactDefinition> deploymentArtifacts = Optional.ofNullable(component.getDeploymentArtifacts()).orElse(Collections.emptyMap());
         Map<String, ArtifactDefinition> artifacts = Optional.ofNullable(component.getArtifacts()).orElse(Collections.emptyMap());
-        Map<String, ArtifactDefinition> interfaceArtifacts= Collections.emptyMap();
+        Map<String, ArtifactDefinition> interfaceArtifacts = Collections.emptyMap();
         Map<String, InterfaceDefinition> interfaces = component.getInterfaces();
         if (MapUtils.isNotEmpty(interfaces)) {
-            interfaceArtifacts = interfaces.values().stream()
-                    .flatMap(inte -> inte.getOperationsMap().values().stream())
-                    .map(operation -> operation.getImplementationArtifact()).filter(Objects::nonNull)
-                    .collect(Collectors.toMap(artifactDefinition -> artifactDefinition.getUniqueId(),
-                            artifactDefinition -> artifactDefinition, (a1, a2) -> a1));
+            interfaceArtifacts = interfaces.values().stream().flatMap(inte -> inte.getOperationsMap().values().stream())
+                .map(operation -> operation.getImplementationArtifact()).filter(Objects::nonNull).collect(Collectors
+                    .toMap(artifactDefinition -> artifactDefinition.getUniqueId(), artifactDefinition -> artifactDefinition, (a1, a2) -> a1));
         }
-
         Map<String, ArtifactDefinition> serviceApiArtifacts = Collections.emptyMap();
         if (componentType == ComponentTypeEnum.SERVICE) {
             serviceApiArtifacts = Optional.ofNullable(((Service) component).getServiceApiArtifacts()).orElse(Collections.emptyMap());
         }
-
         return appendAllArtifacts(deploymentArtifacts, artifacts, interfaceArtifacts, serviceApiArtifacts);
     }
 
@@ -93,5 +84,4 @@ public class ArtifactResolverImpl implements ArtifactsResolver {
         Arrays.stream(artifacts).forEach(a -> allArtifacts.addAll(a.values()));
         return allArtifacts;
     }
-
 }
index 046ad22..849e3c8 100644 (file)
@@ -19,7 +19,6 @@
  * Modifications copyright (c) 2020 Nokia
  * ================================================================================
  */
-
 package org.openecomp.sdc.be.components.impl;
 
 import static org.openecomp.sdc.be.dao.api.ActionStatus.MISMATCH_BETWEEN_ARTIFACT_TYPE_AND_COMPONENT_TYPE;
@@ -143,6 +142,13 @@ import org.yaml.snakeyaml.Yaml;
 
 @org.springframework.stereotype.Component("artifactBusinessLogic")
 public class ArtifactsBusinessLogic extends BaseBusinessLogic {
+
+    public static final String HEAT_ENV_NAME = "heatEnv";
+    public static final String HEAT_VF_ENV_NAME = "VfHeatEnv";
+    public static final String HEAT_ENV_SUFFIX = "env";
+    public static final String ARTIFACT_ACTION_LOCK = "Artifact action - lock ";
+    public static final String FAILED_UPLOAD_ARTIFACT_TO_COMPONENT = "Failed to upload artifact to component with type {} and uuid {}. Status is {}. ";
+    public static final String COMPONENT_INSTANCE_NOT_FOUND = "Component instance {} was not found for component {}";
     private static final String RESOURCE_INSTANCE = "resource instance";
     private static final String ARTIFACT_TYPE_OTHER = "OTHER";
     private static final String ARTIFACT_DESCRIPTION = "artifact description";
@@ -150,41 +156,28 @@ public class ArtifactsBusinessLogic extends BaseBusinessLogic {
     private static final String ARTIFACT_URL = "artifact url";
     private static final String ARTIFACT_NAME = "artifact name";
     private static final String ARTIFACT_PAYLOAD = "artifact payload";
-
     private static final String ARTIFACT_PLACEHOLDER_TYPE = "type";
     private static final String ARTIFACT_PLACEHOLDER_DISPLAY_NAME = "displayName";
     private static final Object ARTIFACT_PLACEHOLDER_DESCRIPTION = "description";
-
-    public static final String HEAT_ENV_NAME = "heatEnv";
-    public static final String HEAT_VF_ENV_NAME = "VfHeatEnv";
-    public static final String HEAT_ENV_SUFFIX = "env";
     private static final String ARTIFACT_PLACEHOLDER_FILE_EXTENSION = "fileExtension";
-
     private static final Logger log = Logger.getLogger(ArtifactsBusinessLogic.class.getName());
     private static final String FAILED_UPDATE_GROUPS = "Failed to update groups of the component {}. ";
     private static final String FAILED_SAVE_ARTIFACT = "Failed to save the artifact.";
-    public static final String ARTIFACT_ACTION_LOCK = "Artifact action - lock ";
-    public static final String FAILED_UPLOAD_ARTIFACT_TO_COMPONENT = "Failed to upload artifact to component with type {} and uuid {}. Status is {}. ";
     private static final String FAILED_FETCH_COMPONENT = "Could not fetch component with type {} and uuid {}. Status is {}. ";
     private static final String NULL_PARAMETER = "One of the function parameteres is null";
-    public static final String COMPONENT_INSTANCE_NOT_FOUND = "Component instance {} was not found for component {}";
     private static final String ROLLBACK = "all changes rollback";
     private static final String COMMIT = "all changes committed";
     private static final String UPDATE_ARTIFACT = "Update Artifact";
     private static final String FOUND_DEPLOYMENT_ARTIFACT = "Found deployment artifact {}";
     private Gson gson = new GsonBuilder().setPrettyPrinting().create();
-
     @javax.annotation.Resource
     private IInterfaceLifecycleOperation interfaceLifecycleOperation;
     @javax.annotation.Resource
     private UserAdminOperation userOperaton;
-
     @javax.annotation.Resource
     private IElementOperation elementOperation;
-
     @javax.annotation.Resource
     private IHeatParametersOperation heatParametersOperation;
-
     private ArtifactCassandraDao artifactCassandraDao;
     private ToscaExportHandler toscaExportUtils;
     private CsarUtils csarUtils;
@@ -194,13 +187,14 @@ public class ArtifactsBusinessLogic extends BaseBusinessLogic {
     private NodeTemplateOperation nodeTemplateOperation;
 
     @Autowired
-    public ArtifactsBusinessLogic(ArtifactCassandraDao artifactCassandraDao, ToscaExportHandler toscaExportUtils,
-                                  CsarUtils csarUtils, LifecycleBusinessLogic lifecycleBusinessLogic, UserBusinessLogic userBusinessLogic,
+    public ArtifactsBusinessLogic(ArtifactCassandraDao artifactCassandraDao, ToscaExportHandler toscaExportUtils, CsarUtils csarUtils,
+                                  LifecycleBusinessLogic lifecycleBusinessLogic, UserBusinessLogic userBusinessLogic,
                                   ArtifactsResolver artifactsResolver, IElementOperation elementDao, IGroupOperation groupOperation,
-                                  IGroupInstanceOperation groupInstanceOperation, IGroupTypeOperation groupTypeOperation, InterfaceOperation interfaceOperation,
-                                  InterfaceLifecycleOperation interfaceLifecycleTypeOperation, ArtifactsOperations artifactToscaOperation) {
-        super(elementDao, groupOperation, groupInstanceOperation, groupTypeOperation,
-            interfaceOperation, interfaceLifecycleTypeOperation, artifactToscaOperation);
+                                  IGroupInstanceOperation groupInstanceOperation, IGroupTypeOperation groupTypeOperation,
+                                  InterfaceOperation interfaceOperation, InterfaceLifecycleOperation interfaceLifecycleTypeOperation,
+                                  ArtifactsOperations artifactToscaOperation) {
+        super(elementDao, groupOperation, groupInstanceOperation, groupTypeOperation, interfaceOperation, interfaceLifecycleTypeOperation,
+            artifactToscaOperation);
         this.artifactCassandraDao = artifactCassandraDao;
         this.toscaExportUtils = toscaExportUtils;
         this.csarUtils = csarUtils;
@@ -209,20 +203,27 @@ public class ArtifactsBusinessLogic extends BaseBusinessLogic {
         this.artifactsResolver = artifactsResolver;
     }
 
-    public enum ArtifactOperationEnum {
-        CREATE, UPDATE, DELETE, DOWNLOAD, LINK;
+    public static <R> Either<Boolean, R> ifTrue(boolean predicate, Supplier<Either<Boolean, R>> ifTrue) {
+        return predicate ? ifTrue.get() : Either.left(false);
+    }
 
-        public static boolean isCreateOrLink(ArtifactOperationEnum operation) {
-            return operation == CREATE || operation == LINK;
-        }
+    public static <L, R> Either<L, R> forEach(Either<L, R> e, Consumer<L> c) {
+        return e.left().map(l -> {
+            c.accept(l);
+            return l;
+        });
+    }
+
+    private static Option<ComponentInstance> findFirstMatching(Component component, Predicate<ComponentInstance> filter) {
+        return Option.ofOptional(component.getComponentInstances().stream().filter(filter).findFirst());
     }
 
     // new flow US556184
     public Either<ArtifactDefinition, Operation> handleArtifactRequest(String componentId, String userId, ComponentTypeEnum componentType,
-                                                                       ArtifactOperationInfo operation, String artifactId, ArtifactDefinition artifactInfo,
-                                                                       String origMd5, String originData, String interfaceName, String operationName,
-                                                                       String parentId, String containerComponentType, boolean shouldLock, boolean inTransaction) {
-
+                                                                       ArtifactOperationInfo operation, String artifactId,
+                                                                       ArtifactDefinition artifactInfo, String origMd5, String originData,
+                                                                       String interfaceName, String operationName, String parentId,
+                                                                       String containerComponentType, boolean shouldLock, boolean inTransaction) {
         // step 1 - detect auditing type
         AuditingActionEnum auditingAction = detectAuditingType(operation, origMd5);
         // step 2 - check header
@@ -233,13 +234,16 @@ public class ArtifactsBusinessLogic extends BaseBusinessLogic {
             throw new ByActionStatusComponentException(ActionStatus.MISSING_INFORMATION);
         }
         // step 3 - check user existence
+
         // step 4 - check user's role
         User user = validateUserExists(userId, auditingAction, componentId, artifactId, componentType, inTransaction);
         validateUserRole(user, auditingAction, componentId, artifactId, componentType, operation);
-
         // steps 5 - 6 - 7
+
         // 5. check service/resource existence
+
         // 6. check service/resource check out
+
         // 7. user is owner of checkout state
         Component component = null;
         String realComponentId = componentType == ComponentTypeEnum.RESOURCE_INSTANCE ? parentId : componentId;
@@ -249,45 +253,49 @@ public class ArtifactsBusinessLogic extends BaseBusinessLogic {
             validateResourceInstanceById(component, componentId);
         }
         // step 8
-
-        return validateAndHandleArtifact(componentId, componentType, operation, artifactId, artifactInfo, origMd5,
-                originData, interfaceName, operationName, user, component, shouldLock, inTransaction, true);
+        return validateAndHandleArtifact(componentId, componentType, operation, artifactId, artifactInfo, origMd5, originData, interfaceName,
+            operationName, user, component, shouldLock, inTransaction, true);
     }
 
-    public Either<ArtifactDefinition, Operation> handleArtifactRequest(String componentId, String userId, ComponentTypeEnum componentType, ArtifactOperationInfo operation, String artifactId, ArtifactDefinition artifactInfo,
-                                                                       String origMd5, String originData, String interfaceName, String operationName, String parentId, String containerComponentType) {
-        return handleArtifactRequest(componentId, userId, componentType, operation, artifactId, artifactInfo, origMd5, originData, interfaceName, operationName, parentId, containerComponentType, true, false);
+    public Either<ArtifactDefinition, Operation> handleArtifactRequest(String componentId, String userId, ComponentTypeEnum componentType,
+                                                                       ArtifactOperationInfo operation, String artifactId,
+                                                                       ArtifactDefinition artifactInfo, String origMd5, String originData,
+                                                                       String interfaceName, String operationName, String parentId,
+                                                                       String containerComponentType) {
+        return handleArtifactRequest(componentId, userId, componentType, operation, artifactId, artifactInfo, origMd5, originData, interfaceName,
+            operationName, parentId, containerComponentType, true, false);
     }
 
     /**
-     * This Method validates only the Artifact and does not validate user / role / component ect...<br>
-     * For regular usage use <br>
-     * {@link #handleArtifactRequest(String, String, ComponentTypeEnum, ArtifactOperationInfo, String, ArtifactDefinition, String, String, String, String, String, String)}
+     * This Method validates only the Artifact and does not validate user / role / component ect...<br> For regular usage use <br> {@link
+     * #handleArtifactRequest(String, String, ComponentTypeEnum, ArtifactOperationInfo, String, ArtifactDefinition, String, String, String, String,
+     * String, String)}
      *
      * @return
      */
-    public Either<ArtifactDefinition, Operation> validateAndHandleArtifact(
-            String componentUniqueId, ComponentTypeEnum componentType, ArtifactOperationInfo operation, String artifactUniqueId,
-            ArtifactDefinition artifactDefinition, String origMd5, String originData, String interfaceName,
-            String operationName, User user, Component component, boolean shouldLock, boolean inTransaction, boolean needUpdateGroup) {
+    public Either<ArtifactDefinition, Operation> validateAndHandleArtifact(String componentUniqueId, ComponentTypeEnum componentType,
+                                                                           ArtifactOperationInfo operation, String artifactUniqueId,
+                                                                           ArtifactDefinition artifactDefinition, String origMd5, String originData,
+                                                                           String interfaceName, String operationName, User user, Component component,
+                                                                           boolean shouldLock, boolean inTransaction, boolean needUpdateGroup) {
         AuditingActionEnum auditingAction = detectAuditingType(operation, origMd5);
-        artifactDefinition = validateArtifact(componentUniqueId, componentType, operation,
-                artifactUniqueId, artifactDefinition, auditingAction, user,
-                component, shouldLock, inTransaction);
-
+        artifactDefinition = validateArtifact(componentUniqueId, componentType, operation, artifactUniqueId, artifactDefinition, auditingAction, user,
+            component, shouldLock, inTransaction);
         // step 10
         Either<ArtifactDefinition, Operation> result = doAction(componentUniqueId, componentType, operation, artifactUniqueId, artifactDefinition,
-                origMd5, originData, interfaceName, operationName, auditingAction, user, component, shouldLock, inTransaction, needUpdateGroup);
+            origMd5, originData, interfaceName, operationName, auditingAction, user, component, shouldLock, inTransaction, needUpdateGroup);
         //TODO: audit positive action
         return result;
     }
 
     @VisibleForTesting
-    ArtifactDefinition validateArtifact(String componentId, ComponentTypeEnum componentType, ArtifactOperationInfo operation, String artifactId, ArtifactDefinition artifactInfo, AuditingActionEnum auditingAction, User user,
-                                        Component component, boolean shouldLock, boolean inTransaction) {
+    ArtifactDefinition validateArtifact(String componentId, ComponentTypeEnum componentType, ArtifactOperationInfo operation, String artifactId,
+                                        ArtifactDefinition artifactInfo, AuditingActionEnum auditingAction, User user, Component component,
+                                        boolean shouldLock, boolean inTransaction) {
         ArtifactDefinition artifactInfoToReturn = artifactInfo;
         ArtifactOperationEnum operationEnum = operation.getArtifactOperationEnum();
-        if (operationEnum == ArtifactOperationEnum.UPDATE || operationEnum == ArtifactOperationEnum.DELETE || operationEnum == ArtifactOperationEnum.DOWNLOAD) {
+        if (operationEnum == ArtifactOperationEnum.UPDATE || operationEnum == ArtifactOperationEnum.DELETE
+            || operationEnum == ArtifactOperationEnum.DOWNLOAD) {
             ArtifactDefinition dbArtifact = getArtifactIfBelongsToComponent(componentId, componentType, artifactId, component);
             if (operation.isDownload()) {
                 artifactInfoToReturn = dbArtifact;
@@ -300,28 +308,19 @@ public class ArtifactsBusinessLogic extends BaseBusinessLogic {
     @VisibleForTesting
     void handleHeatEnvDownload(String componentId, ComponentTypeEnum componentType, User user, Component component,
                                ArtifactDefinition artifactDefinition, boolean shouldLock, boolean inTransaction) {
-
-        if (artifactDefinition.getArtifactType().equalsIgnoreCase(ArtifactTypeEnum.HEAT_ENV.getType())
-                && ComponentTypeEnum.SERVICE == component.getComponentType()) {
-            ComponentInstance componentInstance = component.getComponentInstances()
-                    .stream()
-                    .filter(p -> p.getUniqueId().equals(componentId))
-                    .findAny()
-                    .orElse(null);
+        if (artifactDefinition.getArtifactType().equalsIgnoreCase(ArtifactTypeEnum.HEAT_ENV.getType()) && ComponentTypeEnum.SERVICE == component
+            .getComponentType()) {
+            ComponentInstance componentInstance = component.getComponentInstances().stream().filter(p -> p.getUniqueId().equals(componentId))
+                .findAny().orElse(null);
             if (componentInstance == null) {
-                throw new ByActionStatusComponentException(ActionStatus.COMPONENT_INSTANCE_NOT_FOUND_ON_CONTAINER, componentId,
-                        "instance", "Service", component.getName());
+                throw new ByActionStatusComponentException(ActionStatus.COMPONENT_INSTANCE_NOT_FOUND_ON_CONTAINER, componentId, "instance", "Service",
+                    component.getName());
             }
             Map<String, ArtifactDefinition> deploymentArtifacts = componentInstance.getDeploymentArtifacts();
-
-            ArtifactDefinition heatEnvWithHeatParams = deploymentArtifacts.values()
-                    .stream()
-                    .filter(p -> p.getUniqueId()
-                            .equals(artifactDefinition.getUniqueId()))
-                    .findAny()
-                    .orElse(null);
-            Either<ArtifactDefinition, ResponseFormat> eitherGenerated = generateHeatEnvArtifact(heatEnvWithHeatParams,
-                    componentType, component, componentInstance.getName(), user, componentId, shouldLock, inTransaction);
+            ArtifactDefinition heatEnvWithHeatParams = deploymentArtifacts.values().stream()
+                .filter(p -> p.getUniqueId().equals(artifactDefinition.getUniqueId())).findAny().orElse(null);
+            Either<ArtifactDefinition, ResponseFormat> eitherGenerated = generateHeatEnvArtifact(heatEnvWithHeatParams, componentType, component,
+                componentInstance.getName(), user, componentId, shouldLock, inTransaction);
             if (eitherGenerated.isRight()) {
                 throw new ByResponseFormatComponentException((eitherGenerated.right().value()));
             }
@@ -330,72 +329,62 @@ public class ArtifactsBusinessLogic extends BaseBusinessLogic {
 
     private boolean artifactGenerationRequired(Component component, ArtifactDefinition artifactInfo) {
         boolean needGenerate;
-        needGenerate = artifactInfo.getArtifactGroupType() == ArtifactGroupTypeEnum.TOSCA && (component.getLifecycleState() == LifecycleStateEnum.NOT_CERTIFIED_CHECKIN || component
-                .getLifecycleState() == LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT);
-        needGenerate = needGenerate || (ComponentTypeEnum.RESOURCE == component.getComponentType() && (artifactInfo.getArtifactType()
-                .equalsIgnoreCase(ArtifactTypeEnum.HEAT_ENV
-                        .getType()) || isAbstractVfcEmptyCsar((Resource) component, artifactInfo)));
+        needGenerate = artifactInfo.getArtifactGroupType() == ArtifactGroupTypeEnum.TOSCA && (
+            component.getLifecycleState() == LifecycleStateEnum.NOT_CERTIFIED_CHECKIN
+                || component.getLifecycleState() == LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT);
+        needGenerate = needGenerate || (ComponentTypeEnum.RESOURCE == component.getComponentType() && (
+            artifactInfo.getArtifactType().equalsIgnoreCase(ArtifactTypeEnum.HEAT_ENV.getType()) || isAbstractVfcEmptyCsar((Resource) component,
+                artifactInfo)));
         return needGenerate;
     }
 
     private boolean isAbstractVfcEmptyCsar(Resource resource, ArtifactDefinition artifactInfo) {
-        return resource.isAbstract() && artifactInfo.getArtifactGroupType() == ArtifactGroupTypeEnum.TOSCA && artifactInfo
-                .getArtifactType()
-                .equals(ArtifactTypeEnum.TOSCA_CSAR.getType()) && StringUtils.isEmpty(artifactInfo.getArtifactChecksum());
-    }
-
-    public Either<ArtifactDefinition, Operation> generateAndSaveToscaArtifact(
-        ArtifactDefinition artifactDefinition, Component component,
-        User user, boolean isInCertificationRequest, boolean shouldLock, boolean inTransaction,
-        boolean fetchTemplatesFromDB) {
-
-        return decodeToscaArtifactPayload(
-            component, isInCertificationRequest, fetchTemplatesFromDB, artifactDefinition.getArtifactType()
-        ).left().bind(payload -> {
-            // TODO: Avoid output argument
-            artifactDefinition.setPayload(payload);
-            artifactDefinition.setEsId(artifactDefinition.getUniqueId());
-            artifactDefinition.setArtifactChecksum(GeneralUtility.calculateMD5Base64EncodedByByteArray(payload));
-            return lockComponentAndUpdateArtifact(component.getUniqueId(), artifactDefinition,
-                AuditingActionEnum.ARTIFACT_PAYLOAD_UPDATE, artifactDefinition.getUniqueId(),
-                user, component.getComponentType(), component, payload, shouldLock, inTransaction
-            );
-        }).right().map(ex -> {
-            // TODO: This should not be done but in order to keep this refactoring small enough, we stop here.
-            // Bubble up this exception
-            throw ex;
-        });
+        return resource.isAbstract() && artifactInfo.getArtifactGroupType() == ArtifactGroupTypeEnum.TOSCA && artifactInfo.getArtifactType()
+            .equals(ArtifactTypeEnum.TOSCA_CSAR.getType()) && StringUtils.isEmpty(artifactInfo.getArtifactChecksum());
+    }
+
+    public Either<ArtifactDefinition, Operation> generateAndSaveToscaArtifact(ArtifactDefinition artifactDefinition, Component component, User user,
+                                                                              boolean isInCertificationRequest, boolean shouldLock,
+                                                                              boolean inTransaction, boolean fetchTemplatesFromDB) {
+        return decodeToscaArtifactPayload(component, isInCertificationRequest, fetchTemplatesFromDB, artifactDefinition.getArtifactType()).left()
+            .bind(payload -> {
+                // TODO: Avoid output argument
+                artifactDefinition.setPayload(payload);
+                artifactDefinition.setEsId(artifactDefinition.getUniqueId());
+                artifactDefinition.setArtifactChecksum(GeneralUtility.calculateMD5Base64EncodedByByteArray(payload));
+                return lockComponentAndUpdateArtifact(component.getUniqueId(), artifactDefinition, AuditingActionEnum.ARTIFACT_PAYLOAD_UPDATE,
+                    artifactDefinition.getUniqueId(), user, component.getComponentType(), component, payload, shouldLock, inTransaction);
+            }).right().map(ex -> {
+                // TODO: This should not be done but in order to keep this refactoring small enough, we stop here.
+
+                // Bubble up this exception
+                throw ex;
+            });
     }
 
-    private Either<byte[], ComponentException> decodeToscaArtifactPayload(
-        Component parent,
-        boolean isInCertificationRequest,
-        boolean fetchTemplatesFromDB,
-        String artifactType
-    ) {
+    private Either<byte[], ComponentException> decodeToscaArtifactPayload(Component parent, boolean isInCertificationRequest,
+                                                                          boolean fetchTemplatesFromDB, String artifactType) {
         log.debug("tosca artifact generation");
         if (ArtifactTypeEnum.TOSCA_CSAR.getType().equals(artifactType)) {
-            return csarUtils
-                .createCsar(parent, fetchTemplatesFromDB, isInCertificationRequest)
-                .right().map(error -> {
-                    log.debug("Failed to generate tosca csar for component {} error {}", parent.getUniqueId(), error);
-                    return new ByResponseFormatComponentException(error);
-                });
+            return csarUtils.createCsar(parent, fetchTemplatesFromDB, isInCertificationRequest).right().map(error -> {
+                log.debug("Failed to generate tosca csar for component {} error {}", parent.getUniqueId(), error);
+                return new ByResponseFormatComponentException(error);
+            });
         } else {
-            return toscaExportUtils
-                .exportComponent(parent)
-                .left().map(toscaRepresentation -> {
-                    log.debug("Tosca yaml exported for component {} ", parent.getUniqueId());
-                    return toscaRepresentation.getMainYaml();
-                }).right().map(toscaError -> {
-                    log.debug("Failed export tosca yaml for component {} error {}", parent.getUniqueId(), toscaError);
-                    return new ByActionStatusComponentException(componentsUtils.convertFromToscaError(toscaError));
-                });
+            return toscaExportUtils.exportComponent(parent).left().map(toscaRepresentation -> {
+                log.debug("Tosca yaml exported for component {} ", parent.getUniqueId());
+                return toscaRepresentation.getMainYaml();
+            }).right().map(toscaError -> {
+                log.debug("Failed export tosca yaml for component {} error {}", parent.getUniqueId(), toscaError);
+                return new ByActionStatusComponentException(componentsUtils.convertFromToscaError(toscaError));
+            });
         }
     }
 
-    private Either<ArtifactDefinition, Operation> doAction(String componentId, ComponentTypeEnum componentType, ArtifactOperationInfo operation, String artifactId, ArtifactDefinition artifactInfo, String origMd5,
-                                                           String originData, String interfaceName, String operationName, AuditingActionEnum auditingAction, User user, Component parent, boolean shouldLock, boolean inTransaction, boolean needUpdateGroup) {
+    private Either<ArtifactDefinition, Operation> doAction(String componentId, ComponentTypeEnum componentType, ArtifactOperationInfo operation,
+                                                           String artifactId, ArtifactDefinition artifactInfo, String origMd5, String originData,
+                                                           String interfaceName, String operationName, AuditingActionEnum auditingAction, User user,
+                                                           Component parent, boolean shouldLock, boolean inTransaction, boolean needUpdateGroup) {
         if (interfaceName != null && operationName != null) {
             interfaceName = interfaceName.toLowerCase();
             operationName = operationName.toLowerCase();
@@ -418,23 +407,23 @@ public class ArtifactsBusinessLogic extends BaseBusinessLogic {
                     result = Either.left(handleDeleteInternal(componentId, artifactId, componentType, parent));
                     break;
                 case UPDATE:
-                    result = handleUpdate(componentId, componentType, operation, artifactId, artifactInfo, null, origMd5, originData, interfaceName, operationName,
-                            auditingAction, user, parent, needUpdateGroup);
+                    result = handleUpdate(componentId, componentType, operation, artifactId, artifactInfo, null, origMd5, originData, interfaceName,
+                        operationName, auditingAction, user, parent, needUpdateGroup);
                     break;
                 case CREATE:
-                    result = handleCreate(componentId, artifactInfo, operation, auditingAction, user, componentType, parent, origMd5, originData, interfaceName,
-                            operationName);
+                    result = handleCreate(componentId, artifactInfo, operation, auditingAction, user, componentType, parent, origMd5, originData,
+                        interfaceName, operationName);
                     break;
                 case LINK:
                     result = Either.left(handleLink(componentId, artifactInfo, componentType, parent));
                     break;
                 default:
-                    throw new UnsupportedOperationException("In ArtifactsBusinessLogic received illegal operation: " + operation.getArtifactOperationEnum());
+                    throw new UnsupportedOperationException(
+                        "In ArtifactsBusinessLogic received illegal operation: " + operation.getArtifactOperationEnum());
             }
             operationSucceeded = true;
             return result;
-        }
-        finally {
+        } finally {
             handleLockingAndCommit(parent, shouldLock, inTransaction, operationSucceeded);
         }
     }
@@ -442,44 +431,41 @@ public class ArtifactsBusinessLogic extends BaseBusinessLogic {
     private void lockComponent(ComponentTypeEnum componentType, String artifactId, AuditingActionEnum auditingAction, User user, Component parent) {
         try {
             lockComponent(parent, ARTIFACT_ACTION_LOCK);
-        }catch (ComponentException e){
-            handleAuditing(auditingAction, parent, parent.getUniqueId(), user, null, null, artifactId, e.getResponseFormat(),
-                    componentType, null);
+        } catch (ComponentException e) {
+            handleAuditing(auditingAction, parent, parent.getUniqueId(), user, null, null, artifactId, e.getResponseFormat(), componentType, null);
             throw e;
         }
     }
 
     @VisibleForTesting
-    public Either<ArtifactDefinition, Operation> handleUpdate(String componentId, ComponentTypeEnum componentType, ArtifactOperationInfo operation, String artifactId,
-                                                       ArtifactDefinition artifactInfo, byte[] decodedPayload, String origMd5, String originData, String interfaceName,
-                                                       String operationName, AuditingActionEnum auditingAction, User user, Component parent,
-                                                       boolean needUpdateGroup) {
+    public Either<ArtifactDefinition, Operation> handleUpdate(String componentId, ComponentTypeEnum componentType, ArtifactOperationInfo operation,
+                                                              String artifactId, ArtifactDefinition artifactInfo, byte[] decodedPayload,
+                                                              String origMd5, String originData, String interfaceName, String operationName,
+                                                              AuditingActionEnum auditingAction, User user, Component parent,
+                                                              boolean needUpdateGroup) {
         Either<ArtifactDefinition, Operation> result;
         validateArtifactType(artifactInfo);
         final String artifactType = artifactInfo.getArtifactType();
-        if (componentType == ComponentTypeEnum.RESOURCE_INSTANCE &&
-            (ArtifactTypeEnum.HEAT.getType().equals(artifactType) ||
-                ArtifactTypeEnum.HEAT_VOL.getType().equals(artifactType) ||
-                ArtifactTypeEnum.HEAT_NET.getType().equals(artifactType) ||
-                ArtifactTypeEnum.HEAT_ENV.getType().equals(artifactType))) {
-            result = handleUpdateHeatEnvAndHeatMeta(componentId, artifactInfo, auditingAction, artifactId, user, componentType, parent, originData, origMd5, operation);
+        if (componentType == ComponentTypeEnum.RESOURCE_INSTANCE && (ArtifactTypeEnum.HEAT.getType().equals(artifactType) || ArtifactTypeEnum.HEAT_VOL
+            .getType().equals(artifactType) || ArtifactTypeEnum.HEAT_NET.getType().equals(artifactType) || ArtifactTypeEnum.HEAT_ENV.getType()
+            .equals(artifactType))) {
+            result = handleUpdateHeatEnvAndHeatMeta(componentId, artifactInfo, auditingAction, artifactId, user, componentType, parent, originData,
+                origMd5, operation);
             if (needUpdateGroup) {
                 ActionStatus error = updateGroupInstance(artifactInfo, result.left().value(), parent, componentId);
                 if (error != ActionStatus.OK) {
                     throw new ByActionStatusComponentException(error);
                 }
             }
-        }
-        else if (componentType == ComponentTypeEnum.RESOURCE && ArtifactTypeEnum.HEAT_ENV.getType().equals(artifactType)) {
-            result = handleUpdateHeatWithHeatEnvParams(componentId, artifactInfo, auditingAction, componentType, parent, originData, origMd5, operation, needUpdateGroup);
-        }
-        else {
+        } else if (componentType == ComponentTypeEnum.RESOURCE && ArtifactTypeEnum.HEAT_ENV.getType().equals(artifactType)) {
+            result = handleUpdateHeatWithHeatEnvParams(componentId, artifactInfo, auditingAction, componentType, parent, originData, origMd5,
+                operation, needUpdateGroup);
+        } else {
             if (decodedPayload == null) {
-                decodedPayload = validateInput(componentId, artifactInfo, operation, auditingAction, artifactId, user,
-                        componentType, parent, origMd5, originData, interfaceName, operationName);
+                decodedPayload = validateInput(componentId, artifactInfo, operation, auditingAction, artifactId, user, componentType, parent, origMd5,
+                    originData, interfaceName, operationName);
             }
-            result = updateArtifactFlow(parent, componentId, artifactId, artifactInfo, decodedPayload, componentType, auditingAction
-            );
+            result = updateArtifactFlow(parent, componentId, artifactId, artifactInfo, decodedPayload, componentType, auditingAction);
             if (needUpdateGroup && result.isLeft()) {
                 ArtifactDefinition updatedArtifact = result.left().value();
                 updateGroupForHeat(artifactInfo, updatedArtifact, parent);
@@ -494,30 +480,25 @@ public class ArtifactsBusinessLogic extends BaseBusinessLogic {
         }
     }
 
-    private void validateArtifactType(final ArtifactDefinition artifactInfo,
-                                      final ComponentTypeEnum componentType) {
-        final ArtifactConfiguration artifactConfiguration =
-            loadArtifactTypeConfig(artifactInfo.getArtifactType()).orElse(null);
+    private void validateArtifactType(final ArtifactDefinition artifactInfo, final ComponentTypeEnum componentType) {
+        final ArtifactConfiguration artifactConfiguration = loadArtifactTypeConfig(artifactInfo.getArtifactType()).orElse(null);
         if (artifactConfiguration == null) {
-            BeEcompErrorManager.getInstance()
-                .logBeMissingArtifactInformationError("Artifact Update / Upload", "artifactLabel");
+            BeEcompErrorManager.getInstance().logBeMissingArtifactInformationError("Artifact Update / Upload", "artifactLabel");
             log.debug("Missing artifact type for artifact {}", artifactInfo.getArtifactName());
             final ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.MISSING_ARTIFACT_TYPE);
             throw new ByResponseFormatComponentException(responseFormat);
         }
-
         final ArtifactGroupTypeEnum artifactGroupType = artifactInfo.getArtifactGroupType();
         try {
             validateArtifactType(componentType, artifactGroupType, artifactConfiguration);
         } catch (final ComponentException e) {
             log.debug("Artifact is invalid", e);
             BeEcompErrorManager.getInstance()
-                .logBeInvalidTypeError("Artifact Upload / Delete / Update - Not supported artifact type", artifactInfo
-                    .getArtifactType(), "Artifact " + artifactInfo.getArtifactName());
+                .logBeInvalidTypeError("Artifact Upload / Delete / Update - Not supported artifact type", artifactInfo.getArtifactType(),
+                    "Artifact " + artifactInfo.getArtifactName());
             log.debug("Not supported artifact type = {}", artifactInfo.getArtifactType());
             final ResponseFormat responseFormat = componentsUtils
-                .getResponseFormat(ActionStatus.ARTIFACT_TYPE_NOT_SUPPORTED, artifactInfo
-                    .getArtifactType());
+                .getResponseFormat(ActionStatus.ARTIFACT_TYPE_NOT_SUPPORTED, artifactInfo.getArtifactType());
             throw new ByResponseFormatComponentException(responseFormat);
         }
     }
@@ -525,22 +506,17 @@ public class ArtifactsBusinessLogic extends BaseBusinessLogic {
     private void validateArtifactType(final ComponentTypeEnum componentType, final ArtifactGroupTypeEnum groupType,
                                       final ArtifactConfiguration artifactConfiguration) {
         final boolean supportComponentType =
-            CollectionUtils.isNotEmpty(artifactConfiguration.getComponentTypes()) &&
-                artifactConfiguration.getComponentTypes().stream()
-                    .anyMatch(componentType1 -> componentType1.getValue().equalsIgnoreCase(componentType.getValue()));
+            CollectionUtils.isNotEmpty(artifactConfiguration.getComponentTypes()) && artifactConfiguration.getComponentTypes().stream()
+                .anyMatch(componentType1 -> componentType1.getValue().equalsIgnoreCase(componentType.getValue()));
         if (!supportComponentType) {
-            log.debug("Artifact Type '{}' not supported for Component Type '{}'",
-                artifactConfiguration.getType(), componentType.getValue());
-            throw new ByActionStatusComponentException(ActionStatus.ARTIFACT_TYPE_NOT_SUPPORTED,
-                artifactConfiguration.getType());
+            log.debug("Artifact Type '{}' not supported for Component Type '{}'", artifactConfiguration.getType(), componentType.getValue());
+            throw new ByActionStatusComponentException(ActionStatus.ARTIFACT_TYPE_NOT_SUPPORTED, artifactConfiguration.getType());
         }
-
         final boolean supportResourceType = artifactConfiguration.hasSupport(groupType);
         if (!supportResourceType) {
-            log.debug("Artifact Type '{}' not supported for Component Type '{}' and Category '{}'",
-                artifactConfiguration.getType(), componentType.getValue(), groupType.getType());
-            throw new ByActionStatusComponentException(ActionStatus.ARTIFACT_TYPE_NOT_SUPPORTED,
-                artifactConfiguration.getType());
+            log.debug("Artifact Type '{}' not supported for Component Type '{}' and Category '{}'", artifactConfiguration.getType(),
+                componentType.getValue(), groupType.getType());
+            throw new ByActionStatusComponentException(ActionStatus.ARTIFACT_TYPE_NOT_SUPPORTED, artifactConfiguration.getType());
         }
     }
 
@@ -550,8 +526,7 @@ public class ArtifactsBusinessLogic extends BaseBusinessLogic {
         if (CollectionUtils.isEmpty(artifactConfigurationList)) {
             return false;
         }
-        return artifactConfigurationList.stream()
-            .anyMatch(artifactConfiguration -> artifactConfiguration.getType().equalsIgnoreCase(artifactType));
+        return artifactConfigurationList.stream().anyMatch(artifactConfiguration -> artifactConfiguration.getType().equalsIgnoreCase(artifactType));
     }
 
     @VisibleForTesting
@@ -559,17 +534,14 @@ public class ArtifactsBusinessLogic extends BaseBusinessLogic {
         List<GroupDefinition> groups = parent.getGroups();
         if (groups != null && !groups.isEmpty()) {
             List<GroupDataDefinition> groupToUpdate = groups.stream()
-                    .filter(g -> g.getArtifacts() != null && g.getArtifacts()
-                            .contains(artifactInfo
-                                    .getUniqueId()))
-                    .collect(Collectors.toList());
+                .filter(g -> g.getArtifacts() != null && g.getArtifacts().contains(artifactInfo.getUniqueId())).collect(Collectors.toList());
             if (groupToUpdate != null && !groupToUpdate.isEmpty()) {
                 groupToUpdate.forEach(g -> {
                     g.getArtifacts().remove(artifactInfo.getUniqueId());
                     g.getArtifactsUuid().remove(artifactInfo.getArtifactUUID());
                     g.getArtifacts().add(artAfterUpdate.getUniqueId());
                     g.getArtifactsUuid().add(artAfterUpdate.getArtifactUUID());
-                    if(!artifactInfo.getArtifactUUID().equals(artAfterUpdate.getArtifactUUID())){
+                    if (!artifactInfo.getArtifactUUID().equals(artAfterUpdate.getArtifactUUID())) {
                         g.setGroupUUID(UniqueIdBuilder.generateUUID());
                     }
                 });
@@ -584,14 +556,12 @@ public class ArtifactsBusinessLogic extends BaseBusinessLogic {
     }
 
     @VisibleForTesting
-    ActionStatus updateGroupForHeat(ArtifactDefinition artifactInfoHeat, ArtifactDefinition artHeatAfterUpdate, ArtifactDefinition artifactInfoHeatE, ArtifactDefinition artHEAfterUpdate, Component parent) {
+    ActionStatus updateGroupForHeat(ArtifactDefinition artifactInfoHeat, ArtifactDefinition artHeatAfterUpdate, ArtifactDefinition artifactInfoHeatE,
+                                    ArtifactDefinition artHEAfterUpdate, Component parent) {
         List<GroupDefinition> groups = parent.getGroups();
         if (groups != null && !groups.isEmpty()) {
             List<GroupDataDefinition> groupToUpdate = groups.stream()
-                    .filter(g -> g.getArtifacts() != null && g.getArtifacts()
-                            .contains(artifactInfoHeat
-                                    .getUniqueId()))
-                    .collect(Collectors.toList());
+                .filter(g -> g.getArtifacts() != null && g.getArtifacts().contains(artifactInfoHeat.getUniqueId())).collect(Collectors.toList());
             if (groupToUpdate != null && !groupToUpdate.isEmpty()) {
                 groupToUpdate.forEach(g -> {
                     g.getArtifacts().remove(artifactInfoHeat.getUniqueId());
@@ -614,10 +584,8 @@ public class ArtifactsBusinessLogic extends BaseBusinessLogic {
     private ActionStatus updateGroupInstance(ArtifactDefinition artifactInfo, ArtifactDefinition artAfterUpdate, Component parent, String parentId) {
         List<GroupInstance> updatedGroupInstances = new ArrayList<>();
         List<GroupInstance> groupInstances = null;
-        Optional<ComponentInstance> componentInstOp = parent.getComponentInstances()
-                .stream()
-                .filter(ci -> ci.getUniqueId().equals(parentId))
-                .findFirst();
+        Optional<ComponentInstance> componentInstOp = parent.getComponentInstances().stream().filter(ci -> ci.getUniqueId().equals(parentId))
+            .findFirst();
         if (componentInstOp.isPresent()) {
             groupInstances = componentInstOp.get().getGroupInstances();
         }
@@ -626,15 +594,13 @@ public class ArtifactsBusinessLogic extends BaseBusinessLogic {
             for (GroupInstance groupInstance : groupInstances) {
                 isUpdated = false;
                 if (CollectionUtils.isNotEmpty(groupInstance.getGroupInstanceArtifacts()) && groupInstance.getGroupInstanceArtifacts()
-                        .contains(artifactInfo
-                                .getUniqueId())) {
+                    .contains(artifactInfo.getUniqueId())) {
                     groupInstance.getGroupInstanceArtifacts().remove(artifactInfo.getUniqueId());
                     groupInstance.getGroupInstanceArtifacts().add(artAfterUpdate.getUniqueId());
                     isUpdated = true;
                 }
                 if (CollectionUtils.isNotEmpty(groupInstance.getGroupInstanceArtifactsUuid()) && groupInstance.getGroupInstanceArtifactsUuid()
-                        .contains(artifactInfo
-                                .getArtifactUUID())) {
+                    .contains(artifactInfo.getArtifactUUID())) {
                     groupInstance.getGroupInstanceArtifactsUuid().remove(artifactInfo.getArtifactUUID());
                     groupInstance.getGroupInstanceArtifacts().add(artAfterUpdate.getArtifactUUID());
                     isUpdated = true;
@@ -644,7 +610,8 @@ public class ArtifactsBusinessLogic extends BaseBusinessLogic {
                 }
             }
         }
-        Either<List<GroupInstance>, StorageOperationStatus> status = toscaOperationFacade.updateGroupInstancesOnComponent(parent, parentId, updatedGroupInstances);
+        Either<List<GroupInstance>, StorageOperationStatus> status = toscaOperationFacade
+            .updateGroupInstancesOnComponent(parent, parentId, updatedGroupInstances);
         if (status.isRight()) {
             log.debug(FAILED_UPDATE_GROUPS, parent.getUniqueId());
             return componentsUtils.convertFromStorageResponse(status.right().value());
@@ -654,17 +621,16 @@ public class ArtifactsBusinessLogic extends BaseBusinessLogic {
 
     ArtifactDefinition generateNotSavedArtifact(Component parent, ArtifactDefinition artifactDefinition) {
         if (artifactDefinition.getArtifactGroupType() == ArtifactGroupTypeEnum.TOSCA) {
-            Either<byte[], ComponentException> decodedPayload = decodeToscaArtifactPayload(parent, false,
-                false, artifactDefinition.getArtifactType());
+            Either<byte[], ComponentException> decodedPayload = decodeToscaArtifactPayload(parent, false, false,
+                artifactDefinition.getArtifactType());
             // TODO: This should not be done, but in order to keep this refactoring relatively small, we stop here
-            if(decodedPayload.isRight())
+            if (decodedPayload.isRight()) {
                 throw decodedPayload.right().value();
-            else {
+            else {
                 artifactDefinition.setPayload(decodedPayload.left().value());
                 return artifactDefinition;
             }
-        }
-        else {
+        } else {
             String heatArtifactId = artifactDefinition.getGeneratedFromId();
             Either<ArtifactDefinition, StorageOperationStatus> heatRes = artifactToscaOperation.getArtifactById(parent.getUniqueId(), heatArtifactId);
             if (heatRes.isRight()) {
@@ -677,11 +643,13 @@ public class ArtifactsBusinessLogic extends BaseBusinessLogic {
         }
     }
 
-    private Either<ArtifactDefinition, Operation> handleUpdateHeatWithHeatEnvParams(String componentId, ArtifactDefinition artifactInfo, AuditingActionEnum auditingAction,
-                                                                                    ComponentTypeEnum componentType, Component parent, String originData, String origMd5, ArtifactOperationInfo operation,
-                                                                                    boolean needToUpdateGroup) {
-        Either<ArtifactDefinition, StorageOperationStatus> artifactHeatRes = artifactToscaOperation.getArtifactById(componentId, artifactInfo
-                .getGeneratedFromId());
+    private Either<ArtifactDefinition, Operation> handleUpdateHeatWithHeatEnvParams(String componentId, ArtifactDefinition artifactInfo,
+                                                                                    AuditingActionEnum auditingAction,
+                                                                                    ComponentTypeEnum componentType, Component parent,
+                                                                                    String originData, String origMd5,
+                                                                                    ArtifactOperationInfo operation, boolean needToUpdateGroup) {
+        Either<ArtifactDefinition, StorageOperationStatus> artifactHeatRes = artifactToscaOperation
+            .getArtifactById(componentId, artifactInfo.getGeneratedFromId());
         ArtifactDefinition currHeatArtifact = artifactHeatRes.left().value();
         if (origMd5 != null) {
             validateMd5(origMd5, originData, artifactInfo.getPayloadData(), operation);
@@ -703,7 +671,7 @@ public class ArtifactsBusinessLogic extends BaseBusinessLogic {
         } else {
             log.debug(ROLLBACK);
             if (!inTransaction) {
-                    janusGraphDao.rollback();
+                janusGraphDao.rollback();
             }
         }
         if (shouldLock) {
@@ -714,10 +682,8 @@ public class ArtifactsBusinessLogic extends BaseBusinessLogic {
     public ImmutablePair<String, byte[]> handleDownloadToscaModelRequest(Component component, ArtifactDefinition csarArtifact) {
         if (artifactGenerationRequired(component, csarArtifact)) {
             Either<byte[], ResponseFormat> generated = csarUtils.createCsar(component, false, false);
-
             if (generated.isRight()) {
-                log.debug("Failed to export tosca csar for component {} error {}", component.getUniqueId(), generated.right()
-                        .value());
+                log.debug("Failed to export tosca csar for component {} error {}", component.getUniqueId(), generated.right().value());
                 throw new ByResponseFormatComponentException(generated.right().value());
             }
             return new ImmutablePair<>(csarArtifact.getArtifactName(), generated.left().value());
@@ -725,47 +691,54 @@ public class ArtifactsBusinessLogic extends BaseBusinessLogic {
         return downloadArtifact(csarArtifact);
     }
 
-    public ImmutablePair<String, byte[]> handleDownloadRequestById(String componentId, String artifactId, String userId, ComponentTypeEnum componentType, String parentId, String containerComponentType) {
+    public ImmutablePair<String, byte[]> handleDownloadRequestById(String componentId, String artifactId, String userId,
+                                                                   ComponentTypeEnum componentType, String parentId, String containerComponentType) {
         // perform all validation in common flow
-        Either<ArtifactDefinition, Operation> result = handleArtifactRequest(componentId, userId, componentType, new ArtifactOperationInfo(false, false, ArtifactOperationEnum.DOWNLOAD), artifactId, null, null, null, null,
-                null, parentId, containerComponentType);
+        Either<ArtifactDefinition, Operation> result = handleArtifactRequest(componentId, userId, componentType,
+            new ArtifactOperationInfo(false, false, ArtifactOperationEnum.DOWNLOAD), artifactId, null, null, null, null, null, parentId,
+            containerComponentType);
         ArtifactDefinition artifactDefinition;
         Either<ArtifactDefinition, Operation> insideValue = result;
         if (insideValue.isLeft()) {
             artifactDefinition = insideValue.left().value();
-        }
-        else {
+        } else {
             artifactDefinition = insideValue.right().value().getImplementationArtifact();
         }
         // for tosca artifacts and heat env on VF level generated on download without saving
         if (artifactDefinition.getPayloadData() != null) {
-            return (new ImmutablePair<>(artifactDefinition.getArtifactName(), artifactDefinition
-                    .getPayloadData()));
+            return (new ImmutablePair<>(artifactDefinition.getArtifactName(), artifactDefinition.getPayloadData()));
         }
         return downloadArtifact(artifactDefinition);
     }
 
-    public Map<String, ArtifactDefinition> handleGetArtifactsByType(String containerComponentType, String parentId, ComponentTypeEnum componentType, String componentId, String artifactGroupType, String userId) {
+    public Map<String, ArtifactDefinition> handleGetArtifactsByType(String containerComponentType, String parentId, ComponentTypeEnum componentType,
+                                                                    String componentId, String artifactGroupType, String userId) {
         // step 1
+
         // detect auditing type
         Map<String, ArtifactDefinition> resMap = null;
-
         new Wrapper<>();
         // step 2
+
         // check header
         if (userId == null) {
             log.debug("handleGetArtifactsByType - no HTTP_CSP_HEADER , component id {}", componentId);
             throw new ByActionStatusComponentException(ActionStatus.MISSING_INFORMATION);
         }
         // step 3
+
         // check user existence
+
         // step 4
-        // check user's role
 
+        // check user's role
         validateUserExists(userId);
         // steps 5 - 6 - 7
+
         // 5. check service/resource existence
+
         // 6. check service/resource check out
+
         // 7. user is owner of checkout state
         String realComponentId = componentType == ComponentTypeEnum.RESOURCE_INSTANCE ? parentId : componentId;
         ComponentParametersView componentFilter = new ComponentParametersView();
@@ -774,14 +747,12 @@ public class ArtifactsBusinessLogic extends BaseBusinessLogic {
         if (componentType == ComponentTypeEnum.RESOURCE_INSTANCE) {
             componentFilter.setIgnoreComponentInstances(false);
         }
-
-        Component component = validateComponentExistsByFilter(realComponentId, ComponentTypeEnum
-                .findByParamName(containerComponentType), componentFilter);
+        Component component = validateComponentExistsByFilter(realComponentId, ComponentTypeEnum.findByParamName(containerComponentType),
+            componentFilter);
         lockComponent(component, ARTIFACT_ACTION_LOCK);
         boolean failed = false;
         try {
             ArtifactGroupTypeEnum groupType = ArtifactGroupTypeEnum.findType(artifactGroupType);
-
             if (groupType == null) {
                 log.debug("handleGetArtifactsByType - not failed groupType {} , component id {}", artifactGroupType, componentId);
                 throw new ByActionStatusComponentException(ActionStatus.MISSING_INFORMATION);
@@ -790,30 +761,26 @@ public class ArtifactsBusinessLogic extends BaseBusinessLogic {
                 List<ArtifactDefinition> list = getDeploymentArtifacts(component, componentId);
                 if (list != null && !list.isEmpty()) {
                     resMap = list.stream().collect(Collectors.toMap(ArtifactDataDefinition::getArtifactLabel, Function.identity()));
-                }
-                else {
+                } else {
                     resMap = new HashMap<>();
                 }
                 return resMap;
             } else {
-
-                Either<Map<String, ArtifactDefinition>, StorageOperationStatus> artifactsMapStatus = getArtifacts(realComponentId, componentType
-                        .getNodeType(), groupType, componentId);
+                Either<Map<String, ArtifactDefinition>, StorageOperationStatus> artifactsMapStatus = getArtifacts(realComponentId,
+                    componentType.getNodeType(), groupType, componentId);
                 if (artifactsMapStatus.isRight()) {
                     if (artifactsMapStatus.right().value() != StorageOperationStatus.NOT_FOUND) {
                         log.debug("handleGetArtifactsByType - not failed groupType {} , component id {}", artifactGroupType, componentId);
                         throw new ByActionStatusComponentException(ActionStatus.MISSING_INFORMATION);
-                    }
-                    else {
+                    } else {
                         resMap = new HashMap<>();
                     }
-                }
-                else {
+                } else {
                     resMap = artifactsMapStatus.left().value();
                 }
                 return resMap;
             }
-        }catch (ComponentException e){
+        } catch (ComponentException e) {
             failed = true;
             throw e;
         } finally {
@@ -821,23 +788,21 @@ public class ArtifactsBusinessLogic extends BaseBusinessLogic {
             if (failed) {
                 log.debug(ROLLBACK);
                 janusGraphDao.rollback();
-            }
-            else {
+            } else {
                 log.debug(COMMIT);
                 janusGraphDao.commit();
             }
-
             componentType = component.getComponentType();
             NodeTypeEnum nodeType = componentType.getNodeType();
             graphLockOperation.unlockComponent(component.getUniqueId(), nodeType);
         }
-
     }
 
-    private ArtifactDefinition getArtifactIfBelongsToComponent(String componentId, ComponentTypeEnum componentType, String artifactId, Component component) {
+    private ArtifactDefinition getArtifactIfBelongsToComponent(String componentId, ComponentTypeEnum componentType, String artifactId,
+                                                               Component component) {
         // check artifact existence
-        Either<ArtifactDefinition, StorageOperationStatus> artifactResult = artifactToscaOperation.getArtifactById(componentId, artifactId,
-                componentType, component.getUniqueId());
+        Either<ArtifactDefinition, StorageOperationStatus> artifactResult = artifactToscaOperation
+            .getArtifactById(componentId, artifactId, componentType, component.getUniqueId());
         if (artifactResult.isRight()) {
             throw new ByActionStatusComponentException(ActionStatus.COMPONENT_ARTIFACT_NOT_FOUND, artifactId, componentId);
         }
@@ -860,22 +825,24 @@ public class ArtifactsBusinessLogic extends BaseBusinessLogic {
         return artifactResult.left().value();
     }
 
-    private Either<ArtifactDefinition, Operation> handleCreate(String componentId, ArtifactDefinition artifactInfo, ArtifactOperationInfo operation, AuditingActionEnum auditingAction, User user, ComponentTypeEnum componentType,
-                                                               Component parent, String origMd5, String originData, String interfaceType, String operationName) {
-        byte[] decodedPayload = validateInput(componentId, artifactInfo, operation, auditingAction, null, user, componentType, parent, origMd5, originData, interfaceType, operationName);
+    private Either<ArtifactDefinition, Operation> handleCreate(String componentId, ArtifactDefinition artifactInfo, ArtifactOperationInfo operation,
+                                                               AuditingActionEnum auditingAction, User user, ComponentTypeEnum componentType,
+                                                               Component parent, String origMd5, String originData, String interfaceType,
+                                                               String operationName) {
+        byte[] decodedPayload = validateInput(componentId, artifactInfo, operation, auditingAction, null, user, componentType, parent, origMd5,
+            originData, interfaceType, operationName);
         return createArtifact(parent, componentId, artifactInfo, decodedPayload, componentType, auditingAction, interfaceType, operationName);
     }
 
-    private ArtifactDefinition handleLink(String componentId, ArtifactDefinition artifactInfo, ComponentTypeEnum componentType,
-                                          Component parent) {
+    private ArtifactDefinition handleLink(String componentId, ArtifactDefinition artifactInfo, ComponentTypeEnum componentType, Component parent) {
         ComponentInstance foundInstance = findComponentInstance(componentId, parent);
         String instanceId = null;
         if (foundInstance != null) {
             instanceId = foundInstance.getUniqueId();
         }
         NodeTypeEnum nodeType = convertParentType(componentType);
-        Either<ArtifactDefinition, StorageOperationStatus> artifactDefinitionEither = artifactToscaOperation.addArtifactToComponent(artifactInfo, parent,
-                nodeType, true, instanceId);
+        Either<ArtifactDefinition, StorageOperationStatus> artifactDefinitionEither = artifactToscaOperation
+            .addArtifactToComponent(artifactInfo, parent, nodeType, true, instanceId);
         if (artifactDefinitionEither.isRight()) {
             throw new StorageException(artifactDefinitionEither.right().value(), artifactInfo.getArtifactDisplayName());
         }
@@ -885,55 +852,52 @@ public class ArtifactsBusinessLogic extends BaseBusinessLogic {
         return artifactDefinitionEither.left().value();
     }
 
-    private <T> Either<ArtifactDefinition, T> lockComponentAndUpdateArtifact(
-        String parentId, ArtifactDefinition artifactInfo, AuditingActionEnum auditingAction, String artifactId,
-        User user, ComponentTypeEnum componentType, Component parent, byte[] decodedPayload,
-        boolean shouldLock, boolean inTransaction) {
-
+    private <T> Either<ArtifactDefinition, T> lockComponentAndUpdateArtifact(String parentId, ArtifactDefinition artifactInfo,
+                                                                             AuditingActionEnum auditingAction, String artifactId, User user,
+                                                                             ComponentTypeEnum componentType, Component parent, byte[] decodedPayload,
+                                                                             boolean shouldLock, boolean inTransaction) {
         boolean failed = false;
         boolean writeAudit = true;
         try {
             lockComponent(parent, shouldLock, ARTIFACT_ACTION_LOCK);
             writeAudit = false;
-            return updateArtifactFlow(parent, parentId, artifactId, artifactInfo, decodedPayload, componentType,
-                auditingAction);
-        }
-        catch (ComponentException ce) {
-            if(writeAudit) {
-                handleAuditing(auditingAction, parent, parentId, user, null, null, artifactId, ce.getResponseFormat(),
-                    componentType, null);
+            return updateArtifactFlow(parent, parentId, artifactId, artifactInfo, decodedPayload, componentType, auditingAction);
+        } catch (ComponentException ce) {
+            if (writeAudit) {
+                handleAuditing(auditingAction, parent, parentId, user, null, null, artifactId, ce.getResponseFormat(), componentType, null);
             }
             failed = true;
             throw ce;
-        }
-        catch (StorageException se) {
+        } catch (StorageException se) {
             //TODO: audit
             failed = true;
             throw se;
-        }
-        finally {
+        } finally {
             if (shouldLock) {
                 unlockComponent(failed, parent, inTransaction);
             }
         }
     }
 
-    private byte[] validateInput(String componentId, ArtifactDefinition artifactInfo, ArtifactOperationInfo operation, AuditingActionEnum auditingAction, String artifactId, User user, ComponentTypeEnum componentType,
-                                 Component parent, String origMd5, String originData, String interfaceType, String operationName) {
+    private byte[] validateInput(String componentId, ArtifactDefinition artifactInfo, ArtifactOperationInfo operation,
+                                 AuditingActionEnum auditingAction, String artifactId, User user, ComponentTypeEnum componentType, Component parent,
+                                 String origMd5, String originData, String interfaceType, String operationName) {
         validateMd5(origMd5, originData, artifactInfo.getPayloadData(), operation);
-        return getValidPayload(componentId, artifactInfo, operation, auditingAction, artifactId, user, componentType, parent, interfaceType, operationName);
+        return getValidPayload(componentId, artifactInfo, operation, auditingAction, artifactId, user, componentType, parent, interfaceType,
+            operationName);
     }
 
-    private byte[] getValidPayload(String componentId, ArtifactDefinition artifactInfo, ArtifactOperationInfo operation, AuditingActionEnum auditingAction,
-                                   String artifactId, User user, ComponentTypeEnum componentType, Component parent, String interfaceType, String operationName) {
+    private byte[] getValidPayload(String componentId, ArtifactDefinition artifactInfo, ArtifactOperationInfo operation,
+                                   AuditingActionEnum auditingAction, String artifactId, User user, ComponentTypeEnum componentType, Component parent,
+                                   String interfaceType, String operationName) {
         // step 11
-        Either<ArtifactDefinition, ResponseFormat> validateResult = validateInput(componentId, artifactInfo, operation, artifactId, user, interfaceType, operationName, componentType, parent);
+        Either<ArtifactDefinition, ResponseFormat> validateResult = validateInput(componentId, artifactInfo, operation, artifactId, user,
+            interfaceType, operationName, componentType, parent);
         if (validateResult.isRight()) {
             ResponseFormat responseFormat = validateResult.right().value();
             handleAuditing(auditingAction, parent, componentId, user, null, null, artifactId, responseFormat, componentType, null);
             throw new ByResponseFormatComponentException(responseFormat);
         }
-
         Either<byte[], ResponseFormat> payloadEither = handlePayload(artifactInfo, isArtifactMetadataUpdate(auditingAction));
         if (payloadEither.isRight()) {
             ResponseFormat responseFormat = payloadEither.right().value();
@@ -942,9 +906,10 @@ public class ArtifactsBusinessLogic extends BaseBusinessLogic {
             throw new ByResponseFormatComponentException(responseFormat);
         }
         // validate heat parameters. this part must be after the parameters are
+
         // extracted in "handlePayload"
-        Either<ArtifactDefinition, ResponseFormat> validateAndConvertHeatParameters = validateAndConvertHeatParameters(artifactInfo, artifactInfo
-                .getArtifactType());
+        Either<ArtifactDefinition, ResponseFormat> validateAndConvertHeatParameters = validateAndConvertHeatParameters(artifactInfo,
+            artifactInfo.getArtifactType());
         if (validateAndConvertHeatParameters.isRight()) {
             ResponseFormat responseFormat = validateAndConvertHeatParameters.right().value();
             handleAuditing(auditingAction, parent, componentId, user, artifactInfo, null, artifactId, responseFormat, componentType, null);
@@ -957,19 +922,20 @@ public class ArtifactsBusinessLogic extends BaseBusinessLogic {
     public void handleAuditing(AuditingActionEnum auditingActionEnum, Component component, String componentId, User user,
                                ArtifactDefinition artifactDefinition, String prevArtifactUuid, String currentArtifactUuid,
                                ResponseFormat responseFormat, ComponentTypeEnum componentTypeEnum, String resourceInstanceName) {
-
         if (componentsUtils.isExternalApiEvent(auditingActionEnum)) {
             return;
         }
-
         if (user == null) {
             user = new User();
             user.setUserId("UNKNOWN");
         }
-        handleInternalAuditEvent(auditingActionEnum, component, componentId, user, artifactDefinition, prevArtifactUuid, currentArtifactUuid, responseFormat, componentTypeEnum, resourceInstanceName);
+        handleInternalAuditEvent(auditingActionEnum, component, componentId, user, artifactDefinition, prevArtifactUuid, currentArtifactUuid,
+            responseFormat, componentTypeEnum, resourceInstanceName);
     }
 
-    private void handleInternalAuditEvent(AuditingActionEnum auditingActionEnum, Component component, String componentId, User user, ArtifactDefinition artifactDefinition, String prevArtifactUuid, String currentArtifactUuid, ResponseFormat responseFormat, ComponentTypeEnum componentTypeEnum, String resourceInstanceName) {
+    private void handleInternalAuditEvent(AuditingActionEnum auditingActionEnum, Component component, String componentId, User user,
+                                          ArtifactDefinition artifactDefinition, String prevArtifactUuid, String currentArtifactUuid,
+                                          ResponseFormat responseFormat, ComponentTypeEnum componentTypeEnum, String resourceInstanceName) {
         switch (componentTypeEnum) {
             case RESOURCE:
                 Resource resource = (Resource) component;
@@ -979,11 +945,8 @@ public class ArtifactsBusinessLogic extends BaseBusinessLogic {
                     resource.setName(componentId);
                 }
                 componentsUtils.auditResource(responseFormat, user, resource, resource.getName(), auditingActionEnum,
-                        ResourceVersionInfo.newBuilder()
-                                .artifactUuid(prevArtifactUuid)
-                                .build(), currentArtifactUuid, artifactDefinition);
+                    ResourceVersionInfo.newBuilder().artifactUuid(prevArtifactUuid).build(), currentArtifactUuid, artifactDefinition);
                 break;
-
             case SERVICE:
                 Service service = (Service) component;
                 if (service == null) {
@@ -991,29 +954,19 @@ public class ArtifactsBusinessLogic extends BaseBusinessLogic {
                     service = new Service();
                     service.setName(componentId);
                 }
-                componentsUtils.auditComponent(responseFormat, user, service, auditingActionEnum, new ResourceCommonInfo(ComponentTypeEnum.SERVICE.getValue()),
-                        ResourceVersionInfo.newBuilder()
-                                .artifactUuid(prevArtifactUuid)
-                                .build(),
-                        ResourceVersionInfo.newBuilder()
-                                .artifactUuid(currentArtifactUuid)
-                                .build(),
-                        null, artifactDefinition, null);
+                componentsUtils
+                    .auditComponent(responseFormat, user, service, auditingActionEnum, new ResourceCommonInfo(ComponentTypeEnum.SERVICE.getValue()),
+                        ResourceVersionInfo.newBuilder().artifactUuid(prevArtifactUuid).build(),
+                        ResourceVersionInfo.newBuilder().artifactUuid(currentArtifactUuid).build(), null, artifactDefinition, null);
                 break;
-
             case RESOURCE_INSTANCE:
                 if (resourceInstanceName == null) {
                     resourceInstanceName = getResourceInstanceNameFromComponent(component, componentId);
                 }
                 componentsUtils.auditComponent(responseFormat, user, component, auditingActionEnum,
-                        new ResourceCommonInfo(resourceInstanceName, ComponentTypeEnum.RESOURCE_INSTANCE.getValue()),
-                        ResourceVersionInfo.newBuilder()
-                                .artifactUuid(prevArtifactUuid)
-                                .build(),
-                        ResourceVersionInfo.newBuilder()
-                                .artifactUuid(currentArtifactUuid)
-                                .build(),
-                        null, artifactDefinition, null);
+                    new ResourceCommonInfo(resourceInstanceName, ComponentTypeEnum.RESOURCE_INSTANCE.getValue()),
+                    ResourceVersionInfo.newBuilder().artifactUuid(prevArtifactUuid).build(),
+                    ResourceVersionInfo.newBuilder().artifactUuid(currentArtifactUuid).build(), null, artifactDefinition, null);
                 break;
             default:
                 break;
@@ -1021,11 +974,8 @@ public class ArtifactsBusinessLogic extends BaseBusinessLogic {
     }
 
     private String getResourceInstanceNameFromComponent(Component component, String componentId) {
-        ComponentInstance resourceInstance = component.getComponentInstances()
-                .stream()
-                .filter(p -> p.getUniqueId().equals(componentId))
-                .findFirst()
-                .orElse(null);
+        ComponentInstance resourceInstance = component.getComponentInstances().stream().filter(p -> p.getUniqueId().equals(componentId)).findFirst()
+            .orElse(null);
         String resourceInstanceName = null;
         if (resourceInstance != null) {
             resourceInstanceName = resourceInstance.getName();
@@ -1053,19 +1003,12 @@ public class ArtifactsBusinessLogic extends BaseBusinessLogic {
         }
     }
 
-    private Either<ArtifactDefinition, ResponseFormat> validateInput(final String componentId,
-                                                                     final ArtifactDefinition artifactInfo,
-                                                                     final ArtifactOperationInfo operation,
-                                                                     final String artifactId, final User user,
-                                                                     String interfaceName,
-                                                                     String operationName,
-                                                                     final ComponentTypeEnum componentType,
-                                                                     final Component parentComponent) {
-
-        final ArtifactDefinition existingArtifactInfo =
-            findArtifact(parentComponent, componentType, componentId, operation, artifactId);
-        final boolean isCreateOrLinkOperation =
-            ArtifactOperationEnum.isCreateOrLink(operation.getArtifactOperationEnum());
+    private Either<ArtifactDefinition, ResponseFormat> validateInput(final String componentId, final ArtifactDefinition artifactInfo,
+                                                                     final ArtifactOperationInfo operation, final String artifactId, final User user,
+                                                                     String interfaceName, String operationName,
+                                                                     final ComponentTypeEnum componentType, final Component parentComponent) {
+        final ArtifactDefinition existingArtifactInfo = findArtifact(parentComponent, componentType, componentId, operation, artifactId);
+        final boolean isCreateOrLinkOperation = ArtifactOperationEnum.isCreateOrLink(operation.getArtifactOperationEnum());
         if (!isCreateOrLinkOperation && existingArtifactInfo == null) {
             throw new ByActionStatusComponentException(ActionStatus.ARTIFACT_NOT_FOUND, artifactId);
         }
@@ -1094,13 +1037,14 @@ public class ArtifactsBusinessLogic extends BaseBusinessLogic {
             operationName = operationName.toLowerCase();
             interfaceName = interfaceName.toLowerCase();
         }
-        Either<ActionStatus, ResponseFormat> logicalNameStatus = handleArtifactLabel(componentId, parentComponent, operation, artifactInfo, operationName, componentType);
+        Either<ActionStatus, ResponseFormat> logicalNameStatus = handleArtifactLabel(componentId, parentComponent, operation, artifactInfo,
+            operationName, componentType);
         if (logicalNameStatus.isRight()) {
             return Either.right(logicalNameStatus.right().value());
         }
         // This is a patch to block possibility of updating service api fields
-        // through other artifacts flow
 
+        // through other artifacts flow
         final ArtifactGroupTypeEnum artifactGroupType =
             operationName != null ? ArtifactGroupTypeEnum.LIFE_CYCLE : ArtifactGroupTypeEnum.INFORMATIONAL;
         if (operation.isNotCreateOrLink()) {
@@ -1108,7 +1052,6 @@ public class ArtifactsBusinessLogic extends BaseBusinessLogic {
         } else {
             checkCreateFields(user, artifactInfo, artifactGroupType);
         }
-
         composeArtifactId(componentId, artifactId, artifactInfo, interfaceName, operationName);
         if (existingArtifactInfo != null) {
             artifactInfo.setMandatory(existingArtifactInfo.getMandatory());
@@ -1116,7 +1059,6 @@ public class ArtifactsBusinessLogic extends BaseBusinessLogic {
                 validateArtifactTypeNotChanged(artifactInfo, existingArtifactInfo);
             }
         }
-
         // artifactGroupType is not allowed to be updated
         if (operation.isNotCreateOrLink()) {
             Either<ArtifactDefinition, ResponseFormat> validateGroupType = validateOrSetArtifactGroupType(artifactInfo, existingArtifactInfo);
@@ -1124,7 +1066,6 @@ public class ArtifactsBusinessLogic extends BaseBusinessLogic {
                 return Either.right(validateGroupType.right().value());
             }
         }
-
         setArtifactTimeout(artifactInfo, existingArtifactInfo);
         if (isHeatArtifact(artifactInfo)) {
             validateHeatArtifact(parentComponent, componentId, artifactInfo);
@@ -1132,34 +1073,26 @@ public class ArtifactsBusinessLogic extends BaseBusinessLogic {
         if (isDeploymentArtifact(artifactInfo)) {
             if (componentType != ComponentTypeEnum.RESOURCE_INSTANCE) {
                 final String artifactName = artifactInfo.getArtifactName();
-                final String existingArtifactName =
-                    (existingArtifactInfo == null) ? null : existingArtifactInfo.getArtifactName();
-
-                if (operation.isCreateOrLink()
-                    || ((artifactName != null) && !artifactName.equalsIgnoreCase(existingArtifactName))) {
+                final String existingArtifactName = (existingArtifactInfo == null) ? null : existingArtifactInfo.getArtifactName();
+                if (operation.isCreateOrLink() || ((artifactName != null) && !artifactName.equalsIgnoreCase(existingArtifactName))) {
                     validateSingleDeploymentArtifactName(artifactName, parentComponent);
                 }
             }
             validateDeploymentArtifact(artifactInfo, component);
         }
-
         Either<Boolean, ResponseFormat> descriptionResult = validateAndCleanDescription(artifactInfo);
         if (descriptionResult.isRight()) {
             return Either.right(descriptionResult.right().value());
         }
-
         validateArtifactType(artifactInfo, component.getComponentType());
         artifactInfo.setArtifactType(artifactInfo.getArtifactType().toUpperCase());
         if (existingArtifactInfo != null && existingArtifactInfo.getArtifactGroupType() == ArtifactGroupTypeEnum.SERVICE_API) {
             // Change of type is not allowed and should be ignored
-
             artifactInfo.setArtifactType(ARTIFACT_TYPE_OTHER);
-
             Either<Boolean, ResponseFormat> validateUrl = validateAndServiceApiUrl(artifactInfo);
             if (validateUrl.isRight()) {
                 return Either.right(validateUrl.right().value());
             }
-
             Either<Boolean, ResponseFormat> validateUpdate = validateFirstUpdateHasPayload(artifactInfo, existingArtifactInfo);
             if (validateUpdate.isRight()) {
                 log.debug("serviceApi first update cnnot be without payload.");
@@ -1170,13 +1103,11 @@ public class ArtifactsBusinessLogic extends BaseBusinessLogic {
                 artifactInfo.setApiUrl(null);
                 log.error("Artifact URL cannot be set through this API - ignoring");
             }
-
             if (Boolean.TRUE.equals(artifactInfo.getServiceApi())) {
                 artifactInfo.setServiceApi(false);
                 log.error("Artifact service API flag cannot be changed - ignoring");
             }
         }
-
         return Either.left(artifactInfo);
     }
 
@@ -1186,12 +1117,10 @@ public class ArtifactsBusinessLogic extends BaseBusinessLogic {
             log.debug("Component '{}' not found ", componentId);
             throw new ByActionStatusComponentException(ActionStatus.COMPONENT_NOT_FOUND, componentId);
         }
-
         return component.left().value();
     }
 
-    private void ignoreUnupdateableFieldsInUpdate(final ArtifactOperationInfo operation,
-                                                  final ArtifactDefinition artifactInfo,
+    private void ignoreUnupdateableFieldsInUpdate(final ArtifactOperationInfo operation, final ArtifactDefinition artifactInfo,
                                                   final ArtifactDefinition currentArtifactInfo) {
         if (operation.isUpdate()) {
             artifactInfo.setArtifactType(currentArtifactInfo.getArtifactType());
@@ -1200,9 +1129,8 @@ public class ArtifactsBusinessLogic extends BaseBusinessLogic {
         }
     }
 
-    private ArtifactDefinition findArtifact(final Component parentComponent, final ComponentTypeEnum componentType,
-                                            final String parentId, final ArtifactOperationInfo operation,
-                                            final String artifactId) {
+    private ArtifactDefinition findArtifact(final Component parentComponent, final ComponentTypeEnum componentType, final String parentId,
+                                            final ArtifactOperationInfo operation, final String artifactId) {
         ArtifactDefinition foundArtifact = null;
         if (StringUtils.isNotEmpty(artifactId)) {
             foundArtifact = findArtifact(parentComponent, componentType, parentId, artifactId);
@@ -1222,8 +1150,7 @@ public class ArtifactsBusinessLogic extends BaseBusinessLogic {
         ArtifactDefinition foundArtifact;
         if (parentComponent.getUniqueId().equals(parentId)) {
             foundArtifact = artifactsResolver.findArtifactOnComponent(parentComponent, componentType, artifactId);
-        }
-        else {
+        } else {
             ComponentInstance instance = findComponentInstance(parentId, parentComponent);
             foundArtifact = artifactsResolver.findArtifactOnComponentInstance(instance, artifactId);
         }
@@ -1242,10 +1169,7 @@ public class ArtifactsBusinessLogic extends BaseBusinessLogic {
             throw new ByActionStatusComponentException(ActionStatus.ARTIFACT_TYPE_NOT_SUPPORTED, artifactType);
         }
         validateArtifactType(parentComponentType, artifactInfo.getArtifactGroupType(), artifactConfiguration);
-
-        if (component.getComponentType() == ComponentTypeEnum.RESOURCE ||
-            component.getComponentType() == ComponentTypeEnum.RESOURCE_INSTANCE) {
-
+        if (component.getComponentType() == ComponentTypeEnum.RESOURCE || component.getComponentType() == ComponentTypeEnum.RESOURCE_INSTANCE) {
             final ResourceTypeEnum resourceType = ((Resource) component).getResourceType();
             validateResourceType(resourceType, artifactInfo, artifactConfiguration.getResourceTypes());
         }
@@ -1255,89 +1179,70 @@ public class ArtifactsBusinessLogic extends BaseBusinessLogic {
     private NodeTypeEnum convertParentType(ComponentTypeEnum componentType) {
         if (componentType == ComponentTypeEnum.RESOURCE) {
             return NodeTypeEnum.Resource;
-        }
-        else if (componentType == ComponentTypeEnum.RESOURCE_INSTANCE) {
+        } else if (componentType == ComponentTypeEnum.RESOURCE_INSTANCE) {
             return NodeTypeEnum.ResourceInstance;
-        }
-        else {
+        } else {
             return NodeTypeEnum.Service;
         }
     }
 
     // This method is here for backward compatibility - when other parts of the code are cleaned can change to use the internal version
-    public Either<ArtifactDefinition, ResponseFormat> handleDelete(
-        String parentId, String artifactId, User user, Component parent,
-        boolean shouldLock, boolean inTransaction) {
-
+    public Either<ArtifactDefinition, ResponseFormat> handleDelete(String parentId, String artifactId, User user, Component parent,
+                                                                   boolean shouldLock, boolean inTransaction) {
         ResponseFormat responseFormat;
         boolean operationSucceeded = false;
         if (shouldLock) {
             lockComponent(ComponentTypeEnum.RESOURCE, artifactId, AuditingActionEnum.ARTIFACT_DELETE, user, parent);
         }
         try {
-            ArtifactDefinition artifactDefinition = handleDeleteInternal(parentId, artifactId,
-                ComponentTypeEnum.RESOURCE, parent);
+            ArtifactDefinition artifactDefinition = handleDeleteInternal(parentId, artifactId, ComponentTypeEnum.RESOURCE, parent);
             operationSucceeded = true;
             return Either.left(artifactDefinition);
-        }
-        catch (ComponentException ce) {
+        } catch (ComponentException ce) {
             responseFormat = componentsUtils.getResponseFormat(ce);
-            handleAuditing(AuditingActionEnum.ARTIFACT_DELETE, parent, parentId, user, null, null,
-                artifactId, responseFormat, ComponentTypeEnum.RESOURCE, null);
+            handleAuditing(AuditingActionEnum.ARTIFACT_DELETE, parent, parentId, user, null, null, artifactId, responseFormat,
+                ComponentTypeEnum.RESOURCE, null);
             return Either.right(responseFormat);
-        }
-        catch (StorageException se) {
+        } catch (StorageException se) {
             responseFormat = componentsUtils.getResponseFormat(se);
-            handleAuditing(AuditingActionEnum.ARTIFACT_DELETE, parent, parentId, user, null, null,
-                artifactId, responseFormat, ComponentTypeEnum.RESOURCE, null);
+            handleAuditing(AuditingActionEnum.ARTIFACT_DELETE, parent, parentId, user, null, null, artifactId, responseFormat,
+                ComponentTypeEnum.RESOURCE, null);
             return Either.right(responseFormat);
         } finally {
             handleLockingAndCommit(parent, shouldLock, inTransaction, operationSucceeded);
         }
     }
 
-    private ArtifactDefinition handleDeleteInternal(
-        String parentId, String artifactId,
-        ComponentTypeEnum componentType, Component parent
-    ) {
+    private ArtifactDefinition handleDeleteInternal(String parentId, String artifactId, ComponentTypeEnum componentType, Component parent) {
         NodeTypeEnum parentType = convertParentType(componentType);
         log.debug("Going to find the artifact {} on the component {}", artifactId, parent.getUniqueId());
-
-        Either<ImmutablePair<ArtifactDefinition, ComponentInstance>, ActionStatus> getArtifactRes =
-            findArtifact(artifactId, parent, parentId, componentType);
+        Either<ImmutablePair<ArtifactDefinition, ComponentInstance>, ActionStatus> getArtifactRes = findArtifact(artifactId, parent, parentId,
+            componentType);
         if (getArtifactRes.isRight()) {
-            log.debug("Failed to find the artifact {} belonging to {} on the component {}",
-                artifactId, parentId, parent.getUniqueId());
+            log.debug("Failed to find the artifact {} belonging to {} on the component {}", artifactId, parentId, parent.getUniqueId());
             throw new ByActionStatusComponentException(getArtifactRes.right().value(), artifactId);
         }
         ArtifactDefinition foundArtifact = getArtifactRes.left().value().getLeft();
         ComponentInstance foundInstance = getArtifactRes.left().value().getRight();
-
         String esId = foundArtifact.getEsId();
-        Either<Boolean, StorageOperationStatus> needClone = ifTrue(StringUtils.isNotEmpty(esId), () -> forEach(
-            artifactToscaOperation.isCloneNeeded(parent.getUniqueId(), foundArtifact, parentType),
-            b -> log.debug("handleDelete: clone is needed for deleting {} held by {} in component {} {}? {}",
-                foundArtifact.getArtifactName(), parentType, parent.getUniqueId(), parent.getName(), b)
-        ));
-
+        Either<Boolean, StorageOperationStatus> needClone = ifTrue(StringUtils.isNotEmpty(esId),
+            () -> forEach(artifactToscaOperation.isCloneNeeded(parent.getUniqueId(), foundArtifact, parentType), b -> log
+                .debug("handleDelete: clone is needed for deleting {} held by {} in component {} {}? {}", foundArtifact.getArtifactName(), parentType,
+                    parent.getUniqueId(), parent.getName(), b)));
         boolean needToClone = false;
         // TODO: This should not be done, but in order to keep this refactoring small, we stop here.
+
         // Remove this block once the above refactoring is merged.
-        if(needClone.isLeft()) {
+        if (needClone.isLeft()) {
             needToClone = needClone.left().value();
         } else {
             throw new StorageException(needClone.right().value(), foundArtifact.getArtifactDisplayName());
         }
-
         boolean isNeedToDeleteArtifactFromDB =
-            componentType == ComponentTypeEnum.RESOURCE_INSTANCE &&
-                isArtifactOnlyResourceInstanceArtifact(foundArtifact, parent, parentId);
-
+            componentType == ComponentTypeEnum.RESOURCE_INSTANCE && isArtifactOnlyResourceInstanceArtifact(foundArtifact, parent, parentId);
         boolean isDuplicated = false;
-
         ArtifactDataDefinition updatedArtifact = deleteOrUpdateArtifactOnGraph(parent, parentId, artifactId, parentType, foundArtifact, needToClone);
         isDuplicated = updatedArtifact.getDuplicated();
-
         if (!needToClone && !isDuplicated && isNeedToDeleteArtifactFromDB) {
             log.debug("Going to delete the artifact {} from the database. ", artifactId);
             CassandraOperationStatus cassandraStatus = artifactCassandraDao.deleteArtifact(esId);
@@ -1349,7 +1254,8 @@ public class ArtifactsBusinessLogic extends BaseBusinessLogic {
         if (componentType == ComponentTypeEnum.RESOURCE_INSTANCE) {
             List<GroupInstance> updatedGroupInstances = getUpdatedGroupInstances(artifactId, foundArtifact, foundInstance.getGroupInstances());
             if (CollectionUtils.isNotEmpty(updatedGroupInstances)) {
-                Either<List<GroupInstance>, StorageOperationStatus> status = toscaOperationFacade.updateGroupInstancesOnComponent(parent, parentId, updatedGroupInstances);
+                Either<List<GroupInstance>, StorageOperationStatus> status = toscaOperationFacade
+                    .updateGroupInstancesOnComponent(parent, parentId, updatedGroupInstances);
                 if (status.isRight()) {
                     log.debug(FAILED_UPDATE_GROUPS, parent.getUniqueId());
                     throw new StorageException(status.right().value(), foundArtifact.getArtifactDisplayName());
@@ -1373,17 +1279,6 @@ public class ArtifactsBusinessLogic extends BaseBusinessLogic {
         return foundArtifact;
     }
 
-    public static <R> Either<Boolean, R> ifTrue(boolean predicate, Supplier<Either<Boolean, R>> ifTrue) {
-        return predicate ? ifTrue.get() : Either.left(false);
-    }
-
-    public static <L, R> Either<L, R> forEach(Either<L, R> e, Consumer<L> c) {
-        return e.left().map(l -> {
-            c.accept(l);
-            return l;
-        });
-    }
-
     private boolean isArtifactOnlyResourceInstanceArtifact(ArtifactDefinition foundArtifact, Component parent, String instanceId) {
         Optional<ComponentInstance> componentInstanceOpt = parent.getComponentInstanceById(instanceId);
         if (!componentInstanceOpt.isPresent()) {
@@ -1399,20 +1294,14 @@ public class ArtifactsBusinessLogic extends BaseBusinessLogic {
         Component origComponent = getContainerRes.left().value();
         Map<String, ArtifactDefinition> deploymentArtifacts = origComponent.getDeploymentArtifacts();
         if (MapUtils.isNotEmpty(deploymentArtifacts)) {
-            Optional<String> op = deploymentArtifacts.keySet()
-                    .stream()
-                    .filter(a -> a.equals(foundArtifact.getArtifactLabel()))
-                    .findAny();
+            Optional<String> op = deploymentArtifacts.keySet().stream().filter(a -> a.equals(foundArtifact.getArtifactLabel())).findAny();
             if (op.isPresent()) {
                 return false;
             }
         }
         Map<String, ArtifactDefinition> artifacts = origComponent.getArtifacts();
         if (MapUtils.isNotEmpty(artifacts)) {
-            Optional<String> op = artifacts.keySet()
-                    .stream()
-                    .filter(a -> a.equals(foundArtifact.getArtifactLabel()))
-                    .findAny();
+            Optional<String> op = artifacts.keySet().stream().filter(a -> a.equals(foundArtifact.getArtifactLabel())).findAny();
             if (op.isPresent()) {
                 return false;
             }
@@ -1430,8 +1319,7 @@ public class ArtifactsBusinessLogic extends BaseBusinessLogic {
                     group.getArtifacts().remove(artifactId);
                     isUpdated = true;
                 }
-                if (CollectionUtils.isNotEmpty(group.getArtifactsUuid()) && group.getArtifactsUuid()
-                        .contains(foundArtifact.getArtifactUUID())) {
+                if (CollectionUtils.isNotEmpty(group.getArtifactsUuid()) && group.getArtifactsUuid().contains(foundArtifact.getArtifactUUID())) {
                     group.getArtifactsUuid().remove(foundArtifact.getArtifactUUID());
                     isUpdated = true;
                 }
@@ -1443,29 +1331,27 @@ public class ArtifactsBusinessLogic extends BaseBusinessLogic {
         return updatedGroups;
     }
 
-    private List<GroupInstance> getUpdatedGroupInstances(
-        String artifactId, ArtifactDefinition foundArtifact, List<GroupInstance> groupInstances
-    ) {
+    private List<GroupInstance> getUpdatedGroupInstances(String artifactId, ArtifactDefinition foundArtifact, List<GroupInstance> groupInstances) {
         if (CollectionUtils.isEmpty(groupInstances)) {
             return new ArrayList<>();
         }
         // TODO: A defensive copy should be created here for groupInstances. Modifying
+
         // arguments (aka output arguments) is overall a bad practice as explained in
+
         // Clean Code by Robert Martin.
-        // A better approach would be to use Lenses.
 
+        // A better approach would be to use Lenses.
         return groupInstances.stream().filter(gi -> {
-            boolean groupInstanceArtifactRemoved = gi.getGroupInstanceArtifacts() != null &&
-                gi.getGroupInstanceArtifacts().remove(artifactId);
-            boolean groupInstanceArtifactUUIDRemoved = gi.getGroupInstanceArtifactsUuid() != null &&
-                gi.getGroupInstanceArtifactsUuid().remove(foundArtifact.getArtifactUUID());
-
+            boolean groupInstanceArtifactRemoved = gi.getGroupInstanceArtifacts() != null && gi.getGroupInstanceArtifacts().remove(artifactId);
+            boolean groupInstanceArtifactUUIDRemoved =
+                gi.getGroupInstanceArtifactsUuid() != null && gi.getGroupInstanceArtifactsUuid().remove(foundArtifact.getArtifactUUID());
             return groupInstanceArtifactRemoved || groupInstanceArtifactUUIDRemoved;
         }).collect(Collectors.toList());
     }
 
-    private ArtifactDataDefinition deleteOrUpdateArtifactOnGraph(Component component, String parentId, String artifactId, NodeTypeEnum parentType, ArtifactDefinition foundArtifact, Boolean cloneIsNeeded) {
-
+    private ArtifactDataDefinition deleteOrUpdateArtifactOnGraph(Component component, String parentId, String artifactId, NodeTypeEnum parentType,
+                                                                 ArtifactDefinition foundArtifact, Boolean cloneIsNeeded) {
         Either<ArtifactDataDefinition, StorageOperationStatus> result;
         boolean isMandatory = foundArtifact.getMandatory() || foundArtifact.getServiceApi();
         String componentId = component.getUniqueId();
@@ -1474,12 +1360,10 @@ public class ArtifactsBusinessLogic extends BaseBusinessLogic {
             log.debug("Going to update mandatory artifact {} from the component {}", artifactId, parentId);
             resetMandatoryArtifactFields(foundArtifact);
             result = artifactToscaOperation.updateArtifactOnGraph(component, foundArtifact, parentType, artifactId, instanceId, true, true);
-        }
-        else if (cloneIsNeeded) {
+        } else if (cloneIsNeeded) {
             log.debug("Going to clone artifacts and to delete the artifact {} from the component {}", artifactId, parentId);
             result = artifactToscaOperation.deleteArtifactWithCloningOnGraph(componentId, foundArtifact, parentType, instanceId, false);
-        }
-        else {
+        } else {
             log.debug("Going to delete the artifact {} from the component {}", artifactId, parentId);
             result = artifactToscaOperation.removeArtifactOnGraph(foundArtifact, componentId, instanceId, parentType, false);
         }
@@ -1489,33 +1373,29 @@ public class ArtifactsBusinessLogic extends BaseBusinessLogic {
         return result.left().value();
     }
 
-    private Either<ImmutablePair<ArtifactDefinition, ComponentInstance>, ActionStatus> findArtifact(String artifactId, Component fetchedContainerComponent, String parentId, ComponentTypeEnum componentType) {
-
+    private Either<ImmutablePair<ArtifactDefinition, ComponentInstance>, ActionStatus> findArtifact(String artifactId,
+                                                                                                    Component fetchedContainerComponent,
+                                                                                                    String parentId,
+                                                                                                    ComponentTypeEnum componentType) {
         Either<ImmutablePair<ArtifactDefinition, ComponentInstance>, ActionStatus> result = null;
         Map<String, ArtifactDefinition> artifacts = new HashMap<>();
         ComponentInstance foundInstance = null;
         if (componentType == ComponentTypeEnum.RESOURCE_INSTANCE && StringUtils.isNotEmpty(parentId)) {
-            Optional<ComponentInstance> componentInstanceOpt = fetchedContainerComponent.getComponentInstances()
-                    .stream()
-                    .filter(i -> i.getUniqueId()
-                            .equals(parentId))
-                    .findFirst();
+            Optional<ComponentInstance> componentInstanceOpt = fetchedContainerComponent.getComponentInstances().stream()
+                .filter(i -> i.getUniqueId().equals(parentId)).findFirst();
             if (!componentInstanceOpt.isPresent()) {
                 result = Either.right(ActionStatus.COMPONENT_INSTANCE_NOT_FOUND_ON_CONTAINER);
-            }
-            else {
+            } else {
                 foundInstance = componentInstanceOpt.get();
                 fetchArtifactsFromInstance(artifactId, artifacts, foundInstance);
             }
-        }
-        else {
+        } else {
             fetchArtifactsFromComponent(artifactId, fetchedContainerComponent, artifacts);
         }
         if (result == null) {
             if (artifacts.containsKey(artifactId)) {
                 result = Either.left(new ImmutablePair<>(artifacts.get(artifactId), foundInstance));
-            }
-            else {
+            } else {
                 result = Either.right(ActionStatus.ARTIFACT_NOT_FOUND);
             }
         }
@@ -1525,28 +1405,22 @@ public class ArtifactsBusinessLogic extends BaseBusinessLogic {
     private void fetchArtifactsFromComponent(String artifactId, Component component, Map<String, ArtifactDefinition> artifacts) {
         Map<String, ArtifactDefinition> currArtifacts;
         if (!artifacts.containsKey(artifactId) && MapUtils.isNotEmpty(component.getDeploymentArtifacts())) {
-            currArtifacts = component.getDeploymentArtifacts()
-                    .values()
-                    .stream()
-                    .collect(Collectors.toMap(ArtifactDataDefinition::getUniqueId, i -> i));
+            currArtifacts = component.getDeploymentArtifacts().values().stream()
+                .collect(Collectors.toMap(ArtifactDataDefinition::getUniqueId, i -> i));
             if (MapUtils.isNotEmpty(currArtifacts)) {
                 artifacts.putAll(currArtifacts);
             }
         }
         if (!artifacts.containsKey(artifactId) && MapUtils.isNotEmpty(component.getArtifacts())) {
-            currArtifacts = component.getArtifacts()
-                    .values()
-                    .stream()
-                    .collect(Collectors.toMap(ArtifactDataDefinition::getUniqueId, Function.identity()));
+            currArtifacts = component.getArtifacts().values().stream()
+                .collect(Collectors.toMap(ArtifactDataDefinition::getUniqueId, Function.identity()));
             if (MapUtils.isNotEmpty(currArtifacts)) {
                 artifacts.putAll(currArtifacts);
             }
         }
         if (!artifacts.containsKey(artifactId) && MapUtils.isNotEmpty(component.getArtifacts())) {
-            currArtifacts = component.getToscaArtifacts()
-                    .values()
-                    .stream()
-                    .collect(Collectors.toMap(ArtifactDataDefinition::getUniqueId, Function.identity()));
+            currArtifacts = component.getToscaArtifacts().values().stream()
+                .collect(Collectors.toMap(ArtifactDataDefinition::getUniqueId, Function.identity()));
             if (MapUtils.isNotEmpty(currArtifacts)) {
                 artifacts.putAll(currArtifacts);
             }
@@ -1556,19 +1430,15 @@ public class ArtifactsBusinessLogic extends BaseBusinessLogic {
     private void fetchArtifactsFromInstance(String artifactId, Map<String, ArtifactDefinition> artifacts, ComponentInstance instance) {
         Map<String, ArtifactDefinition> currArtifacts;
         if (MapUtils.isNotEmpty(instance.getDeploymentArtifacts())) {
-            currArtifacts = instance.getDeploymentArtifacts()
-                    .values()
-                    .stream()
-                    .collect(Collectors.toMap(ArtifactDataDefinition::getUniqueId, Function.identity()));
+            currArtifacts = instance.getDeploymentArtifacts().values().stream()
+                .collect(Collectors.toMap(ArtifactDataDefinition::getUniqueId, Function.identity()));
             if (MapUtils.isNotEmpty(currArtifacts)) {
                 artifacts.putAll(currArtifacts);
             }
         }
         if (!artifacts.containsKey(artifactId) && MapUtils.isNotEmpty(instance.getArtifacts())) {
-            currArtifacts = instance.getArtifacts()
-                    .values()
-                    .stream()
-                    .collect(Collectors.toMap(ArtifactDataDefinition::getUniqueId, Function.identity()));
+            currArtifacts = instance.getArtifacts().values().stream()
+                .collect(Collectors.toMap(ArtifactDataDefinition::getUniqueId, Function.identity()));
             if (MapUtils.isNotEmpty(currArtifacts)) {
                 artifacts.putAll(currArtifacts);
             }
@@ -1621,10 +1491,9 @@ public class ArtifactsBusinessLogic extends BaseBusinessLogic {
         return error;
     }
 
-    private ArtifactDefinition handleDownload(String componentId, String artifactId, ComponentTypeEnum componentType,
-                                              Component parent) {
-        Either<ArtifactDefinition, StorageOperationStatus> artifactById = artifactToscaOperation.getArtifactById(componentId, artifactId, componentType,
-                parent.getUniqueId());
+    private ArtifactDefinition handleDownload(String componentId, String artifactId, ComponentTypeEnum componentType, Component parent) {
+        Either<ArtifactDefinition, StorageOperationStatus> artifactById = artifactToscaOperation
+            .getArtifactById(componentId, artifactId, componentType, parent.getUniqueId());
         if (artifactById.isRight()) {
             throw new StorageException(artifactById.right().value());
         }
@@ -1635,25 +1504,21 @@ public class ArtifactsBusinessLogic extends BaseBusinessLogic {
         return artifactDefinition;
     }
 
-    private Either<ActionStatus, ResponseFormat> handleArtifactLabel(String componentId, Component parentComponent, ArtifactOperationInfo operation, ArtifactDefinition artifactInfo, String operationName,
+    private Either<ActionStatus, ResponseFormat> handleArtifactLabel(String componentId, Component parentComponent, ArtifactOperationInfo operation,
+                                                                     ArtifactDefinition artifactInfo, String operationName,
                                                                      ComponentTypeEnum componentType) {
-
         String artifactLabel = artifactInfo.getArtifactLabel();
-        if (operationName == null && (artifactInfo.getArtifactLabel() == null || artifactInfo.getArtifactLabel()
-                .isEmpty())) {
-            BeEcompErrorManager.getInstance()
-                    .logBeMissingArtifactInformationError("Artifact Update / Upload", "artifactLabel");
+        if (operationName == null && (artifactInfo.getArtifactLabel() == null || artifactInfo.getArtifactLabel().isEmpty())) {
+            BeEcompErrorManager.getInstance().logBeMissingArtifactInformationError("Artifact Update / Upload", "artifactLabel");
             log.debug("missing artifact logical name for component {}", componentId);
             return Either.right(componentsUtils.getResponseFormat(ActionStatus.MISSING_DATA, ARTIFACT_LABEL));
         }
         if (operation.isCreateOrLink() && !artifactInfo.getMandatory()) {
-
             if (operationName != null) {
                 if (artifactInfo.getArtifactLabel() != null && !operationName.equals(artifactInfo.getArtifactLabel())) {
                     log.debug("artifact label cannot be set {}", artifactLabel);
                     return Either.right(componentsUtils.getResponseFormat(ActionStatus.ARTIFACT_LOGICAL_NAME_CANNOT_BE_CHANGED));
-                }
-                else {
+                } else {
                     artifactLabel = operationName;
                 }
             }
@@ -1663,22 +1528,19 @@ public class ArtifactsBusinessLogic extends BaseBusinessLogic {
             }
             displayName = ValidationUtils.cleanArtifactDisplayName(displayName);
             artifactInfo.setArtifactDisplayName(displayName);
-
             if (!ValidationUtils.validateArtifactLabel(artifactLabel)) {
                 log.debug("Invalid format form Artifact label : {}", artifactLabel);
                 return Either.right(componentsUtils.getResponseFormat(ActionStatus.INVALID_CONTENT));
             }
             artifactLabel = ValidationUtils.normalizeArtifactLabel(artifactLabel);
-
             if (artifactLabel.isEmpty()) {
                 log.debug("missing normalized artifact logical name for component {}", componentId);
                 return Either.right(componentsUtils.getResponseFormat(ActionStatus.MISSING_DATA, ARTIFACT_LABEL));
             }
-
             if (!ValidationUtils.validateArtifactLabelLength(artifactLabel)) {
                 log.debug("Invalid lenght form Artifact label : {}", artifactLabel);
-                return Either.right(componentsUtils.getResponseFormat(ActionStatus.EXCEEDS_LIMIT, ARTIFACT_LABEL, String
-                        .valueOf(ValidationUtils.ARTIFACT_LABEL_LENGTH)));
+                return Either.right(componentsUtils
+                    .getResponseFormat(ActionStatus.EXCEEDS_LIMIT, ARTIFACT_LABEL, String.valueOf(ValidationUtils.ARTIFACT_LABEL_LENGTH)));
             }
             if (!validateLabelUniqueness(componentId, parentComponent, artifactLabel, componentType)) {
                 log.debug("Non unique Artifact label : {}", artifactLabel);
@@ -1686,7 +1548,6 @@ public class ArtifactsBusinessLogic extends BaseBusinessLogic {
             }
         }
         artifactInfo.setArtifactLabel(artifactLabel);
-
         return Either.left(ActionStatus.OK);
     }
 
@@ -1695,11 +1556,9 @@ public class ArtifactsBusinessLogic extends BaseBusinessLogic {
         Either<Map<String, ArtifactDefinition>, StorageOperationStatus> artifacts;
         if (componentType == ComponentTypeEnum.RESOURCE_INSTANCE) {
             artifacts = artifactToscaOperation.getAllInstanceArtifacts(parentComponent.getUniqueId(), componentId);
-        }
-        else {
+        } else {
             artifacts = artifactToscaOperation.getArtifacts(componentId);
         }
-
         if (artifacts.isLeft()) {
             for (String label : artifacts.left().value().keySet()) {
                 if (label.equals(artifactLabel)) {
@@ -1716,14 +1575,13 @@ public class ArtifactsBusinessLogic extends BaseBusinessLogic {
 
     boolean validateArtifactNameUniqueness(String componentId, Component parentComponent, ArtifactDefinition artifactInfo,
                                            ComponentTypeEnum componentType) {
-        Either<Map<String, ArtifactDefinition>, StorageOperationStatus> artifacts = getArtifacts(componentType,
-                parentComponent, componentId, artifactInfo.getArtifactGroupType());
+        Either<Map<String, ArtifactDefinition>, StorageOperationStatus> artifacts = getArtifacts(componentType, parentComponent, componentId,
+            artifactInfo.getArtifactGroupType());
         String artifactName = artifactInfo.getArtifactName();
-        if (artifacts.isLeft() && Objects.nonNull(artifacts.left().value())){
-            if (artifacts.left().value().values().stream()
-                    .anyMatch(ad -> artifactName.equals(ad.getArtifactName())
-                            //check whether it is the same artifact we hold (by label)
-                            && !artifactInfo.getArtifactLabel().equals(ad.getArtifactLabel()))){
+        if (artifacts.isLeft() && Objects.nonNull(artifacts.left().value())) {
+            if (artifacts.left().value().values().stream().anyMatch(ad -> artifactName.equals(ad.getArtifactName())
+                //check whether it is the same artifact we hold (by label)
+                && !artifactInfo.getArtifactLabel().equals(ad.getArtifactLabel()))) {
                 return false;
             }
         }
@@ -1735,61 +1593,47 @@ public class ArtifactsBusinessLogic extends BaseBusinessLogic {
 
     private boolean isUniqueArtifactNameInResourceInterfaces(String componentId, String artifactName, String artifactLabel) {
         Either<Map<String, InterfaceDefinition>, StorageOperationStatus> allInterfacesOfResource = interfaceLifecycleOperation
-                .getAllInterfacesOfResource(componentId, true, true);
-
-        if (allInterfacesOfResource.isLeft()){
-            return allInterfacesOfResource.left().value()
-                    .values()
-                    .stream().map(InterfaceDefinition :: getOperationsMap)
-                    .flatMap(map -> map.values().stream())
-                    .map(OperationDataDefinition::getImplementation)
-                    .filter(Objects::nonNull)
-                    .noneMatch(add -> artifactName.equals(add.getArtifactName())
-                            && !artifactLabel.equals(add.getArtifactLabel()));
+            .getAllInterfacesOfResource(componentId, true, true);
+        if (allInterfacesOfResource.isLeft()) {
+            return allInterfacesOfResource.left().value().values().stream().map(InterfaceDefinition::getOperationsMap)
+                .flatMap(map -> map.values().stream()).map(OperationDataDefinition::getImplementation).filter(Objects::nonNull)
+                .noneMatch(add -> artifactName.equals(add.getArtifactName()) && !artifactLabel.equals(add.getArtifactLabel()));
         }
         return true;
     }
 
     private boolean isUniqueLabelInResourceInterfaces(String componentId, String artifactLabel) {
         Either<Map<String, InterfaceDefinition>, StorageOperationStatus> allInterfacesOfResource = interfaceLifecycleOperation
-                .getAllInterfacesOfResource(componentId, true, true);
-
-        if (allInterfacesOfResource.isLeft()){
-            return allInterfacesOfResource.left().value()
-                    .values()
-                    .stream().map(InterfaceDefinition :: getOperationsMap)
-                    .flatMap(map -> map.values().stream())
-                    .map(OperationDataDefinition::getImplementation)
-                    .filter(Objects::nonNull)
-                    .noneMatch(add -> artifactLabel.equals(add.getArtifactLabel()));
+            .getAllInterfacesOfResource(componentId, true, true);
+        if (allInterfacesOfResource.isLeft()) {
+            return allInterfacesOfResource.left().value().values().stream().map(InterfaceDefinition::getOperationsMap)
+                .flatMap(map -> map.values().stream()).map(OperationDataDefinition::getImplementation).filter(Objects::nonNull)
+                .noneMatch(add -> artifactLabel.equals(add.getArtifactLabel()));
         }
         return true;
     }
 
     private Either<Map<String, ArtifactDefinition>, StorageOperationStatus> getArtifacts(ComponentTypeEnum componentType, Component parentComponent,
-                                                                                         String componentId, ArtifactGroupTypeEnum artifactGroupType) {
+                                                                                         String componentId,
+                                                                                         ArtifactGroupTypeEnum artifactGroupType) {
         Either<Map<String, ArtifactDefinition>, StorageOperationStatus> artifactsResponse;
         if (componentType == ComponentTypeEnum.RESOURCE_INSTANCE) {
             artifactsResponse = artifactToscaOperation.getAllInstanceArtifacts(parentComponent.getUniqueId(), componentId);
-        }
-        else {
+        } else {
             artifactsResponse = artifactToscaOperation.getArtifacts(componentId);
         }
         if (artifactsResponse.isRight() && artifactsResponse.right().value() == StorageOperationStatus.NOT_FOUND) {
             log.debug("failed to retrieve artifacts for {} ", componentId);
             return Either.right(artifactsResponse.right().value());
         }
-        return Either.left(artifactsResponse.left().value().entrySet()
-                .stream()
-                .filter(x -> artifactGroupType == x.getValue().getArtifactGroupType())
-                .collect(Collectors.toMap(Entry::getKey, Entry::getValue)));
+        return Either.left(artifactsResponse.left().value().entrySet().stream().filter(x -> artifactGroupType == x.getValue().getArtifactGroupType())
+            .collect(Collectors.toMap(Entry::getKey, Entry::getValue)));
     }
 
     // ***************************************************************
-
-    private Either<ArtifactDefinition, Operation> createArtifact(Component parent, String parentId, ArtifactDefinition artifactInfo, byte[] decodedPayload,
-                                                                 ComponentTypeEnum componentTypeEnum, AuditingActionEnum auditingActionEnum, String interfaceType, String operationName) {
-
+    private Either<ArtifactDefinition, Operation> createArtifact(Component parent, String parentId, ArtifactDefinition artifactInfo,
+                                                                 byte[] decodedPayload, ComponentTypeEnum componentTypeEnum,
+                                                                 AuditingActionEnum auditingActionEnum, String interfaceType, String operationName) {
         DAOArtifactData artifactData = createEsArtifactData(artifactInfo, decodedPayload);
         if (artifactData == null) {
             BeEcompErrorManager.getInstance().logBeDaoSystemError("Upload Artifact");
@@ -1807,29 +1651,27 @@ public class ArtifactsBusinessLogic extends BaseBusinessLogic {
         }
         // set on graph object id of artifact in ES!
         artifactInfo.setEsId(artifactData.getId());
-
         Either<ArtifactDefinition, Operation> operationResult;
         if (interfaceType != null && operationName != null) {
             // lifecycle artifact
             Operation operation = convertToOperation(artifactInfo, operationName);
-            Either<Operation, StorageOperationStatus> result = interfaceLifecycleOperation.updateInterfaceOperation(parentId, interfaceType, operationName, operation);
+            Either<Operation, StorageOperationStatus> result = interfaceLifecycleOperation
+                .updateInterfaceOperation(parentId, interfaceType, operationName, operation);
             if (result.isRight()) {
                 throw new StorageException(result.right().value());
             }
             operationResult = Either.right(result.left().value());
-        }
-        else {
+        } else {
             // information/deployment/api artifacts
             NodeTypeEnum nodeType = convertParentType(componentTypeEnum);
-            Either<ArtifactDefinition, StorageOperationStatus> result = artifactToscaOperation.addArtifactToComponent(
-                    artifactInfo, parent, nodeType, true, instanceId);
+            Either<ArtifactDefinition, StorageOperationStatus> result = artifactToscaOperation
+                .addArtifactToComponent(artifactInfo, parent, nodeType, true, instanceId);
             if (result.isRight()) {
                 throw new StorageException(result.right().value());
             }
             ArtifactDefinition artifactDefinition = result.left().value();
             artifactData.setId(artifactDefinition.getEsId());
             operationResult = Either.left(artifactDefinition);
-
             if (generateCustomizationUUIDOnInstance(parent.getUniqueId(), parentId, componentTypeEnum) != StorageOperationStatus.OK) {
                 throw new StorageException(generateCustomizationUUIDOnInstance(parent.getUniqueId(), parentId, componentTypeEnum));
             }
@@ -1841,24 +1683,19 @@ public class ArtifactsBusinessLogic extends BaseBusinessLogic {
     private ComponentInstance findComponentInstance(String componentInstanceId, Component containerComponent) {
         ComponentInstance foundInstance = null;
         if (CollectionUtils.isNotEmpty(containerComponent.getComponentInstances())) {
-            foundInstance = containerComponent.getComponentInstances()
-                    .stream()
-                    .filter(i -> i.getUniqueId().equals(componentInstanceId))
-                    .findFirst()
-                    .orElse(null);
+            foundInstance = containerComponent.getComponentInstances().stream().filter(i -> i.getUniqueId().equals(componentInstanceId)).findFirst()
+                .orElse(null);
         }
         return foundInstance;
     }
 
     private void validateDeploymentArtifact(final ArtifactDefinition artifactInfo, final Component component) {
         final ComponentTypeEnum componentType = component.getComponentType();
-        if (componentType != ComponentTypeEnum.RESOURCE &&
-            componentType != ComponentTypeEnum.SERVICE &&
-            componentType != ComponentTypeEnum.RESOURCE_INSTANCE) {
-            log.debug("Invalid component type '{}' for artifact. "
-                + "Expected Resource, Component or Resource Instance", componentType.getValue());
-            throw new ByActionStatusComponentException(MISMATCH_BETWEEN_ARTIFACT_TYPE_AND_COMPONENT_TYPE,
-                componentType.getValue(), "Service, Resource or ResourceInstance", componentType.getValue());
+        if (componentType != ComponentTypeEnum.RESOURCE && componentType != ComponentTypeEnum.SERVICE
+            && componentType != ComponentTypeEnum.RESOURCE_INSTANCE) {
+            log.debug("Invalid component type '{}' for artifact. " + "Expected Resource, Component or Resource Instance", componentType.getValue());
+            throw new ByActionStatusComponentException(MISMATCH_BETWEEN_ARTIFACT_TYPE_AND_COMPONENT_TYPE, componentType.getValue(),
+                "Service, Resource or ResourceInstance", componentType.getValue());
         }
         final String artifactType = artifactInfo.getArtifactType();
         final ArtifactConfiguration artifactConfiguration = loadArtifactTypeConfig(artifactType).orElse(null);
@@ -1869,21 +1706,17 @@ public class ArtifactsBusinessLogic extends BaseBusinessLogic {
         if (componentType == ComponentTypeEnum.RESOURCE || componentType == ComponentTypeEnum.RESOURCE_INSTANCE) {
             final Resource resource = (Resource) component;
             final ResourceTypeEnum resourceType = resource.getResourceType();
-
             validateResourceType(resourceType, artifactInfo, artifactConfiguration.getResourceTypes());
         }
-
         validateArtifactExtension(artifactConfiguration, artifactInfo);
     }
 
-    private void validateHeatArtifact(final Component parentComponent, final String componentId,
-                                      final ArtifactDefinition artifactDefinition) {
+    private void validateHeatArtifact(final Component parentComponent, final String componentId, final ArtifactDefinition artifactDefinition) {
         final String artifactType = artifactDefinition.getArtifactType();
         final ArtifactTypeEnum artifactTypeEnum = ArtifactTypeEnum.parse(artifactType);
         if (artifactTypeEnum == null) {
             return;
         }
-
         switch (artifactTypeEnum) {
             case HEAT:
             case HEAT_VOL:
@@ -1898,9 +1731,7 @@ public class ArtifactsBusinessLogic extends BaseBusinessLogic {
         }
     }
 
-    private void setArtifactTimeout(final ArtifactDefinition newArtifactInfo,
-                                    final ArtifactDefinition existingArtifactInfo) {
-
+    private void setArtifactTimeout(final ArtifactDefinition newArtifactInfo, final ArtifactDefinition existingArtifactInfo) {
         final String artifactType = newArtifactInfo.getArtifactType();
         final ArtifactTypeEnum artifactTypeEnum = ArtifactTypeEnum.parse(artifactType);
         if (artifactTypeEnum == null) {
@@ -1926,7 +1757,8 @@ public class ArtifactsBusinessLogic extends BaseBusinessLogic {
     }
 
     @VisibleForTesting
-    void validateDeploymentArtifactTypeIsLegalForParent(ArtifactDefinition artifactInfo, ArtifactTypeEnum artifactType, Map<String, ArtifactTypeConfig> resourceDeploymentArtifacts) {
+    void validateDeploymentArtifactTypeIsLegalForParent(ArtifactDefinition artifactInfo, ArtifactTypeEnum artifactType,
+                                                        Map<String, ArtifactTypeConfig> resourceDeploymentArtifacts) {
         if ((resourceDeploymentArtifacts == null) || !resourceDeploymentArtifacts.containsKey(artifactType.name())) {
             log.debug("Artifact Type: {} Not found !", artifactInfo.getArtifactType());
             throw new ByActionStatusComponentException(ActionStatus.ARTIFACT_TYPE_NOT_SUPPORTED, artifactInfo.getArtifactType());
@@ -1937,14 +1769,12 @@ public class ArtifactsBusinessLogic extends BaseBusinessLogic {
         if (artifactType == null) {
             return Optional.empty();
         }
-        final List<ArtifactConfiguration> artifactConfigurationList =
-            ConfigurationManager.getConfigurationManager().getConfiguration().getArtifacts();
+        final List<ArtifactConfiguration> artifactConfigurationList = ConfigurationManager.getConfigurationManager().getConfiguration()
+            .getArtifacts();
         if (CollectionUtils.isEmpty(artifactConfigurationList)) {
             return Optional.empty();
         }
-
-        return artifactConfigurationList.stream()
-            .filter(artifactConfiguration -> artifactConfiguration.getType().equalsIgnoreCase(artifactType))
+        return artifactConfigurationList.stream().filter(artifactConfiguration -> artifactConfiguration.getType().equalsIgnoreCase(artifactType))
             .findFirst();
     }
 
@@ -1952,25 +1782,22 @@ public class ArtifactsBusinessLogic extends BaseBusinessLogic {
         // extract heat parameters
         if (artifactInfo.getPayloadData() != null) {
             String heatDecodedPayload = new String(Base64.decodeBase64(artifactInfo.getPayloadData()));
-            Either<List<HeatParameterDefinition>, ResultStatusEnum> heatParameters = ImportUtils.getHeatParamsWithoutImplicitTypes(heatDecodedPayload, artifactInfo
-                    .getArtifactType());
+            Either<List<HeatParameterDefinition>, ResultStatusEnum> heatParameters = ImportUtils
+                .getHeatParamsWithoutImplicitTypes(heatDecodedPayload, artifactInfo.getArtifactType());
             if (heatParameters.isRight() && (heatParameters.right().value() != ResultStatusEnum.ELEMENT_NOT_FOUND)) {
                 log.info("failed to parse heat parameters ");
-                ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.INVALID_DEPLOYMENT_ARTIFACT_HEAT, artifactInfo
-                        .getArtifactType());
+                ResponseFormat responseFormat = componentsUtils
+                    .getResponseFormat(ActionStatus.INVALID_DEPLOYMENT_ARTIFACT_HEAT, artifactInfo.getArtifactType());
                 return Either.right(responseFormat);
-            }
-            else if (heatParameters.isLeft() && heatParameters.left().value() != null) {
+            } else if (heatParameters.isLeft() && heatParameters.left().value() != null) {
                 artifactInfo.setListHeatParameters(heatParameters.left().value());
             }
         }
         return Either.left(true);
-
     }
 
     @VisibleForTesting
-    void validateArtifactExtension(final ArtifactConfiguration artifactConfiguration,
-                                   final ArtifactDefinition artifactDefinition) {
+    void validateArtifactExtension(final ArtifactConfiguration artifactConfiguration, final ArtifactDefinition artifactDefinition) {
         final List<String> acceptedTypes = artifactConfiguration.getAcceptedTypes();
         /*
          * No need to check specific types. In case there are no acceptedTypes in configuration, then any type is accepted.
@@ -1980,7 +1807,6 @@ public class ArtifactsBusinessLogic extends BaseBusinessLogic {
         }
         final String artifactName = artifactDefinition.getArtifactName();
         final String fileExtension = FilenameUtils.getExtension(artifactName);
-
         if (fileExtension == null || !acceptedTypes.contains(fileExtension.toLowerCase())) {
             final String artifactType = artifactDefinition.getArtifactType();
             log.debug("File extension \"{}\" is not allowed for artifact type \"{}\"", fileExtension, artifactType);
@@ -1989,18 +1815,14 @@ public class ArtifactsBusinessLogic extends BaseBusinessLogic {
     }
 
     @VisibleForTesting
-    void validateHeatEnvDeploymentArtifact(final Component parentComponent, final String parentId,
-                                           final ArtifactDefinition artifactInfo) {
+    void validateHeatEnvDeploymentArtifact(final Component parentComponent, final String parentId, final ArtifactDefinition artifactInfo) {
         final Wrapper<ArtifactDefinition> heatMDWrapper = new Wrapper<>();
         final Wrapper<byte[]> payloadWrapper = new Wrapper<>();
-
         validateYaml(artifactInfo);
         validateHeatExist(parentComponent.getUniqueId(), parentId, heatMDWrapper, artifactInfo, parentComponent.getComponentType());
-
         if (!heatMDWrapper.isEmpty()) {
             fillArtifactPayload(payloadWrapper, heatMDWrapper.getInnerElement());
         }
-
         if (!heatMDWrapper.isEmpty()) {
             validateEnvVsHeat(artifactInfo, heatMDWrapper.getInnerElement(), payloadWrapper.getInnerElement());
         }
@@ -2012,13 +1834,11 @@ public class ArtifactsBusinessLogic extends BaseBusinessLogic {
             if (eitherArtifactData.isLeft()) {
                 byte[] data = eitherArtifactData.left().value().getDataAsArray();
                 payloadWrapper.setInnerElement(Base64.encodeBase64(data));
-            }
-            else {
+            } else {
                 log.debug("Error getting payload for artifact:{}", artifactDefinition.getArtifactName());
                 throw new StorageException(DaoStatusConverter.convertCassandraStatusToStorageStatus(eitherArtifactData.right().value()));
             }
-        }
-        else {
+        } else {
             payloadWrapper.setInnerElement(artifactDefinition.getPayloadData());
         }
     }
@@ -2028,13 +1848,14 @@ public class ArtifactsBusinessLogic extends BaseBusinessLogic {
         Map<String, Object> heatEnvToscaJson = (Map<String, Object>) new Yaml().load(envPayload);
         String heatDecodedPayload = new String(Base64.decodeBase64(heatPayloadData));
         Map<String, Object> heatToscaJson = (Map<String, Object>) new Yaml().load(heatDecodedPayload);
-
-        Either<Map<String, Object>, ResultStatusEnum> eitherHeatEnvProperties = ImportUtils.findFirstToscaMapElement(heatEnvToscaJson, TypeUtils.ToscaTagNamesEnum.PARAMETERS);
+        Either<Map<String, Object>, ResultStatusEnum> eitherHeatEnvProperties = ImportUtils
+            .findFirstToscaMapElement(heatEnvToscaJson, TypeUtils.ToscaTagNamesEnum.PARAMETERS);
         if (eitherHeatEnvProperties.isRight()) {
             log.debug("Invalid heat env format for file:{}", envArtifact.getArtifactName());
             throw new ByActionStatusComponentException(ActionStatus.CORRUPTED_FORMAT, "Heat Env");
         }
-        Either<Map<String, Object>, ResultStatusEnum> eitherHeatProperties = ImportUtils.findFirstToscaMapElement(heatToscaJson, TypeUtils.ToscaTagNamesEnum.PARAMETERS);
+        Either<Map<String, Object>, ResultStatusEnum> eitherHeatProperties = ImportUtils
+            .findFirstToscaMapElement(heatToscaJson, TypeUtils.ToscaTagNamesEnum.PARAMETERS);
         if (eitherHeatProperties.isRight()) {
             log.debug("Invalid heat format for file:{}", heatArtifact.getArtifactName());
             throw new ByActionStatusComponentException(ActionStatus.CORRUPTED_FORMAT, "Heat");
@@ -2043,8 +1864,10 @@ public class ArtifactsBusinessLogic extends BaseBusinessLogic {
         Set<String> heatEnvPropertiesKeys = eitherHeatEnvProperties.left().value().keySet();
         heatEnvPropertiesKeys.removeAll(heatPropertiesKeys);
         if (!heatEnvPropertiesKeys.isEmpty()) {
-            log.debug("Validation of heat_env for artifact:{} vs heat artifact for artifact :{} failed", envArtifact.getArtifactName(), heatArtifact.getArtifactName());
-            throw new ByActionStatusComponentException(ActionStatus.MISMATCH_HEAT_VS_HEAT_ENV, envArtifact.getArtifactName(), heatArtifact.getArtifactName());
+            log.debug("Validation of heat_env for artifact:{} vs heat artifact for artifact :{} failed", envArtifact.getArtifactName(),
+                heatArtifact.getArtifactName());
+            throw new ByActionStatusComponentException(ActionStatus.MISMATCH_HEAT_VS_HEAT_ENV, envArtifact.getArtifactName(),
+                heatArtifact.getArtifactName());
         }
     }
 
@@ -2059,28 +1882,25 @@ public class ArtifactsBusinessLogic extends BaseBusinessLogic {
 
     private void validateSingleDeploymentArtifactName(final String artifactName, final Component parentComponent) {
         boolean artifactNameFound = false;
-        final Iterator<ArtifactDefinition> parentDeploymentArtifactsItr =
-            getDeploymentArtifacts(parentComponent, null).iterator();
-
+        final Iterator<ArtifactDefinition> parentDeploymentArtifactsItr = getDeploymentArtifacts(parentComponent, null).iterator();
         while (!artifactNameFound && parentDeploymentArtifactsItr.hasNext()) {
             artifactNameFound = artifactName.equalsIgnoreCase(parentDeploymentArtifactsItr.next().getArtifactName());
         }
         if (artifactNameFound) {
             final ComponentTypeEnum componentType = parentComponent.getComponentType();
             log.debug("Can't upload artifact: {}, because another artifact with this name already exist.", artifactName);
-            throw new ByActionStatusComponentException(ActionStatus.DEPLOYMENT_ARTIFACT_NAME_ALREADY_EXISTS,
-                componentType.getValue(), parentComponent.getName(), artifactName);
+            throw new ByActionStatusComponentException(ActionStatus.DEPLOYMENT_ARTIFACT_NAME_ALREADY_EXISTS, componentType.getValue(),
+                parentComponent.getName(), artifactName);
         }
     }
 
-    private void validateHeatExist(String componentId, String parentRiId, Wrapper<ArtifactDefinition> heatArtifactMDWrapper, ArtifactDefinition heatEnvArtifact,
-                                   ComponentTypeEnum componentType) {
+    private void validateHeatExist(String componentId, String parentRiId, Wrapper<ArtifactDefinition> heatArtifactMDWrapper,
+                                   ArtifactDefinition heatEnvArtifact, ComponentTypeEnum componentType) {
         final Either<ArtifactDefinition, StorageOperationStatus> res = artifactToscaOperation
             .getHeatArtifactByHeatEnvId(parentRiId, heatEnvArtifact, componentId, componentType);
         if (res.isRight()) {
             throw new ByActionStatusComponentException(ActionStatus.MISSING_HEAT);
         }
-
         heatArtifactMDWrapper.setInnerElement(res.left().value());
     }
 
@@ -2096,14 +1916,13 @@ public class ArtifactsBusinessLogic extends BaseBusinessLogic {
     }
 
     @VisibleForTesting
-    void validateResourceType(final ResourceTypeEnum resourceType, final ArtifactDefinition artifactInfo,
-                              final List<String> typeList) {
+    void validateResourceType(final ResourceTypeEnum resourceType, final ArtifactDefinition artifactInfo, final List<String> typeList) {
         if (CollectionUtils.isEmpty(typeList) || typeList.contains(resourceType.getValue())) {
             return;
         }
         final String listToString = typeList.stream().collect(Collectors.joining(", "));
-        throw new ByActionStatusComponentException(MISMATCH_BETWEEN_ARTIFACT_TYPE_AND_COMPONENT_TYPE,
-            artifactInfo.getArtifactGroupType().getType(), listToString, resourceType.getValue());
+        throw new ByActionStatusComponentException(MISMATCH_BETWEEN_ARTIFACT_TYPE_AND_COMPONENT_TYPE, artifactInfo.getArtifactGroupType().getType(),
+            listToString, resourceType.getValue());
     }
 
     @VisibleForTesting
@@ -2114,17 +1933,16 @@ public class ArtifactsBusinessLogic extends BaseBusinessLogic {
                 HeatParameterType heatParameterType = HeatParameterType.isValidType(parameterType);
                 String artifactTypeStr = artifactType != null ? artifactType : ArtifactTypeEnum.HEAT.getType();
                 if (heatParameterType == null) {
-                    ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.INVALID_HEAT_PARAMETER_TYPE, artifactTypeStr, heatParam
-                            .getType());
+                    ResponseFormat responseFormat = componentsUtils
+                        .getResponseFormat(ActionStatus.INVALID_HEAT_PARAMETER_TYPE, artifactTypeStr, heatParam.getType());
                     return Either.right(responseFormat);
                 }
-
                 StorageOperationStatus validateAndUpdateProperty = heatParametersOperation.validateAndUpdateProperty(heatParam);
                 if (validateAndUpdateProperty != StorageOperationStatus.OK) {
                     log.debug("Heat parameter {} is invalid. Status is {}", heatParam.getName(), validateAndUpdateProperty);
                     ActionStatus status = ActionStatus.INVALID_HEAT_PARAMETER_VALUE;
-                    ResponseFormat responseFormat = componentsUtils.getResponseFormat(status, artifactTypeStr, heatParam
-                            .getType(), heatParam.getName());
+                    ResponseFormat responseFormat = componentsUtils
+                        .getResponseFormat(status, artifactTypeStr, heatParam.getType(), heatParam.getName());
                     return Either.right(responseFormat);
                 }
             }
@@ -2139,8 +1957,7 @@ public class ArtifactsBusinessLogic extends BaseBusinessLogic {
         }
         final List<ArtifactDefinition> deploymentArtifacts = new ArrayList<>();
         if (ComponentTypeEnum.RESOURCE == componentType && ciId != null) {
-            final Either<ComponentInstance, ResponseFormat> getRI =
-                getRIFromComponent(component, ciId, null, null, null);
+            final Either<ComponentInstance, ResponseFormat> getRI = getRIFromComponent(component, ciId, null, null, null);
             if (getRI.isRight()) {
                 return Collections.emptyList();
             }
@@ -2163,73 +1980,61 @@ public class ArtifactsBusinessLogic extends BaseBusinessLogic {
             log.error("artifact uniqid cannot be set ignoring");
         }
         artifactInfo.setUniqueId(null);
-
         if (artifactInfo.getArtifactRef() != null) {
             log.error("artifact ref cannot be set ignoring");
         }
         artifactInfo.setArtifactRef(null);
-
         if (artifactInfo.getArtifactRepository() != null) {
             log.error("artifact repository cannot be set ignoring");
         }
         artifactInfo.setArtifactRepository(null);
-
         if (artifactInfo.getUserIdCreator() != null) {
             log.error("creator uuid cannot be set ignoring");
         }
         artifactInfo.setArtifactCreator(user.getUserId());
-
         if (artifactInfo.getUserIdLastUpdater() != null) {
             log.error("userId of last updater cannot be set ignoring");
         }
         artifactInfo.setUserIdLastUpdater(user.getUserId());
-
         if (artifactInfo.getCreatorFullName() != null) {
             log.error("creator Full name cannot be set ignoring");
         }
         String fullName = user.getFirstName() + " " + user.getLastName();
         artifactInfo.setUpdaterFullName(fullName);
-
         if (artifactInfo.getUpdaterFullName() != null) {
             log.error("updater Full name cannot be set ignoring");
         }
         artifactInfo.setUpdaterFullName(fullName);
-
         if (artifactInfo.getCreationDate() != null) {
             log.error("Creation Date cannot be set ignoring");
         }
         long time = System.currentTimeMillis();
         artifactInfo.setCreationDate(time);
-
         if (artifactInfo.getLastUpdateDate() != null) {
             log.error("Last Update Date cannot be set ignoring");
         }
         artifactInfo.setLastUpdateDate(time);
-
         if (artifactInfo.getEsId() != null) {
             log.error("es id cannot be set ignoring");
         }
         artifactInfo.setEsId(null);
-
     }
 
-
-    private String composeArtifactId(String resourceId, String artifactId, ArtifactDefinition artifactInfo, String interfaceName, String operationName) {
+    private String composeArtifactId(String resourceId, String artifactId, ArtifactDefinition artifactInfo, String interfaceName,
+                                     String operationName) {
         String id = artifactId;
         if (artifactId == null || artifactId.isEmpty()) {
             String uniqueId = null;
             if (interfaceName != null && operationName != null) {
-                uniqueId = UniqueIdBuilder.buildArtifactByInterfaceUniqueId(resourceId, interfaceName, operationName, artifactInfo
-                        .getArtifactLabel());
-            }
-            else {
+                uniqueId = UniqueIdBuilder
+                    .buildArtifactByInterfaceUniqueId(resourceId, interfaceName, operationName, artifactInfo.getArtifactLabel());
+            } else {
                 uniqueId = UniqueIdBuilder.buildPropertyUniqueId(resourceId, artifactInfo.getArtifactLabel());
             }
             artifactInfo.setUniqueId(uniqueId);
             artifactInfo.setEsId(uniqueId);
             id = uniqueId;
-        }
-        else {
+        } else {
             artifactInfo.setUniqueId(artifactId);
             artifactInfo.setEsId(artifactId);
         }
@@ -2241,7 +2046,6 @@ public class ArtifactsBusinessLogic extends BaseBusinessLogic {
             return Either.right(componentsUtils.getResponseFormat(ActionStatus.MISSING_DATA, ARTIFACT_PAYLOAD));
         }
         return Either.left(true);
-
     }
 
     @VisibleForTesting
@@ -2254,11 +2058,10 @@ public class ArtifactsBusinessLogic extends BaseBusinessLogic {
             return Either.right(componentsUtils.getResponseFormat(ActionStatus.MISSING_ARTIFACT_NAME));
         }
         artifactInfo.setArtifactName(normalizeFileName);
-
         if (!ValidationUtils.validateArtifactNameLength(artifactInfo.getArtifactName())) {
-            return Either.right(componentsUtils.getResponseFormat(ActionStatus.EXCEEDS_LIMIT, ARTIFACT_NAME, String.valueOf(ValidationUtils.ARTIFACT_NAME_LENGTH)));
+            return Either.right(
+                componentsUtils.getResponseFormat(ActionStatus.EXCEEDS_LIMIT, ARTIFACT_NAME, String.valueOf(ValidationUtils.ARTIFACT_NAME_LENGTH)));
         }
-
         return Either.left(true);
     }
 
@@ -2267,21 +2070,18 @@ public class ArtifactsBusinessLogic extends BaseBusinessLogic {
             log.info("artifact type is missing operation ignored");
             throw new ByActionStatusComponentException(ActionStatus.MISSING_ARTIFACT_TYPE);
         }
-
         if (!currentArtifact.getArtifactType().equalsIgnoreCase(artifactInfo.getArtifactType())) {
             log.info("artifact type cannot be changed operation ignored");
             throw new ByActionStatusComponentException(ActionStatus.INVALID_CONTENT);
         }
     }
 
-    private Either<ArtifactDefinition, ResponseFormat> validateOrSetArtifactGroupType(ArtifactDefinition artifactInfo, ArtifactDefinition currentArtifact) {
-
+    private Either<ArtifactDefinition, ResponseFormat> validateOrSetArtifactGroupType(ArtifactDefinition artifactInfo,
+                                                                                      ArtifactDefinition currentArtifact) {
         if (Objects.nonNull(artifactInfo) && Objects.nonNull(currentArtifact)) {
             if (artifactInfo.getArtifactGroupType() == null) {
                 artifactInfo.setArtifactGroupType(currentArtifact.getArtifactGroupType());
-            } else if (!currentArtifact.getArtifactGroupType()
-                    .getType()
-                    .equalsIgnoreCase(artifactInfo.getArtifactGroupType().getType())) {
+            } else if (!currentArtifact.getArtifactGroupType().getType().equalsIgnoreCase(artifactInfo.getArtifactGroupType().getType())) {
                 log.info("artifact group type cannot be changed. operation failed");
                 return Either.right(componentsUtils.getResponseFormat(ActionStatus.INVALID_CONTENT));
             }
@@ -2289,126 +2089,93 @@ public class ArtifactsBusinessLogic extends BaseBusinessLogic {
         return Either.left(artifactInfo);
     }
 
-    private void checkAndSetUnUpdatableFields(User user, ArtifactDefinition artifactInfo, ArtifactDefinition currentArtifact, ArtifactGroupTypeEnum type) {
-
+    private void checkAndSetUnUpdatableFields(User user, ArtifactDefinition artifactInfo, ArtifactDefinition currentArtifact,
+                                              ArtifactGroupTypeEnum type) {
         // on update if null add informational to current
         if (currentArtifact.getArtifactGroupType() == null && type != null) {
             currentArtifact.setArtifactGroupType(type);
         }
-
         if (artifactInfo.getUniqueId() != null && !currentArtifact.getUniqueId().equals(artifactInfo.getUniqueId())) {
             log.error("artifact uniqid cannot be set ignoring");
         }
         artifactInfo.setUniqueId(currentArtifact.getUniqueId());
-
-        if (artifactInfo.getArtifactRef() != null && !currentArtifact.getArtifactRef()
-                .equals(artifactInfo.getArtifactRef())) {
+        if (artifactInfo.getArtifactRef() != null && !currentArtifact.getArtifactRef().equals(artifactInfo.getArtifactRef())) {
             log.error("artifact ref cannot be set ignoring");
         }
         artifactInfo.setArtifactRef(currentArtifact.getArtifactRef());
-
-        if (artifactInfo.getArtifactRepository() != null && !currentArtifact.getArtifactRepository()
-                .equals(artifactInfo.getArtifactRepository())) {
+        if (artifactInfo.getArtifactRepository() != null && !currentArtifact.getArtifactRepository().equals(artifactInfo.getArtifactRepository())) {
             log.error("artifact repository cannot be set ignoring");
         }
         artifactInfo.setArtifactRepository(currentArtifact.getArtifactRepository());
-
-        if (artifactInfo.getUserIdCreator() != null && !currentArtifact.getUserIdCreator()
-                .equals(artifactInfo.getUserIdCreator())) {
+        if (artifactInfo.getUserIdCreator() != null && !currentArtifact.getUserIdCreator().equals(artifactInfo.getUserIdCreator())) {
             log.error("creator uuid cannot be set ignoring");
         }
         artifactInfo.setUserIdCreator(currentArtifact.getUserIdCreator());
-
-        if (artifactInfo.getArtifactCreator() != null && !currentArtifact.getArtifactCreator()
-                .equals(artifactInfo.getArtifactCreator())) {
+        if (artifactInfo.getArtifactCreator() != null && !currentArtifact.getArtifactCreator().equals(artifactInfo.getArtifactCreator())) {
             log.error("artifact creator cannot be set ignoring");
         }
         artifactInfo.setArtifactCreator(currentArtifact.getArtifactCreator());
-
-        if (artifactInfo.getUserIdLastUpdater() != null && !currentArtifact.getUserIdLastUpdater()
-                .equals(artifactInfo.getUserIdLastUpdater())) {
+        if (artifactInfo.getUserIdLastUpdater() != null && !currentArtifact.getUserIdLastUpdater().equals(artifactInfo.getUserIdLastUpdater())) {
             log.error("userId of last updater cannot be set ignoring");
         }
         artifactInfo.setUserIdLastUpdater(user.getUserId());
-
-        if (artifactInfo.getCreatorFullName() != null && !currentArtifact.getCreatorFullName()
-                .equals(artifactInfo.getCreatorFullName())) {
+        if (artifactInfo.getCreatorFullName() != null && !currentArtifact.getCreatorFullName().equals(artifactInfo.getCreatorFullName())) {
             log.error("creator Full name cannot be set ignoring");
         }
         artifactInfo.setCreatorFullName(currentArtifact.getCreatorFullName());
-
-        if (artifactInfo.getUpdaterFullName() != null && !currentArtifact.getUpdaterFullName()
-                .equals(artifactInfo.getUpdaterFullName())) {
+        if (artifactInfo.getUpdaterFullName() != null && !currentArtifact.getUpdaterFullName().equals(artifactInfo.getUpdaterFullName())) {
             log.error("updater Full name cannot be set ignoring");
         }
         String fullName = user.getFirstName() + " " + user.getLastName();
         artifactInfo.setUpdaterFullName(fullName);
-
-        if (artifactInfo.getCreationDate() != null && !currentArtifact.getCreationDate()
-                .equals(artifactInfo.getCreationDate())) {
+        if (artifactInfo.getCreationDate() != null && !currentArtifact.getCreationDate().equals(artifactInfo.getCreationDate())) {
             log.error("Creation Date cannot be set ignoring");
         }
         artifactInfo.setCreationDate(currentArtifact.getCreationDate());
-
-        if (artifactInfo.getLastUpdateDate() != null && !currentArtifact.getLastUpdateDate()
-                .equals(artifactInfo.getLastUpdateDate())) {
+        if (artifactInfo.getLastUpdateDate() != null && !currentArtifact.getLastUpdateDate().equals(artifactInfo.getLastUpdateDate())) {
             log.error("Last Update Date cannot be set ignoring");
         }
         long time = System.currentTimeMillis();
         artifactInfo.setLastUpdateDate(time);
-
         if (artifactInfo.getEsId() != null && !currentArtifact.getEsId().equals(artifactInfo.getEsId())) {
             log.error("es id cannot be set ignoring");
         }
         artifactInfo.setEsId(currentArtifact.getUniqueId());
-
         if (artifactInfo.getArtifactDisplayName() != null && !currentArtifact.getArtifactDisplayName()
-                .equals(artifactInfo.getArtifactDisplayName())) {
+            .equals(artifactInfo.getArtifactDisplayName())) {
             log.error(" Artifact Display Name cannot be set ignoring");
         }
         artifactInfo.setArtifactDisplayName(currentArtifact.getArtifactDisplayName());
-
-        if (artifactInfo.getServiceApi() != null && !currentArtifact.getServiceApi()
-                .equals(artifactInfo.getServiceApi())) {
+        if (artifactInfo.getServiceApi() != null && !currentArtifact.getServiceApi().equals(artifactInfo.getServiceApi())) {
             log.debug("serviceApi cannot be set. ignoring.");
         }
         artifactInfo.setServiceApi(currentArtifact.getServiceApi());
-
         if (artifactInfo.getArtifactGroupType() != null && currentArtifact.getArtifactGroupType() != artifactInfo.getArtifactGroupType()) {
             log.debug("artifact group cannot be set. ignoring.");
         }
         artifactInfo.setArtifactGroupType(currentArtifact.getArtifactGroupType());
-
         artifactInfo.setArtifactVersion(currentArtifact.getArtifactVersion());
-
-        if (artifactInfo.getArtifactUUID() != null && !artifactInfo.getArtifactUUID()
-                .isEmpty() && !currentArtifact.getArtifactUUID()
-                .equals(artifactInfo.getArtifactUUID())) {
+        if (artifactInfo.getArtifactUUID() != null && !artifactInfo.getArtifactUUID().isEmpty() && !currentArtifact.getArtifactUUID()
+            .equals(artifactInfo.getArtifactUUID())) {
             log.debug("artifact UUID cannot be set. ignoring.");
         }
         artifactInfo.setArtifactUUID(currentArtifact.getArtifactUUID());
-
-        if ((artifactInfo.getHeatParameters() != null) && (currentArtifact.getHeatParameters() != null) && !artifactInfo
-                .getHeatParameters()
-                .isEmpty() && !currentArtifact.getHeatParameters().isEmpty()) {
+        if ((artifactInfo.getHeatParameters() != null) && (currentArtifact.getHeatParameters() != null) && !artifactInfo.getHeatParameters().isEmpty()
+            && !currentArtifact.getHeatParameters().isEmpty()) {
             checkAndSetUnupdatableHeatParams(artifactInfo.getListHeatParameters(), currentArtifact.getListHeatParameters());
         }
     }
 
     private void checkAndSetUnupdatableHeatParams(List<HeatParameterDefinition> heatParameters, List<HeatParameterDefinition> currentParameters) {
-
         Map<String, HeatParameterDefinition> currentParametersMap = getMapOfParameters(currentParameters);
         for (HeatParameterDefinition parameter : heatParameters) {
             HeatParameterDefinition currentParam = currentParametersMap.get(parameter.getUniqueId());
-
             if (currentParam != null) {
-
                 if (parameter.getName() != null && !parameter.getName().equalsIgnoreCase(currentParam.getName())) {
                     log.debug("heat parameter name cannot be updated  ({}). ignoring.", parameter.getName());
                     parameter.setName(currentParam.getName());
                 }
-                if (parameter.getDefaultValue() != null && !parameter.getDefaultValue()
-                        .equalsIgnoreCase(currentParam.getDefaultValue())) {
+                if (parameter.getDefaultValue() != null && !parameter.getDefaultValue().equalsIgnoreCase(currentParam.getDefaultValue())) {
                     log.debug("heat parameter defaultValue cannot be updated  ({}). ignoring.", parameter.getDefaultValue());
                     parameter.setDefaultValue(currentParam.getDefaultValue());
                 }
@@ -2416,12 +2183,10 @@ public class ArtifactsBusinessLogic extends BaseBusinessLogic {
                     log.debug("heat parameter type cannot be updated  ({}). ignoring.", parameter.getType());
                     parameter.setType(currentParam.getType());
                 }
-                if (parameter.getDescription() != null && !parameter.getDescription()
-                        .equalsIgnoreCase(currentParam.getDescription())) {
+                if (parameter.getDescription() != null && !parameter.getDescription().equalsIgnoreCase(currentParam.getDescription())) {
                     log.debug("heat parameter description cannot be updated  ({}). ignoring.", parameter.getDescription());
                     parameter.setDescription(currentParam.getDescription());
                 }
-
                 // check and set current value
                 if ((parameter.getCurrentValue() == null) && (currentParam.getDefaultValue() != null)) {
                     log.debug("heat parameter current value is null. set it to default value {}). ignoring.", parameter.getDefaultValue());
@@ -2432,7 +2197,6 @@ public class ArtifactsBusinessLogic extends BaseBusinessLogic {
     }
 
     private Map<String, HeatParameterDefinition> getMapOfParameters(List<HeatParameterDefinition> currentParameters) {
-
         Map<String, HeatParameterDefinition> currentParamsMap = new HashMap<>();
         for (HeatParameterDefinition param : currentParameters) {
             currentParamsMap.put(param.getUniqueId(), param);
@@ -2446,14 +2210,13 @@ public class ArtifactsBusinessLogic extends BaseBusinessLogic {
             return Either.right(componentsUtils.getResponseFormat(ActionStatus.MISSING_DATA, ARTIFACT_URL));
         }
         artifactInfo.setApiUrl(artifactInfo.getApiUrl().toLowerCase());
-
         if (!ValidationUtils.validateUrl(artifactInfo.getApiUrl())) {
             return Either.right(componentsUtils.getResponseFormat(ActionStatus.INVALID_SERVICE_API_URL));
         }
         if (!ValidationUtils.validateUrlLength(artifactInfo.getApiUrl())) {
-            return Either.right(componentsUtils.getResponseFormat(ActionStatus.EXCEEDS_LIMIT, ARTIFACT_URL, String.valueOf(ValidationUtils.API_URL_LENGTH)));
+            return Either
+                .right(componentsUtils.getResponseFormat(ActionStatus.EXCEEDS_LIMIT, ARTIFACT_URL, String.valueOf(ValidationUtils.API_URL_LENGTH)));
         }
-
         return Either.left(true);
     }
 
@@ -2471,16 +2234,16 @@ public class ArtifactsBusinessLogic extends BaseBusinessLogic {
             return Either.right(componentsUtils.getResponseFormat(ActionStatus.INVALID_CONTENT));
         }
         if (!ValidationUtils.validateLength(description, ValidationUtils.ARTIFACT_DESCRIPTION_MAX_LENGTH)) {
-            return Either.right(componentsUtils.getResponseFormat(ActionStatus.EXCEEDS_LIMIT, ARTIFACT_DESCRIPTION, String
-                    .valueOf(ValidationUtils.ARTIFACT_DESCRIPTION_MAX_LENGTH)));
+            return Either.right(componentsUtils.getResponseFormat(ActionStatus.EXCEEDS_LIMIT, ARTIFACT_DESCRIPTION,
+                String.valueOf(ValidationUtils.ARTIFACT_DESCRIPTION_MAX_LENGTH)));
         }
         artifactInfo.setDescription(description);
         return Either.left(true);
     }
 
     private <T> Either<ArtifactDefinition, T> updateArtifactFlow(Component parent, String parentId, String artifactId,
-        ArtifactDefinition artifactInfo, byte[] decodedPayload,
-        ComponentTypeEnum componentType, AuditingActionEnum auditingAction) {
+                                                                 ArtifactDefinition artifactInfo, byte[] decodedPayload,
+                                                                 ComponentTypeEnum componentType, AuditingActionEnum auditingAction) {
         DAOArtifactData artifactData = createEsArtifactData(artifactInfo, decodedPayload);
         if (artifactData == null) {
             BeEcompErrorManager.getInstance().logBeDaoSystemError(UPDATE_ARTIFACT);
@@ -2490,9 +2253,7 @@ public class ArtifactsBusinessLogic extends BaseBusinessLogic {
         log.debug("Entry on graph is updated. Update artifact in ES");
         // Changing previous and current artifactId for auditing
         String currArtifactId = artifactInfo.getUniqueId();
-
         NodeTypeEnum parentType = convertParentType(componentType);
-
         if (decodedPayload == null) {
             if (!artifactInfo.getMandatory() || artifactInfo.getEsId() != null) {
                 Either<DAOArtifactData, CassandraOperationStatus> artifactFromCassandra = artifactCassandraDao.getArtifact(artifactInfo.getEsId());
@@ -2507,15 +2268,13 @@ public class ArtifactsBusinessLogic extends BaseBusinessLogic {
             artifactInfo.setEsId(artifactInfo.getUniqueId());
             artifactData.setId(artifactInfo.getUniqueId());
         }
-
-        Either<ArtifactDefinition, StorageOperationStatus> result = artifactToscaOperation.updateArtifactOnResource(artifactInfo,
-                parent, artifactId, parentType, parentId, true);
+        Either<ArtifactDefinition, StorageOperationStatus> result = artifactToscaOperation
+            .updateArtifactOnResource(artifactInfo, parent, artifactId, parentType, parentId, true);
         if (result.isRight()) {
             throw new StorageException(result.right().value());
         }
         ArtifactDefinition artifactDefinition = result.left().value();
         updateGeneratedIdInHeatEnv(parent, parentId, artifactId, artifactInfo, artifactDefinition, parentType);
-
         StorageOperationStatus storageOperationStatus = generateCustomizationUUIDOnInstance(parent.getUniqueId(), parentId, componentType);
         if (storageOperationStatus != StorageOperationStatus.OK) {
             throw new StorageException(storageOperationStatus);
@@ -2529,42 +2288,47 @@ public class ArtifactsBusinessLogic extends BaseBusinessLogic {
         return Either.left(artifactDefinition);
     }
 
-    private String updateGeneratedIdInHeatEnv(Component parent, String parentId, String artifactId, ArtifactDefinition artifactInfo, ArtifactDefinition artifactDefinition, NodeTypeEnum parentType) {
+    private String updateGeneratedIdInHeatEnv(Component parent, String parentId, String artifactId, ArtifactDefinition artifactInfo,
+                                              ArtifactDefinition artifactDefinition, NodeTypeEnum parentType) {
         if (NodeTypeEnum.Resource == parentType) {
-            return updateGeneratedIdInHeatEnv(parent.getDeploymentArtifacts(), parent, parentId, artifactId, artifactInfo, artifactDefinition, parentType, false);
+            return updateGeneratedIdInHeatEnv(parent.getDeploymentArtifacts(), parent, parentId, artifactId, artifactInfo, artifactDefinition,
+                parentType, false);
         }
         return artifactDefinition.getUniqueId();
     }
 
-    private String updateGeneratedIdInHeatEnv(Map<String, ArtifactDefinition> deploymentArtifacts, Component parentComponent, String parentId, String artifactId, ArtifactDefinition artifactInfo, ArtifactDefinition artifactDefinition, NodeTypeEnum parentType, boolean isInstanceArtifact) {
+    private String updateGeneratedIdInHeatEnv(Map<String, ArtifactDefinition> deploymentArtifacts, Component parentComponent, String parentId,
+                                              String artifactId, ArtifactDefinition artifactInfo, ArtifactDefinition artifactDefinition,
+                                              NodeTypeEnum parentType, boolean isInstanceArtifact) {
         String artifactUniqueId;
         artifactUniqueId = artifactDefinition.getUniqueId();
         String artifactType = artifactInfo.getArtifactType();
-        if ((ArtifactTypeEnum.HEAT.getType().equalsIgnoreCase(artifactType) ||
-                ArtifactTypeEnum.HEAT_VOL.getType().equalsIgnoreCase(artifactType) ||
-                ArtifactTypeEnum.HEAT_NET.getType().equalsIgnoreCase(artifactType))
-                && !artifactUniqueId.equals(artifactId)) {
+        if ((ArtifactTypeEnum.HEAT.getType().equalsIgnoreCase(artifactType) || ArtifactTypeEnum.HEAT_VOL.getType().equalsIgnoreCase(artifactType)
+            || ArtifactTypeEnum.HEAT_NET.getType().equalsIgnoreCase(artifactType)) && !artifactUniqueId.equals(artifactId)) {
             // need to update the generated id in heat env
-            Optional<Entry<String, ArtifactDefinition>> findFirst = deploymentArtifacts.entrySet()
-                    .stream()
-                    .filter(a -> artifactId.equals(a.getValue().getGeneratedFromId()))
-                    .findFirst();
+            Optional<Entry<String, ArtifactDefinition>> findFirst = deploymentArtifacts.entrySet().stream()
+                .filter(a -> artifactId.equals(a.getValue().getGeneratedFromId())).findFirst();
             if (findFirst.isPresent()) {
                 ArtifactDefinition artifactEnvInfo = findFirst.get().getValue();
                 artifactEnvInfo.setIsFromCsar(artifactDefinition.getIsFromCsar());
                 artifactEnvInfo.setArtifactChecksum(null);
                 if (isInstanceArtifact) {
-                    artifactToscaOperation.updateHeatEnvArtifactOnInstance(parentComponent, artifactEnvInfo, artifactId, artifactUniqueId, parentType, parentId);
+                    artifactToscaOperation
+                        .updateHeatEnvArtifactOnInstance(parentComponent, artifactEnvInfo, artifactId, artifactUniqueId, parentType, parentId);
                 } else {
-                    artifactToscaOperation.updateHeatEnvArtifact(parentComponent, artifactEnvInfo, artifactId, artifactUniqueId, parentType, parentId);
+                    artifactToscaOperation
+                        .updateHeatEnvArtifact(parentComponent, artifactEnvInfo, artifactId, artifactUniqueId, parentType, parentId);
                 }
             }
         }
         return artifactUniqueId;
     }
 
-    private String updateGeneratedIdInHeatEnvOnInstance(ComponentInstance parent, Component parentComponent, String artifactId, ArtifactDefinition artifactInfo, ArtifactDefinition artifactDefinition, NodeTypeEnum parentType) {
-        return updateGeneratedIdInHeatEnv(parent.getDeploymentArtifacts(), parentComponent, parent.getUniqueId(),artifactId, artifactInfo, artifactDefinition, parentType, true);
+    private String updateGeneratedIdInHeatEnvOnInstance(ComponentInstance parent, Component parentComponent, String artifactId,
+                                                        ArtifactDefinition artifactInfo, ArtifactDefinition artifactDefinition,
+                                                        NodeTypeEnum parentType) {
+        return updateGeneratedIdInHeatEnv(parent.getDeploymentArtifacts(), parentComponent, parent.getUniqueId(), artifactId, artifactInfo,
+            artifactDefinition, parentType, true);
     }
 
     @VisibleForTesting
@@ -2572,7 +2336,6 @@ public class ArtifactsBusinessLogic extends BaseBusinessLogic {
         log.trace("Starting payload handling");
         byte[] payload = artifactInfo.getPayloadData();
         byte[] decodedPayload = null;
-
         if (payload != null && payload.length != 0) {
             // the generated artifacts were already decoded by the handler
             decodedPayload = artifactInfo.getGenerated() ? payload : Base64.decodeBase64(payload);
@@ -2581,11 +2344,9 @@ public class ArtifactsBusinessLogic extends BaseBusinessLogic {
                 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.INVALID_CONTENT);
                 return Either.right(responseFormat);
             }
-
             String checkSum = GeneralUtility.calculateMD5Base64EncodedByByteArray(decodedPayload);
             artifactInfo.setArtifactChecksum(checkSum);
             log.trace("Calculated checksum, base64 payload: {},  checksum: {}", payload, checkSum);
-
             // Specific payload validations of different types
             Either<Boolean, ResponseFormat> result = Either.left(true);
             if (isDeploymentArtifact(artifactInfo)) {
@@ -2593,18 +2354,15 @@ public class ArtifactsBusinessLogic extends BaseBusinessLogic {
                 String artifactType = artifactInfo.getArtifactType();
                 String fileExtension = GeneralUtility.getFilenameExtension(artifactInfo.getArtifactName());
                 PayloadTypeEnum payloadType = ArtifactTypeToPayloadTypeSelector.getPayloadType(artifactType, fileExtension);
-
                 final Optional<ResponseFormat> pmDictionaryError = validateIfPmDictionary(artifactType, decodedPayload);
                 if (pmDictionaryError.isPresent()) {
                     return Either.right(pmDictionaryError.get());
                 }
-
                 Either<Boolean, ActionStatus> isPayloadValid = payloadType.isValid(decodedPayload);
                 if (isPayloadValid.isRight()) {
                     ResponseFormat responseFormat = componentsUtils.getResponseFormat(isPayloadValid.right().value(), artifactType);
                     return Either.right(responseFormat);
                 }
-
                 if (payloadType.isHeatRelated()) {
                     log.trace("Payload is heat related so going to extract heat parameters for artifact type {}", artifactType);
                     result = extractHeatParameters(artifactInfo);
@@ -2613,13 +2371,14 @@ public class ArtifactsBusinessLogic extends BaseBusinessLogic {
             if (result.isRight()) {
                 return Either.right(result.right().value());
             }
-
         } // null/empty payload is normal if called from metadata update ONLY.
+
         // The validation of whether this is metadata/payload update case is
+
         // currently done separately
         else {
             if (!isArtifactMetadataUpdate) {
-                log.debug("In artifact: {} Payload is missing.",artifactInfo.getArtifactName());
+                log.debug("In artifact: {} Payload is missing.", artifactInfo.getArtifactName());
                 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.MISSING_DATA, ARTIFACT_PAYLOAD);
                 return Either.right(responseFormat);
             }
@@ -2629,26 +2388,19 @@ public class ArtifactsBusinessLogic extends BaseBusinessLogic {
     }
 
     private Optional<ResponseFormat> validateIfPmDictionary(String artifactType, byte[] decodedPayload) {
-        return new PMDictionaryValidator()
-            .validateIfPmDictionary(artifactType, decodedPayload)
-            .map(this::preparePmDictionaryResponse);
+        return new PMDictionaryValidator().validateIfPmDictionary(artifactType, decodedPayload).map(this::preparePmDictionaryResponse);
     }
 
     private ResponseFormat preparePmDictionaryResponse(String errorMessage) {
         return componentsUtils.getResponseFormat(ActionStatus.INVALID_PM_DICTIONARY_FILE, errorMessage);
     }
 
-    public Either<ArtifactDefinition, ResponseFormat> deleteArtifactByInterface(
-        String resourceId, String userUserId, String artifactId, boolean inTransaction) {
-
-        return toscaOperationFacade
-            .getToscaElement(resourceId, JsonParseFlagEnum.ParseMetadata)
-            .right().map(componentsUtils.toResponseFormat())
+    public Either<ArtifactDefinition, ResponseFormat> deleteArtifactByInterface(String resourceId, String userUserId, String artifactId,
+                                                                                boolean inTransaction) {
+        return toscaOperationFacade.getToscaElement(resourceId, JsonParseFlagEnum.ParseMetadata).right().map(componentsUtils.toResponseFormat())
             .left().bind(parentComponent -> {
                 User user = new User(userUserId);
-                return handleDelete(resourceId, artifactId, user,
-                    parentComponent,
-                    false, inTransaction);
+                return handleDelete(resourceId, artifactId, user, parentComponent, false, inTransaction);
             });
     }
 
@@ -2656,10 +2408,8 @@ public class ArtifactsBusinessLogic extends BaseBusinessLogic {
         Operation op = new Operation();
         long time = System.currentTimeMillis();
         op.setCreationDate(time);
-
         String artifactName = artifactInfo.getArtifactName();
         artifactInfo.setArtifactName(createInterfaceArtifactNameFromOperation(operationName, artifactName));
-
         op.setImplementation(artifactInfo);
         op.setLastUpdateDate(time);
         return op;
@@ -2672,46 +2422,37 @@ public class ArtifactsBusinessLogic extends BaseBusinessLogic {
     }
 
     // download by MSO
-    public byte[] downloadRsrcArtifactByNames(String serviceName, String serviceVersion, String resourceName, String resourceVersion, String artifactName) {
-
+    public byte[] downloadRsrcArtifactByNames(String serviceName, String serviceVersion, String resourceName, String resourceVersion,
+                                              String artifactName) {
         // General validation
         if (serviceName == null || serviceVersion == null || resourceName == null || resourceVersion == null || artifactName == null) {
             log.debug(NULL_PARAMETER);
             throw new ByActionStatusComponentException(ActionStatus.INVALID_CONTENT);
         }
-
         // Normalizing artifact name
         artifactName = ValidationUtils.normalizeFileName(artifactName);
-
         // Resource validation
         Resource resource = validateResourceNameAndVersion(resourceName, resourceVersion);
         String resourceId = resource.getUniqueId();
-
         // Service validation
         Service validateServiceNameAndVersion = validateServiceNameAndVersion(serviceName, serviceVersion);
-
         Map<String, ArtifactDefinition> artifacts = resource.getDeploymentArtifacts();
         if (artifacts == null || artifacts.isEmpty()) {
             log.debug("Deployment artifacts of resource {} are not found", resourceId);
             throw new ByActionStatusComponentException(ActionStatus.ARTIFACT_NOT_FOUND, artifactName);
         }
-
         ArtifactDefinition deploymentArtifact = null;
-
         for (ArtifactDefinition artifactDefinition : artifacts.values()) {
-            if (artifactDefinition.getArtifactName() != null && artifactDefinition.getArtifactName()
-                    .equals(artifactName)) {
+            if (artifactDefinition.getArtifactName() != null && artifactDefinition.getArtifactName().equals(artifactName)) {
                 log.debug(FOUND_DEPLOYMENT_ARTIFACT, artifactName);
                 deploymentArtifact = artifactDefinition;
                 break;
             }
         }
-
         if (deploymentArtifact == null) {
             log.debug("No deployment artifact {} was found for resource {}", artifactName, resourceId);
             throw new ByActionStatusComponentException(ActionStatus.ARTIFACT_NOT_FOUND, artifactName);
         }
-
         // Downloading the artifact
         ImmutablePair<String, byte[]> downloadArtifactEither = downloadArtifact(deploymentArtifact);
         log.trace("Download of resource artifact succeeded, uniqueId {}", deploymentArtifact.getUniqueId());
@@ -2720,47 +2461,33 @@ public class ArtifactsBusinessLogic extends BaseBusinessLogic {
 
     // download by MSO
     public byte[] downloadRsrcInstArtifactByNames(String serviceName, String serviceVersion, String resourceInstanceName, String artifactName) {
-
         // General validation
         if (serviceName == null || serviceVersion == null || resourceInstanceName == null || artifactName == null) {
             log.debug(NULL_PARAMETER);
             throw new ByActionStatusComponentException(ActionStatus.INVALID_CONTENT);
         }
-
         // Normalizing artifact name
         artifactName = ValidationUtils.normalizeFileName(artifactName);
-
         // Service validation
         Service service = validateServiceNameAndVersion(serviceName, serviceVersion);
-
         // ResourceInstance validation
         ComponentInstance resourceInstance = validateResourceInstance(service, resourceInstanceName);
-
         Map<String, ArtifactDefinition> artifacts = resourceInstance.getDeploymentArtifacts();
-
         final String finalArtifactName = artifactName;
         Predicate<ArtifactDefinition> filterArtifactByName = p -> p.getArtifactName().equals(finalArtifactName);
-
-        ArtifactDefinition deployableArtifact = artifacts==null ? null :
-                artifacts.values().stream()
-                        .filter(filterArtifactByName)
-                        .findFirst()
-                        .orElse(null);
-
+        ArtifactDefinition deployableArtifact =
+            artifacts == null ? null : artifacts.values().stream().filter(filterArtifactByName).findFirst().orElse(null);
         if (deployableArtifact == null) {
             log.debug("Deployment artifact with name {} not found", artifactName);
             throw new ByResponseFormatComponentException(componentsUtils.getResponseFormat(ActionStatus.ARTIFACT_NOT_FOUND, artifactName));
         }
-
         log.debug(FOUND_DEPLOYMENT_ARTIFACT, artifactName);
         ImmutablePair<String, byte[]> downloadArtifactEither = downloadArtifact(deployableArtifact);
-
         log.trace("Download of resource artifact succeeded, uniqueId {}", deployableArtifact.getUniqueId());
         return downloadArtifactEither.getRight();
     }
 
     private ComponentInstance validateResourceInstance(Service service, String resourceInstanceName) {
-
         List<ComponentInstance> riList = service.getComponentInstances();
         for (ComponentInstance ri : riList) {
             if (ri.getNormalizedName().equals(resourceInstanceName)) {
@@ -2771,7 +2498,6 @@ public class ArtifactsBusinessLogic extends BaseBusinessLogic {
     }
 
     private ComponentInstance validateResourceInstanceById(Component component, String resourceInstanceId) {
-
         List<ComponentInstance> riList = component.getComponentInstances();
         for (ComponentInstance ri : riList) {
             if (ri.getUniqueId().equals(resourceInstanceId)) {
@@ -2782,20 +2508,18 @@ public class ArtifactsBusinessLogic extends BaseBusinessLogic {
     }
 
     private Service validateServiceNameAndVersion(String serviceName, String serviceVersion) {
-
-        Either<List<Service>, StorageOperationStatus> serviceListBySystemName = toscaOperationFacade.getBySystemName(ComponentTypeEnum.SERVICE, serviceName);
+        Either<List<Service>, StorageOperationStatus> serviceListBySystemName = toscaOperationFacade
+            .getBySystemName(ComponentTypeEnum.SERVICE, serviceName);
         if (serviceListBySystemName.isRight()) {
             log.debug("Couldn't fetch any service with name {}", serviceName);
-            throw new ByActionStatusComponentException(componentsUtils.convertFromStorageResponse(serviceListBySystemName
-                    .right()
-                    .value(), ComponentTypeEnum.SERVICE), serviceName);
+            throw new ByActionStatusComponentException(
+                componentsUtils.convertFromStorageResponse(serviceListBySystemName.right().value(), ComponentTypeEnum.SERVICE), serviceName);
         }
         List<Service> serviceList = serviceListBySystemName.left().value();
         if (serviceList == null || serviceList.isEmpty()) {
             log.debug("Couldn't fetch any service with name {}", serviceName);
             throw new ByActionStatusComponentException(ActionStatus.SERVICE_NOT_FOUND, serviceName);
         }
-
         Service foundService = null;
         for (Service service : serviceList) {
             if (service.getVersion().equals(serviceVersion)) {
@@ -2804,59 +2528,53 @@ public class ArtifactsBusinessLogic extends BaseBusinessLogic {
                 break;
             }
         }
-
         if (foundService == null) {
             log.debug("Couldn't find version {} for service {}", serviceVersion, serviceName);
-            throw new ByActionStatusComponentException(ActionStatus.COMPONENT_VERSION_NOT_FOUND, ComponentTypeEnum.SERVICE
-                    .getValue(), serviceVersion);
+            throw new ByActionStatusComponentException(ActionStatus.COMPONENT_VERSION_NOT_FOUND, ComponentTypeEnum.SERVICE.getValue(),
+                serviceVersion);
         }
         return foundService;
     }
 
     private Resource validateResourceNameAndVersion(String resourceName, String resourceVersion) {
-
-        Either<Resource, StorageOperationStatus> resourceListBySystemName = toscaOperationFacade.getComponentByNameAndVersion(ComponentTypeEnum.RESOURCE, resourceName, resourceVersion, JsonParseFlagEnum.ParseMetadata);
+        Either<Resource, StorageOperationStatus> resourceListBySystemName = toscaOperationFacade
+            .getComponentByNameAndVersion(ComponentTypeEnum.RESOURCE, resourceName, resourceVersion, JsonParseFlagEnum.ParseMetadata);
         if (resourceListBySystemName.isRight()) {
             log.debug("Couldn't fetch any resource with name {} and version {}. ", resourceName, resourceVersion);
-            throw new ByActionStatusComponentException(componentsUtils.convertFromStorageResponse(resourceListBySystemName
-                    .right()
-                    .value()), resourceName);
+            throw new ByActionStatusComponentException(componentsUtils.convertFromStorageResponse(resourceListBySystemName.right().value()),
+                resourceName);
         }
         return resourceListBySystemName.left().value();
     }
 
     public byte[] downloadServiceArtifactByNames(String serviceName, String serviceVersion, String artifactName) {
         // Validation
-        log.trace("Starting download of service interface artifact, serviceName {}, serviceVersion {}, artifact name {}", serviceName, serviceVersion, artifactName);
+        log.trace("Starting download of service interface artifact, serviceName {}, serviceVersion {}, artifact name {}", serviceName, serviceVersion,
+            artifactName);
         if (serviceName == null || serviceVersion == null || artifactName == null) {
             log.debug(NULL_PARAMETER);
             throw new ByActionStatusComponentException(ActionStatus.INVALID_CONTENT);
         }
-
         // Normalizing artifact name
         final String normalizedArtifactName = ValidationUtils.normalizeFileName(artifactName);
-
         // Service validation
         Service service = validateServiceNameAndVersion(serviceName, serviceVersion);
         // Looking for deployment or tosca artifacts
         String serviceId = service.getUniqueId();
-
         if (MapUtils.isEmpty(service.getDeploymentArtifacts()) && MapUtils.isEmpty(service.getToscaArtifacts())) {
             log.debug("Neither Deployment nor Tosca artifacts of service {} are found", serviceId);
             throw new ByActionStatusComponentException(ActionStatus.ARTIFACT_NOT_FOUND, normalizedArtifactName);
         }
-
         Optional<ArtifactDefinition> foundArtifactOptl = Optional.empty();
-
         if (!MapUtils.isEmpty(service.getDeploymentArtifacts())) {
             foundArtifactOptl = service.getDeploymentArtifacts().values().stream()
-                    // filters artifact by name
-                    .filter(a -> a.getArtifactName().equals(normalizedArtifactName)).findAny();
+                // filters artifact by name
+                .filter(a -> a.getArtifactName().equals(normalizedArtifactName)).findAny();
         }
         if ((!foundArtifactOptl.isPresent()) && !MapUtils.isEmpty(service.getToscaArtifacts())) {
             foundArtifactOptl = service.getToscaArtifacts().values().stream()
-                    // filters TOSCA artifact by name
-                    .filter(a -> a.getArtifactName().equals(normalizedArtifactName)).findAny();
+                // filters TOSCA artifact by name
+                .filter(a -> a.getArtifactName().equals(normalizedArtifactName)).findAny();
         }
         if (!foundArtifactOptl.isPresent()) {
             log.debug("The artifact {} was not found for service {}", normalizedArtifactName, serviceId);
@@ -2864,8 +2582,7 @@ public class ArtifactsBusinessLogic extends BaseBusinessLogic {
         }
         log.debug(FOUND_DEPLOYMENT_ARTIFACT, normalizedArtifactName);
         // Downloading the artifact
-        ImmutablePair<String, byte[]> downloadArtifactEither = downloadArtifact(foundArtifactOptl
-                .get());
+        ImmutablePair<String, byte[]> downloadArtifactEither = downloadArtifact(foundArtifactOptl.get());
         log.trace("Download of service artifact succeeded, uniqueId {}", foundArtifactOptl.get().getUniqueId());
         return downloadArtifactEither.getRight();
     }
@@ -2883,21 +2600,18 @@ public class ArtifactsBusinessLogic extends BaseBusinessLogic {
             log.debug("Empty artifact definition returned from DB by artifact id {}", artifactUniqueId);
             throw new ByResponseFormatComponentException(componentsUtils.getResponseFormat(ActionStatus.ARTIFACT_NOT_FOUND, ""));
         }
-
         return downloadArtifact(artifactDefinition);
     }
 
-    private Component validateComponentExists(String componentId, AuditingActionEnum auditingAction, User user, String artifactId, ComponentTypeEnum componentType,
-                                              String containerComponentType) {
-
-        ComponentTypeEnum componentForAudit = null == containerComponentType ? componentType : ComponentTypeEnum.findByParamName(containerComponentType);
+    private Component validateComponentExists(String componentId, AuditingActionEnum auditingAction, User user, String artifactId,
+                                              ComponentTypeEnum componentType, String containerComponentType) {
+        ComponentTypeEnum componentForAudit =
+            null == containerComponentType ? componentType : ComponentTypeEnum.findByParamName(containerComponentType);
         componentForAudit.getNodeType();
-
-        Either<? extends Component, StorageOperationStatus> componentResult = toscaOperationFacade
-                .getToscaFullElement(componentId);
-
+        Either<? extends Component, StorageOperationStatus> componentResult = toscaOperationFacade.getToscaFullElement(componentId);
         if (componentResult.isRight()) {
-            ActionStatus status = componentForAudit == ComponentTypeEnum.RESOURCE ? ActionStatus.RESOURCE_NOT_FOUND : componentForAudit == ComponentTypeEnum.SERVICE ? ActionStatus.SERVICE_NOT_FOUND : ActionStatus.PRODUCT_NOT_FOUND;
+            ActionStatus status = componentForAudit == ComponentTypeEnum.RESOURCE ? ActionStatus.RESOURCE_NOT_FOUND
+                : componentForAudit == ComponentTypeEnum.SERVICE ? ActionStatus.SERVICE_NOT_FOUND : ActionStatus.PRODUCT_NOT_FOUND;
             ResponseFormat responseFormat = componentsUtils.getResponseFormat(status, componentId);
             log.debug("Service not found, serviceId {}", componentId);
             handleAuditing(auditingAction, null, componentId, user, null, null, artifactId, responseFormat, componentForAudit, null);
@@ -2906,22 +2620,23 @@ public class ArtifactsBusinessLogic extends BaseBusinessLogic {
         return componentResult.left().value();
     }
 
-    private void validateWorkOnComponent(Component component, String userId, AuditingActionEnum auditingAction, User user, String artifactId, ArtifactOperationInfo operation) {
+    private void validateWorkOnComponent(Component component, String userId, AuditingActionEnum auditingAction, User user, String artifactId,
+                                         ArtifactOperationInfo operation) {
         if (operation.getArtifactOperationEnum() != ArtifactOperationEnum.DOWNLOAD && !operation.ignoreLifecycleState()) {
             try {
                 validateCanWorkOnComponent(component, userId);
-            }catch (ComponentException e) {
+            } catch (ComponentException e) {
                 String uniqueId = component.getUniqueId();
                 log.debug("Service status isn't  CHECKOUT or user isn't owner, serviceId {}", uniqueId);
-                handleAuditing(auditingAction, component, uniqueId, user, null, null, artifactId, e.getResponseFormat(),
-                        component.getComponentType(), null);
+                handleAuditing(auditingAction, component, uniqueId, user, null, null, artifactId, e.getResponseFormat(), component.getComponentType(),
+                    null);
                 throw e;
             }
         }
     }
 
-    private void validateUserRole(User user, AuditingActionEnum auditingAction, String componentId, String artifactId, ComponentTypeEnum componentType, ArtifactOperationInfo operation) {
-
+    private void validateUserRole(User user, AuditingActionEnum auditingAction, String componentId, String artifactId,
+                                  ComponentTypeEnum componentType, ArtifactOperationInfo operation) {
         if (operation.isNotDownload()) {
             String role = user.getRole();
             if (!role.equals(Role.ADMIN.name()) && !role.equals(Role.DESIGNER.name())) {
@@ -2933,15 +2648,16 @@ public class ArtifactsBusinessLogic extends BaseBusinessLogic {
         }
     }
 
-    private User validateUserExists(String userId, AuditingActionEnum auditingAction, String componentId, String artifactId, ComponentTypeEnum componentType, boolean inTransaction) {
+    private User validateUserExists(String userId, AuditingActionEnum auditingAction, String componentId, String artifactId,
+                                    ComponentTypeEnum componentType, boolean inTransaction) {
         User user;
-        try{
+        try {
             user = validateUserExists(userId);
-        } catch(ByResponseFormatComponentException e){
+        } catch (ByResponseFormatComponentException e) {
             ResponseFormat responseFormat = e.getResponseFormat();
             handleComponentException(auditingAction, componentId, artifactId, responseFormat, componentType, userId);
             throw e;
-        } catch(ByActionStatusComponentException e){
+        } catch (ByActionStatusComponentException e) {
             ResponseFormat responseFormat = componentsUtils.getResponseFormat(e.getActionStatus(), e.getParams());
             handleComponentException(auditingAction, componentId, artifactId, responseFormat, componentType, userId);
             throw e;
@@ -2949,8 +2665,8 @@ public class ArtifactsBusinessLogic extends BaseBusinessLogic {
         return user;
     }
 
-    private void handleComponentException(AuditingActionEnum auditingAction, String componentId, String artifactId,
-        ResponseFormat responseFormat, ComponentTypeEnum componentType, String userId){
+    private void handleComponentException(AuditingActionEnum auditingAction, String componentId, String artifactId, ResponseFormat responseFormat,
+                                          ComponentTypeEnum componentType, String userId) {
         User user = new User();
         user.setUserId(userId);
         handleAuditing(auditingAction, null, componentId, user, null, null, artifactId, responseFormat, componentType, null);
@@ -2963,7 +2679,8 @@ public class ArtifactsBusinessLogic extends BaseBusinessLogic {
                 auditingAction = operation.isExternalApi() ? AuditingActionEnum.ARTIFACT_UPLOAD_BY_API : AuditingActionEnum.ARTIFACT_UPLOAD;
                 break;
             case UPDATE:
-                auditingAction = operation.isExternalApi() ? AuditingActionEnum.ARTIFACT_UPLOAD_BY_API : origMd5 == null ? AuditingActionEnum.ARTIFACT_METADATA_UPDATE : AuditingActionEnum.ARTIFACT_PAYLOAD_UPDATE;
+                auditingAction = operation.isExternalApi() ? AuditingActionEnum.ARTIFACT_UPLOAD_BY_API
+                    : origMd5 == null ? AuditingActionEnum.ARTIFACT_METADATA_UPDATE : AuditingActionEnum.ARTIFACT_PAYLOAD_UPDATE;
                 break;
             case DELETE:
                 auditingAction = operation.isExternalApi() ? AuditingActionEnum.ARTIFACT_DELETE_BY_API : AuditingActionEnum.ARTIFACT_DELETE;
@@ -2987,7 +2704,6 @@ public class ArtifactsBusinessLogic extends BaseBusinessLogic {
             log.debug("Error when getting artifact from ES, error: {}", actionStatus);
             throw new ByActionStatusComponentException(actionStatus, artifactDefinition.getArtifactDisplayName());
         }
-
         DAOArtifactData DAOArtifactData = artifactfromES.left().value();
         byte[] data = DAOArtifactData.getDataAsArray();
         if (data == null) {
@@ -3003,21 +2719,20 @@ public class ArtifactsBusinessLogic extends BaseBusinessLogic {
         return new DAOArtifactData(artifactInfo.getEsId(), artifactPayload);
     }
 
-    private void saveArtifactInCassandra(DAOArtifactData artifactData, Component parent, ArtifactDefinition artifactInfo,
-                                         String currArtifactId, String prevArtifactId, AuditingActionEnum auditingAction, ComponentTypeEnum componentType) {
+    private void saveArtifactInCassandra(DAOArtifactData artifactData, Component parent, ArtifactDefinition artifactInfo, String currArtifactId,
+                                         String prevArtifactId, AuditingActionEnum auditingAction, ComponentTypeEnum componentType) {
         CassandraOperationStatus resourceUploadStatus = artifactCassandraDao.saveArtifact(artifactData);
-
         if (resourceUploadStatus == CassandraOperationStatus.OK) {
             log.debug("Artifact {} was saved in component {}.", artifactData.getId(), parent.getUniqueId());
             ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.OK);
-            handleAuditing(auditingAction, parent, parent.getUniqueId(), null, artifactInfo, prevArtifactId,
-                    currArtifactId, responseFormat, componentType, null);
-        }
-        else {
+            handleAuditing(auditingAction, parent, parent.getUniqueId(), null, artifactInfo, prevArtifactId, currArtifactId, responseFormat,
+                componentType, null);
+        } else {
             BeEcompErrorManager.getInstance().logBeDaoSystemError(UPDATE_ARTIFACT);
             log.info(FAILED_SAVE_ARTIFACT);
             ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR);
-            handleAuditing(auditingAction, parent, parent.getUniqueId(), null, artifactInfo, prevArtifactId, currArtifactId, responseFormat, componentType, null);
+            handleAuditing(auditingAction, parent, parent.getUniqueId(), null, artifactInfo, prevArtifactId, currArtifactId, responseFormat,
+                componentType, null);
             throw new StorageException(resourceUploadStatus);
         }
     }
@@ -3052,66 +2767,57 @@ public class ArtifactsBusinessLogic extends BaseBusinessLogic {
         }
     }
 
-
-    public ArtifactDefinition createArtifactPlaceHolderInfo(String resourceId, String logicalName, Map<String, Object> artifactInfoMap, String userUserId, ArtifactGroupTypeEnum groupType, boolean inTransaction) {
+    public ArtifactDefinition createArtifactPlaceHolderInfo(String resourceId, String logicalName, Map<String, Object> artifactInfoMap,
+                                                            String userUserId, ArtifactGroupTypeEnum groupType, boolean inTransaction) {
         User user = userBusinessLogic.getUser(userUserId, inTransaction);
         return createArtifactPlaceHolderInfo(resourceId, logicalName, artifactInfoMap, user, groupType);
     }
 
-    public ArtifactDefinition createArtifactPlaceHolderInfo(String resourceId, String logicalName, Map<String, Object> artifactInfoMap, User user, ArtifactGroupTypeEnum groupType) {
+    public ArtifactDefinition createArtifactPlaceHolderInfo(String resourceId, String logicalName, Map<String, Object> artifactInfoMap, User user,
+                                                            ArtifactGroupTypeEnum groupType) {
         ArtifactDefinition artifactInfo = new ArtifactDefinition();
-
         String artifactName = (String) artifactInfoMap.get(ARTIFACT_PLACEHOLDER_DISPLAY_NAME);
         String artifactType = (String) artifactInfoMap.get(ARTIFACT_PLACEHOLDER_TYPE);
         String artifactDescription = (String) artifactInfoMap.get(ARTIFACT_PLACEHOLDER_DESCRIPTION);
-
         artifactInfo.setArtifactDisplayName(artifactName);
         artifactInfo.setArtifactLabel(logicalName.toLowerCase());
         artifactInfo.setArtifactType(artifactType);
         artifactInfo.setDescription(artifactDescription);
         artifactInfo.setArtifactGroupType(groupType);
         nodeTemplateOperation.setDefaultArtifactTimeout(groupType, artifactInfo);
-
         setArtifactPlaceholderCommonFields(resourceId, user, artifactInfo);
-
         return artifactInfo;
     }
 
     private void setArtifactPlaceholderCommonFields(String resourceId, User user, ArtifactDefinition artifactInfo) {
         String uniqueId = null;
-
         if (resourceId != null) {
-            uniqueId = UniqueIdBuilder.buildPropertyUniqueId(resourceId.toLowerCase(), artifactInfo.getArtifactLabel()
-                    .toLowerCase());
+            uniqueId = UniqueIdBuilder.buildPropertyUniqueId(resourceId.toLowerCase(), artifactInfo.getArtifactLabel().toLowerCase());
             artifactInfo.setUniqueId(uniqueId);
         }
         artifactInfo.setUserIdCreator(user.getUserId());
         String fullName = user.getFullName();
         artifactInfo.setUpdaterFullName(fullName);
-
         long time = System.currentTimeMillis();
-
         artifactInfo.setCreatorFullName(fullName);
         artifactInfo.setCreationDate(time);
-
         artifactInfo.setLastUpdateDate(time);
         artifactInfo.setUserIdLastUpdater(user.getUserId());
-
         artifactInfo.setMandatory(true);
     }
 
-    public Either<Map<String, ArtifactDefinition>, StorageOperationStatus> getArtifacts(String parentId, NodeTypeEnum parentType, ArtifactGroupTypeEnum groupType, String instanceId) {
+    public Either<Map<String, ArtifactDefinition>, StorageOperationStatus> getArtifacts(String parentId, NodeTypeEnum parentType,
+                                                                                        ArtifactGroupTypeEnum groupType, String instanceId) {
         return artifactToscaOperation.getArtifacts(parentId, parentType, groupType, instanceId);
     }
 
-    public Either<ArtifactDefinition, StorageOperationStatus> addHeatEnvArtifact(ArtifactDefinition artifactHeatEnv, ArtifactDefinition artifact, Component component, NodeTypeEnum parentType, String instanceId) {
+    public Either<ArtifactDefinition, StorageOperationStatus> addHeatEnvArtifact(ArtifactDefinition artifactHeatEnv, ArtifactDefinition artifact,
+                                                                                 Component component, NodeTypeEnum parentType, String instanceId) {
         return artifactToscaOperation.addHeatEnvArtifact(artifactHeatEnv, artifact, component, parentType, true, instanceId);
     }
 
     private Either<DAOArtifactData, ResponseFormat> createEsHeatEnvArtifactDataFromString(ArtifactDefinition artifactDefinition, String payloadStr) {
-
         byte[] payload = payloadStr.getBytes();
-
         DAOArtifactData artifactData = createEsArtifactData(artifactDefinition, payload);
         return Either.left(artifactData);
     }
@@ -3120,51 +2826,53 @@ public class ArtifactsBusinessLogic extends BaseBusinessLogic {
      * @param artifactDefinition
      * @return
      */
-    public Either<ArtifactDefinition, ResponseFormat> generateHeatEnvArtifact(ArtifactDefinition artifactDefinition, ComponentTypeEnum componentType, Component component, String resourceInstanceName, User modifier,
+    public Either<ArtifactDefinition, ResponseFormat> generateHeatEnvArtifact(ArtifactDefinition artifactDefinition, ComponentTypeEnum componentType,
+                                                                              Component component, String resourceInstanceName, User modifier,
                                                                               String instanceId, boolean shouldLock, boolean inTransaction) {
         String payload = generateHeatEnvPayload(artifactDefinition);
         String prevUUID = artifactDefinition.getArtifactUUID();
         ArtifactDefinition clonedBeforeGenerate = new ArtifactDefinition(artifactDefinition);
-        return generateAndSaveHeatEnvArtifact(artifactDefinition, payload, componentType, component, resourceInstanceName, modifier, instanceId, shouldLock, inTransaction)
-                .left()
-                .bind(artifactDef -> updateArtifactOnGroupInstance(component, instanceId, prevUUID, clonedBeforeGenerate, artifactDef));
+        return generateAndSaveHeatEnvArtifact(artifactDefinition, payload, componentType, component, resourceInstanceName, modifier, instanceId,
+            shouldLock, inTransaction).left()
+            .bind(artifactDef -> updateArtifactOnGroupInstance(component, instanceId, prevUUID, clonedBeforeGenerate, artifactDef));
     }
 
-    public Either<ArtifactDefinition, ResponseFormat> forceGenerateHeatEnvArtifact(ArtifactDefinition artifactDefinition, ComponentTypeEnum componentType, Component component, String resourceInstanceName, User modifier,
-                                                                                   boolean shouldLock, boolean inTransaction, String instanceId) {
+    public Either<ArtifactDefinition, ResponseFormat> forceGenerateHeatEnvArtifact(ArtifactDefinition artifactDefinition,
+                                                                                   ComponentTypeEnum componentType, Component component,
+                                                                                   String resourceInstanceName, User modifier, boolean shouldLock,
+                                                                                   boolean inTransaction, String instanceId) {
         String payload = generateHeatEnvPayload(artifactDefinition);
         String prevUUID = artifactDefinition.getArtifactUUID();
         ArtifactDefinition clonedBeforeGenerate = new ArtifactDefinition(artifactDefinition);
-        return forceGenerateAndSaveHeatEnvArtifact(artifactDefinition, payload, componentType, component, resourceInstanceName, modifier, instanceId, shouldLock, inTransaction)
-                .left()
-                .bind(artifactDef -> updateArtifactOnGroupInstance(component, instanceId, prevUUID, clonedBeforeGenerate, artifactDef));
+        return forceGenerateAndSaveHeatEnvArtifact(artifactDefinition, payload, componentType, component, resourceInstanceName, modifier, instanceId,
+            shouldLock, inTransaction).left()
+            .bind(artifactDef -> updateArtifactOnGroupInstance(component, instanceId, prevUUID, clonedBeforeGenerate, artifactDef));
     }
 
     @VisibleForTesting
-    Either<ArtifactDefinition, ResponseFormat> updateArtifactOnGroupInstance(Component component, String instanceId, String prevUUID, ArtifactDefinition clonedBeforeGenerate, ArtifactDefinition updatedArtDef) {
+    Either<ArtifactDefinition, ResponseFormat> updateArtifactOnGroupInstance(Component component, String instanceId, String prevUUID,
+                                                                             ArtifactDefinition clonedBeforeGenerate,
+                                                                             ArtifactDefinition updatedArtDef) {
         if (prevUUID == null || !prevUUID.equals(updatedArtDef.getArtifactUUID())) {
             List<ComponentInstance> componentInstances = component.getComponentInstances();
             if (componentInstances != null) {
-                Optional<ComponentInstance> findFirst = componentInstances.stream()
-                        .filter(ci -> ci.getUniqueId()
-                                .equals(instanceId))
-                        .findFirst();
+                Optional<ComponentInstance> findFirst = componentInstances.stream().filter(ci -> ci.getUniqueId().equals(instanceId)).findFirst();
                 if (findFirst.isPresent()) {
                     ComponentInstance relevantInst = findFirst.get();
-                    List<GroupInstance> updatedGroupInstances = getUpdatedGroupInstances(updatedArtDef.getUniqueId(), clonedBeforeGenerate, relevantInst
-                            .getGroupInstances());
-
+                    List<GroupInstance> updatedGroupInstances = getUpdatedGroupInstances(updatedArtDef.getUniqueId(), clonedBeforeGenerate,
+                        relevantInst.getGroupInstances());
                     if (CollectionUtils.isNotEmpty(updatedGroupInstances)) {
                         updatedGroupInstances.forEach(gi -> {
                             gi.getGroupInstanceArtifacts().add(updatedArtDef.getUniqueId());
                             gi.getGroupInstanceArtifactsUuid().add(updatedArtDef.getArtifactUUID());
                         });
-                        Either<List<GroupInstance>, StorageOperationStatus> status = toscaOperationFacade.updateGroupInstancesOnComponent(component, instanceId, updatedGroupInstances);
+                        Either<List<GroupInstance>, StorageOperationStatus> status = toscaOperationFacade
+                            .updateGroupInstancesOnComponent(component, instanceId, updatedGroupInstances);
                         if (status.isRight()) {
                             log.debug(FAILED_UPDATE_GROUPS, component.getUniqueId());
-                            ResponseFormat responseFormat = componentsUtils.getResponseFormatByArtifactId(componentsUtils
-                                    .convertFromStorageResponse(status.right()
-                                            .value()), clonedBeforeGenerate.getArtifactDisplayName());
+                            ResponseFormat responseFormat = componentsUtils
+                                .getResponseFormatByArtifactId(componentsUtils.convertFromStorageResponse(status.right().value()),
+                                    clonedBeforeGenerate.getArtifactDisplayName());
                             return Either.right(responseFormat);
                         }
                     }
@@ -3181,11 +2889,8 @@ public class ArtifactsBusinessLogic extends BaseBusinessLogic {
         sb.append("parameters:\n");
         if (heatParameters != null) {
             heatParameters.sort(Comparator.comparing(HeatParameterDataDefinition::getName));
-
             List<HeatParameterDefinition> empltyHeatValues = new ArrayList<>();
-
             for (HeatParameterDefinition heatParameterDefinition : heatParameters) {
-
                 String heatValue = heatParameterDefinition.getCurrentValue();
                 if (!ValidationUtils.validateStringNotEmpty(heatValue)) {
                     heatValue = heatParameterDefinition.getDefaultValue();
@@ -3198,29 +2903,16 @@ public class ArtifactsBusinessLogic extends BaseBusinessLogic {
                 if (type != null) {
                     switch (type) {
                         case BOOLEAN:
-                            sb.append("  ")
-                                    .append(heatParameterDefinition.getName())
-                                    .append(":")
-                                    .append(" ")
-                                    .append(Boolean.parseBoolean(heatValue))
-                                    .append("\n");
+                            sb.append("  ").append(heatParameterDefinition.getName()).append(":").append(" ").append(Boolean.parseBoolean(heatValue))
+                                .append("\n");
                             break;
                         case NUMBER:
-                            sb.append("  ")
-                                    .append(heatParameterDefinition.getName())
-                                    .append(":")
-                                    .append(" ")
-                                    .append(new BigDecimal(heatValue).toPlainString())
-                                    .append("\n");
+                            sb.append("  ").append(heatParameterDefinition.getName()).append(":").append(" ")
+                                .append(new BigDecimal(heatValue).toPlainString()).append("\n");
                             break;
                         case COMMA_DELIMITED_LIST:
                         case JSON:
-                            sb.append("  ")
-                                    .append(heatParameterDefinition.getName())
-                                    .append(":")
-                                    .append(" ")
-                                    .append(heatValue)
-                                    .append("\n");
+                            sb.append("  ").append(heatParameterDefinition.getName()).append(":").append(" ").append(heatValue).append("\n");
                             break;
                         default:
                             String value = heatValue;
@@ -3233,14 +2925,9 @@ public class ArtifactsBusinessLogic extends BaseBusinessLogic {
                                     value = "\"" + value + "\"";
                                 }
                             }
-                            sb.append("  ")
-                                    .append(heatParameterDefinition.getName())
-                                    .append(":")
-                                    .append(" ")
-                                    .append(value);
+                            sb.append("  ").append(heatParameterDefinition.getName()).append(":").append(" ").append(value);
                             sb.append("\n");
                             break;
-
                     }
                 }
             }
@@ -3249,18 +2936,16 @@ public class ArtifactsBusinessLogic extends BaseBusinessLogic {
                 empltyHeatValues.forEach(hv -> {
                     sb.append("  ").append(hv.getName()).append(":");
                     HeatParameterType type = HeatParameterType.isValidType(hv.getType());
-                    if (type != null && type == HeatParameterType.STRING && (hv.getCurrentValue() != null && "".equals(hv
-                            .getCurrentValue()) || hv.getDefaultValue() != null && "".equals(hv.getDefaultValue()))) {
+                    if (type != null && type == HeatParameterType.STRING && (hv.getCurrentValue() != null && "".equals(hv.getCurrentValue())
+                        || hv.getDefaultValue() != null && "".equals(hv.getDefaultValue()))) {
                         sb.append(" \"\"").append("\n");
-                    }
-                    else {
+                    } else {
                         sb.append(" ").append("\n");
                     }
                 });
             }
         }
         sb.append(ConfigurationManager.getConfigurationManager().getConfiguration().getHeatEnvArtifactFooter());
-
         // DE265919 fix
         return sb.toString().replaceAll("\\\\n", "\n");
     }
@@ -3270,41 +2955,42 @@ public class ArtifactsBusinessLogic extends BaseBusinessLogic {
      * @param payload
      * @return
      */
-    public Either<ArtifactDefinition, ResponseFormat> generateAndSaveHeatEnvArtifact(ArtifactDefinition artifactDefinition, String payload, ComponentTypeEnum componentType, Component component, String resourceInstanceName,
-                                                                                     User modifier, String instanceId, boolean shouldLock, boolean inTransaction) {
-        return generateArtifactPayload(artifactDefinition, componentType, component, resourceInstanceName, modifier, shouldLock, inTransaction, artifactDefinition::getHeatParamsUpdateDate,
-                () -> createEsHeatEnvArtifactDataFromString(artifactDefinition, payload), instanceId);
-
-    }
-
-    public Either<ArtifactDefinition, ResponseFormat> forceGenerateAndSaveHeatEnvArtifact(ArtifactDefinition artifactDefinition, String payload, ComponentTypeEnum componentType, Component component, String resourceInstanceName,
-                                                                                          User modifier, String instanceId, boolean shouldLock, boolean inTransaction) {
-        return generateArtifactPayload(artifactDefinition, componentType, component, resourceInstanceName, modifier, shouldLock, inTransaction, System::currentTimeMillis,
-                () -> createEsHeatEnvArtifactDataFromString(artifactDefinition, payload), instanceId);
-
-    }
-
-    protected Either<ArtifactDefinition, ResponseFormat> generateArtifactPayload(ArtifactDefinition artifactDefinition, ComponentTypeEnum componentType, Component component, String resourceInstanceName, User modifier,
-                                                                                 boolean shouldLock, boolean inTransaction, Supplier<Long> payloadUpdateDateGen, Supplier<Either<DAOArtifactData, ResponseFormat>> esDataCreator, String instanceId) {
-
-        log.trace("Start generating payload for {} artifact {}", artifactDefinition.getArtifactType(), artifactDefinition
-                .getEsId());
-        if (artifactDefinition.getPayloadUpdateDate() == null || artifactDefinition.getPayloadUpdateDate() == 0 || artifactDefinition
-                .getPayloadUpdateDate() <= payloadUpdateDateGen.get()) {
-
+    public Either<ArtifactDefinition, ResponseFormat> generateAndSaveHeatEnvArtifact(ArtifactDefinition artifactDefinition, String payload,
+                                                                                     ComponentTypeEnum componentType, Component component,
+                                                                                     String resourceInstanceName, User modifier, String instanceId,
+                                                                                     boolean shouldLock, boolean inTransaction) {
+        return generateArtifactPayload(artifactDefinition, componentType, component, resourceInstanceName, modifier, shouldLock, inTransaction,
+            artifactDefinition::getHeatParamsUpdateDate, () -> createEsHeatEnvArtifactDataFromString(artifactDefinition, payload), instanceId);
+    }
+
+    public Either<ArtifactDefinition, ResponseFormat> forceGenerateAndSaveHeatEnvArtifact(ArtifactDefinition artifactDefinition, String payload,
+                                                                                          ComponentTypeEnum componentType, Component component,
+                                                                                          String resourceInstanceName, User modifier,
+                                                                                          String instanceId, boolean shouldLock,
+                                                                                          boolean inTransaction) {
+        return generateArtifactPayload(artifactDefinition, componentType, component, resourceInstanceName, modifier, shouldLock, inTransaction,
+            System::currentTimeMillis, () -> createEsHeatEnvArtifactDataFromString(artifactDefinition, payload), instanceId);
+    }
+
+    protected Either<ArtifactDefinition, ResponseFormat> generateArtifactPayload(ArtifactDefinition artifactDefinition,
+                                                                                 ComponentTypeEnum componentType, Component component,
+                                                                                 String resourceInstanceName, User modifier, boolean shouldLock,
+                                                                                 boolean inTransaction, Supplier<Long> payloadUpdateDateGen,
+                                                                                 Supplier<Either<DAOArtifactData, ResponseFormat>> esDataCreator,
+                                                                                 String instanceId) {
+        log.trace("Start generating payload for {} artifact {}", artifactDefinition.getArtifactType(), artifactDefinition.getEsId());
+        if (artifactDefinition.getPayloadUpdateDate() == null || artifactDefinition.getPayloadUpdateDate() == 0
+            || artifactDefinition.getPayloadUpdateDate() <= payloadUpdateDateGen.get()) {
             log.trace("Generating payload for {} artifact {}", artifactDefinition.getArtifactType(), artifactDefinition.getEsId());
             Either<DAOArtifactData, ResponseFormat> artifactDataRes = esDataCreator.get();
             DAOArtifactData artifactData = null;
-
             if (artifactDataRes.isLeft()) {
                 artifactData = artifactDataRes.left().value();
-            }
-            else {
+            } else {
                 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR);
-                handleAuditing(AuditingActionEnum.ARTIFACT_PAYLOAD_UPDATE, component, component.getUniqueId(), modifier, artifactDefinition, artifactDefinition
-                                .getUniqueId(), artifactDefinition.getUniqueId(), responseFormat,
-                        ComponentTypeEnum.RESOURCE_INSTANCE, resourceInstanceName);
-
+                handleAuditing(AuditingActionEnum.ARTIFACT_PAYLOAD_UPDATE, component, component.getUniqueId(), modifier, artifactDefinition,
+                    artifactDefinition.getUniqueId(), artifactDefinition.getUniqueId(), responseFormat, ComponentTypeEnum.RESOURCE_INSTANCE,
+                    resourceInstanceName);
                 return Either.right(artifactDataRes.right().value());
             }
             String newCheckSum = GeneralUtility.calculateMD5Base64EncodedByByteArray(artifactData.getDataAsArray());
@@ -3324,127 +3010,111 @@ public class ArtifactsBusinessLogic extends BaseBusinessLogic {
                 }
                 DAOArtifactData = artifactfromES.left().value();
                 oldCheckSum = GeneralUtility.calculateMD5Base64EncodedByByteArray(DAOArtifactData.getDataAsArray());
-            }
-            else {
+            } else {
                 oldCheckSum = artifactDefinition.getArtifactChecksum();
-
             }
             Either<ArtifactDefinition, StorageOperationStatus> updateArifactDefinitionStatus = null;
-
             if (shouldLock) {
                 try {
                     lockComponent(component, "Update Artifact - lock resource: ");
-                }catch (ComponentException e){
-                    handleAuditing(AuditingActionEnum.ARTIFACT_METADATA_UPDATE, component, component.getUniqueId(), modifier, null, null, artifactDefinition
-                            .getUniqueId(), e.getResponseFormat(), component.getComponentType(), null);
+                } catch (ComponentException e) {
+                    handleAuditing(AuditingActionEnum.ARTIFACT_METADATA_UPDATE, component, component.getUniqueId(), modifier, null, null,
+                        artifactDefinition.getUniqueId(), e.getResponseFormat(), component.getComponentType(), null);
                     throw e;
                 }
             }
             try {
                 if (oldCheckSum != null && oldCheckSum.equals(newCheckSum)) {
-
                     artifactDefinition.setPayloadUpdateDate(payloadUpdateDateGen.get());
-                    updateArifactDefinitionStatus = artifactToscaOperation.updateArtifactOnResource(artifactDefinition, component
-                            ,artifactDefinition.getUniqueId(), componentType.getNodeType(), instanceId, true);
-                    log.trace("No real update done in payload for {} artifact, updating payloadUpdateDate {}", artifactDefinition
-                            .getArtifactType(), artifactDefinition.getEsId());
+                    updateArifactDefinitionStatus = artifactToscaOperation
+                        .updateArtifactOnResource(artifactDefinition, component, artifactDefinition.getUniqueId(), componentType.getNodeType(),
+                            instanceId, true);
+                    log.trace("No real update done in payload for {} artifact, updating payloadUpdateDate {}", artifactDefinition.getArtifactType(),
+                        artifactDefinition.getEsId());
                     if (updateArifactDefinitionStatus.isRight()) {
-                        ResponseFormat responseFormat = componentsUtils.getResponseFormatByArtifactId(componentsUtils.convertFromStorageResponse(updateArifactDefinitionStatus
-                                .right()
-                                .value()), artifactDefinition.getArtifactDisplayName());
+                        ResponseFormat responseFormat = componentsUtils
+                            .getResponseFormatByArtifactId(componentsUtils.convertFromStorageResponse(updateArifactDefinitionStatus.right().value()),
+                                artifactDefinition.getArtifactDisplayName());
                         log.trace("Failed to update payloadUpdateDate {}", artifactDefinition.getEsId());
-                        handleAuditing(AuditingActionEnum.ARTIFACT_PAYLOAD_UPDATE, component, component.getUniqueId(), modifier, artifactDefinition, artifactDefinition
-                                        .getUniqueId(), artifactDefinition.getUniqueId(), responseFormat,
-                                ComponentTypeEnum.RESOURCE_INSTANCE, resourceInstanceName);
-
+                        handleAuditing(AuditingActionEnum.ARTIFACT_PAYLOAD_UPDATE, component, component.getUniqueId(), modifier, artifactDefinition,
+                            artifactDefinition.getUniqueId(), artifactDefinition.getUniqueId(), responseFormat, ComponentTypeEnum.RESOURCE_INSTANCE,
+                            resourceInstanceName);
                         return Either.right(responseFormat);
                     }
-                }
-                else {
+                } else {
                     artifactDefinition.getArtifactChecksum();
                     artifactDefinition.setArtifactChecksum(newCheckSum);
                     artifactDefinition.setEsId(artifactDefinition.getUniqueId());
-                    log.trace("No real update done in payload for {} artifact, updating payloadUpdateDate {}", artifactDefinition
-                            .getArtifactType(), artifactDefinition.getEsId());
-                    updateArifactDefinitionStatus = artifactToscaOperation.updateArtifactOnResource(artifactDefinition, component,
-                            artifactDefinition.getUniqueId(), componentType.getNodeType(), instanceId, true);
-
+                    log.trace("No real update done in payload for {} artifact, updating payloadUpdateDate {}", artifactDefinition.getArtifactType(),
+                        artifactDefinition.getEsId());
+                    updateArifactDefinitionStatus = artifactToscaOperation
+                        .updateArtifactOnResource(artifactDefinition, component, artifactDefinition.getUniqueId(), componentType.getNodeType(),
+                            instanceId, true);
                     log.trace("Update Payload {}", artifactDefinition.getEsId());
                 }
                 if (updateArifactDefinitionStatus.isLeft()) {
-
                     artifactDefinition = updateArifactDefinitionStatus.left().value();
                     artifactData.setId(artifactDefinition.getUniqueId());
                     CassandraOperationStatus saveArtifactStatus = artifactCassandraDao.saveArtifact(artifactData);
-
                     if (saveArtifactStatus == CassandraOperationStatus.OK) {
                         if (!inTransaction) {
                             janusGraphDao.commit();
                         }
                         log.debug("Artifact Saved In cassandra {}", artifactData.getId());
                         ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.OK);
-                        handleAuditing(AuditingActionEnum.ARTIFACT_PAYLOAD_UPDATE, component, component.getUniqueId(), modifier, artifactDefinition, artifactDefinition
-                                        .getUniqueId(), artifactDefinition.getUniqueId(), responseFormat,
-                                ComponentTypeEnum.RESOURCE_INSTANCE, resourceInstanceName);
-
-                    }
-                    else {
+                        handleAuditing(AuditingActionEnum.ARTIFACT_PAYLOAD_UPDATE, component, component.getUniqueId(), modifier, artifactDefinition,
+                            artifactDefinition.getUniqueId(), artifactDefinition.getUniqueId(), responseFormat, ComponentTypeEnum.RESOURCE_INSTANCE,
+                            resourceInstanceName);
+                    } else {
                         if (!inTransaction) {
                             janusGraphDao.rollback();
                         }
                         log.info("Failed to save artifact {}.", artifactData.getId());
                         ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR);
-                        handleAuditing(AuditingActionEnum.ARTIFACT_PAYLOAD_UPDATE, component, component.getUniqueId(), modifier, artifactDefinition, artifactDefinition
-                                        .getUniqueId(), artifactDefinition.getUniqueId(), responseFormat,
-                                ComponentTypeEnum.RESOURCE_INSTANCE, resourceInstanceName);
-
+                        handleAuditing(AuditingActionEnum.ARTIFACT_PAYLOAD_UPDATE, component, component.getUniqueId(), modifier, artifactDefinition,
+                            artifactDefinition.getUniqueId(), artifactDefinition.getUniqueId(), responseFormat, ComponentTypeEnum.RESOURCE_INSTANCE,
+                            resourceInstanceName);
                         return Either.right(responseFormat);
                     }
-                }
-                else {
-                    ResponseFormat responseFormat = componentsUtils.getResponseFormatByArtifactId(componentsUtils.convertFromStorageResponse(updateArifactDefinitionStatus
-                            .right()
-                            .value()), artifactDefinition.getArtifactDisplayName());
+                } else {
+                    ResponseFormat responseFormat = componentsUtils
+                        .getResponseFormatByArtifactId(componentsUtils.convertFromStorageResponse(updateArifactDefinitionStatus.right().value()),
+                            artifactDefinition.getArtifactDisplayName());
                     log.debug("Failed To update artifact {}", artifactData.getId());
-                    handleAuditing(AuditingActionEnum.ARTIFACT_PAYLOAD_UPDATE, component, component.getUniqueId(), modifier, artifactDefinition, artifactDefinition
-                                    .getUniqueId(), artifactDefinition.getUniqueId(), responseFormat,
-                            ComponentTypeEnum.RESOURCE_INSTANCE, resourceInstanceName);
-
+                    handleAuditing(AuditingActionEnum.ARTIFACT_PAYLOAD_UPDATE, component, component.getUniqueId(), modifier, artifactDefinition,
+                        artifactDefinition.getUniqueId(), artifactDefinition.getUniqueId(), responseFormat, ComponentTypeEnum.RESOURCE_INSTANCE,
+                        resourceInstanceName);
                     return Either.right(responseFormat);
-
                 }
-            }
-            finally {
+            } finally {
                 if (shouldLock) {
-                    graphLockOperation.unlockComponent(component.getUniqueId(), component.getComponentType()
-                            .getNodeType());
+                    graphLockOperation.unlockComponent(component.getUniqueId(), component.getComponentType().getNodeType());
                 }
             }
         }
-
         return Either.left(artifactDefinition);
     }
 
-
-    public Map<String, Object> buildJsonForUpdateArtifact(ArtifactDefinition artifactDef, ArtifactGroupTypeEnum artifactGroupType, List<ArtifactTemplateInfo> updatedRequiredArtifacts) {
-        return this.buildJsonForUpdateArtifact(artifactDef.getUniqueId(), artifactDef.getArtifactName(), artifactDef.getArtifactType(), artifactGroupType, artifactDef
-                        .getArtifactLabel(), artifactDef.getArtifactDisplayName(),
-                artifactDef.getDescription(), artifactDef.getPayloadData(), updatedRequiredArtifacts, artifactDef.getListHeatParameters());
-
+    public Map<String, Object> buildJsonForUpdateArtifact(ArtifactDefinition artifactDef, ArtifactGroupTypeEnum artifactGroupType,
+                                                          List<ArtifactTemplateInfo> updatedRequiredArtifacts) {
+        return this
+            .buildJsonForUpdateArtifact(artifactDef.getUniqueId(), artifactDef.getArtifactName(), artifactDef.getArtifactType(), artifactGroupType,
+                artifactDef.getArtifactLabel(), artifactDef.getArtifactDisplayName(), artifactDef.getDescription(), artifactDef.getPayloadData(),
+                updatedRequiredArtifacts, artifactDef.getListHeatParameters());
     }
 
-    public Map<String, Object> buildJsonForUpdateArtifact(String artifactId, String artifactName, String artifactType, ArtifactGroupTypeEnum artifactGroupType, String label, String displayName, String description, byte[] artifactContent,
-                                                          List<ArtifactTemplateInfo> updatedRequiredArtifacts, List<HeatParameterDefinition> heatParameters) {
-
+    public Map<String, Object> buildJsonForUpdateArtifact(String artifactId, String artifactName, String artifactType,
+                                                          ArtifactGroupTypeEnum artifactGroupType, String label, String displayName,
+                                                          String description, byte[] artifactContent,
+                                                          List<ArtifactTemplateInfo> updatedRequiredArtifacts,
+                                                          List<HeatParameterDefinition> heatParameters) {
         Map<String, Object> json = new HashMap<>();
         if (artifactId != null && !artifactId.isEmpty()) {
             json.put(Constants.ARTIFACT_ID, artifactId);
         }
-
         json.put(Constants.ARTIFACT_NAME, artifactName);
         json.put(Constants.ARTIFACT_TYPE, artifactType);
         json.put(Constants.ARTIFACT_DESCRIPTION, description);
-
         if (artifactContent != null) {
             log.debug("payload is encoded. perform decode");
             String encodedPayload = Base64.encodeBase64String(artifactContent);
@@ -3454,30 +3124,29 @@ public class ArtifactsBusinessLogic extends BaseBusinessLogic {
         json.put(Constants.ARTIFACT_LABEL, label);
         json.put(Constants.ARTIFACT_GROUP_TYPE, artifactGroupType.getType());
         json.put(Constants.REQUIRED_ARTIFACTS, (updatedRequiredArtifacts == null || updatedRequiredArtifacts.isEmpty()) ? new ArrayList<>()
-                : updatedRequiredArtifacts.stream()
-                .filter(e -> e.getType().equals(ArtifactTypeEnum.HEAT_ARTIFACT.getType()) || e
-                        .getType()
-                        .equals(ArtifactTypeEnum.HEAT_NESTED.getType()))
-                .map(ArtifactTemplateInfo::getFileName)
-                .collect(Collectors.toList()));
-        json.put(Constants.ARTIFACT_HEAT_PARAMS, (heatParameters == null || heatParameters.isEmpty()) ? new ArrayList<>()
-                : heatParameters);
+            : updatedRequiredArtifacts.stream().filter(
+                e -> e.getType().equals(ArtifactTypeEnum.HEAT_ARTIFACT.getType()) || e.getType().equals(ArtifactTypeEnum.HEAT_NESTED.getType()))
+                .map(ArtifactTemplateInfo::getFileName).collect(Collectors.toList()));
+        json.put(Constants.ARTIFACT_HEAT_PARAMS, (heatParameters == null || heatParameters.isEmpty()) ? new ArrayList<>() : heatParameters);
         return json;
     }
 
-    public Either<ArtifactDefinition, Operation> updateResourceInstanceArtifactNoContent(String resourceId, Component containerComponent, User user, Map<String, Object> json, ArtifactOperationInfo operation, ArtifactDefinition artifactInfo) {
-
+    public Either<ArtifactDefinition, Operation> updateResourceInstanceArtifactNoContent(String resourceId, Component containerComponent, User user,
+                                                                                         Map<String, Object> json, ArtifactOperationInfo operation,
+                                                                                         ArtifactDefinition artifactInfo) {
         String jsonStr = gson.toJson(json);
-        ArtifactDefinition artifactDefinitionFromJson = artifactInfo == null ? RepresentationUtils.convertJsonToArtifactDefinition(jsonStr, ArtifactDefinition.class, false) : artifactInfo;
+        ArtifactDefinition artifactDefinitionFromJson =
+            artifactInfo == null ? RepresentationUtils.convertJsonToArtifactDefinition(jsonStr, ArtifactDefinition.class, false) : artifactInfo;
         String artifactUniqueId = artifactDefinitionFromJson == null ? null : artifactDefinitionFromJson.getUniqueId();
-        Either<ArtifactDefinition, Operation> uploadArtifactToService = validateAndHandleArtifact(resourceId, ComponentTypeEnum.RESOURCE_INSTANCE, operation, artifactUniqueId,
-                artifactDefinitionFromJson, null, jsonStr, null, null, user, containerComponent, false, false, true);
-
+        Either<ArtifactDefinition, Operation> uploadArtifactToService = validateAndHandleArtifact(resourceId, ComponentTypeEnum.RESOURCE_INSTANCE,
+            operation, artifactUniqueId, artifactDefinitionFromJson, null, jsonStr, null, null, user, containerComponent, false, false, true);
         return Either.left(uploadArtifactToService.left().value());
     }
 
-    private Either<ArtifactDefinition, Operation> handleUpdateHeatEnvAndHeatMeta(String componentId, ArtifactDefinition artifactInfo, AuditingActionEnum auditingAction, String artifactId, User user, ComponentTypeEnum componentType,
-                                                                                 Component parent, String originData, String origMd5, ArtifactOperationInfo operation) {
+    private Either<ArtifactDefinition, Operation> handleUpdateHeatEnvAndHeatMeta(String componentId, ArtifactDefinition artifactInfo,
+                                                                                 AuditingActionEnum auditingAction, String artifactId, User user,
+                                                                                 ComponentTypeEnum componentType, Component parent, String originData,
+                                                                                 String origMd5, ArtifactOperationInfo operation) {
         if (origMd5 != null) {
             validateMd5(origMd5, originData, artifactInfo.getPayloadData(), operation);
             if (ArrayUtils.isNotEmpty(artifactInfo.getPayloadData())) {
@@ -3490,7 +3159,9 @@ public class ArtifactsBusinessLogic extends BaseBusinessLogic {
         return updateHeatEnvParamsAndMetadata(componentId, artifactId, artifactInfo, user, auditingAction, parent, componentType, origMd5);
     }
 
-    private Either<ArtifactDefinition, Operation> updateHeatEnvParamsAndMetadata(String componentId, String artifactId, ArtifactDefinition artifactInfo, User user, AuditingActionEnum auditingAction, Component parent,
+    private Either<ArtifactDefinition, Operation> updateHeatEnvParamsAndMetadata(String componentId, String artifactId,
+                                                                                 ArtifactDefinition artifactInfo, User user,
+                                                                                 AuditingActionEnum auditingAction, Component parent,
                                                                                  ComponentTypeEnum componentType, String origMd5) {
         Either<ComponentInstance, ResponseFormat> getRI = getRIFromComponent(parent, componentId, artifactId, auditingAction, user);
         if (getRI.isRight()) {
@@ -3502,61 +3173,59 @@ public class ArtifactsBusinessLogic extends BaseBusinessLogic {
             throw new ByResponseFormatComponentException(getArtifactRes.right().value());
         }
         ArtifactDefinition currArtifact = getArtifactRes.left().value();
-
-        if (currArtifact.getArtifactType().equals(ArtifactTypeEnum.HEAT.getType()) ||
-                currArtifact.getArtifactType().equals(ArtifactTypeEnum.HEAT_VOL.getType()) ||
-                currArtifact.getArtifactType().equals(ArtifactTypeEnum.HEAT_NET.getType())) {
+        if (currArtifact.getArtifactType().equals(ArtifactTypeEnum.HEAT.getType()) || currArtifact.getArtifactType()
+            .equals(ArtifactTypeEnum.HEAT_VOL.getType()) || currArtifact.getArtifactType().equals(ArtifactTypeEnum.HEAT_NET.getType())) {
             throw new ByActionStatusComponentException(ActionStatus.RESTRICTED_OPERATION);
         }
         List<HeatParameterDefinition> currentHeatEnvParams = currArtifact.getListHeatParameters();
         List<HeatParameterDefinition> updatedHeatEnvParams = artifactInfo.getListHeatParameters();
-
         // upload
         if (origMd5 != null) {
-            Either<List<HeatParameterDefinition>, ResponseFormat> uploadParamsValidationResult = validateUploadParamsFromEnvFile(auditingAction, parent, user, artifactInfo,
-                    artifactId, componentType, ri.getName(), currentHeatEnvParams, updatedHeatEnvParams, currArtifact.getArtifactName());
+            Either<List<HeatParameterDefinition>, ResponseFormat> uploadParamsValidationResult = validateUploadParamsFromEnvFile(auditingAction,
+                parent, user, artifactInfo, artifactId, componentType, ri.getName(), currentHeatEnvParams, updatedHeatEnvParams,
+                currArtifact.getArtifactName());
             if (uploadParamsValidationResult.isRight()) {
                 throw new ByResponseFormatComponentException(uploadParamsValidationResult.right().value());
             }
             artifactInfo.setListHeatParameters(updatedHeatEnvParams);
         }
-
-        Either<ArtifactDefinition, ResponseFormat> validateAndConvertHeatParamers = validateAndConvertHeatParameters(artifactInfo, ArtifactTypeEnum.HEAT_ENV.getType());
+        Either<ArtifactDefinition, ResponseFormat> validateAndConvertHeatParamers = validateAndConvertHeatParameters(artifactInfo,
+            ArtifactTypeEnum.HEAT_ENV.getType());
         if (validateAndConvertHeatParamers.isRight()) {
             throw new ByResponseFormatComponentException(validateAndConvertHeatParamers.right().value());
         }
-
         if (updatedHeatEnvParams != null && !updatedHeatEnvParams.isEmpty()) {
             // fill reduced heat env parameters List for updating
             boolean updateRequired = replaceCurrHeatValueWithUpdatedValue(currentHeatEnvParams, updatedHeatEnvParams);
             if (updateRequired) {
                 currArtifact.setHeatParamsUpdateDate(System.currentTimeMillis());
                 currArtifact.setListHeatParameters(currentHeatEnvParams);
-                Either<ArtifactDefinition, StorageOperationStatus> updateArtifactRes = artifactToscaOperation.updateArtifactOnResource(
-                        currArtifact, parent, currArtifact.getUniqueId(), componentType.getNodeType(), componentId, true);
+                Either<ArtifactDefinition, StorageOperationStatus> updateArtifactRes = artifactToscaOperation
+                    .updateArtifactOnResource(currArtifact, parent, currArtifact.getUniqueId(), componentType.getNodeType(), componentId, true);
                 if (updateArtifactRes.isRight()) {
                     log.debug("Failed to update artifact on graph  - {}", artifactId);
                     throw new StorageException(updateArtifactRes.right().value());
                 }
-                StorageOperationStatus error = generateCustomizationUUIDOnGroupInstance(ri, updateArtifactRes.left().value().getUniqueId(), parent.getUniqueId());
+                StorageOperationStatus error = generateCustomizationUUIDOnGroupInstance(ri, updateArtifactRes.left().value().getUniqueId(),
+                    parent.getUniqueId());
                 if (error != StorageOperationStatus.OK) {
                     throw new StorageException(error);
                 }
             }
         }
-        updateHeatMetaDataIfNeeded(componentId,user,auditingAction,componentType, parent,ri,artifactInfo);
+        updateHeatMetaDataIfNeeded(componentId, user, auditingAction, componentType, parent, ri, artifactInfo);
         StorageOperationStatus error = generateCustomizationUUIDOnInstance(parent.getUniqueId(), ri.getUniqueId(), componentType);
         if (error != StorageOperationStatus.OK) {
             throw new StorageException(error);
         }
-
         return Either.left(currArtifact);
     }
 
-    private void
-    updateHeatMetaDataIfNeeded(String componentId, User user, AuditingActionEnum auditingAction, ComponentTypeEnum componentType, Component parent, ComponentInstance resourceInstance, ArtifactDefinition updatedHeatEnvArtifact) {
+    private void updateHeatMetaDataIfNeeded(String componentId, User user, AuditingActionEnum auditingAction, ComponentTypeEnum componentType,
+                                            Component parent, ComponentInstance resourceInstance, ArtifactDefinition updatedHeatEnvArtifact) {
         String heatArtifactId = updatedHeatEnvArtifact.getGeneratedFromId();
-        Either<ArtifactDefinition, ResponseFormat> getArtifactRes = getArtifactFromRI(parent, resourceInstance, componentId, heatArtifactId, auditingAction, user);
+        Either<ArtifactDefinition, ResponseFormat> getArtifactRes = getArtifactFromRI(parent, resourceInstance, componentId, heatArtifactId,
+            auditingAction, user);
         if (getArtifactRes.isRight()) {
             throw new ByResponseFormatComponentException(getArtifactRes.right().value());
         }
@@ -3564,16 +3233,18 @@ public class ArtifactsBusinessLogic extends BaseBusinessLogic {
         if (isUpdateHeatMetaDataNeeded(updatedHeatEnvArtifact, heatArtifactToUpdate)) {
             validateHeatMetaData(updatedHeatEnvArtifact);
             updateHeatMetadataFromHeatEnv(updatedHeatEnvArtifact, heatArtifactToUpdate);
-            Either<ArtifactDefinition, StorageOperationStatus> updateArtifactRes = artifactToscaOperation.updateArtifactOnResource(heatArtifactToUpdate, parent,
-                    heatArtifactToUpdate.getUniqueId(), componentType.getNodeType(), componentId, false);
-
+            Either<ArtifactDefinition, StorageOperationStatus> updateArtifactRes = artifactToscaOperation
+                .updateArtifactOnResource(heatArtifactToUpdate, parent, heatArtifactToUpdate.getUniqueId(), componentType.getNodeType(), componentId,
+                    false);
             if (updateArtifactRes.isRight()) {
                 log.debug("Failed to update artifact on graph  - {}", heatArtifactId);
                 throw new StorageException(updateArtifactRes.right().value());
             }
             ArtifactDefinition artifactDefinition = updateArtifactRes.left().value();
-            updateGeneratedIdInHeatEnvOnInstance(resourceInstance, parent, heatArtifactId, heatArtifactToUpdate, artifactDefinition, componentType.getNodeType());
-            StorageOperationStatus error = generateCustomizationUUIDOnGroupInstance(resourceInstance, artifactDefinition.getUniqueId(), parent.getUniqueId());
+            updateGeneratedIdInHeatEnvOnInstance(resourceInstance, parent, heatArtifactId, heatArtifactToUpdate, artifactDefinition,
+                componentType.getNodeType());
+            StorageOperationStatus error = generateCustomizationUUIDOnGroupInstance(resourceInstance, artifactDefinition.getUniqueId(),
+                parent.getUniqueId());
             if (error != StorageOperationStatus.OK) {
                 throw new StorageException(error);
             }
@@ -3599,7 +3270,8 @@ public class ArtifactsBusinessLogic extends BaseBusinessLogic {
         origHeat.setTimeout(updatedHeatEnv.getTimeout());
     }
 
-    private boolean replaceCurrHeatValueWithUpdatedValue(List<HeatParameterDefinition> currentHeatEnvParams, List<HeatParameterDefinition> updatedHeatEnvParams) {
+    private boolean replaceCurrHeatValueWithUpdatedValue(List<HeatParameterDefinition> currentHeatEnvParams,
+                                                         List<HeatParameterDefinition> updatedHeatEnvParams) {
         boolean isUpdate = false;
         List<String> currentParamsNames = currentHeatEnvParams.stream().map(x -> x.getName()).collect(Collectors.toList());
         for (HeatParameterDefinition heatEnvParam : updatedHeatEnvParams) {
@@ -3624,24 +3296,23 @@ public class ArtifactsBusinessLogic extends BaseBusinessLogic {
         }
     }
 
-    private Either<ArtifactDefinition, Operation> updateHeatParams(String componentId, ArtifactDefinition artifactEnvInfo, AuditingActionEnum auditingAction, Component parent,
-                                                                   ComponentTypeEnum componentType, ArtifactDefinition currHeatArtifact, boolean needToUpdateGroup) {
+    private Either<ArtifactDefinition, Operation> updateHeatParams(String componentId, ArtifactDefinition artifactEnvInfo,
+                                                                   AuditingActionEnum auditingAction, Component parent,
+                                                                   ComponentTypeEnum componentType, ArtifactDefinition currHeatArtifact,
+                                                                   boolean needToUpdateGroup) {
         Either<ArtifactDefinition, Operation> insideEither = null;
         String currentHeatId = currHeatArtifact.getUniqueId();
-
         String esArtifactId = currHeatArtifact.getEsId();
         Either<DAOArtifactData, CassandraOperationStatus> artifactFromES = artifactCassandraDao.getArtifact(esArtifactId);
         if (artifactFromES.isRight()) {
             StorageOperationStatus storageResponse = DaoStatusConverter.convertCassandraStatusToStorageStatus(artifactFromES.right().value());
             throw new StorageException(storageResponse, currHeatArtifact.getArtifactDisplayName());
         }
-
         DAOArtifactData DAOArtifactData = artifactFromES.left().value();
         ArtifactDefinition updatedHeatArt = currHeatArtifact;
         List<HeatParameterDefinition> updatedHeatEnvParams = artifactEnvInfo.getListHeatParameters();
         List<HeatParameterDefinition> currentHeatEnvParams = currHeatArtifact.getListHeatParameters();
         List<HeatParameterDefinition> newHeatEnvParams = new ArrayList<>();
-
         if (CollectionUtils.isNotEmpty(updatedHeatEnvParams) && CollectionUtils.isNotEmpty(currentHeatEnvParams)) {
             //TODO: improve complexity - currently N^2
             String paramName;
@@ -3655,8 +3326,8 @@ public class ArtifactsBusinessLogic extends BaseBusinessLogic {
                         }
                         HeatParameterType paramType = HeatParameterType.isValidType(currHeatParam.getType());
                         if (!paramType.getValidator().isValid(updatedParamValue, null)) {
-                            throw new ByActionStatusComponentException(ActionStatus.INVALID_HEAT_PARAMETER_VALUE,
-                                    ArtifactTypeEnum.HEAT_ENV.getType(), paramType.getType(), paramName);
+                            throw new ByActionStatusComponentException(ActionStatus.INVALID_HEAT_PARAMETER_VALUE, ArtifactTypeEnum.HEAT_ENV.getType(),
+                                paramType.getType(), paramName);
                         }
                         currHeatParam.setCurrentValue(paramType.getConverter().convert(updatedParamValue, null, null));
                         newHeatEnvParams.add(currHeatParam);
@@ -3666,9 +3337,9 @@ public class ArtifactsBusinessLogic extends BaseBusinessLogic {
             }
             if (!newHeatEnvParams.isEmpty()) {
                 currHeatArtifact.setListHeatParameters(currentHeatEnvParams);
-                Either<ArtifactDefinition, StorageOperationStatus> operationStatus = artifactToscaOperation.updateArtifactOnResource(
-                        currHeatArtifact, parent, currHeatArtifact.getUniqueId(), componentType.getNodeType(), componentId, true);
-
+                Either<ArtifactDefinition, StorageOperationStatus> operationStatus = artifactToscaOperation
+                    .updateArtifactOnResource(currHeatArtifact, parent, currHeatArtifact.getUniqueId(), componentType.getNodeType(), componentId,
+                        true);
                 if (operationStatus.isRight()) {
                     log.debug("Failed to update artifact on graph  - {}", currHeatArtifact.getUniqueId());
                     throw new StorageException(operationStatus.right().value());
@@ -3677,26 +3348,23 @@ public class ArtifactsBusinessLogic extends BaseBusinessLogic {
                 if (!updatedHeatArt.getDuplicated() || DAOArtifactData.getId() == null) {
                     DAOArtifactData.setId(updatedHeatArt.getEsId());
                 }
-                saveArtifactInCassandra(DAOArtifactData, parent, artifactEnvInfo, currentHeatId, updatedHeatArt
-                        .getUniqueId(), auditingAction, componentType);
+                saveArtifactInCassandra(DAOArtifactData, parent, artifactEnvInfo, currentHeatId, updatedHeatArt.getUniqueId(), auditingAction,
+                    componentType);
                 insideEither = Either.left(updatedHeatArt);
             }
         }
         Either<ArtifactDefinition, StorageOperationStatus> updateHeatEnvArtifact;
         if (!currentHeatId.equals(updatedHeatArt.getUniqueId())) {
             artifactEnvInfo.setArtifactChecksum(null);
-            updateHeatEnvArtifact = artifactToscaOperation.updateHeatEnvArtifact(parent, artifactEnvInfo, currentHeatId, updatedHeatArt
-                    .getUniqueId(), componentType.getNodeType(), componentId);
-        }
-        else {
+            updateHeatEnvArtifact = artifactToscaOperation
+                .updateHeatEnvArtifact(parent, artifactEnvInfo, currentHeatId, updatedHeatArt.getUniqueId(), componentType.getNodeType(),
+                    componentId);
+        else {
             //TODO Andrey check if componentId = parent.getUniqeId
-            updateHeatEnvArtifact = artifactToscaOperation.updateHeatEnvPlaceholder(artifactEnvInfo, parent, componentType
-                    .getNodeType());
-
+            updateHeatEnvArtifact = artifactToscaOperation.updateHeatEnvPlaceholder(artifactEnvInfo, parent, componentType.getNodeType());
         }
         if (needToUpdateGroup && updateHeatEnvArtifact.isLeft()) {
-            ActionStatus result = updateGroupForHeat(currHeatArtifact, updatedHeatArt, artifactEnvInfo,
-                    updateHeatEnvArtifact.left().value(), parent);
+            ActionStatus result = updateGroupForHeat(currHeatArtifact, updatedHeatArt, artifactEnvInfo, updateHeatEnvArtifact.left().value(), parent);
             if (result != ActionStatus.OK) {
                 throw new ByActionStatusComponentException(result);
             }
@@ -3707,7 +3375,6 @@ public class ArtifactsBusinessLogic extends BaseBusinessLogic {
         return insideEither;
     }
 
-
     private StorageOperationStatus generateCustomizationUUIDOnGroupInstance(ComponentInstance ri, String artifactId, String componentId) {
         StorageOperationStatus error = StorageOperationStatus.OK;
         log.debug("Need to re-generate  customization UUID for group instance on component instance  {}", ri.getUniqueId());
@@ -3715,34 +3382,33 @@ public class ArtifactsBusinessLogic extends BaseBusinessLogic {
         List<String> groupInstancesId = null;
         if (groupsInstances != null && !groupsInstances.isEmpty()) {
             groupInstancesId = groupsInstances.stream()
-                    .filter(p -> p.getGroupInstanceArtifacts() != null && p.getGroupInstanceArtifacts()
-                            .contains(artifactId))
-                    .map(GroupInstanceDataDefinition::getUniqueId)
-                    .collect(Collectors.toList());
+                .filter(p -> p.getGroupInstanceArtifacts() != null && p.getGroupInstanceArtifacts().contains(artifactId))
+                .map(GroupInstanceDataDefinition::getUniqueId).collect(Collectors.toList());
         }
         if (groupInstancesId != null && !groupInstancesId.isEmpty()) {
             toscaOperationFacade.generateCustomizationUUIDOnInstanceGroup(componentId, ri.getUniqueId(), groupInstancesId);
         }
         return error;
-
     }
 
-    public Either<List<HeatParameterDefinition>, ResponseFormat> validateUploadParamsFromEnvFile(AuditingActionEnum auditingAction, Component parent, User user, ArtifactDefinition artifactInfo, String artifactId, ComponentTypeEnum componentType,
-                                                                                                 String riName, List<HeatParameterDefinition> currentHeatEnvParams, List<HeatParameterDefinition> updatedHeatEnvParams, String currArtifactName) {
-
+    public Either<List<HeatParameterDefinition>, ResponseFormat> validateUploadParamsFromEnvFile(AuditingActionEnum auditingAction, Component parent,
+                                                                                                 User user, ArtifactDefinition artifactInfo,
+                                                                                                 String artifactId, ComponentTypeEnum componentType,
+                                                                                                 String riName,
+                                                                                                 List<HeatParameterDefinition> currentHeatEnvParams,
+                                                                                                 List<HeatParameterDefinition> updatedHeatEnvParams,
+                                                                                                 String currArtifactName) {
         if (updatedHeatEnvParams == null || updatedHeatEnvParams.isEmpty()) {
-            ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.INVALID_DEPLOYMENT_ARTIFACT_HEAT, artifactInfo
-                    .getArtifactName(), currArtifactName);
+            ResponseFormat responseFormat = componentsUtils
+                .getResponseFormat(ActionStatus.INVALID_DEPLOYMENT_ARTIFACT_HEAT, artifactInfo.getArtifactName(), currArtifactName);
             handleAuditing(auditingAction, parent, parent.getUniqueId(), user, artifactInfo, null, artifactId, responseFormat, componentType, riName);
             return Either.right(responseFormat);
         }
-
         for (HeatParameterDefinition uploadedHeatParam : updatedHeatEnvParams) {
             String paramName = uploadedHeatParam.getName();
             boolean isExistsInHeat = false;
             for (HeatParameterDefinition currHeatParam : currentHeatEnvParams) {
                 if (paramName.equalsIgnoreCase(currHeatParam.getName())) {
-
                     isExistsInHeat = true;
                     uploadedHeatParam.setType(currHeatParam.getType());
                     uploadedHeatParam.setCurrentValue(uploadedHeatParam.getDefaultValue());
@@ -3753,14 +3419,16 @@ public class ArtifactsBusinessLogic extends BaseBusinessLogic {
             }
             if (!isExistsInHeat) {
                 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.MISMATCH_HEAT_VS_HEAT_ENV, currArtifactName);
-                handleAuditing(auditingAction, parent, parent.getUniqueId(), user, artifactInfo, null, artifactId, responseFormat, componentType, riName);
+                handleAuditing(auditingAction, parent, parent.getUniqueId(), user, artifactInfo, null, artifactId, responseFormat, componentType,
+                    riName);
                 return Either.right(responseFormat);
             }
         }
         return Either.left(updatedHeatEnvParams);
     }
 
-    private Either<ComponentInstance, ResponseFormat> getRIFromComponent(Component component, String riID, String artifactId, AuditingActionEnum auditingAction, User user) {
+    private Either<ComponentInstance, ResponseFormat> getRIFromComponent(Component component, String riID, String artifactId,
+                                                                         AuditingActionEnum auditingAction, User user) {
         ResponseFormat responseFormat = null;
         List<ComponentInstance> ris = component.getComponentInstances();
         for (ComponentInstance ri : ris) {
@@ -3774,7 +3442,8 @@ public class ArtifactsBusinessLogic extends BaseBusinessLogic {
         return Either.right(responseFormat);
     }
 
-    private Either<ArtifactDefinition, ResponseFormat> getArtifactFromRI(Component component, ComponentInstance ri, String riID, String artifactId, AuditingActionEnum auditingAction, User user) {
+    private Either<ArtifactDefinition, ResponseFormat> getArtifactFromRI(Component component, ComponentInstance ri, String riID, String artifactId,
+                                                                         AuditingActionEnum auditingAction, User user) {
         ResponseFormat responseFormat = null;
         Map<String, ArtifactDefinition> rtifactsMap = ri.getDeploymentArtifacts();
         for (ArtifactDefinition artifact : rtifactsMap.values()) {
@@ -3783,8 +3452,8 @@ public class ArtifactsBusinessLogic extends BaseBusinessLogic {
             }
         }
         responseFormat = componentsUtils.getResponseFormat(ActionStatus.ARTIFACT_NOT_FOUND, riID, component.getUniqueId());
-        handleAuditing(auditingAction, component, riID, user, null, null, artifactId, responseFormat, ComponentTypeEnum.RESOURCE_INSTANCE, ri
-                .getName());
+        handleAuditing(auditingAction, component, riID, user, null, null, artifactId, responseFormat, ComponentTypeEnum.RESOURCE_INSTANCE,
+            ri.getName());
         return Either.right(responseFormat);
     }
 
@@ -3792,14 +3461,14 @@ public class ArtifactsBusinessLogic extends BaseBusinessLogic {
         ArtifactDefinition ret;
         if (eitherArtifact.isLeft()) {
             ret = eitherArtifact.left().value();
-        }
-        else {
+        } else {
             ret = eitherArtifact.right().value().getImplementationArtifact();
         }
         return ret;
     }
 
-    public byte[] downloadComponentArtifactByUUIDs(ComponentTypeEnum componentType, String componentUuid, String artifactUUID, ResourceCommonInfo resourceCommonInfo) {
+    public byte[] downloadComponentArtifactByUUIDs(ComponentTypeEnum componentType, String componentUuid, String artifactUUID,
+                                                   ResourceCommonInfo resourceCommonInfo) {
         Component component = getComponentByUuid(componentType, componentUuid);
         resourceCommonInfo.setResourceName(component.getName());
         return downloadArtifact(component.getAllArtifacts(), artifactUUID, component.getName());
@@ -3814,10 +3483,9 @@ public class ArtifactsBusinessLogic extends BaseBusinessLogic {
      * @param artifactUUID
      * @return
      */
-    public byte[] downloadResourceInstanceArtifactByUUIDs(ComponentTypeEnum componentType, String componentUuid,
-                                                          String resourceInstanceName, String artifactUUID) {
+    public byte[] downloadResourceInstanceArtifactByUUIDs(ComponentTypeEnum componentType, String componentUuid, String resourceInstanceName,
+                                                          String artifactUUID) {
         ComponentInstance resourceInstance = getRelatedComponentInstance(componentType, componentUuid, resourceInstanceName);
-
         if (resourceInstance != null) {
             return downloadArtifact(resourceInstance.getDeploymentArtifacts(), artifactUUID, resourceInstance.getName());
         } else {
@@ -3837,24 +3505,19 @@ public class ArtifactsBusinessLogic extends BaseBusinessLogic {
      * @return
      */
     public ArtifactDefinition uploadArtifactToComponentByUUID(String data, HttpServletRequest request, ComponentTypeEnum componentType,
-                                                              String componentUuid, ResourceCommonInfo resourceCommonInfo,                                                                                      ArtifactOperationInfo operation) {
+                                                              String componentUuid, ResourceCommonInfo resourceCommonInfo,
+                                                              ArtifactOperationInfo operation) {
         Either<ArtifactDefinition, Operation> actionResult;
         Component component;
         String componentId;
         ArtifactDefinition artifactInfo = RepresentationUtils.convertJsonToArtifactDefinition(data, ArtifactDefinition.class, false);
         String origMd5 = request.getHeader(Constants.MD5_HEADER);
         String userId = request.getHeader(Constants.USER_ID_HEADER);
-
-        Either<ComponentMetadataData, ActionStatus> getComponentRes =
-            fetchLatestComponentMetadataOrThrow(componentType, componentUuid);
-
+        Either<ComponentMetadataData, ActionStatus> getComponentRes = fetchLatestComponentMetadataOrThrow(componentType, componentUuid);
         ComponentMetadataDataDefinition componentMetadataDataDefinition = getComponentRes.left().value().getMetadataDataDefinition();
         componentId = componentMetadataDataDefinition.getUniqueId();
         String componentName = componentMetadataDataDefinition.getName();
-
-        if (!componentMetadataDataDefinition
-                .getState()
-                .equals(LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT.name())) {
+        if (!componentMetadataDataDefinition.getState().equals(LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT.name())) {
             component = checkoutParentComponent(componentType, componentId, userId);
             if (component != null) {
                 componentId = component.getUniqueId();
@@ -3862,9 +3525,8 @@ public class ArtifactsBusinessLogic extends BaseBusinessLogic {
             }
         }
         resourceCommonInfo.setResourceName(componentName);
-
-        actionResult = handleArtifactRequest(componentId, userId, componentType, operation, null, artifactInfo,
-                origMd5, data, null, null, null, null);
+        actionResult = handleArtifactRequest(componentId, userId, componentType, operation, null, artifactInfo, origMd5, data, null, null, null,
+            null);
         return actionResult.left().value();
     }
 
@@ -3879,43 +3541,30 @@ public class ArtifactsBusinessLogic extends BaseBusinessLogic {
      * @param operation
      * @return
      */
-    public ArtifactDefinition uploadArtifactToRiByUUID(String data, HttpServletRequest request, ComponentTypeEnum componentType, String componentUuid, String resourceInstanceName,
-                                                       ArtifactOperationInfo operation) {
+    public ArtifactDefinition uploadArtifactToRiByUUID(String data, HttpServletRequest request, ComponentTypeEnum componentType, String componentUuid,
+                                                       String resourceInstanceName, ArtifactOperationInfo operation) {
         Either<ArtifactDefinition, Operation> actionResult;
         Component component = null;
         String componentInstanceId;
         String componentId;
         String origMd5 = request.getHeader(Constants.MD5_HEADER);
         String userId = request.getHeader(Constants.USER_ID_HEADER);
-
         ImmutablePair<Component, ComponentInstance> componentRiPair = null;
-
-        Either<ComponentMetadataData, ActionStatus> getComponentRes =
-            fetchLatestComponentMetadataOrThrow(componentType, componentUuid, resourceInstanceName);
-        if (!getComponentRes.left()
-                .value()
-                .getMetadataDataDefinition()
-                .getState()
-                .equals(LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT.name())) {
-            component = checkoutParentComponent(componentType, getComponentRes.left()
-                    .value()
-                    .getMetadataDataDefinition()
-                    .getUniqueId(), userId);
+        Either<ComponentMetadataData, ActionStatus> getComponentRes = fetchLatestComponentMetadataOrThrow(componentType, componentUuid,
+            resourceInstanceName);
+        if (!getComponentRes.left().value().getMetadataDataDefinition().getState().equals(LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT.name())) {
+            component = checkoutParentComponent(componentType, getComponentRes.left().value().getMetadataDataDefinition().getUniqueId(), userId);
         }
         if (component == null) {
             componentRiPair = getRelatedComponentComponentInstance(componentType, componentUuid, resourceInstanceName);
-        }
-        else {
+        } else {
             componentRiPair = getRelatedComponentComponentInstance(component, resourceInstanceName);
         }
         componentInstanceId = componentRiPair.getRight().getUniqueId();
         componentId = componentRiPair.getLeft().getUniqueId();
         ArtifactDefinition artifactInfo = RepresentationUtils.convertJsonToArtifactDefinition(data, ArtifactDefinition.class, false);
-
-        actionResult = handleArtifactRequest(componentInstanceId, userId, ComponentTypeEnum.RESOURCE_INSTANCE,
-                operation, null, artifactInfo, origMd5, data, null, null,
-                componentId, ComponentTypeEnum.findParamByType(componentType));
-
+        actionResult = handleArtifactRequest(componentInstanceId, userId, ComponentTypeEnum.RESOURCE_INSTANCE, operation, null, artifactInfo, origMd5,
+            data, null, null, componentId, ComponentTypeEnum.findParamByType(componentType));
         return actionResult.left().value();
     }
 
@@ -3928,29 +3577,23 @@ public class ArtifactsBusinessLogic extends BaseBusinessLogic {
      * @param componentUuid
      * @param artifactUUID
      * @param resourceCommonInfo
-     * @param operation        TODO
+     * @param operation          TODO
      * @return
      */
-    public ArtifactDefinition updateArtifactOnComponentByUUID(String data, HttpServletRequest request, ComponentTypeEnum componentType, String componentUuid, String artifactUUID,
-                                                              ResourceCommonInfo resourceCommonInfo, ArtifactOperationInfo operation) {
+    public ArtifactDefinition updateArtifactOnComponentByUUID(String data, HttpServletRequest request, ComponentTypeEnum componentType,
+                                                              String componentUuid, String artifactUUID, ResourceCommonInfo resourceCommonInfo,
+                                                              ArtifactOperationInfo operation) {
         Either<ArtifactDefinition, Operation> actionResult;
         Component component;
         String componentId;
-        String artifactId ;
+        String artifactId;
         ArtifactDefinition artifactInfo = RepresentationUtils.convertJsonToArtifactDefinitionForUpdate(data, ArtifactDefinition.class);
         String origMd5 = request.getHeader(Constants.MD5_HEADER);
         String userId = request.getHeader(Constants.USER_ID_HEADER);
-
-        Either<ComponentMetadataData, ActionStatus> getComponentRes =
-            fetchLatestComponentMetadataOrThrow(componentType, componentUuid);
+        Either<ComponentMetadataData, ActionStatus> getComponentRes = fetchLatestComponentMetadataOrThrow(componentType, componentUuid);
         componentId = getComponentRes.left().value().getMetadataDataDefinition().getUniqueId();
         String componentName = getComponentRes.left().value().getMetadataDataDefinition().getName();
-
-        if (!getComponentRes.left()
-                .value()
-                .getMetadataDataDefinition()
-                .getState()
-                .equals(LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT.name())) {
+        if (!getComponentRes.left().value().getMetadataDataDefinition().getState().equals(LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT.name())) {
             component = checkoutParentComponent(componentType, componentId, userId);
             if (component != null) {
                 componentId = component.getUniqueId();
@@ -3959,14 +3602,11 @@ public class ArtifactsBusinessLogic extends BaseBusinessLogic {
         }
         resourceCommonInfo.setResourceName(componentName);
         artifactId = getLatestParentArtifactDataIdByArtifactUUID(artifactUUID, componentId, componentType);
-        actionResult = handleArtifactRequest(componentId, userId, componentType, operation, artifactId, artifactInfo,
-                origMd5, data, null, null, null, null);
+        actionResult = handleArtifactRequest(componentId, userId, componentType, operation, artifactId, artifactInfo, origMd5, data, null, null, null,
+            null);
         if (actionResult.isRight()) {
-            log.debug(FAILED_UPLOAD_ARTIFACT_TO_COMPONENT, componentType, componentUuid, actionResult
-                    .right()
-                    .value());
+            log.debug(FAILED_UPLOAD_ARTIFACT_TO_COMPONENT, componentType, componentUuid, actionResult.right().value());
         }
-
         return actionResult.left().value();
     }
 
@@ -3982,9 +3622,8 @@ public class ArtifactsBusinessLogic extends BaseBusinessLogic {
      * @param operation            TODO
      * @return
      */
-    public ArtifactDefinition updateArtifactOnRiByUUID(String data, HttpServletRequest request, ComponentTypeEnum componentType, String componentUuid, String resourceInstanceName, String artifactUUID,
-                                                       ArtifactOperationInfo operation) {
-
+    public ArtifactDefinition updateArtifactOnRiByUUID(String data, HttpServletRequest request, ComponentTypeEnum componentType, String componentUuid,
+                                                       String resourceInstanceName, String artifactUUID, ArtifactOperationInfo operation) {
         Either<ArtifactDefinition, Operation> actionResult;
         Component component = null;
         String componentInstanceId;
@@ -3992,37 +3631,27 @@ public class ArtifactsBusinessLogic extends BaseBusinessLogic {
         String artifactId;
         String origMd5 = request.getHeader(Constants.MD5_HEADER);
         String userId = request.getHeader(Constants.USER_ID_HEADER);
-
         ImmutablePair<Component, ComponentInstance> componentRiPair = null;
-        Either<ComponentMetadataData, ActionStatus> getComponentRes =
-            fetchLatestComponentMetadataOrThrow(componentType, componentUuid);
-        if (!getComponentRes.left()
-                .value()
-                .getMetadataDataDefinition()
-                .getState()
-                .equals(LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT.name())) {
-            component = checkoutParentComponent(componentType, getComponentRes.left()
-                    .value()
-                    .getMetadataDataDefinition()
-                    .getUniqueId(), userId);
+        Either<ComponentMetadataData, ActionStatus> getComponentRes = fetchLatestComponentMetadataOrThrow(componentType, componentUuid);
+        if (!getComponentRes.left().value().getMetadataDataDefinition().getState().equals(LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT.name())) {
+            component = checkoutParentComponent(componentType, getComponentRes.left().value().getMetadataDataDefinition().getUniqueId(), userId);
         }
         if (component == null) {
             componentRiPair = getRelatedComponentComponentInstance(componentType, componentUuid, resourceInstanceName);
-        }
-        else {
+        } else {
             componentRiPair = getRelatedComponentComponentInstance(component, resourceInstanceName);
         }
         componentInstanceId = componentRiPair.getRight().getUniqueId();
         componentId = componentRiPair.getLeft().getUniqueId();
         artifactId = findArtifactId(componentRiPair.getRight(), artifactUUID);
         ArtifactDefinition artifactInfo = RepresentationUtils.convertJsonToArtifactDefinition(data, ArtifactDefinition.class, false);
-
-        actionResult = handleArtifactRequest(componentInstanceId, userId, ComponentTypeEnum.RESOURCE_INSTANCE, operation, artifactId, artifactInfo, origMd5, data, null, null, componentId, ComponentTypeEnum
-                .findParamByType(componentType));
+        actionResult = handleArtifactRequest(componentInstanceId, userId, ComponentTypeEnum.RESOURCE_INSTANCE, operation, artifactId, artifactInfo,
+            origMd5, data, null, null, componentId, ComponentTypeEnum.findParamByType(componentType));
         return actionResult.left().value();
     }
 
-    private Either<ArtifactDefinition, ResponseFormat> updateOperationArtifact(String componentId, String interfaceType, String operationUuid, ArtifactDefinition artifactInfo){
+    private Either<ArtifactDefinition, ResponseFormat> updateOperationArtifact(String componentId, String interfaceType, String operationUuid,
+                                                                               ArtifactDefinition artifactInfo) {
         Either<Component, StorageOperationStatus> componentStorageOperationStatusEither = toscaOperationFacade.getToscaElement(componentId);
         if (componentStorageOperationStatusEither.isRight()) {
             StorageOperationStatus errorStatus = componentStorageOperationStatusEither.right().value();
@@ -4030,28 +3659,23 @@ public class ArtifactsBusinessLogic extends BaseBusinessLogic {
             return Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(errorStatus)));
         }
         Component storedComponent = componentStorageOperationStatusEither.left().value();
-
-        Optional<InterfaceDefinition> optionalInterface = InterfaceOperationUtils.getInterfaceDefinitionFromComponentByInterfaceType(storedComponent, interfaceType);
-        if(!optionalInterface.isPresent()) {
+        Optional<InterfaceDefinition> optionalInterface = InterfaceOperationUtils
+            .getInterfaceDefinitionFromComponentByInterfaceType(storedComponent, interfaceType);
+        if (!optionalInterface.isPresent()) {
             log.debug("Failed to get resource interface for resource Id {}", componentId);
             return Either.right(componentsUtils.getResponseFormat(ActionStatus.INTERFACE_NOT_FOUND_IN_COMPONENT, interfaceType));
         }
-
         //fetch the operation from storage
         InterfaceDefinition gotInterface = optionalInterface.get();
         Map<String, Operation> operationsMap = gotInterface.getOperationsMap();
-        Optional<Operation> optionalOperation = operationsMap.values()
-                .stream()
-                .filter(o -> o.getUniqueId().equals(operationUuid))
-                .findFirst();
+        Optional<Operation> optionalOperation = operationsMap.values().stream().filter(o -> o.getUniqueId().equals(operationUuid)).findFirst();
         if (!optionalOperation.isPresent()) {
             log.debug("Failed to get resource interface operation for resource Id {} and operationId {}", componentId, operationUuid);
             ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.INTERFACE_OPERATION_NOT_FOUND, componentId);
             return Either.right(responseFormat);
         }
-
         Operation operation = optionalOperation.get();
-        ArtifactDefinition implementationArtifact =  operation.getImplementationArtifact();
+        ArtifactDefinition implementationArtifact = operation.getImplementationArtifact();
         implementationArtifact.setArtifactUUID(artifactInfo.getArtifactUUID());
         implementationArtifact.setUniqueId(artifactInfo.getUniqueId());
         implementationArtifact.setArtifactName(artifactInfo.getArtifactName());
@@ -4062,15 +3686,13 @@ public class ArtifactsBusinessLogic extends BaseBusinessLogic {
         implementationArtifact.setEsId(artifactInfo.getEsId());
         operation.setImplementation(implementationArtifact);
         gotInterface.setOperationsMap(operationsMap);
-        Either<List<InterfaceDefinition>, StorageOperationStatus> interfaceDefinitionStorageOperationStatusEither =
-                interfaceOperation.updateInterfaces(storedComponent.getUniqueId(), Collections.singletonList(gotInterface));
-        if (interfaceDefinitionStorageOperationStatusEither.isRight()){
+        Either<List<InterfaceDefinition>, StorageOperationStatus> interfaceDefinitionStorageOperationStatusEither = interfaceOperation
+            .updateInterfaces(storedComponent.getUniqueId(), Collections.singletonList(gotInterface));
+        if (interfaceDefinitionStorageOperationStatusEither.isRight()) {
             StorageOperationStatus storageOperationStatus = interfaceDefinitionStorageOperationStatusEither.right().value();
-            ActionStatus actionStatus =
-                    componentsUtils.convertFromStorageResponseForDataType(storageOperationStatus);
+            ActionStatus actionStatus = componentsUtils.convertFromStorageResponseForDataType(storageOperationStatus);
             return Either.right(componentsUtils.getResponseFormat(actionStatus));
         }
-
         return Either.left(artifactInfo);
     }
 
@@ -4085,129 +3707,107 @@ public class ArtifactsBusinessLogic extends BaseBusinessLogic {
      * @param operation
      * @return
      */
-    public Either<ArtifactDefinition, ResponseFormat> updateArtifactOnInterfaceOperationByResourceUUID(
-            String data, HttpServletRequest request, ComponentTypeEnum componentType,
-            String componentUuid, String interfaceUUID, String operationUUID, String artifactUUID,
-        ResourceCommonInfo resourceCommonInfo,ArtifactOperationInfo operation) {
+    public Either<ArtifactDefinition, ResponseFormat> updateArtifactOnInterfaceOperationByResourceUUID(String data, HttpServletRequest request,
+                                                                                                       ComponentTypeEnum componentType,
+                                                                                                       String componentUuid, String interfaceUUID,
+                                                                                                       String operationUUID, String artifactUUID,
+                                                                                                       ResourceCommonInfo resourceCommonInfo,
+                                                                                                       ArtifactOperationInfo operation) {
         Wrapper<ResponseFormat> errorWrapper = new Wrapper<>();
         Either<ArtifactDefinition, ResponseFormat> updateArtifactResult;
         String componentId = null;
         ArtifactDefinition existingArtifactInfo = null;
         String interfaceName = null;
-
         ArtifactDefinition artifactInfo = RepresentationUtils.convertJsonToArtifactDefinitionForUpdate(data, ArtifactDefinition.class);
         String origMd5 = request.getHeader(Constants.MD5_HEADER);
         String userId = request.getHeader(Constants.USER_ID_HEADER);
-
-        Either<ComponentMetadataData, ActionStatus> getComponentRes =
-            fetchLatestComponentMetadata(componentType, componentUuid)
-                .right().map(as -> {
-                errorWrapper.setInnerElement(componentsUtils.getResponseFormat(as));
-                return as;
-            });
-
+        Either<ComponentMetadataData, ActionStatus> getComponentRes = fetchLatestComponentMetadata(componentType, componentUuid).right().map(as -> {
+            errorWrapper.setInnerElement(componentsUtils.getResponseFormat(as));
+            return as;
+        });
         if (errorWrapper.isEmpty()) {
             componentId = getComponentRes.left().value().getMetadataDataDefinition().getUniqueId();
             String componentName = getComponentRes.left().value().getMetadataDataDefinition().getName();
-            if (!getComponentRes.left()
-                    .value()
-                    .getMetadataDataDefinition()
-                    .getState()
-                    .equals(LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT.name())) {
+            if (!getComponentRes.left().value().getMetadataDataDefinition().getState().equals(LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT.name())) {
                 Component component = checkoutParentComponent(componentType, componentId, userId);
                 if (component != null) {
                     componentId = component.getUniqueId();
                     componentName = component.getName();
                 }
-
             }
             resourceCommonInfo.setResourceName(componentName);
         }
-
-        if(errorWrapper.isEmpty()){
+        if (errorWrapper.isEmpty()) {
             Either<String, ResponseFormat> interfaceNameEither = fetchInterfaceName(componentId, interfaceUUID);
             if (interfaceNameEither.isRight()) {
                 errorWrapper.setInnerElement(interfaceNameEither.right().value());
-            }
-            else {
+            } else {
                 interfaceName = interfaceNameEither.left().value();
             }
-
-            if(errorWrapper.isEmpty()){
+            if (errorWrapper.isEmpty()) {
                 Either<Component, StorageOperationStatus> toscaComponentEither = toscaOperationFacade.getToscaElement(componentId);
                 if (toscaComponentEither.isRight()) {
                     StorageOperationStatus status = toscaComponentEither.right().value();
                     log.debug("Could not fetch component with type {} and id {}. Status is {}. ", componentType, componentId, status);
                     errorWrapper.setInnerElement(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(status)));
                 }
-
                 if (errorWrapper.isEmpty()) {
                     NodeTypeEnum parentType = convertParentType(componentType);
-                    final List<ArtifactDefinition> existingDeploymentArtifacts =
-                        getDeploymentArtifacts(toscaComponentEither.left().value(),null);
-                    for (ArtifactDefinition artifactDefinition: existingDeploymentArtifacts){
-                        if(artifactInfo.getArtifactName().equalsIgnoreCase(artifactDefinition.getArtifactName())){
+                    final List<ArtifactDefinition> existingDeploymentArtifacts = getDeploymentArtifacts(toscaComponentEither.left().value(), null);
+                    for (ArtifactDefinition artifactDefinition : existingDeploymentArtifacts) {
+                        if (artifactInfo.getArtifactName().equalsIgnoreCase(artifactDefinition.getArtifactName())) {
                             existingArtifactInfo = artifactDefinition;
                             break;
                         }
                     }
-                    if(existingArtifactInfo != null){
+                    if (existingArtifactInfo != null) {
                         return updateOperationArtifact(componentId, interfaceName, operationUUID, existingArtifactInfo);
                     }
                 }
             }
         }
-
         if (errorWrapper.isEmpty()) {
-            updateArtifactResult = handleArtifactRequestAndFlatten(componentId, userId, componentType, operation,
-                artifactUUID, artifactInfo, origMd5, data, interfaceName, operationUUID);
+            updateArtifactResult = handleArtifactRequestAndFlatten(componentId, userId, componentType, operation, artifactUUID, artifactInfo, origMd5,
+                data, interfaceName, operationUUID);
         } else {
             updateArtifactResult = Either.right(errorWrapper.getInnerElement());
         }
-
         return updateArtifactResult;
     }
 
-    private Either<ArtifactDefinition, ResponseFormat> handleArtifactRequestAndFlatten(
-        String componentId, String userId, ComponentTypeEnum componentType, ArtifactOperationInfo operation,
-        String artifactId, ArtifactDefinition artifactInfo, String origMd5, String originData, String interfaceName,
-        String operationName) {
+    private Either<ArtifactDefinition, ResponseFormat> handleArtifactRequestAndFlatten(String componentId, String userId,
+                                                                                       ComponentTypeEnum componentType,
+                                                                                       ArtifactOperationInfo operation, String artifactId,
+                                                                                       ArtifactDefinition artifactInfo, String origMd5,
+                                                                                       String originData, String interfaceName,
+                                                                                       String operationName) {
         try {
-            return handleArtifactRequest(componentId, userId, componentType, operation,
-                artifactId, artifactInfo, origMd5, originData, interfaceName,
-                operationName, null, null)
-                .right().map(op -> {
-                    log.debug("Unexpected value returned while calling handleArtifactRequest: {}", op);
-                    return componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR);
-                });
+            return handleArtifactRequest(componentId, userId, componentType, operation, artifactId, artifactInfo, origMd5, originData, interfaceName,
+                operationName, null, null).right().map(op -> {
+                log.debug("Unexpected value returned while calling handleArtifactRequest: {}", op);
+                return componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR);
+            });
         } catch (ComponentException e) {
             return Either.right(e.getResponseFormat());
         }
     }
 
-    private Either<ComponentMetadataData, ActionStatus> fetchLatestComponentMetadataOrThrow(
-        ComponentTypeEnum componentType, String componentUuid
-    ) {
+    private Either<ComponentMetadataData, ActionStatus> fetchLatestComponentMetadataOrThrow(ComponentTypeEnum componentType, String componentUuid) {
         return fetchLatestComponentMetadataOrThrow(componentType, componentUuid, componentUuid);
     }
 
-    private Either<ComponentMetadataData, ActionStatus> fetchLatestComponentMetadataOrThrow(
-        ComponentTypeEnum componentType, String componentUuid, String resourceInstanceName
-    ) {
+    private Either<ComponentMetadataData, ActionStatus> fetchLatestComponentMetadataOrThrow(ComponentTypeEnum componentType, String componentUuid,
+                                                                                            String resourceInstanceName) {
         return fetchLatestComponentMetadata(componentType, componentUuid).right().map(as -> {
             throw new ByActionStatusComponentException(as, resourceInstanceName);
         });
     }
 
-    private Either<ComponentMetadataData, ActionStatus> fetchLatestComponentMetadata(
-        ComponentTypeEnum componentType, String componentUuid
-    ) {
-        return toscaOperationFacade
-            .getLatestComponentMetadataByUuid(componentUuid, JsonParseFlagEnum.ParseMetadata, true)
-            .right().map(sos -> {
-                log.debug(FAILED_FETCH_COMPONENT, componentType, componentUuid, sos);
-                return componentsUtils.convertFromStorageResponse(sos, componentType);
-            });
+    private Either<ComponentMetadataData, ActionStatus> fetchLatestComponentMetadata(ComponentTypeEnum componentType, String componentUuid) {
+        return toscaOperationFacade.getLatestComponentMetadataByUuid(componentUuid, JsonParseFlagEnum.ParseMetadata, true).right().map(sos -> {
+            log.debug(FAILED_FETCH_COMPONENT, componentType, componentUuid, sos);
+            return componentsUtils.convertFromStorageResponse(sos, componentType);
+        });
     }
 
     private Either<String, ResponseFormat> fetchInterfaceName(String componentId, String interfaceUUID) {
@@ -4218,10 +3818,9 @@ public class ArtifactsBusinessLogic extends BaseBusinessLogic {
             return Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(errorStatus)));
         }
         Component storedComponent = componentStorageOperationStatusEither.left().value();
-
         Optional<InterfaceDefinition> optionalInterface = InterfaceOperationUtils
             .getInterfaceDefinitionFromComponentByInterfaceId(storedComponent, interfaceUUID);
-        if(!optionalInterface.isPresent()) {
+        if (!optionalInterface.isPresent()) {
             return Either.right(componentsUtils.getResponseFormat(ActionStatus.INTERFACE_NOT_FOUND_IN_COMPONENT, interfaceUUID));
         }
         return Either.left(optionalInterface.get().getType());
@@ -4235,28 +3834,22 @@ public class ArtifactsBusinessLogic extends BaseBusinessLogic {
      * @param componentUuid
      * @param artifactUUID
      * @param resourceCommonInfo
-     * @param operation        TODO
+     * @param operation          TODO
      * @return
      */
-    public ArtifactDefinition deleteArtifactOnComponentByUUID(HttpServletRequest request, ComponentTypeEnum componentType, String componentUuid, String artifactUUID, ResourceCommonInfo resourceCommonInfo,
+    public ArtifactDefinition deleteArtifactOnComponentByUUID(HttpServletRequest request, ComponentTypeEnum componentType, String componentUuid,
+                                                              String artifactUUID, ResourceCommonInfo resourceCommonInfo,
                                                               ArtifactOperationInfo operation) {
-
         Either<ArtifactDefinition, Operation> actionResult;
         Component component;
-        String componentId ;
+        String componentId;
         String artifactId;
         String origMd5 = request.getHeader(Constants.MD5_HEADER);
         String userId = request.getHeader(Constants.USER_ID_HEADER);
-
-        Either<ComponentMetadataData, ActionStatus> getComponentRes =
-            fetchLatestComponentMetadataOrThrow(componentType, componentUuid);
+        Either<ComponentMetadataData, ActionStatus> getComponentRes = fetchLatestComponentMetadataOrThrow(componentType, componentUuid);
         componentId = getComponentRes.left().value().getMetadataDataDefinition().getUniqueId();
         String componentName = getComponentRes.left().value().getMetadataDataDefinition().getName();
-        if (!getComponentRes.left()
-                .value()
-                .getMetadataDataDefinition()
-                .getState()
-                .equals(LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT.name())) {
+        if (!getComponentRes.left().value().getMetadataDataDefinition().getState().equals(LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT.name())) {
             component = checkoutParentComponent(componentType, componentId, userId);
             if (component != null) {
                 componentId = component.getUniqueId();
@@ -4280,10 +3873,8 @@ public class ArtifactsBusinessLogic extends BaseBusinessLogic {
      * @param operation            TODO
      * @return
      */
-    public ArtifactDefinition deleteArtifactOnRiByUUID(HttpServletRequest request, ComponentTypeEnum componentType,
-                                                       String componentUuid, String resourceInstanceName,
-                                                       String artifactUUID, ArtifactOperationInfo operation) {
-
+    public ArtifactDefinition deleteArtifactOnRiByUUID(HttpServletRequest request, ComponentTypeEnum componentType, String componentUuid,
+                                                       String resourceInstanceName, String artifactUUID, ArtifactOperationInfo operation) {
         Either<ArtifactDefinition, Operation> actionResult;
         Component component = null;
         String componentInstanceId;
@@ -4292,30 +3883,20 @@ public class ArtifactsBusinessLogic extends BaseBusinessLogic {
         String origMd5 = request.getHeader(Constants.MD5_HEADER);
         String userId = request.getHeader(Constants.USER_ID_HEADER);
         ImmutablePair<Component, ComponentInstance> componentRiPair = null;
-        Either<ComponentMetadataData, ActionStatus> getComponentRes =
-            fetchLatestComponentMetadataOrThrow(componentType, componentUuid);
-        if (!getComponentRes.left()
-                .value()
-                .getMetadataDataDefinition()
-                .getState()
-                .equals(LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT.name())) {
-            component = checkoutParentComponent(componentType, getComponentRes.left()
-                    .value()
-                    .getMetadataDataDefinition()
-                    .getUniqueId(), userId);
+        Either<ComponentMetadataData, ActionStatus> getComponentRes = fetchLatestComponentMetadataOrThrow(componentType, componentUuid);
+        if (!getComponentRes.left().value().getMetadataDataDefinition().getState().equals(LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT.name())) {
+            component = checkoutParentComponent(componentType, getComponentRes.left().value().getMetadataDataDefinition().getUniqueId(), userId);
         }
         if (component == null) {
             componentRiPair = getRelatedComponentComponentInstance(componentType, componentUuid, resourceInstanceName);
-        }
-        else {
+        } else {
             componentRiPair = getRelatedComponentComponentInstance(component, resourceInstanceName);
         }
         componentInstanceId = componentRiPair.getRight().getUniqueId();
         componentId = componentRiPair.getLeft().getUniqueId();
         artifactId = findArtifactId(componentRiPair.getRight(), artifactUUID);
-
-        actionResult = handleArtifactRequest(componentInstanceId, userId, ComponentTypeEnum.RESOURCE_INSTANCE, operation, artifactId, null, origMd5, null, null, null, componentId, ComponentTypeEnum
-                .findParamByType(componentType));
+        actionResult = handleArtifactRequest(componentInstanceId, userId, ComponentTypeEnum.RESOURCE_INSTANCE, operation, artifactId, null, origMd5,
+            null, null, null, componentId, ComponentTypeEnum.findParamByType(componentType));
         return actionResult.left().value();
     }
 
@@ -4323,41 +3904,28 @@ public class ArtifactsBusinessLogic extends BaseBusinessLogic {
         String artifactId = null;
         ArtifactDefinition foundArtifact = null;
         if (instance.getDeploymentArtifacts() != null) {
-            foundArtifact = instance.getDeploymentArtifacts()
-                    .values()
-                    .stream()
-                    .filter(e -> e.getArtifactUUID() != null && e.getArtifactUUID()
-                            .equals(artifactUUID))
-                    .findFirst()
-                    .orElse(null);
+            foundArtifact = instance.getDeploymentArtifacts().values().stream()
+                .filter(e -> e.getArtifactUUID() != null && e.getArtifactUUID().equals(artifactUUID)).findFirst().orElse(null);
         }
         if (foundArtifact == null && instance.getArtifacts() != null) {
-            foundArtifact = instance.getArtifacts()
-                    .values()
-                    .stream()
-                    .filter(e -> e.getArtifactUUID() != null && e.getArtifactUUID()
-                            .equals(artifactUUID))
-                    .findFirst()
-                    .orElse(null);
+            foundArtifact = instance.getArtifacts().values().stream()
+                .filter(e -> e.getArtifactUUID() != null && e.getArtifactUUID().equals(artifactUUID)).findFirst().orElse(null);
         }
         if (foundArtifact == null) {
             log.debug("The artifact {} was not found on instance {}. ", artifactUUID, instance.getUniqueId());
             throw new ByActionStatusComponentException(ActionStatus.ARTIFACT_NOT_FOUND, artifactUUID);
-        }
-        else {
+        } else {
             artifactId = foundArtifact.getUniqueId();
         }
         return artifactId;
     }
 
     @SuppressWarnings("unchecked")
-    public ArtifactDefinition createHeatEnvPlaceHolder(List<ArtifactDefinition> createdArtifacts, ArtifactDefinition heatArtifact,
-                                                       String envType, String parentId, NodeTypeEnum parentType,
-                                                       String parentName, User user, Component component,
+    public ArtifactDefinition createHeatEnvPlaceHolder(List<ArtifactDefinition> createdArtifacts, ArtifactDefinition heatArtifact, String envType,
+                                                       String parentId, NodeTypeEnum parentType, String parentName, User user, Component component,
                                                        Map<String, String> existingEnvVersions) {
-        Map<String, Object> deploymentResourceArtifacts = ConfigurationManager.getConfigurationManager()
-                .getConfiguration()
-                .getDeploymentResourceInstanceArtifacts();
+        Map<String, Object> deploymentResourceArtifacts = ConfigurationManager.getConfigurationManager().getConfiguration()
+            .getDeploymentResourceInstanceArtifacts();
         if (deploymentResourceArtifacts == null) {
             log.debug("no deployment artifacts are configured for generated artifacts");
             throw new ByActionStatusComponentException(ActionStatus.GENERAL_ERROR);
@@ -4367,10 +3935,9 @@ public class ArtifactsBusinessLogic extends BaseBusinessLogic {
             log.debug("no env type {} are configured for generated artifacts", envType);
             throw new ByActionStatusComponentException(ActionStatus.GENERAL_ERROR);
         }
-
         String envLabel = (heatArtifact.getArtifactLabel() + HEAT_ENV_SUFFIX).toLowerCase();
-        ArtifactDefinition createArtifactPlaceHolder = createArtifactPlaceHolderInfo(parentId, envLabel, placeHolderData, user
-                .getUserId(), ArtifactGroupTypeEnum.DEPLOYMENT, true);
+        ArtifactDefinition createArtifactPlaceHolder = createArtifactPlaceHolderInfo(parentId, envLabel, placeHolderData, user.getUserId(),
+            ArtifactGroupTypeEnum.DEPLOYMENT, true);
         ArtifactDefinition artifactHeatEnv = createArtifactPlaceHolder;
         artifactHeatEnv.setGeneratedFromId(heatArtifact.getUniqueId());
         artifactHeatEnv.setHeatParamsUpdateDate(System.currentTimeMillis());
@@ -4384,16 +3951,15 @@ public class ArtifactsBusinessLogic extends BaseBusinessLogic {
         if (parentType != NodeTypeEnum.ResourceInstance) {
             String checkSum = artifactToscaOperation.sortAndCalculateChecksumForHeatParameters(heatArtifact.getHeatParameters());
             artifactHeatEnv.setArtifactChecksum(checkSum);
-            Either<ArtifactDefinition, StorageOperationStatus> addHeatEnvArtifact = addHeatEnvArtifact(artifactHeatEnv, heatArtifact, component, parentType, parentId);
+            Either<ArtifactDefinition, StorageOperationStatus> addHeatEnvArtifact = addHeatEnvArtifact(artifactHeatEnv, heatArtifact, component,
+                parentType, parentId);
             if (addHeatEnvArtifact.isRight()) {
                 log.debug("failed to create heat env artifact on resource instance");
-                throw new ByResponseFormatComponentException(componentsUtils.getResponseFormatForResourceInstance(componentsUtils.convertFromStorageResponseForResourceInstance(addHeatEnvArtifact
-                        .right()
-                        .value(), false), "", null));
+                throw new ByResponseFormatComponentException(componentsUtils.getResponseFormatForResourceInstance(
+                    componentsUtils.convertFromStorageResponseForResourceInstance(addHeatEnvArtifact.right().value(), false), "", null));
             }
             heatEnvPlaceholder = createArtifactPlaceHolder;
-        }
-        else {
+        } else {
             heatEnvPlaceholder = artifactHeatEnv;
             artifactToscaOperation.generateUUID(heatEnvPlaceholder, heatEnvPlaceholder.getArtifactVersion());
             setHeatCurrentValuesOnHeatEnvDefaultValues(heatArtifact, heatEnvPlaceholder);
@@ -4404,10 +3970,8 @@ public class ArtifactsBusinessLogic extends BaseBusinessLogic {
         }
         createdArtifacts.add(heatEnvPlaceholder);
         componentsUtils.auditComponent(componentsUtils.getResponseFormat(ActionStatus.OK), user, component, AuditingActionEnum.ARTIFACT_UPLOAD,
-                new ResourceCommonInfo(parentName, componentType.getValue()),
-                ResourceVersionInfo.newBuilder().build(),
-                ResourceVersionInfo.newBuilder().artifactUuid(heatEnvPlaceholder.getUniqueId()).build(),
-                null, heatEnvPlaceholder, null);
+            new ResourceCommonInfo(parentName, componentType.getValue()), ResourceVersionInfo.newBuilder().build(),
+            ResourceVersionInfo.newBuilder().artifactUuid(heatEnvPlaceholder.getUniqueId()).build(), null, heatEnvPlaceholder, null);
         return heatEnvPlaceholder;
     }
 
@@ -4433,8 +3997,7 @@ public class ArtifactsBusinessLogic extends BaseBusinessLogic {
         if (name == null) {
             name = heatArtifact.getArtifactLabel();
             fileName = name + "." + envExtension;
-        }
-        else {
+        } else {
             fileName = name.replaceAll("." + heatExtension, "." + envExtension);
         }
         heatEnvArtifact.setArtifactName(fileName);
@@ -4449,7 +4012,8 @@ public class ArtifactsBusinessLogic extends BaseBusinessLogic {
         }
     }
 
-    public List<ArtifactDefinition> handleArtifactsForInnerVfcComponent(List<ArtifactDefinition> artifactsToHandle, Resource component, User user, List<ArtifactDefinition> vfcsNewCreatedArtifacts,
+    public List<ArtifactDefinition> handleArtifactsForInnerVfcComponent(List<ArtifactDefinition> artifactsToHandle, Resource component, User user,
+                                                                        List<ArtifactDefinition> vfcsNewCreatedArtifacts,
                                                                         ArtifactOperationInfo operation, boolean shouldLock, boolean inTransaction) {
         ComponentTypeEnum componentType = component.getComponentType();
         List<ArtifactDefinition> uploadedArtifacts = new ArrayList<>();
@@ -4460,8 +4024,7 @@ public class ArtifactsBusinessLogic extends BaseBusinessLogic {
                 uploadedArtifacts.add(result.left().value());
             }
         } catch (ComponentException e) {
-            log.debug(FAILED_UPLOAD_ARTIFACT_TO_COMPONENT, componentType, component
-                    .getName(), e.getResponseFormat());
+            log.debug(FAILED_UPLOAD_ARTIFACT_TO_COMPONENT, componentType, component.getName(), e.getResponseFormat());
             if (operation.isCreateOrLink()) {
                 vfcsNewCreatedArtifacts.addAll(uploadedArtifacts);
             }
@@ -4470,27 +4033,28 @@ public class ArtifactsBusinessLogic extends BaseBusinessLogic {
         return uploadedArtifacts;
     }
 
-    public Either<ArtifactDefinition, Operation> handleLoadedArtifact(Component component, User user, ArtifactOperationInfo operation, boolean shouldLock, boolean inTransaction,
-                                                                      ComponentTypeEnum componentType, ArtifactDefinition artifactDefinition) {
+    public Either<ArtifactDefinition, Operation> handleLoadedArtifact(Component component, User user, ArtifactOperationInfo operation,
+                                                                      boolean shouldLock, boolean inTransaction, ComponentTypeEnum componentType,
+                                                                      ArtifactDefinition artifactDefinition) {
         AuditingActionEnum auditingAction = detectAuditingType(operation, "");
         String componentId = component.getUniqueId();
         String artifactId = artifactDefinition.getUniqueId();
         Either<ArtifactDefinition, Operation> result;
         Wrapper<ResponseFormat> errorWrapper = new Wrapper<>();
         //artifact validation
-        artifactDefinition = validateArtifact(componentId, componentType, operation,
-                artifactId, artifactDefinition, auditingAction, user,
-                component, shouldLock, inTransaction);
+        artifactDefinition = validateArtifact(componentId, componentType, operation, artifactId, artifactDefinition, auditingAction, user, component,
+            shouldLock, inTransaction);
         switch (operation.getArtifactOperationEnum()) {
             case CREATE:
-                byte[] validPayload = getValidPayload(componentId, artifactDefinition, operation, auditingAction, artifactId, user, componentType, component, null, null);
-                result = createArtifact(component, componentId, artifactDefinition, validPayload,
-                        componentType, auditingAction, null, null);
+                byte[] validPayload = getValidPayload(componentId, artifactDefinition, operation, auditingAction, artifactId, user, componentType,
+                    component, null, null);
+                result = createArtifact(component, componentId, artifactDefinition, validPayload, componentType, auditingAction, null, null);
                 break;
             case UPDATE:
-                validPayload = getValidPayload(componentId, artifactDefinition, operation, auditingAction, artifactId, user, componentType, component, null, null);
+                validPayload = getValidPayload(componentId, artifactDefinition, operation, auditingAction, artifactId, user, componentType, component,
+                    null, null);
                 result = handleUpdate(componentId, componentType, operation, artifactId, artifactDefinition, validPayload, null, null, null, null,
-                        auditingAction, user, component, true);
+                    auditingAction, user, component, true);
                 break;
             case DELETE:
                 result = Either.left(handleDeleteInternal(componentId, artifactId, componentType, component));
@@ -4506,14 +4070,16 @@ public class ArtifactsBusinessLogic extends BaseBusinessLogic {
                 result = Either.left(handleLink(componentId, artifactDefinition, componentType, component));
                 break;
             default:
-                throw new UnsupportedOperationException("In ArtifactsBusinessLogic received illegal operation: " + operation.getArtifactOperationEnum());
+                throw new UnsupportedOperationException(
+                    "In ArtifactsBusinessLogic received illegal operation: " + operation.getArtifactOperationEnum());
         }
         return result;
     }
 
-    public List<ArtifactDefinition> handleArtifactsRequestForInnerVfcComponent(List<ArtifactDefinition> artifactsToHandle, Resource component, User user, List<ArtifactDefinition> vfcsNewCreatedArtifacts,
-                                                                               ArtifactOperationInfo operation, boolean shouldLock, boolean inTransaction) {
-
+    public List<ArtifactDefinition> handleArtifactsRequestForInnerVfcComponent(List<ArtifactDefinition> artifactsToHandle, Resource component,
+                                                                               User user, List<ArtifactDefinition> vfcsNewCreatedArtifacts,
+                                                                               ArtifactOperationInfo operation, boolean shouldLock,
+                                                                               boolean inTransaction) {
         List<ArtifactDefinition> handleArtifactsResult;
         ComponentTypeEnum componentType = component.getComponentType();
         List<ArtifactDefinition> uploadedArtifacts = new ArrayList<>();
@@ -4524,12 +4090,12 @@ public class ArtifactsBusinessLogic extends BaseBusinessLogic {
             for (ArtifactDefinition artifact : artifactsToHandle) {
                 originData = ArtifactUtils.buildJsonStringForCsarVfcArtifact(artifact);
                 origMd5 = GeneralUtility.calculateMD5Base64EncodedByString(originData);
-                actionResult = handleArtifactRequest(component.getUniqueId(), user.getUserId(), componentType, operation, artifact
-                        .getUniqueId(), artifact, origMd5, originData, null, null, null, null, shouldLock, inTransaction);
+                actionResult = handleArtifactRequest(component.getUniqueId(), user.getUserId(), componentType, operation, artifact.getUniqueId(),
+                    artifact, origMd5, originData, null, null, null, null, shouldLock, inTransaction);
                 uploadedArtifacts.add(actionResult.left().value());
             }
             handleArtifactsResult = uploadedArtifacts;
-        }catch (ComponentException e){
+        } catch (ComponentException e) {
             if (operation.isCreateOrLink()) {
                 vfcsNewCreatedArtifacts.addAll(uploadedArtifacts);
             }
@@ -4538,36 +4104,27 @@ public class ArtifactsBusinessLogic extends BaseBusinessLogic {
         return handleArtifactsResult;
     }
 
-    private ComponentInstance getRelatedComponentInstance(
-        ComponentTypeEnum componentType, String componentUuid, String resourceInstanceName
-    ) {
+    private ComponentInstance getRelatedComponentInstance(ComponentTypeEnum componentType, String componentUuid, String resourceInstanceName) {
         String normalizedName = ValidationUtils.normalizeComponentInstanceName(resourceInstanceName);
         Option<Component> oComponent = Option.of(getComponentByUuid(componentType, componentUuid));
-        return oComponent
-            .toTry(componentNotFound(componentType, componentUuid))
-            .flatMap(component -> findFirstMatching(component,
-                ci -> ValidationUtils.normalizeComponentInstanceName(ci.getName()).equals(normalizedName)
-            ).toTry(componentInstanceNotFound(componentType, resourceInstanceName, component))
-        ).get();
+        return oComponent.toTry(componentNotFound(componentType, componentUuid)).flatMap(
+            component -> findFirstMatching(component, ci -> ValidationUtils.normalizeComponentInstanceName(ci.getName()).equals(normalizedName))
+                .toTry(componentInstanceNotFound(componentType, resourceInstanceName, component))).get();
     }
 
-    private ImmutablePair<Component, ComponentInstance> getRelatedComponentComponentInstance(
-        Component component, String resourceInstanceName
-    ) {
+    private ImmutablePair<Component, ComponentInstance> getRelatedComponentComponentInstance(Component component, String resourceInstanceName) {
         String normalizedName = ValidationUtils.normalizeComponentInstanceName(resourceInstanceName);
         ComponentInstance componentInstance = findFirstMatching(component,
-            ci -> ValidationUtils.normalizeComponentInstanceName(ci.getName()).equals(normalizedName)
-        ).toTry(componentInstanceNotFound(component.getComponentType(), resourceInstanceName, component)).get();
+            ci -> ValidationUtils.normalizeComponentInstanceName(ci.getName()).equals(normalizedName))
+            .toTry(componentInstanceNotFound(component.getComponentType(), resourceInstanceName, component)).get();
         return new ImmutablePair<>(component, componentInstance);
     }
 
-    private ImmutablePair<Component, ComponentInstance> getRelatedComponentComponentInstance(
-        ComponentTypeEnum componentType, String componentUuid, String resourceInstanceName
-    ) {
+    private ImmutablePair<Component, ComponentInstance> getRelatedComponentComponentInstance(ComponentTypeEnum componentType, String componentUuid,
+                                                                                             String resourceInstanceName) {
         Component component = getLatestComponentByUuid(componentType, componentUuid);
-        ComponentInstance componentInstance = findFirstMatching(component,
-            ci -> ci.getNormalizedName().equals(resourceInstanceName)
-        ).toTry(componentInstanceNotFound(component.getComponentType(), resourceInstanceName, component)).get();
+        ComponentInstance componentInstance = findFirstMatching(component, ci -> ci.getNormalizedName().equals(resourceInstanceName))
+            .toTry(componentInstanceNotFound(component.getComponentType(), resourceInstanceName, component)).get();
         return new ImmutablePair<>(component, componentInstance);
     }
 
@@ -4578,35 +4135,21 @@ public class ArtifactsBusinessLogic extends BaseBusinessLogic {
         };
     }
 
-    private Supplier<Throwable> componentInstanceNotFound(
-        ComponentTypeEnum componentType, String resourceInstanceName, Component component
-    ) {
+    private Supplier<Throwable> componentInstanceNotFound(ComponentTypeEnum componentType, String resourceInstanceName, Component component) {
         return () -> {
             log.debug(COMPONENT_INSTANCE_NOT_FOUND, resourceInstanceName, component.getName());
-            return new ByActionStatusComponentException(ActionStatus.COMPONENT_INSTANCE_NOT_FOUND_ON_CONTAINER,
-                resourceInstanceName,
+            return new ByActionStatusComponentException(ActionStatus.COMPONENT_INSTANCE_NOT_FOUND_ON_CONTAINER, resourceInstanceName,
                 RESOURCE_INSTANCE, componentType.getValue(), component.getName());
         };
     }
 
-    private static Option<ComponentInstance> findFirstMatching(Component component, Predicate<ComponentInstance> filter) {
-        return Option.ofOptional(component.getComponentInstances()
-            .stream()
-            .filter(filter)
-            .findFirst());
-    }
-
     private byte[] downloadArtifact(Map<String, ArtifactDefinition> artifacts, String artifactUUID, String componentName) {
-
         ImmutablePair<String, byte[]> downloadArtifact;
         List<ArtifactDefinition> artifactsList = null;
         ArtifactDefinition deploymentArtifact;
         if (artifacts != null && !artifacts.isEmpty()) {
-            artifactsList = artifacts.values()
-                    .stream()
-                    .filter(art -> art.getArtifactUUID() != null && art.getArtifactUUID()
-                            .equals(artifactUUID))
-                    .collect(Collectors.toList());
+            artifactsList = artifacts.values().stream().filter(art -> art.getArtifactUUID() != null && art.getArtifactUUID().equals(artifactUUID))
+                .collect(Collectors.toList());
         }
         if (artifactsList == null || artifactsList.isEmpty()) {
             log.debug("Deployment artifact with uuid {} was not found for component {}", artifactUUID, componentName);
@@ -4625,8 +4168,7 @@ public class ArtifactsBusinessLogic extends BaseBusinessLogic {
             StorageOperationStatus status = getComponentRes.right().value();
             log.debug(FAILED_FETCH_COMPONENT, componentType, componentUuid, status);
             throw new ByActionStatusComponentException(componentsUtils.convertFromStorageResponse(status));
-        }
-        else {
+        } else {
             component = getComponentRes.left().value();
         }
         return component;
@@ -4639,15 +4181,13 @@ public class ArtifactsBusinessLogic extends BaseBusinessLogic {
             StorageOperationStatus status = getComponentRes.right().value();
             log.debug(FAILED_FETCH_COMPONENT, componentType, componentUuid, status);
             throw new ByActionStatusComponentException(componentsUtils.convertFromStorageResponse(status));
-        }
-        else {
+        } else {
             List<Component> value = getComponentRes.left().value();
             if (value.isEmpty()) {
                 log.debug("Could not fetch component with type {} and uuid {}.", componentType, componentUuid);
                 ActionStatus status = componentType == ComponentTypeEnum.RESOURCE ? ActionStatus.RESOURCE_NOT_FOUND : ActionStatus.SERVICE_NOT_FOUND;
                 throw new ByActionStatusComponentException(status);
-            }
-            else {
+            } else {
                 component = value.get(0);
             }
         }
@@ -4668,41 +4208,39 @@ public class ArtifactsBusinessLogic extends BaseBusinessLogic {
             }
             throw new ByActionStatusComponentException(actionStatus, artifactUUID);
         }
-        artifacts = getArtifactsRes.left()
-                .value()
-                .values()
-                .stream()
-                .filter(a -> a.getArtifactUUID() != null && a.getArtifactUUID()
-                        .equals(artifactUUID))
-                .collect(Collectors.toList());
+        artifacts = getArtifactsRes.left().value().values().stream()
+            .filter(a -> a.getArtifactUUID() != null && a.getArtifactUUID().equals(artifactUUID)).collect(Collectors.toList());
         if (artifacts == null || artifacts.isEmpty()) {
-            log.debug("Couldn't fetch artifact with UUID {} data for parent component {} with uid {}, error: {}", artifactUUID, componentType, parentId, actionStatus);
+            log.debug("Couldn't fetch artifact with UUID {} data for parent component {} with uid {}, error: {}", artifactUUID, componentType,
+                parentId, actionStatus);
             throw new ByActionStatusComponentException(actionStatus, artifactUUID);
         }
         latestArtifact = artifacts.stream().max((a1, a2) -> {
             int compareRes = Double.compare(Double.parseDouble(a1.getArtifactVersion()), Double.parseDouble(a2.getArtifactVersion()));
             if (compareRes == 0) {
-                compareRes = Long.compare(a1.getLastUpdateDate() == null ? 0 : a1.getLastUpdateDate(), a2.getLastUpdateDate() == null ? 0 : a2
-                        .getLastUpdateDate());
+                compareRes = Long.compare(a1.getLastUpdateDate() == null ? 0 : a1.getLastUpdateDate(),
+                    a2.getLastUpdateDate() == null ? 0 : a2.getLastUpdateDate());
             }
             return compareRes;
         }).get();
         if (latestArtifact == null) {
-            log.debug("Couldn't fetch latest artifact with UUID {} data for parent component {} with uid {}, error: {}", artifactUUID, componentType, parentId, actionStatus);
+            log.debug("Couldn't fetch latest artifact with UUID {} data for parent component {} with uid {}, error: {}", artifactUUID, componentType,
+                parentId, actionStatus);
             throw new ByActionStatusComponentException(actionStatus, artifactUUID);
         }
         return latestArtifact.getUniqueId();
     }
 
     private Component checkoutParentComponent(ComponentTypeEnum componentType, String parentId, String userId) {
-
         Component component = null;
         User modifier = userBusinessLogic.getUser(userId, false);
-        LifecycleChangeInfoWithAction changeInfo = new LifecycleChangeInfoWithAction("External API checkout", LifecycleChanceActionEnum.UPDATE_FROM_EXTERNAL_API);
-        Either<? extends Component, ResponseFormat> checkoutRes = lifecycleBusinessLogic.changeComponentState(componentType, parentId, modifier, LifeCycleTransitionEnum.CHECKOUT, changeInfo, false, true);
+        LifecycleChangeInfoWithAction changeInfo = new LifecycleChangeInfoWithAction("External API checkout",
+            LifecycleChanceActionEnum.UPDATE_FROM_EXTERNAL_API);
+        Either<? extends Component, ResponseFormat> checkoutRes = lifecycleBusinessLogic
+            .changeComponentState(componentType, parentId, modifier, LifeCycleTransitionEnum.CHECKOUT, changeInfo, false, true);
         if (checkoutRes.isRight()) {
-            log.debug("Could not change state of component {} with uid {} to checked out. Status is {}. ", componentType
-                    .getNodeType(), parentId, checkoutRes.right().value().getStatus());
+            log.debug("Could not change state of component {} with uid {} to checked out. Status is {}. ", componentType.getNodeType(), parentId,
+                checkoutRes.right().value().getStatus());
             throw new ByResponseFormatComponentException(checkoutRes.right().value());
         }
         return checkoutRes.left().value();
@@ -4716,4 +4254,12 @@ public class ArtifactsBusinessLogic extends BaseBusinessLogic {
     public List<ArtifactConfiguration> getConfiguration() {
         return ConfigurationManager.getConfigurationManager().getConfiguration().getArtifacts();
     }
+
+    public enum ArtifactOperationEnum {
+        CREATE, UPDATE, DELETE, DOWNLOAD, LINK;
+
+        public static boolean isCreateOrLink(ArtifactOperationEnum operation) {
+            return operation == CREATE || operation == LINK;
+        }
+    }
 }
index a44ed3c..3c06e8b 100644 (file)
@@ -17,7 +17,6 @@
  * limitations under the License.
  * ============LICENSE_END=========================================================
  */
-
 package org.openecomp.sdc.be.components.impl;
 
 import fj.data.Either;
@@ -25,7 +24,6 @@ import java.util.List;
 import java.util.Map;
 import java.util.Objects;
 import java.util.Optional;
-import org.apache.commons.collections.MapUtils;
 import org.apache.commons.lang3.tuple.ImmutablePair;
 import org.openecomp.sdc.be.config.BeEcompErrorManager;
 import org.openecomp.sdc.be.dao.api.ActionStatus;
@@ -36,7 +34,6 @@ import org.openecomp.sdc.be.model.AttributeDefinition;
 import org.openecomp.sdc.be.model.Component;
 import org.openecomp.sdc.be.model.ComponentParametersView;
 import org.openecomp.sdc.be.model.DataTypeDefinition;
-import org.openecomp.sdc.be.model.InterfaceDefinition;
 import org.openecomp.sdc.be.model.Resource;
 import org.openecomp.sdc.be.model.jsonjanusgraph.operations.ArtifactsOperations;
 import org.openecomp.sdc.be.model.jsonjanusgraph.operations.InterfaceOperation;
@@ -64,20 +61,15 @@ public class AttributeBusinessLogic extends BaseBusinessLogic {
     private static final String CREATE_ATTRIBUTE = "CreateAttribute";
     private static final String UPDATE_ATTRIBUTE = "UpdateAttribute";
     private static final String DELETE_ATTRIBUTE = "DeleteAttribute";
-
     private static final Logger log = Logger.getLogger(AttributeBusinessLogic.class);
     private static final String FAILED_TO_LOCK_COMPONENT_ERROR = "Failed to lock component {}. Error - {}";
 
     @Autowired
-    public AttributeBusinessLogic(IElementOperation elementDao,
-                                  IGroupOperation groupOperation,
-                                  IGroupInstanceOperation groupInstanceOperation,
-                                  IGroupTypeOperation groupTypeOperation,
-                                  InterfaceOperation interfaceOperation,
-                                  InterfaceLifecycleOperation interfaceLifecycleTypeOperation,
-                                  ArtifactsOperations artifactToscaOperation) {
-        super(elementDao, groupOperation, groupInstanceOperation, groupTypeOperation,
-            interfaceOperation, interfaceLifecycleTypeOperation, artifactToscaOperation);
+    public AttributeBusinessLogic(IElementOperation elementDao, IGroupOperation groupOperation, IGroupInstanceOperation groupInstanceOperation,
+                                  IGroupTypeOperation groupTypeOperation, InterfaceOperation interfaceOperation,
+                                  InterfaceLifecycleOperation interfaceLifecycleTypeOperation, ArtifactsOperations artifactToscaOperation) {
+        super(elementDao, groupOperation, groupInstanceOperation, groupTypeOperation, interfaceOperation, interfaceLifecycleTypeOperation,
+            artifactToscaOperation);
     }
 
     /**
@@ -88,20 +80,15 @@ public class AttributeBusinessLogic extends BaseBusinessLogic {
      * @param userId
      * @return AttributeDefinition if created successfully Or ResponseFormat
      */
-    public Either<AttributeDefinition, ResponseFormat> createAttribute(String resourceId,
-                                                                       AttributeDefinition newAttributeDef,
-                                                                       String userId) {
+    public Either<AttributeDefinition, ResponseFormat> createAttribute(String resourceId, AttributeDefinition newAttributeDef, String userId) {
         Either<AttributeDefinition, ResponseFormat> result = null;
         validateUserExists(userId);
-
         StorageOperationStatus lockResult = graphLockOperation.lockComponent(resourceId, NodeTypeEnum.Resource);
         if (lockResult != StorageOperationStatus.OK) {
-            BeEcompErrorManager.getInstance()
-                .logBeFailedLockObjectError(CREATE_ATTRIBUTE, NodeTypeEnum.Resource.name().toLowerCase(), resourceId);
+            BeEcompErrorManager.getInstance().logBeFailedLockObjectError(CREATE_ATTRIBUTE, NodeTypeEnum.Resource.name().toLowerCase(), resourceId);
             log.info(FAILED_TO_LOCK_COMPONENT_ERROR, resourceId, lockResult);
             return Either.right(componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR));
         }
-
         try {
             // Get the resource from DB
             Either<Resource, StorageOperationStatus> status = toscaOperationFacade.getToscaElement(resourceId);
@@ -109,40 +96,33 @@ public class AttributeBusinessLogic extends BaseBusinessLogic {
                 return Either.right(componentsUtils.getResponseFormat(ActionStatus.RESOURCE_NOT_FOUND, ""));
             }
             Resource resource = status.left().value();
-
             // verify that resource is checked-out and the user is the last updater
             if (!ComponentValidationUtils.canWorkOnResource(resource, userId)) {
                 return Either.right(componentsUtils.getResponseFormat(ActionStatus.RESTRICTED_OPERATION));
             }
-
             // verify attribute does not exist in resource
             if (isAttributeExist(resource.getAttributes(), resourceId, newAttributeDef.getName())) {
-                return Either.right(
-                    componentsUtils.getResponseFormat(ActionStatus.ATTRIBUTE_ALREADY_EXIST, newAttributeDef.getName()));
+                return Either.right(componentsUtils.getResponseFormat(ActionStatus.ATTRIBUTE_ALREADY_EXIST, newAttributeDef.getName()));
             }
             Map<String, DataTypeDefinition> eitherAllDataTypes = getAllDataTypes(applicationDataTypeCache);
             // validate property default values
-            Either<Boolean, ResponseFormat> defaultValuesValidation = validateAttributeDefaultValue(newAttributeDef,
-                eitherAllDataTypes);
+            Either<Boolean, ResponseFormat> defaultValuesValidation = validateAttributeDefaultValue(newAttributeDef, eitherAllDataTypes);
             if (defaultValuesValidation.isRight()) {
                 return Either.right(defaultValuesValidation.right().value());
             }
-
             handleAttributeDefaultValue(newAttributeDef, eitherAllDataTypes);
-
             // add the new attribute to resource on graph
+
             // need to get StorageOperationStatus and convert to ActionStatus from
+
             // componentsUtils
-            Either<AttributeDefinition, StorageOperationStatus> either = toscaOperationFacade
-                .addAttributeOfResource(resource, newAttributeDef);
+            Either<AttributeDefinition, StorageOperationStatus> either = toscaOperationFacade.addAttributeOfResource(resource, newAttributeDef);
             if (either.isRight()) {
-                result = Either.right(componentsUtils
-                    .getResponseFormat(componentsUtils.convertFromStorageResponse(either.right().value()),
-                        resource.getName()));
+                result = Either
+                    .right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(either.right().value()), resource.getName()));
                 return result;
             }
             result = Either.left(either.left().value());
-
             return result;
         } finally {
             commitOrRollback(result);
@@ -152,50 +132,43 @@ public class AttributeBusinessLogic extends BaseBusinessLogic {
 
     private Either<Boolean, ResponseFormat> validateAttributeDefaultValue(final AttributeDefinition attributeDefinition,
                                                                           final Map<String, DataTypeDefinition> dataTypes) {
-
         if (!attributeOperation.isAttributeTypeValid(attributeDefinition)) {
-            log.info("Invalid type for attribute '{}' type '{}'", attributeDefinition.getName(),
-                attributeDefinition.getType());
+            log.info("Invalid type for attribute '{}' type '{}'", attributeDefinition.getName(), attributeDefinition.getType());
             final ResponseFormat responseFormat = componentsUtils
-                .getResponseFormat(ActionStatus.INVALID_PROPERTY_TYPE, attributeDefinition
-                    .getType(), attributeDefinition.getName());
+                .getResponseFormat(ActionStatus.INVALID_PROPERTY_TYPE, attributeDefinition.getType(), attributeDefinition.getName());
             return Either.right(responseFormat);
         }
         String type = attributeDefinition.getType();
         String innerType = null;
         if (type.equals(ToscaPropertyType.LIST.getType()) || type.equals(ToscaPropertyType.MAP.getType())) {
-            final ImmutablePair<String, Boolean> propertyInnerTypeValid = attributeOperation.isAttributeInnerTypeValid(
-                attributeDefinition, dataTypes);
+            final ImmutablePair<String, Boolean> propertyInnerTypeValid = attributeOperation
+                .isAttributeInnerTypeValid(attributeDefinition, dataTypes);
             innerType = propertyInnerTypeValid.getLeft();
             if (!Boolean.TRUE.equals(propertyInnerTypeValid.getRight())) {
-                log.info("Invalid inner type for attribute '{}' type '{}', dataTypeCount '{}'",
-                    attributeDefinition.getName(), attributeDefinition.getType(), dataTypes.size());
+                log.info("Invalid inner type for attribute '{}' type '{}', dataTypeCount '{}'", attributeDefinition.getName(),
+                    attributeDefinition.getType(), dataTypes.size());
                 final ResponseFormat responseFormat = componentsUtils
-                    .getResponseFormat(ActionStatus.INVALID_PROPERTY_INNER_TYPE, innerType,
-                        attributeDefinition.getName());
+                    .getResponseFormat(ActionStatus.INVALID_PROPERTY_INNER_TYPE, innerType, attributeDefinition.getName());
                 return Either.right(responseFormat);
             }
         }
         if (!attributeOperation.isAttributeDefaultValueValid(attributeDefinition, dataTypes)) {
-            log.info("Invalid default value for attribute '{}' type '{}'", attributeDefinition.getName(),
-                attributeDefinition.getType());
+            log.info("Invalid default value for attribute '{}' type '{}'", attributeDefinition.getName(), attributeDefinition.getType());
             ResponseFormat responseFormat;
             if (type.equals(ToscaPropertyType.LIST.getType()) || type.equals(ToscaPropertyType.MAP.getType())) {
-                responseFormat = componentsUtils.getResponseFormat(ActionStatus.INVALID_COMPLEX_DEFAULT_VALUE,
-                    attributeDefinition.getName(), type, innerType,
-                    (String) attributeDefinition.get_default());
+                responseFormat = componentsUtils
+                    .getResponseFormat(ActionStatus.INVALID_COMPLEX_DEFAULT_VALUE, attributeDefinition.getName(), type, innerType,
+                        (String) attributeDefinition.get_default());
             } else {
-                responseFormat = componentsUtils.getResponseFormat(ActionStatus.INVALID_DEFAULT_VALUE,
-                    attributeDefinition.getName(), type, (String) attributeDefinition.get_default());
+                responseFormat = componentsUtils.getResponseFormat(ActionStatus.INVALID_DEFAULT_VALUE, attributeDefinition.getName(), type,
+                    (String) attributeDefinition.get_default());
             }
             return Either.right(responseFormat);
-
         }
         return Either.left(true);
     }
 
-    private void handleAttributeDefaultValue(final AttributeDefinition newAttributeDefinition,
-                                             final Map<String, DataTypeDefinition> dataTypes) {
+    private void handleAttributeDefaultValue(final AttributeDefinition newAttributeDefinition, final Map<String, DataTypeDefinition> dataTypes) {
         final ToscaPropertyType type = ToscaPropertyType.isValidType(newAttributeDefinition.getType());
         final PropertyValueConverter converter = type.getConverter();
         // get inner type
@@ -208,19 +181,16 @@ public class AttributeBusinessLogic extends BaseBusinessLogic {
             }
         }
         if (newAttributeDefinition.get_default() != null) {
-            newAttributeDefinition.set_default(converter
-                .convert((String) newAttributeDefinition.get_default(), innerType, dataTypes));
+            newAttributeDefinition.set_default(converter.convert((String) newAttributeDefinition.get_default(), innerType, dataTypes));
         }
     }
 
     private boolean isAttributeExist(List<AttributeDefinition> attributes, String resourceUid, String propertyName) {
         boolean isExist = false;
         if (attributes != null) {
-            isExist = attributes.stream().anyMatch(
-                p -> Objects.equals(p.getName(), propertyName) && Objects.equals(p.getOwnerId(), resourceUid));
+            isExist = attributes.stream().anyMatch(p -> Objects.equals(p.getName(), propertyName) && Objects.equals(p.getOwnerId(), resourceUid));
         }
         return isExist;
-
     }
 
     /**
@@ -229,27 +199,22 @@ public class AttributeBusinessLogic extends BaseBusinessLogic {
      * @param userId
      * @return
      */
-    public Either<AttributeDefinition, ResponseFormat> getAttribute(String resourceId, String attributeId,
-                                                                    String userId) {
-
+    public Either<AttributeDefinition, ResponseFormat> getAttribute(String resourceId, String attributeId, String userId) {
         validateUserExists(userId);
-
         // Get the resource from DB
         Either<Resource, StorageOperationStatus> status = toscaOperationFacade.getToscaElement(resourceId);
         if (status.isRight()) {
             return Either.right(componentsUtils.getResponseFormat(ActionStatus.RESOURCE_NOT_FOUND, ""));
         }
         Resource resource = status.left().value();
-
         List<AttributeDefinition> attributes = resource.getAttributes();
         if (attributes == null) {
             return Either.right(componentsUtils.getResponseFormat(ActionStatus.ATTRIBUTE_NOT_FOUND, ""));
         } else {
             // verify attribute exist in resource
-            Optional<AttributeDefinition> optionalAtt = attributes.stream().filter(att ->
-                att.getUniqueId().equals(attributeId)).findAny();
-            return optionalAtt.<Either<AttributeDefinition, ResponseFormat>>map(Either::left).orElseGet(() ->
-                Either.right(componentsUtils.getResponseFormat(ActionStatus.ATTRIBUTE_NOT_FOUND, "")));
+            Optional<AttributeDefinition> optionalAtt = attributes.stream().filter(att -> att.getUniqueId().equals(attributeId)).findAny();
+            return optionalAtt.<Either<AttributeDefinition, ResponseFormat>>map(Either::left)
+                .orElseGet(() -> Either.right(componentsUtils.getResponseFormat(ActionStatus.ATTRIBUTE_NOT_FOUND, "")));
         }
     }
 
@@ -262,14 +227,12 @@ public class AttributeBusinessLogic extends BaseBusinessLogic {
      * @param userId
      * @return
      */
-    public Either<AttributeDefinition, ResponseFormat> updateAttribute(String resourceId, String attributeId,
-                                                                       AttributeDefinition newAttDef, String userId) {
+    public Either<AttributeDefinition, ResponseFormat> updateAttribute(String resourceId, String attributeId, AttributeDefinition newAttDef,
+                                                                       String userId) {
         Either<AttributeDefinition, ResponseFormat> result = null;
-
         StorageOperationStatus lockResult = graphLockOperation.lockComponent(resourceId, NodeTypeEnum.Resource);
         if (lockResult != StorageOperationStatus.OK) {
-            BeEcompErrorManager.getInstance()
-                .logBeFailedLockObjectError(UPDATE_ATTRIBUTE, NodeTypeEnum.Resource.name().toLowerCase(), resourceId);
+            BeEcompErrorManager.getInstance().logBeFailedLockObjectError(UPDATE_ATTRIBUTE, NodeTypeEnum.Resource.name().toLowerCase(), resourceId);
             log.info(FAILED_TO_LOCK_COMPONENT_ERROR, resourceId, lockResult);
             return Either.right(componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR));
         }
@@ -280,55 +243,41 @@ public class AttributeBusinessLogic extends BaseBusinessLogic {
                 return Either.right(componentsUtils.getResponseFormat(ActionStatus.RESOURCE_NOT_FOUND, ""));
             }
             Resource resource = eitherResource.left().value();
-
             // verify that resource is checked-out and the user is the last updater
             if (!ComponentValidationUtils.canWorkOnResource(resource, userId)) {
                 return Either.right(componentsUtils.getResponseFormat(ActionStatus.RESTRICTED_OPERATION));
             }
-
             // verify attribute exist in resource
             Either<AttributeDefinition, ResponseFormat> eitherAttribute = getAttribute(resourceId, attributeId, userId);
             if (eitherAttribute.isRight()) {
                 return Either.right(eitherAttribute.right().value());
             }
             Map<String, DataTypeDefinition> eitherAllDataTypes = getAllDataTypes(applicationDataTypeCache);
-
             // validate attribute default values
-            Either<Boolean, ResponseFormat> defaultValuesValidation = validateAttributeDefaultValue(newAttDef,
-                eitherAllDataTypes);
+            Either<Boolean, ResponseFormat> defaultValuesValidation = validateAttributeDefaultValue(newAttDef, eitherAllDataTypes);
             if (defaultValuesValidation.isRight()) {
                 return Either.right(defaultValuesValidation.right().value());
             }
-
             // add the new property to resource on graph
-            StorageOperationStatus validateAndUpdateAttribute = attributeOperation
-                .validateAndUpdateAttribute(newAttDef, eitherAllDataTypes);
+            StorageOperationStatus validateAndUpdateAttribute = attributeOperation.validateAndUpdateAttribute(newAttDef, eitherAllDataTypes);
             if (validateAndUpdateAttribute != StorageOperationStatus.OK) {
-                log.debug("Problem while updating attribute with id {}. Reason - {}", attributeId,
-                    validateAndUpdateAttribute);
+                log.debug("Problem while updating attribute with id {}. Reason - {}", attributeId, validateAndUpdateAttribute);
                 result = Either.right(componentsUtils
-                    .getResponseFormatByResource(componentsUtils.convertFromStorageResponse(validateAndUpdateAttribute),
-                        resource.getName()));
+                    .getResponseFormatByResource(componentsUtils.convertFromStorageResponse(validateAndUpdateAttribute), resource.getName()));
             }
-
-            Either<AttributeDefinition, StorageOperationStatus> eitherAttUpdate = toscaOperationFacade
-                .updateAttributeOfResource(resource, newAttDef);
-
+            Either<AttributeDefinition, StorageOperationStatus> eitherAttUpdate = toscaOperationFacade.updateAttributeOfResource(resource, newAttDef);
             if (eitherAttUpdate.isRight()) {
-                log.debug("Problem while updating attribute with id {}. Reason - {}", attributeId,
-                    eitherAttUpdate.right().value());
-                result = Either.right(componentsUtils.getResponseFormatByResource(
-                    componentsUtils.convertFromStorageResponse(eitherAttUpdate.right().value()), resource.getName()));
+                log.debug("Problem while updating attribute with id {}. Reason - {}", attributeId, eitherAttUpdate.right().value());
+                result = Either.right(componentsUtils
+                    .getResponseFormatByResource(componentsUtils.convertFromStorageResponse(eitherAttUpdate.right().value()), resource.getName()));
                 return result;
             }
-
             result = Either.left(eitherAttUpdate.left().value());
             return result;
         } finally {
             commitOrRollback(result);
             graphLockOperation.unlockComponent(resourceId, NodeTypeEnum.Resource);
         }
-
     }
 
     /**
@@ -339,21 +288,15 @@ public class AttributeBusinessLogic extends BaseBusinessLogic {
      * @param userId
      * @return
      */
-    public Either<AttributeDefinition, ResponseFormat> deleteAttribute(String resourceId, String attributeId,
-                                                                       String userId) {
-
+    public Either<AttributeDefinition, ResponseFormat> deleteAttribute(String resourceId, String attributeId, String userId) {
         Either<AttributeDefinition, ResponseFormat> result = null;
-
         validateUserExists(userId);
-
         StorageOperationStatus lockResult = graphLockOperation.lockComponent(resourceId, NodeTypeEnum.Resource);
         if (lockResult != StorageOperationStatus.OK) {
-            BeEcompErrorManager.getInstance()
-                .logBeFailedLockObjectError(DELETE_ATTRIBUTE, NodeTypeEnum.Resource.name().toLowerCase(), resourceId);
+            BeEcompErrorManager.getInstance().logBeFailedLockObjectError(DELETE_ATTRIBUTE, NodeTypeEnum.Resource.name().toLowerCase(), resourceId);
             log.info(FAILED_TO_LOCK_COMPONENT_ERROR, resourceId, lockResult);
             return Either.right(componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR));
         }
-
         try {
             // Get the resource from DB
             Either<Resource, StorageOperationStatus> eitherResource = toscaOperationFacade.getToscaElement(resourceId);
@@ -361,30 +304,23 @@ public class AttributeBusinessLogic extends BaseBusinessLogic {
                 return Either.right(componentsUtils.getResponseFormat(ActionStatus.RESOURCE_NOT_FOUND, ""));
             }
             Resource resource = eitherResource.left().value();
-
             // verify that resource is checked-out and the user is the last updater
             if (!ComponentValidationUtils.canWorkOnResource(resource, userId)) {
                 return Either.right(componentsUtils.getResponseFormat(ActionStatus.RESTRICTED_OPERATION));
             }
-
             // verify attribute exist in resource
-            Either<AttributeDefinition, ResponseFormat> eitherAttributeExist = getAttribute(resourceId, attributeId,
-                userId);
+            Either<AttributeDefinition, ResponseFormat> eitherAttributeExist = getAttribute(resourceId, attributeId, userId);
             if (eitherAttributeExist.isRight()) {
                 return Either.right(eitherAttributeExist.right().value());
             }
             String attributeName = eitherAttributeExist.left().value().getName();
-
             // delete attribute of resource from graph
-            StorageOperationStatus eitherAttributeDelete = toscaOperationFacade
-                .deleteAttributeOfResource(resource, attributeName);
+            StorageOperationStatus eitherAttributeDelete = toscaOperationFacade.deleteAttributeOfResource(resource, attributeName);
             if (eitherAttributeDelete != StorageOperationStatus.OK) {
-                result = Either.right(componentsUtils
-                    .getResponseFormat(componentsUtils.convertFromStorageResponse(eitherAttributeDelete),
-                        resource.getName()));
+                result = Either
+                    .right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(eitherAttributeDelete), resource.getName()));
                 return result;
             }
-
             result = Either.left(eitherAttributeExist.left().value());
             return result;
         } finally {
@@ -393,10 +329,8 @@ public class AttributeBusinessLogic extends BaseBusinessLogic {
         }
     }
 
-    public Either<List<AttributeDefinition>, ResponseFormat> getAttributesList(final String componentId,
-                                                                               final String userId) {
+    public Either<List<AttributeDefinition>, ResponseFormat> getAttributesList(final String componentId, final String userId) {
         validateUserExists(userId);
-
         // Get the resource from DB
         final ComponentParametersView filter = new ComponentParametersView(true);
         filter.setIgnoreAttributes(false);
@@ -404,42 +338,62 @@ public class AttributeBusinessLogic extends BaseBusinessLogic {
         if (status.isRight()) {
             return Either.right(componentsUtils.getResponseFormat(ActionStatus.RESOURCE_NOT_FOUND, ""));
         }
-
         return Either.left(status.left().value().getAttributes());
     }
 
-    public boolean isAttributeUsedByOperation(Component component,
-                                              AttributeDefinition propertyDefinitionEntry) {
+    public boolean isAttributeUsedByOperation(Component component, AttributeDefinition propertyDefinitionEntry) {
         // TODO - do we need this one
         return false;
-
 //        // Component's own interfaces
+
 //        Map<String, InterfaceDefinition> interfaces = component.getInterfaces();
+
 //        if(MapUtils.isNotEmpty(interfaces)){
+
 //            for(Map.Entry<String, InterfaceDefinition> interfaceEntry : interfaces.entrySet()) {
+
 //                if (isPropertyExistInOperationInterface(propertyDefinitionEntry, interfaceEntry.getValue())) {
+
 //                    return true;
+
 //                }
+
 //            }
+
 //        }
+
 //
+
 //        // Component's child's component interfaces
+
 //        if(isPropertyUsedInCIInterfaces(component.getComponentInstancesInterfaces(), propertyDefinitionEntry)){
+
 //            return true;
+
 //        }
+
 //
+
 //        // Component's parent's component interfaces
+
 //        Either<List<Component>, StorageOperationStatus> componentList = toscaOperationFacade.getParentComponents(component.getUniqueId());
+
 //        if(componentList.isLeft()){
+
 //            for (Component parentComponent : componentList.left().value()) {
+
 //                if(isPropertyUsedInCIInterfaces(parentComponent.getComponentInstancesInterfaces(), propertyDefinitionEntry)){
+
 //                    return true;
+
 //                }
+
 //            }
+
 //        }
+
 //
+
 //        return false;
     }
-
-
 }
index a640de0..fbfeaa5 100644 (file)
@@ -19,7 +19,6 @@
  * Modifications copyright (c) 2019 Nokia
  * ================================================================================
  */
-
 package org.openecomp.sdc.be.components.impl;
 
 import static org.openecomp.sdc.common.log.enums.EcompLoggerErrorCode.BUSINESS_PROCESS_ERROR;
@@ -101,7 +100,6 @@ import org.springframework.beans.factory.annotation.Autowired;
 public abstract class BaseBusinessLogic {
 
     private static final String FAILED_TO_LOCK_COMPONENT_ERROR = "Failed to lock component {} error - {}";
-
     private static final Logger log = Logger.getLogger(BaseBusinessLogic.class);
     private static final String EMPTY_VALUE = null;
     private static final String SCHEMA_DOESN_T_EXISTS_FOR_PROPERTY_OF_TYPE = "Schema doesn't exists for property of type {}";
@@ -127,12 +125,11 @@ public abstract class BaseBusinessLogic {
     protected PolicyTypeOperation policyTypeOperation;
     protected ArtifactsOperations artifactToscaOperation;
     protected UserValidations userValidations;
-
     DataTypeValidatorConverter dataTypeValidatorConverter = DataTypeValidatorConverter.getInstance();
 
-    protected BaseBusinessLogic(IElementOperation elementDao, IGroupOperation groupOperation,
-        IGroupInstanceOperation groupInstanceOperation, IGroupTypeOperation groupTypeOperation, InterfaceOperation interfaceOperation,
-        InterfaceLifecycleOperation interfaceLifecycleTypeOperation, ArtifactsOperations artifactToscaOperation) {
+    protected BaseBusinessLogic(IElementOperation elementDao, IGroupOperation groupOperation, IGroupInstanceOperation groupInstanceOperation,
+                                IGroupTypeOperation groupTypeOperation, InterfaceOperation interfaceOperation,
+                                InterfaceLifecycleOperation interfaceLifecycleTypeOperation, ArtifactsOperations artifactToscaOperation) {
         this.elementDao = elementDao;
         this.groupOperation = groupOperation;
         this.groupInstanceOperation = groupInstanceOperation;
@@ -142,6 +139,12 @@ public abstract class BaseBusinessLogic {
         this.artifactToscaOperation = artifactToscaOperation;
     }
 
+    @SafeVarargs
+    static <T extends Enum<T>> boolean enumHasValueFilter(String name, Function<String, T> enumGetter, T... enumValues) {
+        T enumFound = enumGetter.apply(name);
+        return Arrays.asList(enumValues).contains(enumFound);
+    }
+
     @Autowired
     public void setUserAdmin(UserBusinessLogic userAdmin) {
         this.userAdmin = userAdmin;
@@ -226,11 +229,10 @@ public abstract class BaseBusinessLogic {
         lockComponent(component.getUniqueId(), component, ecompErrorContext);
     }
 
-    protected boolean isVolumeGroup(List<String> artifactsInGroup,List <ArtifactDefinition> deploymentArtifacts) {
+    protected boolean isVolumeGroup(List<String> artifactsInGroup, List<ArtifactDefinition> deploymentArtifacts) {
         for (String artifactId : artifactsInGroup) {
             ArtifactDefinition artifactDef = ArtifactUtils.findArtifactInList(deploymentArtifacts, artifactId);
-            if (artifactDef != null
-                    && artifactDef.getArtifactType().equalsIgnoreCase(ArtifactTypeEnum.HEAT_VOL.getType())) {
+            if (artifactDef != null && artifactDef.getArtifactType().equalsIgnoreCase(ArtifactTypeEnum.HEAT_VOL.getType())) {
                 return true;
             }
         }
@@ -238,14 +240,14 @@ public abstract class BaseBusinessLogic {
     }
 
     protected void lockComponent(Component component, boolean shouldLock, String ecompErrorContext) {
-        if(shouldLock){
+        if (shouldLock) {
             lockComponent(component.getUniqueId(), component, ecompErrorContext);
         }
     }
 
     protected void lockComponent(String componentId, Component component, String ecompErrorContext) {
         ActionStatus lock = lockElement(componentId, component, ecompErrorContext);
-        if (lock!= ActionStatus.OK) {
+        if (lock != ActionStatus.OK) {
             logAndThrowComponentException(lock, component.getUniqueId(), component.getName());
         }
     }
@@ -256,7 +258,7 @@ public abstract class BaseBusinessLogic {
         }
     }
 
-    private ResponseFormat logAndThrowComponentException(ActionStatus status, String componentId, String name){
+    private ResponseFormat logAndThrowComponentException(ActionStatus status, String componentId, String name) {
         log.debug(FAILED_TO_LOCK_COMPONENT_ERROR, componentId, status);
         throw new ByActionStatusComponentException(status, name);
     }
@@ -265,7 +267,6 @@ public abstract class BaseBusinessLogic {
         ComponentTypeEnum componentType = component.getComponentType();
         NodeTypeEnum nodeType = componentType.getNodeType();
         StorageOperationStatus lockResourceStatus = graphLockOperation.lockComponent(componentId, nodeType);
-
         if (lockResourceStatus == StorageOperationStatus.OK) {
             return ActionStatus.OK;
         } else {
@@ -287,16 +288,18 @@ public abstract class BaseBusinessLogic {
             }
             // unlock resource
             graphLockOperation.unlockComponent(component.getUniqueId(), nodeType);
+        } else {
+            log.debug("component is NULL");
         }
-        else log.debug("component is NULL");
     }
 
     protected void unlockComponent(boolean failed, Component component) {
         unlockComponent(failed, component, false);
     }
+
     void unlockComponentById(boolean failed, String componentId) {
         Either<Component, StorageOperationStatus> component = toscaOperationFacade.getToscaElement(componentId);
-        if(component.isLeft()) {
+        if (component.isLeft()) {
             unlockComponent(failed, component.left().value(), false);
         }
     }
@@ -310,7 +313,6 @@ public abstract class BaseBusinessLogic {
         }
     }
 
-
     ComponentTypeEnum validateComponentType(String componentType) {
         ComponentTypeEnum componentTypeEnum = ComponentTypeEnum.findByParamName(componentType);
         if (componentTypeEnum == null) {
@@ -322,9 +324,9 @@ public abstract class BaseBusinessLogic {
     }
 
     Component validateComponentExists(String componentId, ComponentTypeEnum componentType, ComponentParametersView filter) {
-
-        Either<Component, StorageOperationStatus> toscaElement = toscaOperationFacade.getToscaElement(componentId, filter == null ? new ComponentParametersView() : filter);
-        if(toscaElement.isRight()){
+        Either<Component, StorageOperationStatus> toscaElement = toscaOperationFacade
+            .getToscaElement(componentId, filter == null ? new ComponentParametersView() : filter);
+        if (toscaElement.isRight()) {
             handleGetComponentError(componentId, componentType, toscaElement.right().value());
         }
         return validateComponentType(toscaElement.left().value(), componentType);
@@ -342,21 +344,24 @@ public abstract class BaseBusinessLogic {
         Either<Map<String, DataTypeDefinition>, JanusGraphOperationStatus> allDataTypesEither = dataTypeCache.getAll();
         if (allDataTypesEither.isRight()) {
             JanusGraphOperationStatus status = allDataTypesEither.right().value();
-            BeEcompErrorManager.getInstance().logInternalFlowError("UpdatePropertyValueOnComponentInstance", "Failed to update property value on instance. Status is " + status, ErrorSeverity.ERROR);
-            throw new ByActionStatusComponentException(componentsUtils.convertFromStorageResponse(DaoStatusConverter.convertJanusGraphStatusToStorageStatus(status)));
+            BeEcompErrorManager.getInstance()
+                .logInternalFlowError("UpdatePropertyValueOnComponentInstance", "Failed to update property value on instance. Status is " + status,
+                    ErrorSeverity.ERROR);
+            throw new ByActionStatusComponentException(
+                componentsUtils.convertFromStorageResponse(DaoStatusConverter.convertJanusGraphStatusToStorageStatus(status)));
         }
         Map<String, DataTypeDefinition> allDataTypes = allDataTypesEither.left().value();
         String propertyType = property.getType();
         String innerType = getInnerType(property);
         // Specific Update Logic
-        Either<Object, Boolean> isValid =
-                propertyOperation.validateAndUpdatePropertyValue(propertyType, property.getValue(), true,
-                        innerType, allDataTypes);
+        Either<Object, Boolean> isValid = propertyOperation
+            .validateAndUpdatePropertyValue(propertyType, property.getValue(), true, innerType, allDataTypes);
         String newValue = property.getValue();
         if (isValid.isRight()) {
             Boolean res = isValid.right().value();
             if (Boolean.FALSE.equals(res)) {
-                throw new ByActionStatusComponentException(componentsUtils.convertFromStorageResponse(DaoStatusConverter.convertJanusGraphStatusToStorageStatus(JanusGraphOperationStatus.ILLEGAL_ARGUMENT)));
+                throw new ByActionStatusComponentException(componentsUtils.convertFromStorageResponse(
+                    DaoStatusConverter.convertJanusGraphStatusToStorageStatus(JanusGraphOperationStatus.ILLEGAL_ARGUMENT)));
             }
         } else {
             Object object = isValid.left().value();
@@ -367,7 +372,7 @@ public abstract class BaseBusinessLogic {
         return newValue;
     }
 
-    <T extends PropertyDataDefinition> String getInnerType(T property){
+    <T extends PropertyDataDefinition> String getInnerType(T property) {
         ToscaPropertyType type = ToscaPropertyType.isValidType(property.getType());
         log.debug("#getInnerType - The type of the property {} is {}", property.getUniqueId(), property.getType());
         String innerType = null;
@@ -389,35 +394,30 @@ public abstract class BaseBusinessLogic {
     public void validateCanWorkOnComponent(Component component, String userId) {
         ActionStatus actionStatus = ActionStatus.RESTRICTED_OPERATION;
         // verify resource is not archived
-        if (Boolean.TRUE.equals(component.isArchived())){
+        if (Boolean.TRUE.equals(component.isArchived())) {
             actionStatus = ActionStatus.COMPONENT_IS_ARCHIVED;
             throw new ByActionStatusComponentException(actionStatus, component.getName());
         }
-
         if (component.getLifecycleState() != LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT) {
             log.debug("Component {} is not checked-out", component.getName());
             throw new ByActionStatusComponentException(actionStatus);
         }
-
         // verify userId is not null
         if (userId == null) {
             log.debug("Current user userId is null");
             throw new ByActionStatusComponentException(actionStatus);
         }
-
         // verify component last update user is the current user
         String lastUpdaterUserId = component.getLastUpdaterUserId();
         if (!userId.equals(lastUpdaterUserId)) {
             log.debug("Current user is not last updater, last updater userId: {}, current user userId: {}", lastUpdaterUserId, userId);
             throw new ByActionStatusComponentException(actionStatus);
         }
-
         // verify resource is not deleted
         if (Boolean.TRUE.equals(component.getIsDeleted())) {
             log.debug("Component {} is marked as deleted", component.getUniqueId());
             throw new ByActionStatusComponentException(actionStatus);
         }
-
     }
 
     ComponentTypeEnum getComponentTypeByParentComponentType(ComponentTypeEnum parentComponentType) {
@@ -453,7 +453,8 @@ public abstract class BaseBusinessLogic {
         String innerType = null;
         if (!propertyOperation.isPropertyTypeValid(property)) {
             log.info("Invalid type for property '{}' type '{}'", property.getName(), property.getType());
-            ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.INVALID_PROPERTY_TYPE, property.getType(), property.getName());
+            ResponseFormat responseFormat = componentsUtils
+                .getResponseFormat(ActionStatus.INVALID_PROPERTY_TYPE, property.getType(), property.getName());
             return Either.right(responseFormat);
         }
         type = property.getType();
@@ -461,8 +462,10 @@ public abstract class BaseBusinessLogic {
             ImmutablePair<String, Boolean> propertyInnerTypeValid = propertyOperation.isPropertyInnerTypeValid(property, dataTypes);
             innerType = propertyInnerTypeValid.getLeft();
             if (Boolean.FALSE.equals(propertyInnerTypeValid.getRight())) {
-                log.info("Invalid inner type for property '{}' type '{}', dataTypeCount '{}'", property.getName(), property.getType(), dataTypes.size());
-                ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.INVALID_PROPERTY_INNER_TYPE, innerType, property.getName());
+                log.info("Invalid inner type for property '{}' type '{}', dataTypeCount '{}'", property.getName(), property.getType(),
+                    dataTypes.size());
+                ResponseFormat responseFormat = componentsUtils
+                    .getResponseFormat(ActionStatus.INVALID_PROPERTY_INNER_TYPE, innerType, property.getName());
                 return Either.right(responseFormat);
             }
         }
@@ -470,14 +473,13 @@ public abstract class BaseBusinessLogic {
             log.info("Invalid default value for property '{}' type '{}'", property.getName(), property.getType());
             ResponseFormat responseFormat;
             if (type.equals(ToscaPropertyType.LIST.getType()) || type.equals(ToscaPropertyType.MAP.getType())) {
-                responseFormat = componentsUtils.getResponseFormat(ActionStatus.INVALID_COMPLEX_DEFAULT_VALUE, property.getName(), type, innerType,
-                        property.getDefaultValue());
+                responseFormat = componentsUtils
+                    .getResponseFormat(ActionStatus.INVALID_COMPLEX_DEFAULT_VALUE, property.getName(), type, innerType, property.getDefaultValue());
             } else {
-                responseFormat = componentsUtils.getResponseFormat(ActionStatus.INVALID_DEFAULT_VALUE, property.getName(), type,
-                        property.getDefaultValue());
+                responseFormat = componentsUtils
+                    .getResponseFormat(ActionStatus.INVALID_DEFAULT_VALUE, property.getName(), type, property.getDefaultValue());
             }
             return Either.right(responseFormat);
-
         }
         return Either.left(true);
     }
@@ -487,15 +489,14 @@ public abstract class BaseBusinessLogic {
             BeEcompErrorManager.getInstance().logInvalidInputError(errorContext, "invalid component type", ErrorSeverity.INFO);
             errorWrapper.setInnerElement(componentsUtils.getResponseFormat(ActionStatus.NOT_ALLOWED));
         }
-
     }
 
-    protected void validateCanWorkOnComponent(String componentId, ComponentTypeEnum componentTypeEnum, String userId, Wrapper<ResponseFormat> errorWrapper) {
+    protected void validateCanWorkOnComponent(String componentId, ComponentTypeEnum componentTypeEnum, String userId,
+                                              Wrapper<ResponseFormat> errorWrapper) {
         if (!ComponentValidationUtils.canWorkOnComponent(componentId, toscaOperationFacade, userId)) {
             log.info("Restricted operation for user {} on {} {}", userId, componentTypeEnum.getValue(), componentId);
             errorWrapper.setInnerElement(componentsUtils.getResponseFormat(ActionStatus.RESTRICTED_OPERATION));
         }
-
     }
 
     void validateComponentLock(String componentId, ComponentTypeEnum componentTypeEnum, Wrapper<ResponseFormat> errorWrapper) {
@@ -504,7 +505,6 @@ public abstract class BaseBusinessLogic {
             log.debug("Failed to lock {} {}", componentTypeEnum.getValue(), componentId);
             errorWrapper.setInnerElement(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(lockStatus)));
         }
-
     }
 
     protected ToscaPropertyType getType(String propertyType) {
@@ -525,7 +525,6 @@ public abstract class BaseBusinessLogic {
         ComponentTypeEnum componentType = component.getComponentType();
         NodeTypeEnum nodeType = componentType.getNodeType();
         StorageOperationStatus lockResourceStatus = graphLockOperation.lockComponentByName(name, nodeType);
-
         if (lockResourceStatus == StorageOperationStatus.OK) {
             return Either.left(true);
         } else {
@@ -537,11 +536,10 @@ public abstract class BaseBusinessLogic {
         }
     }
 
-    protected Component validateComponentExistsByFilter(String componentId, ComponentTypeEnum componentType, ComponentParametersView componentParametersView) {
-        return toscaOperationFacade.getToscaElement(componentId, componentParametersView)
-                .left()
-                .on(err -> handleGetComponentError(componentId, componentType, err));
-
+    protected Component validateComponentExistsByFilter(String componentId, ComponentTypeEnum componentType,
+                                                        ComponentParametersView componentParametersView) {
+        return toscaOperationFacade.getToscaElement(componentId, componentParametersView).left()
+            .on(err -> handleGetComponentError(componentId, componentType, err));
     }
 
     private Component handleGetComponentError(String componentId, ComponentTypeEnum componentType, StorageOperationStatus getComponentError) {
@@ -550,14 +548,8 @@ public abstract class BaseBusinessLogic {
         throw new ByActionStatusComponentException(actionStatus, componentId);
     }
 
-    @SafeVarargs
-    static <T extends Enum<T>> boolean enumHasValueFilter(String name, Function<String, T> enumGetter, T... enumValues) {
-        T enumFound = enumGetter.apply(name);
-        return Arrays.asList(enumValues).contains(enumFound);
-    }
-
     String validatePropValueBeforeCreate(IPropertyInputCommon property, String value, boolean isValidate,
-        Map<String, DataTypeDefinition> allDataTypes) {
+                                         Map<String, DataTypeDefinition> allDataTypes) {
         String propertyType = property.getType();
         String updatedInnerType = updateInnerType(property);
         Either<Object, Boolean> isValid = validateAndUpdatePropertyValue(propertyType, value, isValidate, updatedInnerType, allDataTypes);
@@ -565,8 +557,7 @@ public abstract class BaseBusinessLogic {
         if (isValid.isRight()) {
             Boolean res = isValid.right().value();
             if (Boolean.FALSE.equals(res)) {
-                throw new StorageException(DaoStatusConverter.convertJanusGraphStatusToStorageStatus(
-                        JanusGraphOperationStatus.ILLEGAL_ARGUMENT));
+                throw new StorageException(DaoStatusConverter.convertJanusGraphStatusToStorageStatus(JanusGraphOperationStatus.ILLEGAL_ARGUMENT));
             }
         } else {
             Object object = isValid.left().value();
@@ -578,8 +569,7 @@ public abstract class BaseBusinessLogic {
         log.trace("After validateAndUpdateRules. pair = {}", pair);
         if (Boolean.FALSE.equals(pair.getRight())) {
             BeEcompErrorManager.getInstance().logBeInvalidValueError(ADD_PROPERTY_VALUE, pair.getLeft(), property.getName(), propertyType);
-            throw new StorageException(DaoStatusConverter.convertJanusGraphStatusToStorageStatus(
-                    JanusGraphOperationStatus.ILLEGAL_ARGUMENT));
+            throw new StorageException(DaoStatusConverter.convertJanusGraphStatusToStorageStatus(JanusGraphOperationStatus.ILLEGAL_ARGUMENT));
         }
         return newValue;
     }
@@ -603,20 +593,19 @@ public abstract class BaseBusinessLogic {
     }
 
     private void failOnIllegalArgument() {
-        throw new ByActionStatusComponentException(
-                componentsUtils.convertFromStorageResponse(
-                        DaoStatusConverter.convertJanusGraphStatusToStorageStatus(JanusGraphOperationStatus.ILLEGAL_ARGUMENT)));
+        throw new ByActionStatusComponentException(componentsUtils
+            .convertFromStorageResponse(DaoStatusConverter.convertJanusGraphStatusToStorageStatus(JanusGraphOperationStatus.ILLEGAL_ARGUMENT)));
     }
 
-    public Either<Object, Boolean> validateAndUpdatePropertyValue(String propertyType, String value, boolean isValidate, String innerType, Map<String, DataTypeDefinition> dataTypes) {
+    public Either<Object, Boolean> validateAndUpdatePropertyValue(String propertyType, String value, boolean isValidate, String innerType,
+                                                                  Map<String, DataTypeDefinition> dataTypes) {
         log.trace("Going to validate property value and its type. type = {}, value = {}", propertyType, value);
         ToscaPropertyType type = getType(propertyType);
-
         if (isValidate) {
-
             if (type == null) {
                 DataTypeDefinition dataTypeDefinition = dataTypes.get(propertyType);
-                ImmutablePair<JsonElement, Boolean> validateResult = dataTypeValidatorConverter.validateAndUpdate(value, dataTypeDefinition, dataTypes);
+                ImmutablePair<JsonElement, Boolean> validateResult = dataTypeValidatorConverter
+                    .validateAndUpdate(value, dataTypeDefinition, dataTypes);
                 if (Boolean.FALSE.equals(validateResult.right)) {
                     log.debug(THE_VALUE_OF_PROPERTY_FROM_TYPE_IS_INVALID, value, propertyType);
                     return Either.right(false);
@@ -640,12 +629,11 @@ public abstract class BaseBusinessLogic {
         return Either.left(convertedValue);
     }
 
-    private ImmutablePair<String, Boolean> validateAndUpdateRules(String propertyType, List<PropertyRule> rules, String innerType, Map<String, DataTypeDefinition> dataTypes, boolean isValidate) {
-
+    private ImmutablePair<String, Boolean> validateAndUpdateRules(String propertyType, List<PropertyRule> rules, String innerType,
+                                                                  Map<String, DataTypeDefinition> dataTypes, boolean isValidate) {
         if (rules == null || rules.isEmpty()) {
             return ImmutablePair.of(null, true);
         }
-
         for (PropertyRule rule : rules) {
             String value = rule.getValue();
             Either<Object, Boolean> updateResult = validateAndUpdatePropertyValue(propertyType, value, isValidate, innerType, dataTypes);
@@ -663,7 +651,6 @@ public abstract class BaseBusinessLogic {
                 rule.setValue(newValue);
             }
         }
-
         return ImmutablePair.of(null, true);
     }
 
@@ -671,9 +658,7 @@ public abstract class BaseBusinessLogic {
         if (isEmptyValue(value)) {
             return true;
         }
-
         PropertyTypeValidator validator = type.getValidator();
-
         return validator.isValid(value, innerType, dataTypes);
     }
 
@@ -696,26 +681,22 @@ public abstract class BaseBusinessLogic {
         throw new ByActionStatusComponentException(actionStatus, params);
     }
 
-    public  <T extends ToscaDataDefinition> Either<List<T>, ResponseFormat> declareProperties(final String userId,
-                                                                                              final String componentId,
-                                                                                              final ComponentTypeEnum componentTypeEnum,
-                                                                                              final ComponentInstInputsMap componentInstInputsMap) {
+    public <T extends ToscaDataDefinition> Either<List<T>, ResponseFormat> declareProperties(final String userId, final String componentId,
+                                                                                             final ComponentTypeEnum componentTypeEnum,
+                                                                                             final ComponentInstInputsMap componentInstInputsMap) {
         return Either.left(new ArrayList<>());
     }
 
-    public  <T extends ToscaDataDefinition> Either<List<T>, ResponseFormat> declareAttributes(final String userId,
-                                                                                              final String componentId,
-                                                                                              final ComponentTypeEnum componentTypeEnum,
-                                                                                              final ComponentInstOutputsMap componentInstOutputsMap) {
+    public <T extends ToscaDataDefinition> Either<List<T>, ResponseFormat> declareAttributes(final String userId, final String componentId,
+                                                                                             final ComponentTypeEnum componentTypeEnum,
+                                                                                             final ComponentInstOutputsMap componentInstOutputsMap) {
         return Either.left(new ArrayList<>());
     }
 
     public <T extends PropertyDataDefinition> List<PropertyConstraint> setInputConstraint(T inputDefinition) {
-        if (StringUtils.isNotBlank(inputDefinition.getParentPropertyType())
-                && StringUtils.isNotBlank(inputDefinition.getSubPropertyInputPath())) {
+        if (StringUtils.isNotBlank(inputDefinition.getParentPropertyType()) && StringUtils.isNotBlank(inputDefinition.getSubPropertyInputPath())) {
             return setConstraint(inputDefinition);
         }
-
         return Collections.emptyList();
     }
 
@@ -725,32 +706,22 @@ public abstract class BaseBusinessLogic {
         if (inputPathArr.length > 1) {
             inputPathArr = ArrayUtils.remove(inputPathArr, 0);
         }
-
-        Map<String, DataTypeDefinition> dataTypeDefinitionMap =
-                applicationDataTypeCache.getAll().left().value();
-
+        Map<String, DataTypeDefinition> dataTypeDefinitionMap = applicationDataTypeCache.getAll().left().value();
         String propertyType = inputDefinition.getParentPropertyType();
-
         for (String anInputPathArr : inputPathArr) {
             if (ToscaType.isPrimitiveType(propertyType)) {
-                constraints.addAll(
-                        dataTypeDefinitionMap.get(propertyType).getConstraints());
+                constraints.addAll(dataTypeDefinitionMap.get(propertyType).getConstraints());
             } else if (!ToscaType.isCollectionType(propertyType)) {
-                propertyType = setConstraintForComplexType(dataTypeDefinitionMap, propertyType, anInputPathArr,
-                        constraints);
+                propertyType = setConstraintForComplexType(dataTypeDefinitionMap, propertyType, anInputPathArr, constraints);
             }
         }
-
         return constraints;
     }
 
-    private String setConstraintForComplexType(Map<String, DataTypeDefinition> dataTypeDefinitionMap,
-                                               String propertyType,
-                                               String anInputPathArr,
+    private String setConstraintForComplexType(Map<String, DataTypeDefinition> dataTypeDefinitionMap, String propertyType, String anInputPathArr,
                                                List<PropertyConstraint> constraints) {
         String type = null;
-        List<PropertyDefinition> propertyDefinitions =
-                dataTypeDefinitionMap.get(propertyType).getProperties();
+        List<PropertyDefinition> propertyDefinitions = dataTypeDefinitionMap.get(propertyType).getProperties();
         for (PropertyDefinition propertyDefinition : propertyDefinitions) {
             if (propertyDefinition.getName().equals(anInputPathArr)) {
                 if (ToscaType.isPrimitiveType(propertyDefinition.getType())) {
@@ -761,18 +732,16 @@ public abstract class BaseBusinessLogic {
                 break;
             }
         }
-
         return type;
     }
 
-
     protected void unlockRollbackWithException(Component component, RuntimeException e) {
         janusGraphDao.rollback();
         graphLockOperation.unlockComponent(component.getUniqueId(), component.getComponentType().getNodeType());
         throw e;
     }
 
-    protected void unlockWithCommit(Component component){
+    protected void unlockWithCommit(Component component) {
         ComponentTypeEnum componentType = component.getComponentType();
         NodeTypeEnum nodeType = componentType.getNodeType();
         janusGraphDao.commit();
@@ -796,17 +765,13 @@ public abstract class BaseBusinessLogic {
     }
 
     protected Component getComponent(final String componentId) throws BusinessLogicException {
-
         final Either<Component, StorageOperationStatus> result = toscaOperationFacade.getToscaElement(componentId);
-
         if (result.isRight()) {
             final StorageOperationStatus errorStatus = result.right().value();
-            log.error(BUSINESS_PROCESS_ERROR, this.getClass().getName(),
-                "Failed to fetch component information by component id, error {}", errorStatus);
-            throw new BusinessLogicException(componentsUtils.getResponseFormat(
-                componentsUtils.convertFromStorageResponse(errorStatus)));
+            log.error(BUSINESS_PROCESS_ERROR, this.getClass().getName(), "Failed to fetch component information by component id, error {}",
+                errorStatus);
+            throw new BusinessLogicException(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(errorStatus)));
         }
         return result.left().value();
     }
-
 }
index f94528c..2fc012b 100644 (file)
  * limitations under the License.
  * ============LICENSE_END=========================================================
  */
-
 package org.openecomp.sdc.be.components.impl;
 
+import static org.openecomp.sdc.common.api.Constants.HC_COMPONENT_CADI;
+import static org.openecomp.sdc.common.api.HealthCheckInfo.HealthCheckStatus.DOWN;
+
 import org.openecomp.sdc.common.api.HealthCheckInfo;
 import org.openecomp.sdc.common.log.wrappers.Logger;
 import org.springframework.stereotype.Component;
 
-import static org.openecomp.sdc.common.api.Constants.HC_COMPONENT_CADI;
-import static org.openecomp.sdc.common.api.HealthCheckInfo.HealthCheckStatus.DOWN;
-
 @Component
 public class CADIHealthCheck {
 
-    private static CADIHealthCheck cadiHealthCheckInstance = new CADIHealthCheck();;
-
-    private static HealthCheckInfo.HealthCheckStatus isCADIUpOrDown = DOWN;
-
     private static final Logger log = Logger.getLogger(CADIHealthCheck.class.getName());
+    private static CADIHealthCheck cadiHealthCheckInstance = new CADIHealthCheck();
+    private static HealthCheckInfo.HealthCheckStatus isCADIUpOrDown = DOWN;
 
     public static CADIHealthCheck getCADIHealthCheckInstance() {
         return cadiHealthCheckInstance;
     }
 
-    public void setIsCADIUp(HealthCheckInfo.HealthCheckStatus cadiStatus) {
-        log.debug("Setting cadiHealthCheckInstance status to: {}", cadiStatus.toString());
-        isCADIUpOrDown = cadiStatus;
-    }
-
     public static HealthCheckInfo getCADIStatus() {
         log.debug("getCADIStatus: Checking whether CADI was up or down while its init.");
         String description = "OK";
-        if (isCADIUpOrDown == DOWN){
+        if (isCADIUpOrDown == DOWN) {
             description = "CADI filter failed initialization";
         }
-        return new HealthCheckInfo(HC_COMPONENT_CADI, isCADIUpOrDown, null,
-                description);
+        return new HealthCheckInfo(HC_COMPONENT_CADI, isCADIUpOrDown, null, description);
     }
 
+    public void setIsCADIUp(HealthCheckInfo.HealthCheckStatus cadiStatus) {
+        log.debug("Setting cadiHealthCheckInstance status to: {}", cadiStatus.toString());
+        isCADIUpOrDown = cadiStatus;
+    }
 }
index 4bfc650..cadaf6f 100644 (file)
  * See the License for the specific language governing permissions and
  * limitations under the License.
  */
-
 package org.openecomp.sdc.be.components.impl;
 
 import fj.data.Either;
+import java.util.ArrayList;
+import java.util.Collection;
+import java.util.Collections;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+import java.util.Objects;
+import java.util.Optional;
+import java.util.UUID;
+import java.util.stream.Collectors;
 import org.apache.commons.collections.CollectionUtils;
 import org.apache.commons.collections.MapUtils;
 import org.apache.commons.lang.StringUtils;
@@ -51,42 +60,25 @@ import org.slf4j.Logger;
 import org.slf4j.LoggerFactory;
 import org.springframework.beans.factory.annotation.Autowired;
 
-import java.util.ArrayList;
-import java.util.Collection;
-import java.util.Collections;
-import java.util.HashMap;
-import java.util.List;
-import java.util.Map;
-import java.util.Objects;
-import java.util.Optional;
-import java.util.UUID;
-import java.util.stream.Collectors;
-
 @org.springframework.stereotype.Component("capabilitiesBusinessLogic")
 public class CapabilitiesBusinessLogic extends BaseBusinessLogic {
+
     private static final Logger LOGGER = LoggerFactory.getLogger(CapabilitiesBusinessLogic.class);
     private static final String FAILED_TO_LOCK_COMPONENT_RESPONSE_IS = "Failed to lock component {}. Response is {}";
     private static final String DELETE_CAPABILITIES = "deleteCapability";
     private static final String GET_CAPABILITIES = "getCapabilities";
     private static final String EXCEPTION_OCCURRED_DURING_CAPABILITIES = "Exception occurred during {}. Response is {}";
-
     private final ICapabilityTypeOperation capabilityTypeOperation;
-
     private CapabilitiesOperation capabilitiesOperation;
     private CapabilitiesValidation capabilitiesValidation;
 
     @Autowired
-    public CapabilitiesBusinessLogic(IElementOperation elementDao,
-        IGroupOperation groupOperation,
-        IGroupInstanceOperation groupInstanceOperation,
-        IGroupTypeOperation groupTypeOperation,
-        GroupBusinessLogic groupBusinessLogic,
-        InterfaceOperation interfaceOperation,
-        InterfaceLifecycleOperation interfaceLifecycleTypeOperation,
-        ICapabilityTypeOperation capabilityTypeOperation,
-        ArtifactsOperations artifactToscaOperation) {
-        super(elementDao, groupOperation, groupInstanceOperation, groupTypeOperation,
-            interfaceOperation, interfaceLifecycleTypeOperation, artifactToscaOperation);
+    public CapabilitiesBusinessLogic(IElementOperation elementDao, IGroupOperation groupOperation, IGroupInstanceOperation groupInstanceOperation,
+                                     IGroupTypeOperation groupTypeOperation, GroupBusinessLogic groupBusinessLogic,
+                                     InterfaceOperation interfaceOperation, InterfaceLifecycleOperation interfaceLifecycleTypeOperation,
+                                     ICapabilityTypeOperation capabilityTypeOperation, ArtifactsOperations artifactToscaOperation) {
+        super(elementDao, groupOperation, groupInstanceOperation, groupTypeOperation, interfaceOperation, interfaceLifecycleTypeOperation,
+            artifactToscaOperation);
         this.capabilityTypeOperation = capabilityTypeOperation;
     }
 
@@ -100,16 +92,14 @@ public class CapabilitiesBusinessLogic extends BaseBusinessLogic {
         this.capabilitiesOperation = capabilitiesOperation;
     }
 
-    public Either<List<CapabilityDefinition>, ResponseFormat> createCapabilities(String componentId,
-                                                                                 List<CapabilityDefinition> capabilityDefinitions,
+    public Either<List<CapabilityDefinition>, ResponseFormat> createCapabilities(String componentId, List<CapabilityDefinition> capabilityDefinitions,
                                                                                  User user, String errorContext, boolean lock) {
-        Either<Component, ResponseFormat> validateUserAndCapabilitiesEither =
-                validateUserAndCapabilities(user, componentId, errorContext, capabilityDefinitions);
-        if(validateUserAndCapabilitiesEither.isRight()) {
+        Either<Component, ResponseFormat> validateUserAndCapabilitiesEither = validateUserAndCapabilities(user, componentId, errorContext,
+            capabilityDefinitions);
+        if (validateUserAndCapabilitiesEither.isRight()) {
             return Either.right(validateUserAndCapabilitiesEither.right().value());
         }
-        Component  storedComponent = validateUserAndCapabilitiesEither.left().value();
-
+        Component storedComponent = validateUserAndCapabilitiesEither.left().value();
         Either<Boolean, ResponseFormat> lockResult = lockComponentResult(lock, storedComponent, errorContext);
         if (lockResult.isRight()) {
             return Either.right(lockResult.right().value());
@@ -122,16 +112,14 @@ public class CapabilitiesBusinessLogic extends BaseBusinessLogic {
             return Either.right(componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR));
         } finally {
             if (lockResult.isLeft() && lockResult.left().value()) {
-                graphLockOperation.unlockComponent(storedComponent.getUniqueId(),
-                        NodeTypeEnum.getByNameIgnoreCase(storedComponent.getComponentType().getValue()));
+                graphLockOperation
+                    .unlockComponent(storedComponent.getUniqueId(), NodeTypeEnum.getByNameIgnoreCase(storedComponent.getComponentType().getValue()));
             }
         }
     }
 
-
-    private Either<Component, ResponseFormat> validateUserAndCapabilities(User user, String componentId,
-                                                                          String errorContext,
-                                                                          List<CapabilityDefinition> capabilityDefinitions ) {
+    private Either<Component, ResponseFormat> validateUserAndCapabilities(User user, String componentId, String errorContext,
+                                                                          List<CapabilityDefinition> capabilityDefinitions) {
         validateUserExists(user.getUserId());
         Either<Component, ResponseFormat> componentEither = getComponentDetails(componentId);
         if (componentEither.isRight()) {
@@ -139,15 +127,14 @@ public class CapabilitiesBusinessLogic extends BaseBusinessLogic {
         }
         Component storedComponent = componentEither.left().value();
         Either<Boolean, ResponseFormat> capabilitiesValidationEither = capabilitiesValidation
-                .validateCapabilities(capabilityDefinitions, storedComponent, false);
+            .validateCapabilities(capabilityDefinitions, storedComponent, false);
         if (capabilitiesValidationEither.isRight()) {
             return Either.right(capabilitiesValidationEither.right().value());
         }
         return Either.left(storedComponent);
     }
 
-    private Either<List<CapabilityDefinition>, ResponseFormat> createCapability(String componentId,
-                                                                                List<CapabilityDefinition> capabilityDefinitions,
+    private Either<List<CapabilityDefinition>, ResponseFormat> createCapability(String componentId, List<CapabilityDefinition> capabilityDefinitions,
                                                                                 Component storedComponent) {
         Either<List<CapabilityDefinition>, StorageOperationStatus> result;
         List<CapabilityDefinition> capabilitiesListStoredInComponent = null;
@@ -157,32 +144,30 @@ public class CapabilitiesBusinessLogic extends BaseBusinessLogic {
             if (Objects.isNull(capabilityDefinitionToGetType)) {
                 return Either.right(componentsUtils.getResponseFormat(ActionStatus.INVALID_CONTENT));
             }
-            capabilitiesListStoredInComponent = getCapabilityStoredInComponentByType(capabilityDefinitionToGetType
-                    .getType(), storedComponentCapabilities);
+            capabilitiesListStoredInComponent = getCapabilityStoredInComponentByType(capabilityDefinitionToGetType.getType(),
+                storedComponentCapabilities);
         }
         List<CapabilityDefinition> capabilitiesDefListToCreate;
         List<CapabilityDefinition> capabilitiesToReturn;
         if (CollectionUtils.isNotEmpty(capabilitiesListStoredInComponent)) {
-            capabilitiesDefListToCreate = capabilityDefinitions.stream().map(capabilityDefinition ->
-                    initiateNewCapability(storedComponent, capabilityDefinition)).collect(Collectors.toList());
+            capabilitiesDefListToCreate = capabilityDefinitions.stream()
+                .map(capabilityDefinition -> initiateNewCapability(storedComponent, capabilityDefinition)).collect(Collectors.toList());
             capabilitiesToReturn = capabilitiesDefListToCreate;
             capabilitiesDefListToCreate.addAll(capabilitiesListStoredInComponent);
             result = capabilitiesOperation.updateCapabilities(componentId, capabilitiesDefListToCreate);
         } else {
-            capabilitiesToReturn = capabilityDefinitions.stream().map(capabilityDefinition ->
-                    initiateNewCapability(storedComponent, capabilityDefinition)).collect(Collectors.toList());
+            capabilitiesToReturn = capabilityDefinitions.stream()
+                .map(capabilityDefinition -> initiateNewCapability(storedComponent, capabilityDefinition)).collect(Collectors.toList());
             result = capabilitiesOperation.addCapabilities(componentId, capabilitiesToReturn);
         }
         if (result.isRight()) {
             janusGraphDao.rollback();
-            return Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(result
-                    .right().value(), storedComponent.getComponentType()), ""));
+            return Either.right(componentsUtils
+                .getResponseFormat(componentsUtils.convertFromStorageResponse(result.right().value(), storedComponent.getComponentType()), ""));
         }
-        Map<String, MapPropertiesDataDefinition> propertiesMap =
-                getCapabilitiesPropertiesDataDefinitionMap(capabilityDefinitions);
+        Map<String, MapPropertiesDataDefinition> propertiesMap = getCapabilitiesPropertiesDataDefinitionMap(capabilityDefinitions);
         if (MapUtils.isNotEmpty(propertiesMap)) {
-            StorageOperationStatus storageOperationStatus = capabilitiesOperation
-                    .createOrUpdateCapabilityProperties(componentId, propertiesMap);
+            StorageOperationStatus storageOperationStatus = capabilitiesOperation.createOrUpdateCapabilityProperties(componentId, propertiesMap);
             if (storageOperationStatus != StorageOperationStatus.OK) {
                 janusGraphDao.rollback();
                 return Either.right(componentsUtils.getResponseFormat(storageOperationStatus));
@@ -192,8 +177,7 @@ public class CapabilitiesBusinessLogic extends BaseBusinessLogic {
         return Either.left(capabilitiesToReturn);
     }
 
-    public Either<List<CapabilityDefinition>, ResponseFormat> updateCapabilities(String componentId,
-                                                                                 List<CapabilityDefinition> capabilityDefinitions,
+    public Either<List<CapabilityDefinition>, ResponseFormat> updateCapabilities(String componentId, List<CapabilityDefinition> capabilityDefinitions,
                                                                                  User user, String errorContext, boolean lock) {
         validateUserExists(user.getUserId());
         Either<Component, ResponseFormat> componentEither = getComponentDetails(componentId);
@@ -202,11 +186,10 @@ public class CapabilitiesBusinessLogic extends BaseBusinessLogic {
         }
         Component storedComponent = componentEither.left().value();
         Either<Boolean, ResponseFormat> capabilitiesValidationEither = capabilitiesValidation
-                .validateCapabilities(capabilityDefinitions, storedComponent, true);
+            .validateCapabilities(capabilityDefinitions, storedComponent, true);
         if (capabilitiesValidationEither.isRight()) {
             return Either.right(capabilitiesValidationEither.right().value());
         }
-
         Either<Boolean, ResponseFormat> lockResult = lockComponentResult(lock, storedComponent, errorContext);
         if (lockResult.isRight()) {
             return Either.right(lockResult.right().value());
@@ -220,32 +203,30 @@ public class CapabilitiesBusinessLogic extends BaseBusinessLogic {
                 if (Objects.isNull(capabilityDefinitionToGetType)) {
                     return Either.right(componentsUtils.getResponseFormat(ActionStatus.INVALID_CONTENT));
                 }
-                capabilitiesListStoredInComponent = getCapabilityStoredInComponentByType(capabilityDefinitionToGetType
-                        .getType(), storedComponentCapabilities);
+                capabilitiesListStoredInComponent = getCapabilityStoredInComponentByType(capabilityDefinitionToGetType.getType(),
+                    storedComponentCapabilities);
             }
             List<CapabilityDefinition> capabilitiesDefListToUpdate = new ArrayList<>();
             List<CapabilityDefinition> capabilitiesToReturn = null;
             if (CollectionUtils.isNotEmpty(capabilitiesListStoredInComponent)) {
-                if (capabilityDefinitions.stream().anyMatch(capabilityDefinition ->
-                        isCapabilityUsedInServiceComposition(capabilityDefinition, storedComponent))) {
+                if (capabilityDefinitions.stream()
+                    .anyMatch(capabilityDefinition -> isCapabilityUsedInServiceComposition(capabilityDefinition, storedComponent))) {
                     LOGGER.error("Capability can't be edited, since it is" + " used in service composition");
-                    return Either.right(componentsUtils.getResponseFormat(ActionStatus.
-                            CAPABILITY_UPDATE_NOT_ALLOWED_USED_IN_COMPOSITION));
+                    return Either.right(componentsUtils.getResponseFormat(ActionStatus.CAPABILITY_UPDATE_NOT_ALLOWED_USED_IN_COMPOSITION));
                 }
                 for (CapabilityDefinition capabilityDefinitionToUpdate : capabilityDefinitions) {
-                    capabilitiesToReturn = capabilitiesListStoredInComponent.stream().filter(capToUpdate ->
-                            capToUpdate.getUniqueId().equals(capabilityDefinitionToUpdate.getUniqueId()))
-                            .map(capabilityDefinition -> updateCapability(capabilityDefinition,
-                                    capabilityDefinitionToUpdate, storedComponent)).collect(Collectors.toList());
-                    capabilitiesListStoredInComponent.removeIf(capToUpdate -> capToUpdate.getUniqueId()
-                            .equals(capabilityDefinitionToUpdate.getUniqueId()));
+                    capabilitiesToReturn = capabilitiesListStoredInComponent.stream()
+                        .filter(capToUpdate -> capToUpdate.getUniqueId().equals(capabilityDefinitionToUpdate.getUniqueId()))
+                        .map(capabilityDefinition -> updateCapability(capabilityDefinition, capabilityDefinitionToUpdate, storedComponent))
+                        .collect(Collectors.toList());
+                    capabilitiesListStoredInComponent
+                        .removeIf(capToUpdate -> capToUpdate.getUniqueId().equals(capabilityDefinitionToUpdate.getUniqueId()));
                     if (CollectionUtils.isNotEmpty(capabilitiesToReturn)) {
                         capabilitiesListStoredInComponent.addAll(capabilitiesToReturn);
                         capabilitiesDefListToUpdate.addAll(capabilitiesListStoredInComponent);
                     } else {
-                        Either<List<CapabilityDefinition>, ResponseFormat> capTypeUpdateEither
-                                = handleCapabilityTypeUpdateWhenNewTypeExist(storedComponent, storedComponent
-                                .getCapabilities(), capabilitiesToReturn, capabilityDefinitionToUpdate);
+                        Either<List<CapabilityDefinition>, ResponseFormat> capTypeUpdateEither = handleCapabilityTypeUpdateWhenNewTypeExist(
+                            storedComponent, storedComponent.getCapabilities(), capabilitiesToReturn, capabilityDefinitionToUpdate);
                         if (capTypeUpdateEither.isRight()) {
                             return Either.right(capTypeUpdateEither.right().value());
                         }
@@ -254,26 +235,23 @@ public class CapabilitiesBusinessLogic extends BaseBusinessLogic {
                 }
                 result = capabilitiesOperation.updateCapabilities(componentId, capabilitiesDefListToUpdate);
             } else {
-                Either<List<CapabilityDefinition>, ResponseFormat> capabilityDefinitionToDelete
-                        = handleCapabilityTypeUpdateWhenNewTypeNotExist(capabilityDefinitions, storedComponent,
-                        storedComponentCapabilities);
+                Either<List<CapabilityDefinition>, ResponseFormat> capabilityDefinitionToDelete = handleCapabilityTypeUpdateWhenNewTypeNotExist(
+                    capabilityDefinitions, storedComponent, storedComponentCapabilities);
                 if (capabilityDefinitionToDelete != null) {
                     return capabilityDefinitionToDelete;
                 }
-                capabilitiesToReturn = capabilityDefinitions.stream().map(capabilityDefinition ->
-                        initiateNewCapability(storedComponent, capabilityDefinition)).collect(Collectors.toList());
+                capabilitiesToReturn = capabilityDefinitions.stream()
+                    .map(capabilityDefinition -> initiateNewCapability(storedComponent, capabilityDefinition)).collect(Collectors.toList());
                 result = capabilitiesOperation.addCapabilities(componentId, capabilitiesToReturn);
             }
             if (result.isRight()) {
                 janusGraphDao.rollback();
-                return Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(result
-                        .right().value(), storedComponent.getComponentType()), ""));
+                return Either.right(componentsUtils
+                    .getResponseFormat(componentsUtils.convertFromStorageResponse(result.right().value(), storedComponent.getComponentType()), ""));
             }
-            Map<String, MapPropertiesDataDefinition> propertiesMap =
-                    getCapabilitiesPropertiesDataDefinitionMap(capabilityDefinitions);
+            Map<String, MapPropertiesDataDefinition> propertiesMap = getCapabilitiesPropertiesDataDefinitionMap(capabilityDefinitions);
             if (MapUtils.isNotEmpty(propertiesMap)) {
-                StorageOperationStatus storageOperationStatus = capabilitiesOperation
-                        .createOrUpdateCapabilityProperties(componentId, propertiesMap);
+                StorageOperationStatus storageOperationStatus = capabilitiesOperation.createOrUpdateCapabilityProperties(componentId, propertiesMap);
                 if (storageOperationStatus != StorageOperationStatus.OK) {
                     janusGraphDao.rollback();
                     return Either.right(componentsUtils.getResponseFormat(storageOperationStatus));
@@ -287,81 +265,67 @@ public class CapabilitiesBusinessLogic extends BaseBusinessLogic {
             return Either.right(componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR));
         } finally {
             if (lockResult.isLeft() && lockResult.left().value()) {
-                graphLockOperation.unlockComponent(storedComponent.getUniqueId(),
-                        NodeTypeEnum.getByNameIgnoreCase(storedComponent.getComponentType().getValue()));
+                graphLockOperation
+                    .unlockComponent(storedComponent.getUniqueId(), NodeTypeEnum.getByNameIgnoreCase(storedComponent.getComponentType().getValue()));
             }
         }
     }
 
-    private Either<List<CapabilityDefinition>, ResponseFormat> handleCapabilityTypeUpdateWhenNewTypeExist(
-            Component storedComponent,
-            Map<String, List<CapabilityDefinition>> storedComponentCapabilities,
-            List<CapabilityDefinition> capabilitiesToReturn,
-            CapabilityDefinition capabilityDefinitionToUpdate) {
-
+    private Either<List<CapabilityDefinition>, ResponseFormat> handleCapabilityTypeUpdateWhenNewTypeExist(Component storedComponent,
+                                                                                                          Map<String, List<CapabilityDefinition>> storedComponentCapabilities,
+                                                                                                          List<CapabilityDefinition> capabilitiesToReturn,
+                                                                                                          CapabilityDefinition capabilityDefinitionToUpdate) {
         List<CapabilityDefinition> capabilitiesListStoredInComponent;
         List<CapabilityDefinition> capabilitiesDefsToCreateOrUpdate = new ArrayList<>();
-        Optional<CapabilityDefinition> definitionOptional = storedComponentCapabilities.values().stream()
-                .flatMap(Collection::stream).filter(capabilityDefinition -> capabilityDefinition.getUniqueId()
-                        .equals(capabilityDefinitionToUpdate.getUniqueId())).findAny();
+        Optional<CapabilityDefinition> definitionOptional = storedComponentCapabilities.values().stream().flatMap(Collection::stream)
+            .filter(capabilityDefinition -> capabilityDefinition.getUniqueId().equals(capabilityDefinitionToUpdate.getUniqueId())).findAny();
         if (!definitionOptional.isPresent()) {
-            return Either.right(componentsUtils.getResponseFormat(ActionStatus.CAPABILITY_NOT_FOUND,
-                    storedComponent.getUniqueId()));
+            return Either.right(componentsUtils.getResponseFormat(ActionStatus.CAPABILITY_NOT_FOUND, storedComponent.getUniqueId()));
         }
         CapabilityDefinition capabilityDefinitionToDelete = definitionOptional.get();
-
-        capabilitiesListStoredInComponent = getCapabilityStoredInComponentByType(capabilityDefinitionToUpdate.getType(),
-                storedComponentCapabilities);
-        Either<List<CapabilityDefinition>, StorageOperationStatus> deleteCapabilityEither
-                = deleteCapability(storedComponent, storedComponentCapabilities, capabilityDefinitionToDelete);
+        capabilitiesListStoredInComponent = getCapabilityStoredInComponentByType(capabilityDefinitionToUpdate.getType(), storedComponentCapabilities);
+        Either<List<CapabilityDefinition>, StorageOperationStatus> deleteCapabilityEither = deleteCapability(storedComponent,
+            storedComponentCapabilities, capabilityDefinitionToDelete);
         if (deleteCapabilityEither.isRight()) {
             janusGraphDao.rollback();
             return Either.right(componentsUtils.getResponseFormat(deleteCapabilityEither.right().value()));
         }
         StorageOperationStatus deleteStorageOperationStatus = capabilitiesOperation
-                .deleteCapabilityProperties(storedComponent, buildCapPropKey(capabilityDefinitionToDelete));
+            .deleteCapabilityProperties(storedComponent, buildCapPropKey(capabilityDefinitionToDelete));
         if (deleteStorageOperationStatus != StorageOperationStatus.OK) {
             janusGraphDao.rollback();
             return Either.right(componentsUtils.getResponseFormat(deleteStorageOperationStatus));
         }
         capabilitiesToReturn.add(initiateNewCapability(storedComponent, capabilityDefinitionToUpdate));
-
         capabilitiesDefsToCreateOrUpdate.addAll(capabilitiesToReturn);
         capabilitiesDefsToCreateOrUpdate.addAll(capabilitiesListStoredInComponent);
         return Either.left(capabilitiesDefsToCreateOrUpdate);
     }
 
     private Either<List<CapabilityDefinition>, ResponseFormat> handleCapabilityTypeUpdateWhenNewTypeNotExist(
-            List<CapabilityDefinition> capabilityDefinitions,
-            Component storedComponent,
-            Map<String, List<CapabilityDefinition>> storedComponentCapabilities) {
+        List<CapabilityDefinition> capabilityDefinitions, Component storedComponent,
+        Map<String, List<CapabilityDefinition>> storedComponentCapabilities) {
         for (CapabilityDefinition capabilityDefinitionToUpdate : capabilityDefinitions) {
-
-            Optional<CapabilityDefinition> definitionOptional = storedComponentCapabilities.values().stream()
-                    .flatMap(Collection::stream).filter(capabilityDefinition -> capabilityDefinition.getUniqueId()
-                            .equals(capabilityDefinitionToUpdate.getUniqueId())).findAny();
+            Optional<CapabilityDefinition> definitionOptional = storedComponentCapabilities.values().stream().flatMap(Collection::stream)
+                .filter(capabilityDefinition -> capabilityDefinition.getUniqueId().equals(capabilityDefinitionToUpdate.getUniqueId())).findAny();
             if (!definitionOptional.isPresent()) {
-                return Either.right(componentsUtils.getResponseFormat(ActionStatus
-                        .CAPABILITY_NOT_FOUND, storedComponent.getUniqueId()));
+                return Either.right(componentsUtils.getResponseFormat(ActionStatus.CAPABILITY_NOT_FOUND, storedComponent.getUniqueId()));
             }
             CapabilityDefinition capabilityDefinitionToDelete = definitionOptional.get();
-            Boolean isCapabilityUsedInServiceComposition = isCapabilityUsedInServiceComposition(capabilityDefinitionToDelete,
-                    storedComponent);
+            Boolean isCapabilityUsedInServiceComposition = isCapabilityUsedInServiceComposition(capabilityDefinitionToDelete, storedComponent);
             if (isCapabilityUsedInServiceComposition) {
-                LOGGER.error("Capability {} can't be edited, since it is used in service composition",
-                        capabilityDefinitionToDelete.getUniqueId());
-                return Either.right(componentsUtils.getResponseFormat(
-                        ActionStatus.CAPABILITY_UPDATE_NOT_ALLOWED_USED_IN_COMPOSITION,
-                        capabilityDefinitionToDelete.getName()));
+                LOGGER.error("Capability {} can't be edited, since it is used in service composition", capabilityDefinitionToDelete.getUniqueId());
+                return Either.right(componentsUtils
+                    .getResponseFormat(ActionStatus.CAPABILITY_UPDATE_NOT_ALLOWED_USED_IN_COMPOSITION, capabilityDefinitionToDelete.getName()));
             }
-            Either<List<CapabilityDefinition>, StorageOperationStatus> deleteCapabilityEither
-                    = deleteCapability(storedComponent, storedComponentCapabilities, capabilityDefinitionToDelete);
+            Either<List<CapabilityDefinition>, StorageOperationStatus> deleteCapabilityEither = deleteCapability(storedComponent,
+                storedComponentCapabilities, capabilityDefinitionToDelete);
             if (deleteCapabilityEither.isRight()) {
                 janusGraphDao.rollback();
                 return Either.right(componentsUtils.getResponseFormat(deleteCapabilityEither.right().value()));
             }
             StorageOperationStatus deleteStorageOperationStatus = capabilitiesOperation
-                    .deleteCapabilityProperties(storedComponent, buildCapPropKey(capabilityDefinitionToDelete));
+                .deleteCapabilityProperties(storedComponent, buildCapPropKey(capabilityDefinitionToDelete));
             if (deleteStorageOperationStatus != StorageOperationStatus.OK) {
                 janusGraphDao.rollback();
                 return Either.right(componentsUtils.getResponseFormat(deleteStorageOperationStatus));
@@ -370,22 +334,19 @@ public class CapabilitiesBusinessLogic extends BaseBusinessLogic {
         return null;
     }
 
-    public Either<CapabilityDefinition, ResponseFormat> getCapability(String componentId, String capabilityToGet,
-                                                                      User user, boolean lock) {
+    public Either<CapabilityDefinition, ResponseFormat> getCapability(String componentId, String capabilityToGet, User user, boolean lock) {
         validateUserExists(user.getUserId());
         Either<Component, ResponseFormat> componentEither = getComponentDetails(componentId);
         if (componentEither.isRight()) {
             return Either.right(componentEither.right().value());
         }
         Component storedComponent = componentEither.left().value();
-
         Either<Boolean, ResponseFormat> lockResult = lockComponentResult(lock, storedComponent, GET_CAPABILITIES);
         if (lockResult.isRight()) {
             return Either.right(lockResult.right().value());
         }
         try {
-            Either<CapabilityDefinition, ResponseFormat> getCapabilityDefinitionEither =
-                    getCapabilityDefinition(capabilityToGet, storedComponent);
+            Either<CapabilityDefinition, ResponseFormat> getCapabilityDefinitionEither = getCapabilityDefinition(capabilityToGet, storedComponent);
             if (getCapabilityDefinitionEither.isRight()) {
                 return Either.right(getCapabilityDefinitionEither.right().value());
             }
@@ -395,42 +356,36 @@ public class CapabilitiesBusinessLogic extends BaseBusinessLogic {
             return Either.right(componentsUtils.getResponseFormat(ActionStatus.CAPABILITY_NOT_FOUND, componentId));
         } finally {
             if (lockResult.isLeft() && lockResult.left().value()) {
-                graphLockOperation.unlockComponent(storedComponent.getUniqueId(),
-                        NodeTypeEnum.getByNameIgnoreCase(storedComponent.getComponentType().getValue()));
+                graphLockOperation
+                    .unlockComponent(storedComponent.getUniqueId(), NodeTypeEnum.getByNameIgnoreCase(storedComponent.getComponentType().getValue()));
             }
         }
     }
 
-    private Either<CapabilityDefinition, ResponseFormat> getCapabilityDefinition(String capabilityIdToGet,
-                                                                                 Component storedComponent) {
-        List<CapabilityDefinition> capabilityDefinitions = storedComponent.getCapabilities().values()
-                .stream().flatMap(Collection::stream).collect(Collectors.toList());
+    private Either<CapabilityDefinition, ResponseFormat> getCapabilityDefinition(String capabilityIdToGet, Component storedComponent) {
+        List<CapabilityDefinition> capabilityDefinitions = storedComponent.getCapabilities().values().stream().flatMap(Collection::stream)
+            .collect(Collectors.toList());
         if (capabilityDefinitions.isEmpty()) {
-            return Either.right(componentsUtils.getResponseFormat(ActionStatus.CAPABILITY_NOT_FOUND,
-                    storedComponent.getUniqueId()));
+            return Either.right(componentsUtils.getResponseFormat(ActionStatus.CAPABILITY_NOT_FOUND, storedComponent.getUniqueId()));
         }
         CapabilityDefinition capabilityDefinitionToReturn;
         Optional<CapabilityDefinition> capabilityDefinitionOptional = capabilityDefinitions.stream()
-                .filter(capabilityDefinition -> capabilityDefinition.getUniqueId().equals(capabilityIdToGet)).findAny();
+            .filter(capabilityDefinition -> capabilityDefinition.getUniqueId().equals(capabilityIdToGet)).findAny();
         if (capabilityDefinitionOptional.isPresent()) {
             capabilityDefinitionToReturn = capabilityDefinitionOptional.get();
         } else {
-            return Either.right(componentsUtils.getResponseFormat(ActionStatus.CAPABILITY_NOT_FOUND,
-                    storedComponent.getUniqueId()));
+            return Either.right(componentsUtils.getResponseFormat(ActionStatus.CAPABILITY_NOT_FOUND, storedComponent.getUniqueId()));
         }
-
         return Either.left(capabilityDefinitionToReturn);
     }
 
-    public Either<CapabilityDefinition, ResponseFormat> deleteCapability(String componentId, String capabilityIdToDelete,
-                                                                         User user, boolean lock) {
+    public Either<CapabilityDefinition, ResponseFormat> deleteCapability(String componentId, String capabilityIdToDelete, User user, boolean lock) {
         validateUserExists(user.getUserId());
         Either<Component, ResponseFormat> componentEither = getComponentDetails(componentId);
         if (componentEither.isRight()) {
             return Either.right(componentEither.right().value());
         }
         Component storedComponent = componentEither.left().value();
-
         Either<Boolean, ResponseFormat> lockResult = lockComponentResult(lock, storedComponent, DELETE_CAPABILITIES);
         if (lockResult.isRight()) {
             return Either.right(lockResult.right().value());
@@ -443,85 +398,74 @@ public class CapabilitiesBusinessLogic extends BaseBusinessLogic {
             return Either.right(componentsUtils.getResponseFormat(ActionStatus.CAPABILITY_NOT_FOUND));
         } finally {
             if (lockResult.isLeft() && lockResult.left().value()) {
-                graphLockOperation.unlockComponent(storedComponent.getUniqueId(),
-                        NodeTypeEnum.getByNameIgnoreCase(storedComponent.getComponentType().getValue()));
+                graphLockOperation
+                    .unlockComponent(storedComponent.getUniqueId(), NodeTypeEnum.getByNameIgnoreCase(storedComponent.getComponentType().getValue()));
             }
         }
     }
 
-    private Either<CapabilityDefinition, ResponseFormat> deleteCapability(String capabilityIdToDelete,
-                                                                          Component storedComponent) {
+    private Either<CapabilityDefinition, ResponseFormat> deleteCapability(String capabilityIdToDelete, Component storedComponent) {
         Map<String, List<CapabilityDefinition>> storedComponentCapabilities = storedComponent.getCapabilities();
         if (storedComponentCapabilities.isEmpty()) {
             return Either.right(componentsUtils.getResponseFormat(ActionStatus.CAPABILITY_NOT_FOUND, storedComponent.getUniqueId()));
         }
-        Either<CapabilityDefinition, ResponseFormat> capabilityDefinitionToDeleteEither =
-                getAndValidateCapabilitiesToDelete(storedComponent, storedComponentCapabilities, capabilityIdToDelete);
-
-        if(capabilityDefinitionToDeleteEither.isRight()) {
+        Either<CapabilityDefinition, ResponseFormat> capabilityDefinitionToDeleteEither = getAndValidateCapabilitiesToDelete(storedComponent,
+            storedComponentCapabilities, capabilityIdToDelete);
+        if (capabilityDefinitionToDeleteEither.isRight()) {
             return Either.right(capabilityDefinitionToDeleteEither.right().value());
         }
-        Either<List<CapabilityDefinition>, StorageOperationStatus> result = deleteCapability(storedComponent,
-                storedComponentCapabilities, capabilityDefinitionToDeleteEither.left().value());
+        Either<List<CapabilityDefinition>, StorageOperationStatus> result = deleteCapability(storedComponent, storedComponentCapabilities,
+            capabilityDefinitionToDeleteEither.left().value());
         if (result.isRight()) {
             janusGraphDao.rollback();
-            LOGGER.error("Failed to delete capability  from component {}. Response is {}", storedComponent.getName(),
-                    result.right().value());
-            return Either.right(componentsUtils.getResponseFormat(
-                    componentsUtils.convertFromStorageResponse(result.right().value(),
-                            storedComponent.getComponentType())));
+            LOGGER.error("Failed to delete capability  from component {}. Response is {}", storedComponent.getName(), result.right().value());
+            return Either.right(componentsUtils
+                .getResponseFormat(componentsUtils.convertFromStorageResponse(result.right().value(), storedComponent.getComponentType())));
         }
         janusGraphDao.commit();
-
         return Either.left(capabilityDefinitionToDeleteEither.left().value());
     }
 
     private Either<CapabilityDefinition, ResponseFormat> getAndValidateCapabilitiesToDelete(Component storedComponent,
                                                                                             Map<String, List<CapabilityDefinition>> storedComponentCapabilities,
                                                                                             String capabilityIdToDelete) {
-
-        Optional<CapabilityDefinition> definitionOptional = storedComponentCapabilities.values().stream()
-                .flatMap(Collection::stream).filter(capabilityDefinition -> capabilityDefinition.getUniqueId()
-                        .equals(capabilityIdToDelete)).findAny();
+        Optional<CapabilityDefinition> definitionOptional = storedComponentCapabilities.values().stream().flatMap(Collection::stream)
+            .filter(capabilityDefinition -> capabilityDefinition.getUniqueId().equals(capabilityIdToDelete)).findAny();
         if (!definitionOptional.isPresent()) {
             return Either.right(componentsUtils.getResponseFormat(ActionStatus.CAPABILITY_NOT_FOUND, storedComponent.getUniqueId()));
         }
         CapabilityDefinition capabilityDefinitionToDelete = definitionOptional.get();
-        Boolean isCapabilityUsedInServiceComposition
-                = isCapabilityUsedInServiceComposition(capabilityDefinitionToDelete, storedComponent);
+        Boolean isCapabilityUsedInServiceComposition = isCapabilityUsedInServiceComposition(capabilityDefinitionToDelete, storedComponent);
         if (isCapabilityUsedInServiceComposition) {
-            LOGGER.error("Capability {} can't be deleted, since it is used in service composition",
-                    capabilityDefinitionToDelete.getUniqueId());
-            return Either.right(componentsUtils.getResponseFormat(ActionStatus
-                    .CAPABILITY_DELETION_NOT_ALLOWED_USED_IN_COMPOSITION, capabilityDefinitionToDelete.getName()));
+            LOGGER.error("Capability {} can't be deleted, since it is used in service composition", capabilityDefinitionToDelete.getUniqueId());
+            return Either.right(componentsUtils
+                .getResponseFormat(ActionStatus.CAPABILITY_DELETION_NOT_ALLOWED_USED_IN_COMPOSITION, capabilityDefinitionToDelete.getName()));
         }
-
         return Either.left(capabilityDefinitionToDelete);
     }
+
     private Either<List<CapabilityDefinition>, StorageOperationStatus> deleteCapability(Component storedComponent,
                                                                                         Map<String, List<CapabilityDefinition>> storedComponentCapabilities,
                                                                                         CapabilityDefinition capabilityDefinitionToDelete) {
-
-        List<CapabilityDefinition> capabilitiesListStoredInComponent =
-                getCapabilityStoredInComponentByType(capabilityDefinitionToDelete.getType(), storedComponentCapabilities);
-        capabilitiesListStoredInComponent.removeIf(capabilityDefinition ->
-                capabilityDefinition.getUniqueId().equals(capabilityDefinitionToDelete.getUniqueId()));
+        List<CapabilityDefinition> capabilitiesListStoredInComponent = getCapabilityStoredInComponentByType(capabilityDefinitionToDelete.getType(),
+            storedComponentCapabilities);
+        capabilitiesListStoredInComponent
+            .removeIf(capabilityDefinition -> capabilityDefinition.getUniqueId().equals(capabilityDefinitionToDelete.getUniqueId()));
         Either<List<CapabilityDefinition>, StorageOperationStatus> result;
         if (capabilitiesListStoredInComponent.isEmpty()) {
-            StorageOperationStatus operationStatus = capabilitiesOperation.deleteCapabilities(storedComponent,
-                    capabilityDefinitionToDelete.getType());
+            StorageOperationStatus operationStatus = capabilitiesOperation
+                .deleteCapabilities(storedComponent, capabilityDefinitionToDelete.getType());
             if (StorageOperationStatus.OK.equals(operationStatus)) {
                 result = Either.left(Collections.singletonList(capabilityDefinitionToDelete));
             } else {
                 result = Either.right(operationStatus);
             }
         } else {
-            result = capabilitiesOperation.updateCapabilities(storedComponent.getUniqueId(),
-                    capabilitiesListStoredInComponent);
+            result = capabilitiesOperation.updateCapabilities(storedComponent.getUniqueId(), capabilitiesListStoredInComponent);
         }
         if (result.isLeft()) {
             StorageOperationStatus deleteStorageOperationStatus = capabilitiesOperation
-                    .deleteCapabilityProperties(storedComponent, buildCapPropKey(capabilityDefinitionToDelete));
+                .deleteCapabilityProperties(storedComponent, buildCapPropKey(capabilityDefinitionToDelete));
             if (deleteStorageOperationStatus != StorageOperationStatus.OK) {
                 result = Either.right(deleteStorageOperationStatus);
             }
@@ -529,17 +473,14 @@ public class CapabilitiesBusinessLogic extends BaseBusinessLogic {
         return result;
     }
 
-
     private Either<Component, ResponseFormat> getComponentDetails(String componentId) {
         ComponentParametersView filter = new ComponentParametersView(true);
         filter.setIgnoreCapabilities(false);
         filter.setIgnoreCapabiltyProperties(false);
-        Either<Component, StorageOperationStatus> componentStorageOperationStatusEither =
-                toscaOperationFacade.getToscaElement(componentId, filter);
+        Either<Component, StorageOperationStatus> componentStorageOperationStatusEither = toscaOperationFacade.getToscaElement(componentId, filter);
         if (componentStorageOperationStatusEither.isRight()) {
             StorageOperationStatus errorStatus = componentStorageOperationStatusEither.right().value();
-            LOGGER.error("Failed to fetch component information by component id {}, Response is {}",
-                    componentId, errorStatus);
+            LOGGER.error("Failed to fetch component information by component id {}, Response is {}", componentId, errorStatus);
             return Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(errorStatus)));
         }
         return Either.left(componentStorageOperationStatusEither.left().value());
@@ -549,7 +490,7 @@ public class CapabilitiesBusinessLogic extends BaseBusinessLogic {
         if (lock) {
             try {
                 lockComponent(component.getUniqueId(), component, action);
-            } catch (ComponentException e){
+            } catch (ComponentException e) {
                 LOGGER.debug(FAILED_TO_LOCK_COMPONENT_RESPONSE_IS, component.getName(), e.getMessage());
                 janusGraphDao.rollback();
                 throw e;
@@ -558,40 +499,41 @@ public class CapabilitiesBusinessLogic extends BaseBusinessLogic {
         return Either.left(true);
     }
 
-    private List<CapabilityDefinition> getCapabilityStoredInComponentByType(String capabilityType, Map<String,
-            List<CapabilityDefinition>> capabilities) {
+    private List<CapabilityDefinition> getCapabilityStoredInComponentByType(String capabilityType,
+                                                                            Map<String, List<CapabilityDefinition>> capabilities) {
         Optional<Map.Entry<String, List<CapabilityDefinition>>> entryOptional = capabilities.entrySet().stream()
-                .filter(map -> map.getKey().equals(capabilityType)).findFirst();
+            .filter(map -> map.getKey().equals(capabilityType)).findFirst();
         return entryOptional.map(Map.Entry::getValue).orElse(Collections.emptyList());
     }
 
     private CapabilityDefinition initiateNewCapability(Component component, CapabilityDefinition capabilityDefinition) {
-        if (StringUtils.isEmpty(capabilityDefinition.getUniqueId()))
+        if (StringUtils.isEmpty(capabilityDefinition.getUniqueId())) {
             capabilityDefinition.setUniqueId(UUID.randomUUID().toString());
-        if (StringUtils.isEmpty(capabilityDefinition.getOwnerId()))
+        }
+        if (StringUtils.isEmpty(capabilityDefinition.getOwnerId())) {
             capabilityDefinition.setOwnerId(component.getUniqueId());
-        if (StringUtils.isEmpty(capabilityDefinition.getOwnerName()))
+        }
+        if (StringUtils.isEmpty(capabilityDefinition.getOwnerName())) {
             capabilityDefinition.setOwnerName(component.getName());
+        }
         capabilityDefinition.setLeftOccurrences(capabilityDefinition.getMaxOccurrences());
         List<ComponentInstanceProperty> capabilityProperties = capabilityDefinition.getProperties();
         initiateProperties(capabilityDefinition, capabilityProperties);
         return capabilityDefinition;
     }
 
-    private void initiateProperties(CapabilityDefinition capabilityDefinition,
-                                    List<ComponentInstanceProperty> capabilityProperties) {
+    private void initiateProperties(CapabilityDefinition capabilityDefinition, List<ComponentInstanceProperty> capabilityProperties) {
         if (CollectionUtils.isNotEmpty(capabilityProperties)) {
-            capabilityProperties.stream().filter(prop -> prop != null && StringUtils.isEmpty(prop.getUniqueId()))
-                    .forEach(propDef -> {
-                        String uid = UniqueIdBuilder.buildRequirementUid(capabilityDefinition.getUniqueId(), propDef.getName());
-                        propDef.setUniqueId(uid);
-                        propDef.setParentUniqueId(capabilityDefinition.getUniqueId());
-                    });
+            capabilityProperties.stream().filter(prop -> prop != null && StringUtils.isEmpty(prop.getUniqueId())).forEach(propDef -> {
+                String uid = UniqueIdBuilder.buildRequirementUid(capabilityDefinition.getUniqueId(), propDef.getName());
+                propDef.setUniqueId(uid);
+                propDef.setParentUniqueId(capabilityDefinition.getUniqueId());
+            });
         }
     }
 
-    private CapabilityDefinition updateCapability(CapabilityDefinition storedCapability,
-                                                  CapabilityDefinition capabilityToUpdate, Component component) {
+    private CapabilityDefinition updateCapability(CapabilityDefinition storedCapability, CapabilityDefinition capabilityToUpdate,
+                                                  Component component) {
         storedCapability.setName(capabilityToUpdate.getName());
         storedCapability.setDescription(capabilityToUpdate.getDescription());
         storedCapability.setType(capabilityToUpdate.getType());
@@ -605,48 +547,44 @@ public class CapabilitiesBusinessLogic extends BaseBusinessLogic {
         }
         if (!storedCapability.getName().equals(capabilityToUpdate.getName())) {
             StorageOperationStatus deleteStorageOperationStatus = capabilitiesOperation
-                    .deleteCapabilityProperties(component, buildCapPropKey(storedCapability));
+                .deleteCapabilityProperties(component, buildCapPropKey(storedCapability));
             if (deleteStorageOperationStatus != StorageOperationStatus.OK) {
                 janusGraphDao.rollback();
             }
         }
-
         return storedCapability;
     }
 
-
     private Boolean isCapabilityUsedInServiceComposition(CapabilityDefinition capabilityDefinition, Component component) {
-        Either<List<Component>, StorageOperationStatus> componentList = toscaOperationFacade
-                .getParentComponents(component.getUniqueId());
+        Either<List<Component>, StorageOperationStatus> componentList = toscaOperationFacade.getParentComponents(component.getUniqueId());
         if (componentList.isRight()) {
             return Boolean.FALSE;
         }
-        return componentList.left().value().stream().flatMap(parentComponent -> parentComponent
-                .getComponentInstancesRelations().stream()).flatMap(requirementCapabilityRelDef ->
-                requirementCapabilityRelDef.getRelationships().stream()).anyMatch(capabilityRequirementRelationship ->
-                capabilityRequirementRelationship.getRelation().getCapabilityUid().equals(capabilityDefinition.getUniqueId()));
+        return componentList.left().value().stream().flatMap(parentComponent -> parentComponent.getComponentInstancesRelations().stream())
+            .flatMap(requirementCapabilityRelDef -> requirementCapabilityRelDef.getRelationships().stream()).anyMatch(
+                capabilityRequirementRelationship -> capabilityRequirementRelationship.getRelation().getCapabilityUid()
+                    .equals(capabilityDefinition.getUniqueId()));
     }
 
     public Either<Map<String, CapabilityTypeDefinition>, ResponseFormat> getAllCapabilityTypes() {
-        Either<Map<String, CapabilityTypeDefinition>, JanusGraphOperationStatus> capabilityTypeCacheAll =
-                capabilityTypeOperation.getAllCapabilityTypes();
+        Either<Map<String, CapabilityTypeDefinition>, JanusGraphOperationStatus> capabilityTypeCacheAll = capabilityTypeOperation
+            .getAllCapabilityTypes();
         if (capabilityTypeCacheAll.isRight()) {
             JanusGraphOperationStatus operationStatus = capabilityTypeCacheAll.right().value();
             if (JanusGraphOperationStatus.NOT_FOUND == operationStatus) {
-                BeEcompErrorManager.getInstance().logInternalDataError("FetchCapabilityTypes",
-                        "Capability types are not loaded", BeEcompErrorManager.ErrorSeverity.ERROR);
+                BeEcompErrorManager.getInstance()
+                    .logInternalDataError("FetchCapabilityTypes", "Capability types are not loaded", BeEcompErrorManager.ErrorSeverity.ERROR);
                 return Either.right(componentsUtils.getResponseFormat(ActionStatus.DATA_TYPE_CANNOT_BE_EMPTY));
             } else {
-                BeEcompErrorManager.getInstance().logInternalFlowError("FetchCapabilityTypes",
-                        "Failed to fetch capability types", BeEcompErrorManager.ErrorSeverity.ERROR);
+                BeEcompErrorManager.getInstance()
+                    .logInternalFlowError("FetchCapabilityTypes", "Failed to fetch capability types", BeEcompErrorManager.ErrorSeverity.ERROR);
                 return Either.right(componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR));
             }
         }
         return Either.left(capabilityTypeCacheAll.left().value());
     }
 
-    private Map<String, MapPropertiesDataDefinition> getCapabilitiesPropertiesDataDefinitionMap(
-            List<CapabilityDefinition> capabilityDefinitions) {
+    private Map<String, MapPropertiesDataDefinition> getCapabilitiesPropertiesDataDefinitionMap(List<CapabilityDefinition> capabilityDefinitions) {
         CapabilityDefinition capabilityDefinitionToAddOrUpdateCapProp = capabilityDefinitions.get(0);
         List<ComponentInstanceProperty> componentInstanceProperties = null;
         if (Objects.nonNull(capabilityDefinitionToAddOrUpdateCapProp)) {
@@ -664,7 +602,7 @@ public class CapabilitiesBusinessLogic extends BaseBusinessLogic {
     }
 
     private String buildCapPropKey(CapabilityDefinition capabilityDefinitionToAddOrUpdateCapProp) {
-        return capabilityDefinitionToAddOrUpdateCapProp.getType() + ModelConverter.CAP_PROP_DELIM +
-                capabilityDefinitionToAddOrUpdateCapProp.getName();
+        return capabilityDefinitionToAddOrUpdateCapProp.getType() + ModelConverter.CAP_PROP_DELIM + capabilityDefinitionToAddOrUpdateCapProp
+            .getName();
     }
 }
index ebe79f5..df7650f 100644 (file)
@@ -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.
  * limitations under the License.
  * ============LICENSE_END=========================================================
  */
-
 package org.openecomp.sdc.be.components.impl;
 
 import fj.data.Either;
+import java.util.List;
+import java.util.Map;
 import org.apache.commons.lang3.tuple.ImmutablePair;
 import org.openecomp.sdc.be.dao.api.ActionStatus;
 import org.openecomp.sdc.be.model.CapabilityTypeDefinition;
@@ -33,9 +34,6 @@ import org.openecomp.sdc.exception.ResponseFormat;
 import org.springframework.beans.factory.annotation.Autowired;
 import org.springframework.stereotype.Component;
 
-import java.util.List;
-import java.util.Map;
-
 @Component("capabilityTypeImportManager")
 public class CapabilityTypeImportManager {
 
@@ -50,51 +48,44 @@ public class CapabilityTypeImportManager {
     }
 
     public Either<List<ImmutablePair<CapabilityTypeDefinition, Boolean>>, ResponseFormat> createCapabilityTypes(String capabilityTypesYml) {
-        return  commonImportManager.createElementTypes(capabilityTypesYml, this::createCapabilityTypesFromYml, this::upsertCapabilityTypesByDao, CommonImportManager.ElementTypeEnum.CAPABILITY_TYPE);
-
+        return commonImportManager.createElementTypes(capabilityTypesYml, this::createCapabilityTypesFromYml, this::upsertCapabilityTypesByDao,
+            CommonImportManager.ElementTypeEnum.CAPABILITY_TYPE);
     }
 
     private Either<List<CapabilityTypeDefinition>, ActionStatus> createCapabilityTypesFromYml(String capabilityTypesYml) {
         return commonImportManager.createElementTypesFromYml(capabilityTypesYml, this::createCapabilityType);
-
     }
 
-    private Either<List<ImmutablePair<CapabilityTypeDefinition, Boolean>>, ResponseFormat> upsertCapabilityTypesByDao(List<CapabilityTypeDefinition> capabilityTypesToCreate) {
-        return commonImportManager.createElementTypesByDao(capabilityTypesToCreate,
-                capabilityType -> Either.left(ActionStatus.OK),
-                capabilityType -> new ImmutablePair<>(CommonImportManager.ElementTypeEnum.CAPABILITY_TYPE, capabilityType.getType()),
-                capabilityTypeOperation::getCapabilityType,
-                capabilityTypeOperation::addCapabilityType,
-                this::updateCapabilityType);
+    private Either<List<ImmutablePair<CapabilityTypeDefinition, Boolean>>, ResponseFormat> upsertCapabilityTypesByDao(
+        List<CapabilityTypeDefinition> capabilityTypesToCreate) {
+        return commonImportManager.createElementTypesByDao(capabilityTypesToCreate, capabilityType -> Either.left(ActionStatus.OK),
+            capabilityType -> new ImmutablePair<>(CommonImportManager.ElementTypeEnum.CAPABILITY_TYPE, capabilityType.getType()),
+            capabilityTypeOperation::getCapabilityType, capabilityTypeOperation::addCapabilityType, this::updateCapabilityType);
     }
-    
-    private Either<CapabilityTypeDefinition, StorageOperationStatus> updateCapabilityType(CapabilityTypeDefinition newCapabilityType, CapabilityTypeDefinition oldCapabilityType) {
+
+    private Either<CapabilityTypeDefinition, StorageOperationStatus> updateCapabilityType(CapabilityTypeDefinition newCapabilityType,
+                                                                                          CapabilityTypeDefinition oldCapabilityType) {
         Either<CapabilityTypeDefinition, StorageOperationStatus> validationRes = capabilityTypeOperation.validateUpdateProperties(newCapabilityType);
         if (validationRes.isRight()) {
-            log.error("#updateCapabilityType - One or all properties of capability type {} not valid. status is {}", newCapabilityType, validationRes.right().value());
+            log.error("#updateCapabilityType - One or all properties of capability type {} not valid. status is {}", newCapabilityType,
+                validationRes.right().value());
             return validationRes;
         }
-        
         if (TypeCompareUtils.isCapabilityTypesEquals(newCapabilityType, oldCapabilityType)) {
             return TypeCompareUtils.typeAlreadyExists();
         }
-        
         return capabilityTypeOperation.updateCapabilityType(newCapabilityType, oldCapabilityType);
     }
 
     private CapabilityTypeDefinition createCapabilityType(String capabilityTypeName, Map<String, Object> toscaJson) {
         CapabilityTypeDefinition capabilityType = new CapabilityTypeDefinition();
-
         capabilityType.setType(capabilityTypeName);
-
         // Description
         commonImportManager.setField(toscaJson, TypeUtils.ToscaTagNamesEnum.DESCRIPTION.getElementName(), capabilityType::setDescription);
         // Derived From
         commonImportManager.setField(toscaJson, TypeUtils.ToscaTagNamesEnum.DERIVED_FROM.getElementName(), capabilityType::setDerivedFrom);
         // Properties
         commonImportManager.setPropertiesMap(toscaJson, capabilityType::setProperties);
-
         return capabilityType;
     }
-
 }
index fb85ab5..6ebdb9b 100644 (file)
@@ -24,15 +24,6 @@ package org.openecomp.sdc.be.components.impl;
 import com.datastax.driver.core.KeyspaceMetadata;
 import com.datastax.driver.core.Metadata;
 import com.datastax.driver.core.Session;
-import org.openecomp.sdc.be.config.ConfigurationManager;
-import org.openecomp.sdc.be.dao.cassandra.schema.SdcSchemaUtils;
-import org.openecomp.sdc.be.dao.cassandra.schema.Table;
-import org.openecomp.sdc.common.log.wrappers.Logger;
-import org.openecomp.sdc.common.util.GeneralUtility;
-import org.springframework.stereotype.Component;
-
-import javax.annotation.PostConstruct;
-import javax.annotation.PreDestroy;
 import java.io.FileInputStream;
 import java.io.InputStream;
 import java.util.ArrayList;
@@ -42,40 +33,38 @@ import java.util.List;
 import java.util.Map;
 import java.util.Properties;
 import java.util.Set;
+import javax.annotation.PostConstruct;
+import javax.annotation.PreDestroy;
+import org.openecomp.sdc.be.config.ConfigurationManager;
+import org.openecomp.sdc.be.dao.cassandra.schema.SdcSchemaUtils;
+import org.openecomp.sdc.be.dao.cassandra.schema.Table;
+import org.openecomp.sdc.common.log.wrappers.Logger;
+import org.openecomp.sdc.common.util.GeneralUtility;
+import org.springframework.stereotype.Component;
 
 @Component("cassandra-health-check")
 public class CassandraHealthCheck {
 
     private static final Logger log = Logger.getLogger(CassandraHealthCheck.class);
-
-    private String localDataCenterName;
-
     private final Set<String> sdcKeyspaces = new HashSet<>();
-
+    private String localDataCenterName;
     private int HC_FormulaNumber;
-
     private SdcSchemaUtils sdcSchemaUtils;
 
     @PostConstruct
     private void init() {
-
         //Initialize local data center name - this field must be filled by DevOps
         localDataCenterName = ConfigurationManager.getConfigurationManager().getConfiguration().getCassandraConfig().getLocalDataCenter();
-
-        if (GeneralUtility.isEmptyString(localDataCenterName))  {
+        if (GeneralUtility.isEmptyString(localDataCenterName)) {
             log.error("localDataCenter Name in configuration.yaml is missing.");
             return;
         }
-
         //Collect all SDC keyspaces
         for (Table table : Table.values()) {
             sdcKeyspaces.add(table.getTableDescription().getKeyspace());
         }
-
-        String janusGraphCfgFile = ConfigurationManager.getConfigurationManager()
-            .getConfiguration().getJanusGraphCfgFile();
+        String janusGraphCfgFile = ConfigurationManager.getConfigurationManager().getConfiguration().getJanusGraphCfgFile();
         Properties prop = new Properties();
-
         try (final InputStream janusGraphProp = new FileInputStream(janusGraphCfgFile)) {
             //load a properties file
             prop.load(janusGraphProp);
@@ -87,34 +76,25 @@ public class CassandraHealthCheck {
         } catch (Exception e) {
             log.error("Failed to open janusGraph.properties file , url is : {}", janusGraphCfgFile, e);
         }
-
         log.info("All sdc keyspaces are : {}", sdcKeyspaces);
         sdcSchemaUtils = new SdcSchemaUtils();
         //Calculate the Formula of Health Check
         try {
-
             log.info("creating cluster for Cassandra Health Check.");
             //Create cluster from nodes in cassandra configuration
-
             Metadata metadata = sdcSchemaUtils.getMetadata();
-
             if (metadata == null) {
                 log.error("Failure get cassandra metadata.");
                 return;
             }
-
             log.info("Cluster Metadata: {}", metadata);
             List<KeyspaceMetadata> keyspaces = metadata.getKeyspaces();
             List<Integer> replactionFactorList = new ArrayList<>();
-
             //Collect the keyspaces Replication Factor of current localDataCenter
             for (KeyspaceMetadata keyspace : keyspaces) {
-
-                if (sdcKeyspaces.contains(keyspace.getName()))  {
-
-                    log.info("keyspace : {} , replication: {}",  keyspace.getName(), keyspace.getReplication());
+                if (sdcKeyspaces.contains(keyspace.getName())) {
+                    log.info("keyspace : {} , replication: {}", keyspace.getName(), keyspace.getReplication());
                     Map<String, String> replicationOptions = keyspace.getReplication();
-
                     //In 1 site with one data center
                     if (replicationOptions.containsKey("replication_factor")) {
                         replactionFactorList.add(Integer.parseInt(replicationOptions.get("replication_factor")));
@@ -125,61 +105,43 @@ public class CassandraHealthCheck {
                     }
                 }
             }
-
             if (replactionFactorList.isEmpty()) {
                 log.error("Replication factor NOT found in all keyspaces");
                 return;
             }
-
             int maxReplicationFactor = Collections.max(replactionFactorList);
             log.info("maxReplication Factor is: {}", maxReplicationFactor);
-
             int localQuorum = maxReplicationFactor / 2 + 1;
             log.info("localQuorum is: {}", localQuorum);
-
             HC_FormulaNumber = maxReplicationFactor - localQuorum;
-
             log.info("Health Check formula : Replication Factor â€“ Local_Quorum = {}", HC_FormulaNumber);
-
-
         } catch (Exception e) {
             log.error("create cassandra cluster failed with exception.", e);
         }
-
     }
 
     public boolean getCassandraStatus() {
-
         if (GeneralUtility.isEmptyString(localDataCenterName)) {
             log.error("localDataCenter Name in configuration.yaml is missing.");
             return false;
         }
-
         try (final Session session = sdcSchemaUtils.connect()) {
             log.info("creating cluster for Cassandra for monitoring.");
-
             log.info("The cassandra session is {}", session);
             if (session == null) {
                 log.error("Failed to connect to cassandra ");
                 return false;
             }
-
             Metadata metadata = sdcSchemaUtils.getMetadata();
-
             if (metadata == null) {
                 log.error("Failure get cassandra metadata.");
                 return false;
             }
-
             log.info("The number of cassandra nodes is:{}", metadata.getAllHosts().size());
-
             //Count the number of data center nodes that are down
-            Long downHostsNumber = metadata.getAllHosts().stream()
-                .filter(x -> x.getDatacenter().equals(localDataCenterName) && !x.isUp()).count();
-
+            Long downHostsNumber = metadata.getAllHosts().stream().filter(x -> x.getDatacenter().equals(localDataCenterName) && !x.isUp()).count();
             log.info("The cassandra down nodes number is {}", downHostsNumber);
             return HC_FormulaNumber >= downHostsNumber;
-
         } catch (Exception e) {
             log.error("create cassandra cluster failed with exception.", e);
             return false;
@@ -188,7 +150,7 @@ public class CassandraHealthCheck {
 
     @PreDestroy
     public void closeClient() {
-        if (sdcSchemaUtils!= null) {
+        if (sdcSchemaUtils != null) {
             sdcSchemaUtils.closeCluster();
         }
         log.info("** sdcSchemaUtils cluster closed");
index 754420d..1efb4b6 100644 (file)
@@ -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.
  * limitations under the License.
  * ============LICENSE_END=========================================================
  */
-
 package org.openecomp.sdc.be.components.impl;
 
 import fj.data.Either;
+import java.util.ArrayList;
+import java.util.Collections;
+import java.util.HashMap;
+import java.util.Iterator;
+import java.util.List;
+import java.util.Map;
+import java.util.Map.Entry;
 import org.openecomp.sdc.be.dao.api.ActionStatus;
-import org.openecomp.sdc.be.dao.neo4j.GraphPropertiesDictionary;
 import org.openecomp.sdc.be.datamodel.api.CategoryTypeEnum;
 import org.openecomp.sdc.be.datamodel.utils.NodeTypeConvertUtils;
 import org.openecomp.sdc.be.datatypes.category.MetadataKeyDataDefinition;
@@ -41,27 +46,16 @@ import org.openecomp.sdc.exception.ResponseFormat;
 import org.springframework.stereotype.Component;
 import org.yaml.snakeyaml.Yaml;
 
-import java.util.ArrayList;
-import java.util.Collections;
-import java.util.HashMap;
-import java.util.Iterator;
-import java.util.List;
-import java.util.Map;
-import java.util.Map.Entry;
-
 @Component("categoriesImportManager")
 public class CategoriesImportManager {
 
+    private static final Logger log = Logger.getLogger(CategoriesImportManager.class.getName());
     @javax.annotation.Resource
     private IElementOperation elementOperation;
-
     @javax.annotation.Resource
     private ComponentsUtils componentsUtils;
 
-    private static final Logger log = Logger.getLogger(CategoriesImportManager.class.getName());
-
     public Either<Map<String, List<CategoryDefinition>>, ResponseFormat> createCategories(String categoriesTypesYml) {
-
         Map<String, List<CategoryDefinition>> allCategories = createCategoriesFromYml(categoriesTypesYml);
         return createCategoriesByDao(allCategories);
     }
@@ -74,21 +68,21 @@ public class CategoriesImportManager {
             NodeTypeEnum nodeTypeCategory = NodeTypeConvertUtils.getCategoryNodeTypeByComponentParam(componentType, CategoryTypeEnum.CATEGORY);
             NodeTypeEnum nodeTypeSubCategory = NodeTypeConvertUtils.getCategoryNodeTypeByComponentParam(componentType, CategoryTypeEnum.SUBCATEGORY);
             NodeTypeEnum nodeTypeGroup = NodeTypeConvertUtils.getCategoryNodeTypeByComponentParam(componentType, CategoryTypeEnum.GROUPING);
-            log.debug("createCategoriesByDao: creating componentType:{}  nodeTypeCategory:{} nodeTypeSubCategory:{} nodeTypeGroup:{}", componentType, nodeTypeCategory, nodeTypeSubCategory, nodeTypeGroup);
+            log.debug("createCategoriesByDao: creating componentType:{}  nodeTypeCategory:{} nodeTypeSubCategory:{} nodeTypeGroup:{}", componentType,
+                nodeTypeCategory, nodeTypeSubCategory, nodeTypeGroup);
             List<CategoryDefinition> newCategoriesvalue = new ArrayList<>();
             for (CategoryDefinition category : entry.getValue()) {
-
                 Either<CategoryDefinition, ResponseFormat> createdCategoryRes = createCategorieDeo(entry, category, nodeTypeCategory);
                 if (createdCategoryRes.isRight()) {
                     return Either.right(createdCategoryRes.right().value());
                 }
-
                 CategoryDefinition newcategory = createdCategoryRes.left().value();
                 log.debug("createCategoriesByDao: create category was successful {}", newcategory);
                 List<SubCategoryDefinition> newsubcategories = new ArrayList<>();
                 List<SubCategoryDefinition> subcategories = category.getSubcategories();
                 if (subcategories != null) {
-                    boolean createdNewSubCategory = isCreatedNewSubCategory(entry, nodeTypeSubCategory, nodeTypeGroup, category, newcategory, newsubcategories, subcategories);
+                    boolean createdNewSubCategory = isCreatedNewSubCategory(entry, nodeTypeSubCategory, nodeTypeGroup, category, newcategory,
+                        newsubcategories, subcategories);
                     if (!createdNewSubCategory) {
                         return Either.right(createdCategoryRes.right().value());
                     }
@@ -101,9 +95,12 @@ public class CategoriesImportManager {
         return Either.left(result);
     }
 
-    private boolean isCreatedNewSubCategory(Entry<String, List<CategoryDefinition>> entry, NodeTypeEnum nodeTypeSubCategory, NodeTypeEnum nodeTypeGroup, CategoryDefinition category, CategoryDefinition newcategory, List<SubCategoryDefinition> newsubcategories, List<SubCategoryDefinition> subcategories) {
+    private boolean isCreatedNewSubCategory(Entry<String, List<CategoryDefinition>> entry, NodeTypeEnum nodeTypeSubCategory,
+                                            NodeTypeEnum nodeTypeGroup, CategoryDefinition category, CategoryDefinition newcategory,
+                                            List<SubCategoryDefinition> newsubcategories, List<SubCategoryDefinition> subcategories) {
         for (SubCategoryDefinition subcategory : subcategories) {
-            Either<SubCategoryDefinition, ResponseFormat> createdSubCategory = createSubCategorieDeo(entry, newcategory, subcategory, nodeTypeSubCategory);
+            Either<SubCategoryDefinition, ResponseFormat> createdSubCategory = createSubCategorieDeo(entry, newcategory, subcategory,
+                nodeTypeSubCategory);
             if (createdSubCategory.isRight()) {
                 return false;
             }
@@ -112,7 +109,8 @@ public class CategoriesImportManager {
             if (groupings != null) {
                 List<GroupingDefinition> newgroupings = new ArrayList<>();
                 for (GroupingDefinition grouping : groupings) {
-                    Either<GroupingDefinition, ResponseFormat> createdGrouping = createGroupingDeo(entry, grouping, subcategory, category, nodeTypeGroup);
+                    Either<GroupingDefinition, ResponseFormat> createdGrouping = createGroupingDeo(entry, grouping, subcategory, category,
+                        nodeTypeGroup);
                     if (createdGrouping.isRight()) {
                         return false;
                     }
@@ -125,10 +123,12 @@ public class CategoriesImportManager {
         return true;
     }
 
-    private Either<GroupingDefinition, ResponseFormat> createGroupingDeo(Map.Entry<String, List<CategoryDefinition>> entry, GroupingDefinition grouping, SubCategoryDefinition subcategory, CategoryDefinition category, NodeTypeEnum nodeTypeGroup) {
-
+    private Either<GroupingDefinition, ResponseFormat> createGroupingDeo(Map.Entry<String, List<CategoryDefinition>> entry,
+                                                                         GroupingDefinition grouping, SubCategoryDefinition subcategory,
+                                                                         CategoryDefinition category, NodeTypeEnum nodeTypeGroup) {
         log.debug("createGroupingDeo: creating grouping  {}", grouping);
-        Either<GroupingDefinition, ActionStatus> createdGrouping = elementOperation.createGrouping(subcategory.getUniqueId(), grouping, nodeTypeGroup);
+        Either<GroupingDefinition, ActionStatus> createdGrouping = elementOperation
+            .createGrouping(subcategory.getUniqueId(), grouping, nodeTypeGroup);
         if (createdGrouping.isRight()) {
             if (ActionStatus.COMPONENT_GROUPING_EXISTS_FOR_SUB_CATEGORY == createdGrouping.right().value()) {
                 log.debug(" create grouping for {}  group {} already exists ", entry.getKey(), grouping.getName());
@@ -139,28 +139,31 @@ public class CategoriesImportManager {
                     return Either.right(componentsUtils.getResponseFormat(createdGrouping.right().value()));
                 }
             }
-            log.debug("Failed to create groupingcategory for {}  category {} subcategory {} grouping {} error {}", entry.getKey(),
-                    category.getName(), subcategory.getName(), grouping != null ? grouping.getName() : null,
-                            createdGrouping != null && createdGrouping.right() != null ? createdGrouping.right().value() : null);
-
+            log.debug("Failed to create groupingcategory for {}  category {} subcategory {} grouping {} error {}", entry.getKey(), category.getName(),
+                subcategory.getName(), grouping != null ? grouping.getName() : null,
+                createdGrouping != null && createdGrouping.right() != null ? createdGrouping.right().value() : null);
             return Either.right(componentsUtils.getResponseFormat(createdGrouping.right().value()));
         } else {
             log.debug("createGroupingDeo: create Grouping was successful {}", createdGrouping.left().value());
         }
         return Either.left(createdGrouping.left().value());
-
     }
 
-    private Either<SubCategoryDefinition, ResponseFormat> createSubCategorieDeo(Map.Entry<String, List<CategoryDefinition>> entry, CategoryDefinition newcategory, SubCategoryDefinition subcategory, NodeTypeEnum nodeTypeSubCategory) {
+    private Either<SubCategoryDefinition, ResponseFormat> createSubCategorieDeo(Map.Entry<String, List<CategoryDefinition>> entry,
+                                                                                CategoryDefinition newcategory, SubCategoryDefinition subcategory,
+                                                                                NodeTypeEnum nodeTypeSubCategory) {
         log.debug("createSubCategorieDeo: creating subcategory  {}", subcategory);
-        Either<SubCategoryDefinition, ActionStatus> createdSubCategory = elementOperation.createSubCategory(newcategory.getUniqueId(), subcategory, nodeTypeSubCategory);
+        Either<SubCategoryDefinition, ActionStatus> createdSubCategory = elementOperation
+            .createSubCategory(newcategory.getUniqueId(), subcategory, nodeTypeSubCategory);
         if (createdSubCategory.isRight() && ActionStatus.COMPONENT_SUB_CATEGORY_EXISTS_FOR_CATEGORY == createdSubCategory.right().value()) {
-            log.debug(" create subcategory for {}  category {} subcategory {} already exists, updating", entry.getKey(), newcategory.getName(), subcategory.getName());
+            log.debug(" create subcategory for {}  category {} subcategory {} already exists, updating", entry.getKey(), newcategory.getName(),
+                subcategory.getName());
             String subCategoryId = UniqueIdBuilder.buildSubCategoryUid(newcategory.getUniqueId(), subcategory.getNormalizedName());
             createdSubCategory = elementOperation.updateSubCategory(subCategoryId, subcategory, nodeTypeSubCategory);
         }
         if (createdSubCategory.isRight()) {
-            log.debug("Failed to create subcategory for {}  category: {} subcategory: {} error {}", entry.getKey(), newcategory.getName(), subcategory.getName(), createdSubCategory.right().value());
+            log.debug("Failed to create subcategory for {}  category: {} subcategory: {} error {}", entry.getKey(), newcategory.getName(),
+                subcategory.getName(), createdSubCategory.right().value());
             return Either.right(componentsUtils.getResponseFormat(createdSubCategory.right().value()));
         } else {
             log.debug("createSubCategorieDeo: create subcategory was successful {}", createdSubCategory.left().value());
@@ -168,14 +171,14 @@ public class CategoriesImportManager {
         return Either.left(createdSubCategory.left().value());
     }
 
-    private Either<CategoryDefinition, ResponseFormat> createCategorieDeo(Map.Entry<String, List<CategoryDefinition>> entry, CategoryDefinition category, NodeTypeEnum nodeTypeCategory) {
+    private Either<CategoryDefinition, ResponseFormat> createCategorieDeo(Map.Entry<String, List<CategoryDefinition>> entry,
+                                                                          CategoryDefinition category, NodeTypeEnum nodeTypeCategory) {
         log.debug("createCategorieDeo: creating category {}", category);
         Either<CategoryDefinition, ActionStatus> createdCategory = elementOperation.createCategory(category, nodeTypeCategory);
         if (createdCategory.isRight() && ActionStatus.COMPONENT_CATEGORY_ALREADY_EXISTS == createdCategory.right().value()) {
             log.debug("createCategorieDeo: already exists, updating {}", category);
             createdCategory = elementOperation.updateCategory(category, nodeTypeCategory);
         }
-        
         if (createdCategory.isRight()) {
             log.debug("Failed to create category for {}  {} error {}", entry.getKey(), category.getName(), createdCategory.right().value());
             return Either.right(componentsUtils.getResponseFormat(createdCategory.right().value()));
@@ -188,7 +191,6 @@ public class CategoriesImportManager {
     private Map<String, List<CategoryDefinition>> createCategoriesFromYml(String categoriesTypesYml) {
         Map<String, Object> toscaJson = (Map<String, Object>) new Yaml().load(categoriesTypesYml);
         Map<String, List<CategoryDefinition>> allCategories = new HashMap<>();
-
         Iterator<Entry<String, Object>> categoryEntryItr = toscaJson.entrySet().iterator();
         while (categoryEntryItr.hasNext()) {
             Entry<String, Object> categoryTypeEntry = categoryEntryItr.next();
@@ -196,20 +198,20 @@ public class CategoriesImportManager {
             List<CategoryDefinition> categoriesPerType = null;
             Map<String, Object> categoryPerType = null;
             switch (categoryType) {
-            case ComponentTypeEnum.SERVICE_PARAM_NAME:
-                categoryPerType = (Map<String, Object>) categoryTypeEntry.getValue();
-                categoriesPerType = createServiceCategories(categoryPerType);
-                break;
-            case ComponentTypeEnum.RESOURCE_PARAM_NAME:
-                categoryPerType = (Map<String, Object>) categoryTypeEntry.getValue();
-                categoriesPerType = createResourceCategories(categoryPerType);
-                break;
-            case ComponentTypeEnum.PRODUCT_PARAM_NAME:
-                // TODO
-                break;
-            default:
-                log.debug("Not supported category type - {}", categoryType);
-                break;
+                case ComponentTypeEnum.SERVICE_PARAM_NAME:
+                    categoryPerType = (Map<String, Object>) categoryTypeEntry.getValue();
+                    categoriesPerType = createServiceCategories(categoryPerType);
+                    break;
+                case ComponentTypeEnum.RESOURCE_PARAM_NAME:
+                    categoryPerType = (Map<String, Object>) categoryTypeEntry.getValue();
+                    categoriesPerType = createResourceCategories(categoryPerType);
+                    break;
+                case ComponentTypeEnum.PRODUCT_PARAM_NAME:
+                    // TODO
+                    break;
+                default:
+                    log.debug("Not supported category type - {}", categoryType);
+                    break;
             }
             if (categoriesPerType != null) {
                 allCategories.put(categoryType, categoriesPerType);
@@ -232,18 +234,18 @@ public class CategoriesImportManager {
             String normalizedName = ValidationUtils.normalizeCategoryName4Uniqueness(catName);
             catDef.setNormalizedName(normalizedName);
             final Object useServiceSubstitutionForNestedServicesProperty = category.get("useServiceSubstitutionForNestedServices");
-            final boolean useServiceSubstitutionForNestedServices = useServiceSubstitutionForNestedServicesProperty == null ? 
-                    false : (Boolean) useServiceSubstitutionForNestedServicesProperty;
+            final boolean useServiceSubstitutionForNestedServices =
+                useServiceSubstitutionForNestedServicesProperty == null ? false : (Boolean) useServiceSubstitutionForNestedServicesProperty;
             catDef.setUseServiceSubstitutionForNestedServices(useServiceSubstitutionForNestedServices);
             catDef.setMetadataKeys(getMetadataKeys(category));
             categoriesDef.add(catDef);
         }
-
         return categoriesDef;
     }
-    
+
     private List<MetadataKeyDataDefinition> getMetadataKeys(Map<String, Object> parentObject) {
-        Map<String, Object> metadataKeys = (Map<String, Object>) parentObject.getOrDefault(MetadataKeyEnum.METADATA_KEYS.getName(), Collections.EMPTY_MAP);
+        Map<String, Object> metadataKeys = (Map<String, Object>) parentObject
+            .getOrDefault(MetadataKeyEnum.METADATA_KEYS.getName(), Collections.EMPTY_MAP);
         List<MetadataKeyDataDefinition> metadataKeyDefs = new ArrayList<>();
         for (Entry<String, Object> metadataKey : metadataKeys.entrySet()) {
             Map<String, Object> metadataKeyInfo = (Map<String, Object>) metadataKey.getValue();
@@ -284,7 +286,6 @@ public class CategoriesImportManager {
                 subDef.setMetadataKeys(getMetadataKeys(subcategoryInfo));
                 subcateDef.add(subDef);
             }
-
             catDef.setSubcategories(subcateDef);
             categroiesDef.add(catDef);
         }
index c3ecda3..326022d 100644 (file)
@@ -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.
  * Modifications copyright (c) 2019 Nokia
  * ================================================================================
  */
-
 package org.openecomp.sdc.be.components.impl;
 
+import static java.util.stream.Collectors.toList;
+
 import fj.data.Either;
+import java.util.ArrayList;
+import java.util.HashMap;
+import java.util.Iterator;
+import java.util.List;
+import java.util.Map;
+import java.util.Map.Entry;
+import java.util.function.BiFunction;
+import java.util.function.Consumer;
+import java.util.function.Function;
+import java.util.stream.Collectors;
 import org.apache.commons.lang3.tuple.ImmutablePair;
 import org.openecomp.sdc.be.components.impl.ImportUtils.ResultStatusEnum;
 import org.openecomp.sdc.be.components.impl.exceptions.ByActionStatusComponentException;
@@ -47,24 +58,10 @@ import org.springframework.beans.factory.annotation.Autowired;
 import org.springframework.stereotype.Component;
 import org.yaml.snakeyaml.Yaml;
 
-import java.util.ArrayList;
-import java.util.HashMap;
-import java.util.Iterator;
-import java.util.List;
-import java.util.Map;
-import java.util.Map.Entry;
-import java.util.function.BiFunction;
-import java.util.function.Consumer;
-import java.util.function.Function;
-import java.util.stream.Collectors;
-
-import static java.util.stream.Collectors.toList;
-
 @Component("commonImportManager")
 public class CommonImportManager {
 
     private static final Logger log = Logger.getLogger(CommonImportManager.class.getName());
-
     private final ComponentsUtils componentsUtils;
     private final PropertyOperation propertyOperation;
 
@@ -81,12 +78,10 @@ public class CommonImportManager {
     private static List<PropertyDefinition> getProperties(Map<String, Object> toscaJson) {
         List<PropertyDefinition> values = null;
         Either<Map<String, PropertyDefinition>, ResultStatusEnum> properties = ImportUtils.getProperties(toscaJson);
-
         if (properties.isLeft()) {
             values = new ArrayList<>();
             Map<String, PropertyDefinition> propertiesMap = properties.left().value();
             if (propertiesMap != null && !propertiesMap.isEmpty()) {
-
                 for (Entry<String, PropertyDefinition> entry : propertiesMap.entrySet()) {
                     String propName = entry.getKey();
                     PropertyDefinition propertyDefinition = entry.getValue();
@@ -96,28 +91,27 @@ public class CommonImportManager {
                 }
             }
         }
-
         return values;
     }
 
+    private static <T> List<T> append(List<T> list, T value) {
+        list.add(value);
+        return list;
+    }
+
     protected void setPropertiesMap(Map<String, Object> toscaJson, Consumer<Map<String, PropertyDefinition>> consumer) {
         final List<PropertyDefinition> properties = getProperties(toscaJson);
         if (properties != null) {
-            Map<String, PropertyDefinition> collect = properties.stream()
-                                                        .collect(Collectors.toMap(PropertyDefinition::getName, Function.identity()));
+            Map<String, PropertyDefinition> collect = properties.stream().collect(Collectors.toMap(PropertyDefinition::getName, Function.identity()));
             consumer.accept(collect);
         }
     }
 
-    public interface ICreateElementType<T1, T2, T3> {
-        T3 createElement(T1 firstArg, T2 secondArg);
-    }
-
-    protected <T> Either<List<T>, ActionStatus> createElementTypesFromYml(String elementTypesYml, ICreateElementType<String, Map<String, Object>, T> createApi) {
-
+    protected <T> Either<List<T>, ActionStatus> createElementTypesFromYml(String elementTypesYml,
+                                                                          ICreateElementType<String, Map<String, Object>, T> createApi) {
         List<T> elementTypes;
         Map<String, Object> toscaJson = convertToFieldMap(elementTypesYml);
-        if (toscaJson==null) {
+        if (toscaJson == null) {
             return Either.right(ActionStatus.INVALID_YAML_FILE);
         }
         elementTypes = createElementTypesFromToscaJsonMap(createApi, toscaJson);
@@ -135,11 +129,9 @@ public class CommonImportManager {
         return toscaJson;
     }
 
-
-    protected <T extends ToscaDataDefinition> List<T> createTypesFromToscaJsonMap(
-            BiFunction<String, Map<String, Object>, T> createApi, Map<String, Object> toscaJson) {
+    protected <T extends ToscaDataDefinition> List<T> createTypesFromToscaJsonMap(BiFunction<String, Map<String, Object>, T> createApi,
+                                                                                  Map<String, Object> toscaJson) {
         List<T> elementTypes = new ArrayList<>();
-
         for (Entry<String, Object> elementTypeNameDataEntry : toscaJson.entrySet()) {
             String elementTypeName = elementTypeNameDataEntry.getKey();
             Map<String, Object> elementTypeJsonData = (Map<String, Object>) elementTypeNameDataEntry.getValue();
@@ -149,10 +141,9 @@ public class CommonImportManager {
         return elementTypes;
     }
 
-    protected <T> List<T> createElementTypesFromToscaJsonMap(
-                ICreateElementType<String, Map<String, Object>, T> createApi, Map<String, Object> toscaJson) {
+    protected <T> List<T> createElementTypesFromToscaJsonMap(ICreateElementType<String, Map<String, Object>, T> createApi,
+                                                             Map<String, Object> toscaJson) {
         List<T> elementTypes = new ArrayList<>();
-
         for (Entry<String, Object> elementTypeNameDataEntry : toscaJson.entrySet()) {
             String elementTypeName = elementTypeNameDataEntry.getKey();
             Map<String, Object> elementTypeJsonData = (Map<String, Object>) elementTypeNameDataEntry.getValue();
@@ -162,10 +153,9 @@ public class CommonImportManager {
         return elementTypes;
     }
 
-    protected <T> Map<String, T> createElementTypesMapFromToscaJsonMap(
-                ICreateElementType<String, Map<String, Object>, T> createApi, Map<String, Object> toscaJson) {
+    protected <T> Map<String, T> createElementTypesMapFromToscaJsonMap(ICreateElementType<String, Map<String, Object>, T> createApi,
+                                                                       Map<String, Object> toscaJson) {
         Map<String, T> elementTypesMap = new HashMap<>();
-        
         Iterator<Entry<String, Object>> elementTypesEntryItr = toscaJson.entrySet().iterator();
         while (elementTypesEntryItr.hasNext()) {
             Entry<String, Object> elementTypeNameDataEntry = elementTypesEntryItr.next();
@@ -184,31 +174,27 @@ public class CommonImportManager {
         }
     }
 
-    public enum ElementTypeEnum {
-        POLICY_TYPE, GROUP_TYPE, DATA_TYPE, CAPABILITY_TYPE, INTERFACE_LIFECYCLE_TYPE, RELATIONSHIP_TYPE
-    }
-
     private ActionStatus convertFromStorageResponseForElementType(StorageOperationStatus status, ElementTypeEnum elementTypeEnum) {
         ActionStatus ret;
         switch (elementTypeEnum) {
-        case GROUP_TYPE:
-            ret = componentsUtils.convertFromStorageResponseForGroupType(status);
-            break;
-        case DATA_TYPE:
-            ret = componentsUtils.convertFromStorageResponseForDataType(status);
-            break;
-        case CAPABILITY_TYPE:
-            ret = componentsUtils.convertFromStorageResponseForCapabilityType(status);
-            break;
-        case INTERFACE_LIFECYCLE_TYPE:
-            ret = componentsUtils.convertFromStorageResponseForLifecycleType(status);
-            break;
-        case RELATIONSHIP_TYPE:
-            ret = componentsUtils.convertFromStorageResponseForRelationshipType(status);
-            break;
-        default:
-            ret = componentsUtils.convertFromStorageResponse(status);
-            break;
+            case GROUP_TYPE:
+                ret = componentsUtils.convertFromStorageResponseForGroupType(status);
+                break;
+            case DATA_TYPE:
+                ret = componentsUtils.convertFromStorageResponseForDataType(status);
+                break;
+            case CAPABILITY_TYPE:
+                ret = componentsUtils.convertFromStorageResponseForCapabilityType(status);
+                break;
+            case INTERFACE_LIFECYCLE_TYPE:
+                ret = componentsUtils.convertFromStorageResponseForLifecycleType(status);
+                break;
+            case RELATIONSHIP_TYPE:
+                ret = componentsUtils.convertFromStorageResponseForRelationshipType(status);
+                break;
+            default:
+                ret = componentsUtils.convertFromStorageResponse(status);
+                break;
         }
         return ret;
     }
@@ -216,22 +202,21 @@ public class CommonImportManager {
     private <T> ResponseFormat getResponseFormatForElementType(ActionStatus actionStatus, ElementTypeEnum elementTypeEnum, T elementTypeDefinition) {
         ResponseFormat ret;
         switch (elementTypeEnum) {
-        case GROUP_TYPE:
-            ret = componentsUtils.getResponseFormatByGroupType(actionStatus, (GroupTypeDefinition) elementTypeDefinition);
-            break;
-        case POLICY_TYPE:
-            ret = componentsUtils.getResponseFormatByPolicyType(actionStatus, (PolicyTypeDefinition) elementTypeDefinition);
-            break;
-        case DATA_TYPE:
-            ret = componentsUtils.getResponseFormatByDataType(actionStatus, (DataTypeDefinition) elementTypeDefinition, null);
-            break;
-        case CAPABILITY_TYPE:
-            ret = componentsUtils.getResponseFormatByCapabilityType(actionStatus, (CapabilityTypeDefinition) elementTypeDefinition);
-            break;
-
-        default:
-            ret = componentsUtils.getResponseFormat(actionStatus);
-            break;
+            case GROUP_TYPE:
+                ret = componentsUtils.getResponseFormatByGroupType(actionStatus, (GroupTypeDefinition) elementTypeDefinition);
+                break;
+            case POLICY_TYPE:
+                ret = componentsUtils.getResponseFormatByPolicyType(actionStatus, (PolicyTypeDefinition) elementTypeDefinition);
+                break;
+            case DATA_TYPE:
+                ret = componentsUtils.getResponseFormatByDataType(actionStatus, (DataTypeDefinition) elementTypeDefinition, null);
+                break;
+            case CAPABILITY_TYPE:
+                ret = componentsUtils.getResponseFormatByCapabilityType(actionStatus, (CapabilityTypeDefinition) elementTypeDefinition);
+                break;
+            default:
+                ret = componentsUtils.getResponseFormat(actionStatus);
+                break;
         }
         return ret;
     }
@@ -264,11 +249,13 @@ public class CommonImportManager {
         }
         return createdElementTypes;
     }
-    
+
     protected <T> Either<List<ImmutablePair<T, Boolean>>, ResponseFormat> createElementTypesByDao(List<T> elementTypesToCreate,
-            Function<T, Either<ActionStatus, ResponseFormat>> validator, Function<T, ImmutablePair<ElementTypeEnum, String>> elementInfoGetter,
-            Function<String, Either<T, StorageOperationStatus>> elementFetcher, Function<T, Either<T, StorageOperationStatus>> elementAdder,
-            BiFunction<T, T, Either<T, StorageOperationStatus>> elementUpgrader) {
+                                                                                                  Function<T, Either<ActionStatus, ResponseFormat>> validator,
+                                                                                                  Function<T, ImmutablePair<ElementTypeEnum, String>> elementInfoGetter,
+                                                                                                  Function<String, Either<T, StorageOperationStatus>> elementFetcher,
+                                                                                                  Function<T, Either<T, StorageOperationStatus>> elementAdder,
+                                                                                                  BiFunction<T, T, Either<T, StorageOperationStatus>> elementUpgrader) {
 
         List<ImmutablePair<T, Boolean>> createdElementTypes = new ArrayList<>();
 
@@ -279,49 +266,42 @@ public class CommonImportManager {
             while (elementTypeItr.hasNext()) {
                 T elementType = elementTypeItr.next();
                 eitherResult = handleType(elementType, validator, elementInfoGetter, elementFetcher, elementAdder, elementUpgrader)
-                                            .left()
-                                            .map(elem -> append(createdElementTypes, elem));
-                
+                    .left()
+                    .map(elem -> append(createdElementTypes, elem));
+
                 if (eitherResult.isRight()) {
                     break;
                 }
-                
-                if(!elementTypeItr.hasNext()) {
+
+                if (!elementTypeItr.hasNext()) {
                     log.info("all {} were created successfully!!!", elementType);
                 }
             }
-        }
-        catch(Exception e) {
+        } catch (Exception e) {
             eitherResult = Either.right(componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR));
             throw e;
-        } 
-        finally {
+        } finally {
             if (eitherResult.isLeft()) {
                 propertyOperation.getJanusGraphGenericDao().commit();
-            }
-            else {
+            } else {
                 propertyOperation.getJanusGraphGenericDao().rollback();
             }
         }
 
         return eitherResult;
     }
-    
-    private static <T> List<T> append(List<T> list, T value) {
-        list.add(value);
-        return list;
-    }
-    
-    
-    private <T> Either<ImmutablePair<T, Boolean>, ResponseFormat> handleType(T elementType, 
-            Function<T, Either<ActionStatus, ResponseFormat>> validator, Function<T, ImmutablePair<ElementTypeEnum, String>> elementInfoGetter,
-            Function<String, Either<T, StorageOperationStatus>> elementFetcher, Function<T, Either<T, StorageOperationStatus>> elementAdder,
-            BiFunction<T, T, Either<T, StorageOperationStatus>> elementUpgrader) {
-        
+
+    private <T> Either<ImmutablePair<T, Boolean>, ResponseFormat> handleType(T elementType,
+                                                                             Function<T, Either<ActionStatus, ResponseFormat>> validator,
+                                                                             Function<T, ImmutablePair<ElementTypeEnum, String>> elementInfoGetter,
+                                                                             Function<String, Either<T, StorageOperationStatus>> elementFetcher,
+                                                                             Function<T, Either<T, StorageOperationStatus>> elementAdder,
+                                                                             BiFunction<T, T, Either<T, StorageOperationStatus>> elementUpgrader) {
+
         final ImmutablePair<ElementTypeEnum, String> elementInfo = elementInfoGetter.apply(elementType);
         ElementTypeEnum elementTypeEnum = elementInfo.left;
         String elementName = elementInfo.right;
-        
+
         Either<ActionStatus, ResponseFormat> validateElementType = validator.apply(elementType);
         if (validateElementType.isRight()) {
             ResponseFormat responseFormat = validateElementType.right().value();
@@ -336,7 +316,8 @@ public class CommonImportManager {
             StorageOperationStatus status = findElementType.right().value();
             log.debug("searched {} finished with result:{}", elementTypeEnum, status);
             if (status != StorageOperationStatus.NOT_FOUND) {
-                ResponseFormat responseFormat = getResponseFormatForElementType(convertFromStorageResponseForElementType(status, elementTypeEnum), elementTypeEnum, elementType);
+                ResponseFormat responseFormat = getResponseFormatForElementType(convertFromStorageResponseForElementType(status, elementTypeEnum),
+                    elementTypeEnum, elementType);
                 return Either.right(responseFormat);
             } else {
                 return addElementType(elementType, elementAdder, elementTypeEnum, elementName);
@@ -356,15 +337,18 @@ public class CommonImportManager {
         }
     }
 
-    private <T> Either<ImmutablePair<T, Boolean>, ResponseFormat> addElementType(T elementType, Function<T, Either<T, StorageOperationStatus>> elementAdder, ElementTypeEnum elementTypeEnum, String elementName) {
+    private <T> Either<ImmutablePair<T, Boolean>, ResponseFormat> addElementType(T elementType,
+                                                                                 Function<T, Either<T, StorageOperationStatus>> elementAdder,
+                                                                                 ElementTypeEnum elementTypeEnum, String elementName) {
         Either<T, StorageOperationStatus> dataModelResponse = elementAdder.apply(elementType);
-        
+
         if (dataModelResponse.isRight()) {
             BeEcompErrorManager.getInstance().logBeFailedAddingNodeTypeError("Create {}", elementTypeEnum.name());
             log.debug("failed to create {}: {}", elementTypeEnum, elementName);
             if (dataModelResponse.right().value() != StorageOperationStatus.OK) {
-                ResponseFormat responseFormat = getResponseFormatForElementType(convertFromStorageResponseForElementType(dataModelResponse.right().value(), elementTypeEnum), elementTypeEnum, elementType);
-                
+                ResponseFormat responseFormat = getResponseFormatForElementType(
+                    convertFromStorageResponseForElementType(dataModelResponse.right().value(), elementTypeEnum), elementTypeEnum, elementType);
+
                 return Either.right(responseFormat);
             } else {
                 return Either.left(new ImmutablePair<>(elementType, false));
@@ -374,17 +358,19 @@ public class CommonImportManager {
             return Either.left(new ImmutablePair<>(elementType, true));
         }
     }
-    
-    
-    private <T> Either<ImmutablePair<T, Boolean>, ResponseFormat> updateElementType(T elementType, BiFunction<T, T, Either<T, StorageOperationStatus>> elementUpgrader, 
-                                                        ElementTypeEnum elementTypeEnum, String elementName, T existingElementType) {
+
+    private <T> Either<ImmutablePair<T, Boolean>, ResponseFormat> updateElementType(T elementType,
+                                                                                    BiFunction<T, T, Either<T, StorageOperationStatus>> elementUpgrader,
+                                                                                    ElementTypeEnum elementTypeEnum, String elementName,
+                                                                                    T existingElementType) {
         Either<T, StorageOperationStatus> upgradeResponse = elementUpgrader.apply(elementType, existingElementType);
         if (upgradeResponse.isRight()) {
             StorageOperationStatus status = upgradeResponse.right().value();
             if (status == StorageOperationStatus.OK) {
                 return Either.left(new ImmutablePair<>(elementType, false));
             } else {
-                ResponseFormat responseFormat = getResponseFormatForElementType(convertFromStorageResponseForElementType(upgradeResponse.right().value(), elementTypeEnum), elementTypeEnum, elementType);
+                ResponseFormat responseFormat = getResponseFormatForElementType(
+                    convertFromStorageResponseForElementType(upgradeResponse.right().value(), elementTypeEnum), elementTypeEnum, elementType);
                 return Either.right(responseFormat);
             }
         } else {
@@ -393,34 +379,35 @@ public class CommonImportManager {
         }
     }
 
-    
-    public <T extends ToscaTypeDataDefinition> Either<List<ImmutablePair<T, Boolean>>, ResponseFormat> createElementTypes(ToscaTypeImportData toscaTypeImportData, Function<String, Either<List<T>, ActionStatus>> elementTypeFromYmlCreater,
-                                                                                                                          Function<List<T>, Either<List<ImmutablePair<T, Boolean>>, ResponseFormat>> elementTypeDaoCreater) {
+    public <T extends ToscaTypeDataDefinition> Either<List<ImmutablePair<T, Boolean>>, ResponseFormat> createElementTypes(
+        ToscaTypeImportData toscaTypeImportData, Function<String, Either<List<T>, ActionStatus>> elementTypeFromYmlCreater,
+        Function<List<T>, Either<List<ImmutablePair<T, Boolean>>, ResponseFormat>> elementTypeDaoCreater) {
         Either<List<T>, ActionStatus> elementTypes = elementTypeFromYmlCreater.apply(toscaTypeImportData.getToscaTypesYml());
         return elementTypes
-                .right()
-                .map(err -> componentsUtils.getResponseFormat(err, ""))
-                .left()
-                .map(toscaTypes -> enrichTypesWithNonToscaMetadata(toscaTypes, toscaTypeImportData.getToscaTypeMetadata()))
-                .left()
-                .bind(elementTypeDaoCreater::apply);
+            .right()
+            .map(err -> componentsUtils.getResponseFormat(err, ""))
+            .left()
+            .map(toscaTypes -> enrichTypesWithNonToscaMetadata(toscaTypes, toscaTypeImportData.getToscaTypeMetadata()))
+            .left()
+            .bind(elementTypeDaoCreater::apply);
     }
 
     public <T extends ToscaDataDefinition> List<ImmutablePair<T, Boolean>> createElementTypes(String toscaTypesYml,
                                                                                               BiFunction<String, Map<String, Object>, T> createApi,
                                                                                               TypeOperations<T> typeOperations) {
         Map<String, Object> fieldMap = convertToFieldMap(toscaTypesYml);
-        if (fieldMap==null) {
+        if (fieldMap == null) {
             throw new ByActionStatusComponentException(ActionStatus.INVALID_YAML_FILE);
         }
         List<T> elementTypes = createTypesFromToscaJsonMap(createApi, fieldMap);
         return createTypesByDao(elementTypes, typeOperations);
     }
 
-    private <T extends ToscaTypeDataDefinition> List<T> enrichTypesWithNonToscaMetadata(List<T> toscaTypes, Map<String, ToscaTypeMetadata> toscaTypeMetadata) {
+    private <T extends ToscaTypeDataDefinition> List<T> enrichTypesWithNonToscaMetadata(List<T> toscaTypes,
+                                                                                        Map<String, ToscaTypeMetadata> toscaTypeMetadata) {
         return toscaTypes.stream()
-                  .map(toscaType -> setNonToscaMetaDataOnType(toscaTypeMetadata, toscaType))
-                  .collect(toList());
+            .map(toscaType -> setNonToscaMetaDataOnType(toscaTypeMetadata, toscaType))
+            .collect(toList());
     }
 
     private <T extends ToscaTypeDataDefinition> T setNonToscaMetaDataOnType(Map<String, ToscaTypeMetadata> toscaTypeMetadata, T toscaTypeDefinition) {
@@ -435,8 +422,10 @@ public class CommonImportManager {
         return toscaTypeDefinition;
     }
 
-    public <T> Either<List<ImmutablePair<T, Boolean>>, ResponseFormat> createElementTypes(String elementTypesYml, Function<String, Either<List<T>, ActionStatus>> elementTypeFromYmlCreater,
-            Function<List<T>, Either<List<ImmutablePair<T, Boolean>>, ResponseFormat>> elementTypeDaoCreater, ElementTypeEnum elementTypeEnum) {
+    public <T> Either<List<ImmutablePair<T, Boolean>>, ResponseFormat> createElementTypes(String elementTypesYml,
+                                                                                          Function<String, Either<List<T>, ActionStatus>> elementTypeFromYmlCreater,
+                                                                                          Function<List<T>, Either<List<ImmutablePair<T, Boolean>>, ResponseFormat>> elementTypeDaoCreater,
+                                                                                          ElementTypeEnum elementTypeEnum) {
 
         Either<List<T>, ActionStatus> elementTypes = elementTypeFromYmlCreater.apply(elementTypesYml);
         if (elementTypes.isRight()) {
@@ -447,4 +436,13 @@ public class CommonImportManager {
         return elementTypeDaoCreater.apply(elementTypes.left().value());
 
     }
+
+    public enum ElementTypeEnum {
+        POLICY_TYPE, GROUP_TYPE, DATA_TYPE, CAPABILITY_TYPE, INTERFACE_LIFECYCLE_TYPE, RELATIONSHIP_TYPE
+    }
+
+    public interface ICreateElementType<T1, T2, T3> {
+
+        T3 createElement(T1 firstArg, T2 secondArg);
+    }
 }
index efab859..9ce54c2 100644 (file)
@@ -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.
  * Modifications copyright (c) 2019 Nokia
  * ================================================================================
  */
-
 package org.openecomp.sdc.be.components.impl;
 
 import fj.data.Either;
+import java.util.ArrayList;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+import java.util.Map.Entry;
 import java.util.Optional;
 import java.util.function.BiFunction;
 import java.util.function.BooleanSupplier;
+import java.util.stream.Collectors;
 import org.apache.commons.collections.CollectionUtils;
 import org.apache.commons.lang3.StringUtils;
 import org.apache.commons.lang3.tuple.ImmutablePair;
@@ -96,51 +101,31 @@ import org.openecomp.sdc.common.util.ValidationUtils;
 import org.openecomp.sdc.exception.ResponseFormat;
 import org.springframework.beans.factory.annotation.Autowired;
 
-import java.util.ArrayList;
-import java.util.HashMap;
-import java.util.List;
-import java.util.Map;
-import java.util.Map.Entry;
-import java.util.stream.Collectors;
-
 public abstract class ComponentBusinessLogic extends BaseBusinessLogic {
 
-    protected ArtifactsBusinessLogic artifactsBusinessLogic;
-
+    private static final Logger log = Logger.getLogger(ComponentBusinessLogic.class.getName());
     protected final GroupBusinessLogic groupBusinessLogic;
-
+    protected ArtifactsBusinessLogic artifactsBusinessLogic;
     protected GenericTypeBusinessLogic genericTypeBusinessLogic;
-
     protected ComponentDescriptionValidator componentDescriptionValidator;
     protected ComponentProjectCodeValidator componentProjectCodeValidator;
-
     protected CatalogOperation catalogOperations;
     protected ComponentIconValidator componentIconValidator;
-
     protected ComponentValidator componentValidator;
     protected ComponentTagsValidator componentTagsValidator;
     protected ComponentNameValidator componentNameValidator;
     protected ComponentContactIdValidator componentContactIdValidator;
 
-    public ComponentBusinessLogic(IElementOperation elementDao,
-        IGroupOperation groupOperation,
-        IGroupInstanceOperation groupInstanceOperation,
-        IGroupTypeOperation groupTypeOperation,
-        GroupBusinessLogic groupBusinessLogic,
-        InterfaceOperation interfaceOperation,
-        InterfaceLifecycleOperation interfaceLifecycleTypeOperation,
-        ArtifactsBusinessLogic artifactsBusinessLogic,
-        ArtifactsOperations artifactToscaOperation,
-        ComponentContactIdValidator componentContactIdValidator,
-        ComponentNameValidator componentNameValidator,
-        ComponentTagsValidator componentTagsValidator,
-        ComponentValidator componentValidator,
-        ComponentIconValidator componentIconValidator,
-        ComponentProjectCodeValidator componentProjectCodeValidator,
-        ComponentDescriptionValidator componentDescriptionValidator){
-
-        super(elementDao, groupOperation, groupInstanceOperation, groupTypeOperation,
-            interfaceOperation, interfaceLifecycleTypeOperation, artifactToscaOperation);
+    public ComponentBusinessLogic(IElementOperation elementDao, IGroupOperation groupOperation, IGroupInstanceOperation groupInstanceOperation,
+                                  IGroupTypeOperation groupTypeOperation, GroupBusinessLogic groupBusinessLogic,
+                                  InterfaceOperation interfaceOperation, InterfaceLifecycleOperation interfaceLifecycleTypeOperation,
+                                  ArtifactsBusinessLogic artifactsBusinessLogic, ArtifactsOperations artifactToscaOperation,
+                                  ComponentContactIdValidator componentContactIdValidator, ComponentNameValidator componentNameValidator,
+                                  ComponentTagsValidator componentTagsValidator, ComponentValidator componentValidator,
+                                  ComponentIconValidator componentIconValidator, ComponentProjectCodeValidator componentProjectCodeValidator,
+                                  ComponentDescriptionValidator componentDescriptionValidator) {
+        super(elementDao, groupOperation, groupInstanceOperation, groupTypeOperation, interfaceOperation, interfaceLifecycleTypeOperation,
+            artifactToscaOperation);
         this.artifactsBusinessLogic = artifactsBusinessLogic;
         this.groupBusinessLogic = groupBusinessLogic;
         this.componentContactIdValidator = componentContactIdValidator;
@@ -152,6 +137,33 @@ public abstract class ComponentBusinessLogic extends BaseBusinessLogic {
         this.componentDescriptionValidator = componentDescriptionValidator;
     }
 
+    private static Either<ArtifactDefinition, Operation> saveToscaArtifactAndPopulateToscaArtifactsWithResult(Component component,
+                                                                                                              final ComponentsUtils componentsUtils,
+                                                                                                              final ArtifactTypeEnum artifactEnum,
+                                                                                                              final BiFunction<Component, ArtifactDefinition, Either<ArtifactDefinition, Operation>> saveToscaArtifactPayloadFunction) {
+        ArtifactDefinition artifactDefinition = getToscaArtifactByTypeOrThrowException(component, artifactEnum, componentsUtils);
+        Either<ArtifactDefinition, Operation> result = saveToscaArtifactPayloadFunction.apply(component, artifactDefinition);
+        if (result.isLeft()) {
+            ArtifactDefinition def = result.left().value();
+            component.getToscaArtifacts().put(def.getArtifactLabel(), def);
+        }
+        return result;
+    }
+
+    private static Optional<ArtifactDefinition> getToscaArtifactByType(final Map<String, ArtifactDefinition> toscaArtifacts,
+                                                                       final ArtifactTypeEnum typeEnum) {
+        return toscaArtifacts.values().stream().filter(p -> p.getArtifactType().equals(typeEnum.getType())).findAny();
+    }
+
+    private static ArtifactDefinition getToscaArtifactByTypeOrThrowException(final Component component, final ArtifactTypeEnum typeEnum,
+                                                                             final ComponentsUtils componentsUtils) {
+        return Optional.ofNullable(component.getToscaArtifacts()).flatMap(toscaArtifacts -> getToscaArtifactByType(toscaArtifacts, typeEnum))
+            .orElseThrow(() -> {
+                log.debug("Impossible to find a ToscaArtifact with type '{}' for {}", typeEnum.getType(), component);
+                return new ByResponseFormatComponentException(componentsUtils.getResponseFormat(ActionStatus.ARTIFACT_NOT_FOUND, typeEnum.name()));
+            });
+    }
+
     public void setComponentDescriptionValidator(ComponentDescriptionValidator componentDescriptionValidator) {
         this.componentDescriptionValidator = componentDescriptionValidator;
     }
@@ -176,27 +188,25 @@ public abstract class ComponentBusinessLogic extends BaseBusinessLogic {
         this.componentNameValidator = componentNameValidator;
     }
 
-
     @Autowired
     public void setGenericTypeBusinessLogic(GenericTypeBusinessLogic genericTypeBusinessLogic) {
         this.genericTypeBusinessLogic = genericTypeBusinessLogic;
     }
 
-    private static final Logger log = Logger.getLogger(ComponentBusinessLogic.class.getName());
-
     public abstract Either<List<String>, ResponseFormat> deleteMarkedComponents();
 
     public abstract ComponentInstanceBusinessLogic getComponentInstanceBL();
 
-    public abstract Either<List<ComponentInstance>, ResponseFormat> getComponentInstancesFilteredByPropertiesAndInputs(String componentId, String userId);
+    public abstract Either<List<ComponentInstance>, ResponseFormat> getComponentInstancesFilteredByPropertiesAndInputs(String componentId,
+                                                                                                                       String userId);
 
     /**
-     *
      * @param componentId
      * @param dataParamsToReturn
      * @return
      */
-    public abstract  Either<UiComponentDataTransfer, ResponseFormat> getUiComponentDataTransferByComponentId(String componentId, List<String> dataParamsToReturn);
+    public abstract Either<UiComponentDataTransfer, ResponseFormat> getUiComponentDataTransferByComponentId(String componentId,
+                                                                                                            List<String> dataParamsToReturn);
 
     User validateUser(User user, String ecompErrorContext, Component component, AuditingActionEnum auditAction, boolean inTransaction) {
         User validatedUser;
@@ -204,14 +214,14 @@ public abstract class ComponentBusinessLogic extends BaseBusinessLogic {
         try {
             validateUserNotEmpty(user, ecompErrorContext);
             validatedUser = validateUserExists(user);
-        } catch(ByActionStatusComponentException e){
-            if(e.getActionStatus() == ActionStatus.MISSING_INFORMATION){
+        } catch (ByActionStatusComponentException e) {
+            if (e.getActionStatus() == ActionStatus.MISSING_INFORMATION) {
                 user.setUserId("UNKNOWN");
             }
             responseFormat = componentsUtils.getResponseFormat(e.getActionStatus(), e.getParams());
             componentsUtils.auditComponentAdmin(responseFormat, user, component, auditAction, component.getComponentType());
             throw e;
-        } catch(ByResponseFormatComponentException e){
+        } catch (ByResponseFormatComponentException e) {
             responseFormat = e.getResponseFormat();
             componentsUtils.auditComponentAdmin(responseFormat, user, component, auditAction, component.getComponentType());
             throw e;
@@ -226,69 +236,64 @@ public abstract class ComponentBusinessLogic extends BaseBusinessLogic {
         }
         try {
             validateUserRole(user, roles);
-        }catch (ByActionStatusComponentException e) {
+        } catch (ByActionStatusComponentException e) {
             ResponseFormat responseFormat = componentsUtils.getResponseFormat(e.getActionStatus(), e.getParams());
             handleComponentException(component, comment, responseFormat, user, auditAction);
             throw e;
-        }catch (ByResponseFormatComponentException e) {
+        } catch (ByResponseFormatComponentException e) {
             ResponseFormat responseFormat = e.getResponseFormat();
             handleComponentException(component, comment, responseFormat, user, auditAction);
             throw e;
         }
     }
 
-    private void handleComponentException(Component component, String comment, ResponseFormat responseFormat,
-        User user, AuditingActionEnum auditAction){
+    private void handleComponentException(Component component, String comment, ResponseFormat responseFormat, User user,
+                                          AuditingActionEnum auditAction) {
         String commentStr = null;
         String distrStatus = null;
         ComponentTypeEnum componentType = component.getComponentType();
-            if (componentType == ComponentTypeEnum.SERVICE) {
-            distrStatus = ((ServiceMetadataDataDefinition) component.getComponentMetadataDefinition().getMetadataDataDefinition()).getDistributionStatus();
+        if (componentType == ComponentTypeEnum.SERVICE) {
+            distrStatus = ((ServiceMetadataDataDefinition) component.getComponentMetadataDefinition().getMetadataDataDefinition())
+                .getDistributionStatus();
             commentStr = comment;
         }
         componentsUtils.auditComponent(responseFormat, user, component, auditAction, new ResourceCommonInfo(componentType.getValue()),
             ResourceVersionInfo.newBuilder().distributionStatus(distrStatus).build(),
-            ResourceVersionInfo.newBuilder().distributionStatus(distrStatus).build(),
-            commentStr, null, null);
+            ResourceVersionInfo.newBuilder().distributionStatus(distrStatus).build(), commentStr, null, null);
     }
 
     public Either<Boolean, ResponseFormat> validateConformanceLevel(String componentUuid, ComponentTypeEnum componentTypeEnum, String userId) {
         log.trace("validate conformance level");
-
         if (componentTypeEnum != ComponentTypeEnum.SERVICE) {
             log.error("conformance level validation for non service component, id {}", componentUuid);
             ResponseFormat errorResponse = componentsUtils.getResponseFormat(ActionStatus.INVALID_CONTENT);
             return Either.right(errorResponse);
         }
-
         validateUserExists(userId);
-
-        Either<ComponentMetadataData, StorageOperationStatus> eitherComponent = toscaOperationFacade.getLatestComponentMetadataByUuid(componentUuid, JsonParseFlagEnum.ParseMetadata, null);
+        Either<ComponentMetadataData, StorageOperationStatus> eitherComponent = toscaOperationFacade
+            .getLatestComponentMetadataByUuid(componentUuid, JsonParseFlagEnum.ParseMetadata, null);
         if (eitherComponent.isRight()) {
             log.error("can't validate conformance level, component not found, uuid {}", componentUuid);
             BeEcompErrorManager.getInstance().logBeComponentMissingError("validateConformanceLevel", componentTypeEnum.getValue(), componentUuid);
-
             StorageOperationStatus status = eitherComponent.right().value();
             ActionStatus actionStatus = componentsUtils.convertFromStorageResponse(status, componentTypeEnum);
             ResponseFormat responseFormat = componentsUtils.getResponseFormat(actionStatus);
             return Either.right(responseFormat);
         }
-
         String componentConformanceLevel = eitherComponent.left().value().getMetadataDataDefinition().getConformanceLevel();
         if (StringUtils.isBlank(componentConformanceLevel)) {
             log.error("component conformance level property is null or empty, uuid {}", componentUuid);
             ResponseFormat errorResponse = componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR);
             return Either.right(errorResponse);
         }
-
         String configConformanceLevel = ConfigurationManager.getConfigurationManager().getConfiguration().getMinToscaConformanceLevel();
         Boolean result = true;
         if (CommonBeUtils.conformanceLevelCompare(componentConformanceLevel, configConformanceLevel) < 0) {
-            log.error("invalid asset conformance level, uuid {}, asset conformanceLevel {}, config conformanceLevel {}", componentUuid, componentConformanceLevel, configConformanceLevel);
+            log.error("invalid asset conformance level, uuid {}, asset conformanceLevel {}, config conformanceLevel {}", componentUuid,
+                componentConformanceLevel, configConformanceLevel);
             result = false;
         }
         log.trace("conformance level validation finished");
-
         return Either.left(result);
     }
 
@@ -304,9 +309,9 @@ public abstract class ComponentBusinessLogic extends BaseBusinessLogic {
         }
         try {
             validateIcon(icon, type);
-        } catch(ComponentException e){
-            ResponseFormat responseFormat = e.getResponseFormat() != null ? e.getResponseFormat()
-                    : componentsUtils.getResponseFormat(e.getActionStatus(), e.getParams());
+        } catch (ComponentException e) {
+            ResponseFormat responseFormat =
+                e.getResponseFormat() != null ? e.getResponseFormat() : componentsUtils.getResponseFormat(e.getActionStatus(), e.getParams());
             componentsUtils.auditComponentAdmin(responseFormat, user, component, actionEnum, type);
             throw e;
         }
@@ -318,7 +323,6 @@ public abstract class ComponentBusinessLogic extends BaseBusinessLogic {
                 log.debug("icon exceeds max length");
                 throw new ComponentException(ActionStatus.COMPONENT_ICON_EXCEEDS_LIMIT, type.getValue(), "" + ValidationUtils.ICON_MAX_LENGTH);
             }
-
             if (!ValidationUtils.validateIcon(icon)) {
                 log.info("icon is invalid.");
                 throw new ComponentException(ActionStatus.COMPONENT_INVALID_ICON, type.getValue());
@@ -377,67 +381,70 @@ public abstract class ComponentBusinessLogic extends BaseBusinessLogic {
         log.debug("validate icon");
         validateIcon(user, component, actionEnum);
     }
-       
-    public CapReqDef getRequirementsAndCapabilities(String componentId, ComponentTypeEnum componentTypeEnum, String userId) {
 
+    public CapReqDef getRequirementsAndCapabilities(String componentId, ComponentTypeEnum componentTypeEnum, String userId) {
         validateUserExists(userId);
         ComponentParametersView filter = new ComponentParametersView(true);
         filter.setIgnoreCapabilities(false);
         filter.setIgnoreRequirements(false);
         filter.setIgnoreComponentInstances(false);
-
         try {
             Component component = validateComponentExists(componentId, componentTypeEnum, filter);
             return new CapReqDef(component.getRequirements(), component.getCapabilities());
-        }catch (ComponentException e){
+        } catch (ComponentException e) {
             BeEcompErrorManager.getInstance().logBeComponentMissingError("getRequirementsAndCapabilities", componentTypeEnum.getValue(), componentId);
             throwComponentException(e.getResponseFormat());
         }
         return null;
     }
 
-    public Either<List<Component>, ResponseFormat> getLatestVersionNotAbstractComponents(boolean isAbstractAbstract, ComponentTypeEnum componentTypeEnum, String internalComponentType, List<String> componentUids,
+    public Either<List<Component>, ResponseFormat> getLatestVersionNotAbstractComponents(boolean isAbstractAbstract,
+                                                                                         ComponentTypeEnum componentTypeEnum,
+                                                                                         String internalComponentType, List<String> componentUids,
                                                                                          String userId) {
-        try{
+        try {
             validateUserExists(userId);
             List<Component> result = new ArrayList<>();
             List<String> componentsUidToFetch = new ArrayList<>();
             componentsUidToFetch.addAll(componentUids);
             if (!componentsUidToFetch.isEmpty()) {
                 log.debug("Number of Components to fetch from graph is {}", componentsUidToFetch.size());
-                Either<List<Component>, StorageOperationStatus> nonCheckoutCompResponse = toscaOperationFacade.getLatestVersionNotAbstractComponents(isAbstractAbstract, componentTypeEnum, internalComponentType, componentsUidToFetch);
-
+                Either<List<Component>, StorageOperationStatus> nonCheckoutCompResponse = toscaOperationFacade
+                    .getLatestVersionNotAbstractComponents(isAbstractAbstract, componentTypeEnum, internalComponentType, componentsUidToFetch);
                 if (nonCheckoutCompResponse.isLeft()) {
                     log.debug("Retrived Resource successfully.");
                     result.addAll(nonCheckoutCompResponse.left().value());
                 } else {
-                    return Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(nonCheckoutCompResponse.right().value())));
+                    return Either.right(
+                        componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(nonCheckoutCompResponse.right().value())));
                 }
             }
             return Either.left(result);
-        }
-        finally{
+        } finally {
             janusGraphDao.commit();
         }
     }
 
-    public Either<List<Component>, ResponseFormat> getLatestVersionNotAbstractComponentsMetadata(boolean isAbstractAbstract, HighestFilterEnum highestFilter, ComponentTypeEnum componentTypeEnum, String internalComponentType, String userId) {
-        try{
+    public Either<List<Component>, ResponseFormat> getLatestVersionNotAbstractComponentsMetadata(boolean isAbstractAbstract,
+                                                                                                 HighestFilterEnum highestFilter,
+                                                                                                 ComponentTypeEnum componentTypeEnum,
+                                                                                                 String internalComponentType, String userId) {
+        try {
             validateUserExists(userId);
-            Either<List<Component>, StorageOperationStatus> nonCheckoutCompResponse = toscaOperationFacade.getLatestVersionNotAbstractMetadataOnly(isAbstractAbstract, componentTypeEnum, internalComponentType);
-
+            Either<List<Component>, StorageOperationStatus> nonCheckoutCompResponse = toscaOperationFacade
+                .getLatestVersionNotAbstractMetadataOnly(isAbstractAbstract, componentTypeEnum, internalComponentType);
             if (nonCheckoutCompResponse.isLeft()) {
                 log.debug("Retrieved Resource successfully.");
                 return Either.left(nonCheckoutCompResponse.left().value());
             }
-            return Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(nonCheckoutCompResponse.right().value())));
+            return Either
+                .right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(nonCheckoutCompResponse.right().value())));
         } finally {
             janusGraphDao.commit();
         }
     }
 
     public void setDeploymentArtifactsPlaceHolder(Component component, User user) {
-
     }
 
     @SuppressWarnings("unchecked")
@@ -450,141 +457,101 @@ public abstract class ComponentBusinessLogic extends BaseBusinessLogic {
         String componentSystemName = component.getSystemName();
         String componentType = component.getComponentType().getValue().toLowerCase();
         Map<String, Object> toscaArtifacts = ConfigurationManager.getConfigurationManager().getConfiguration().getToscaArtifacts();
-
         if (toscaArtifacts != null) {
             for (Entry<String, Object> artifactInfoMap : toscaArtifacts.entrySet()) {
                 Map<String, Object> artifactInfo = (Map<String, Object>) artifactInfoMap.getValue();
-                ArtifactDefinition artifactDefinition = artifactsBusinessLogic.createArtifactPlaceHolderInfo(componentUniqueId, artifactInfoMap.getKey(), artifactInfo, user, ArtifactGroupTypeEnum.TOSCA);
-                artifactDefinition.setArtifactName(ValidationUtils.normalizeFileName(componentType + "-" + componentSystemName + artifactInfo.get("artifactName")));
+                ArtifactDefinition artifactDefinition = artifactsBusinessLogic
+                    .createArtifactPlaceHolderInfo(componentUniqueId, artifactInfoMap.getKey(), artifactInfo, user, ArtifactGroupTypeEnum.TOSCA);
+                artifactDefinition
+                    .setArtifactName(ValidationUtils.normalizeFileName(componentType + "-" + componentSystemName + artifactInfo.get("artifactName")));
                 artifactMap.put(artifactDefinition.getArtifactLabel(), artifactDefinition);
             }
         }
         component.setToscaArtifacts(artifactMap);
     }
 
-    public Either<ArtifactDefinition, Operation> populateToscaArtifacts(Component component, User user, boolean isInCertificationRequest, boolean inTransaction, boolean shouldLock) {
+    public Either<ArtifactDefinition, Operation> populateToscaArtifacts(Component component, User user, boolean isInCertificationRequest,
+                                                                        boolean inTransaction, boolean shouldLock) {
         return populateToscaArtifacts(component, user, isInCertificationRequest, inTransaction, shouldLock, true, true);
     }
 
-    public Either<ArtifactDefinition, Operation> populateToscaArtifacts(Component component, User user, boolean isInCertificationRequest, boolean inTransaction, boolean shouldLock, boolean retrieveResource) {
+    public Either<ArtifactDefinition, Operation> populateToscaArtifacts(Component component, User user, boolean isInCertificationRequest,
+                                                                        boolean inTransaction, boolean shouldLock, boolean retrieveResource) {
         return populateToscaArtifacts(component, user, isInCertificationRequest, inTransaction, shouldLock, true, retrieveResource);
     }
 
-    private Either<ArtifactDefinition, Operation> populateToscaArtifacts(Component component, User user, boolean isInCertificationRequest, boolean inTransaction, boolean shouldLock, boolean fetchTemplatesFromDB, boolean retrieveResource) {
+    private Either<ArtifactDefinition, Operation> populateToscaArtifacts(Component component, User user, boolean isInCertificationRequest,
+                                                                         boolean inTransaction, boolean shouldLock, boolean fetchTemplatesFromDB,
+                                                                         boolean retrieveResource) {
         if (retrieveResource) {
             Either<Component, StorageOperationStatus> toscaElement = toscaOperationFacade.getToscaFullElement(component.getUniqueId());
-            if ( toscaElement.isRight() ){
-                throw new ByActionStatusComponentException(componentsUtils.convertFromStorageResponse(toscaElement.right().value(), component.getComponentType()));
+            if (toscaElement.isRight()) {
+                throw new ByActionStatusComponentException(
+                    componentsUtils.convertFromStorageResponse(toscaElement.right().value(), component.getComponentType()));
             }
             component = toscaElement.left().value();
         }
-
-        Either<ArtifactDefinition, Operation> generateToscaRes =
-            saveToscaArtifactAndPopulateToscaArtifactsWithResult(component, componentsUtils,
-                ArtifactTypeEnum.TOSCA_TEMPLATE,
-                (comp, toscaArtifact) ->
-                    saveToscaArtifactPayload(toscaArtifact, comp, user, isInCertificationRequest, shouldLock,
-                        inTransaction, fetchTemplatesFromDB));
-
+        Either<ArtifactDefinition, Operation> generateToscaRes = saveToscaArtifactAndPopulateToscaArtifactsWithResult(component, componentsUtils,
+            ArtifactTypeEnum.TOSCA_TEMPLATE,
+            (comp, toscaArtifact) -> saveToscaArtifactPayload(toscaArtifact, comp, user, isInCertificationRequest, shouldLock, inTransaction,
+                fetchTemplatesFromDB));
         if (!isAbstractResource(component)) {
-            generateToscaRes = saveToscaArtifactAndPopulateToscaArtifactsWithResult(component, componentsUtils,
-                ArtifactTypeEnum.TOSCA_CSAR,
-                (comp, toscaArtifactArg) -> saveToscaArtifactPayload(toscaArtifactArg, comp, user,
-                    isInCertificationRequest, shouldLock, inTransaction, true));
+            generateToscaRes = saveToscaArtifactAndPopulateToscaArtifactsWithResult(component, componentsUtils, ArtifactTypeEnum.TOSCA_CSAR,
+                (comp, toscaArtifactArg) -> saveToscaArtifactPayload(toscaArtifactArg, comp, user, isInCertificationRequest, shouldLock,
+                    inTransaction, true));
         }
         return generateToscaRes;
     }
 
-    private static Either<ArtifactDefinition, Operation> saveToscaArtifactAndPopulateToscaArtifactsWithResult(
-        Component component,
-        final ComponentsUtils componentsUtils,
-        final ArtifactTypeEnum artifactEnum,
-        final BiFunction<Component, ArtifactDefinition, Either<ArtifactDefinition, Operation>> saveToscaArtifactPayloadFunction) {
-
-        ArtifactDefinition artifactDefinition = getToscaArtifactByTypeOrThrowException(component, artifactEnum,
-            componentsUtils);
-
-        Either<ArtifactDefinition, Operation> result =
-            saveToscaArtifactPayloadFunction.apply(component, artifactDefinition);
-
-        if (result.isLeft()) {
-            ArtifactDefinition def = result.left().value();
-            component.getToscaArtifacts().put(def.getArtifactLabel(), def);
-        }
-
-        return result;
-    }
-
-    private static Optional<ArtifactDefinition> getToscaArtifactByType(
-        final Map<String, ArtifactDefinition> toscaArtifacts,
-        final ArtifactTypeEnum typeEnum) {
-        return toscaArtifacts.values().stream()
-            .filter(p -> p.getArtifactType().equals(typeEnum.getType()))
-            .findAny();
-    }
-
-    private static ArtifactDefinition getToscaArtifactByTypeOrThrowException(
-        final Component component,
-        final ArtifactTypeEnum typeEnum,
-        final ComponentsUtils componentsUtils) {
-
-        return Optional.ofNullable(component.getToscaArtifacts())
-            .flatMap(toscaArtifacts -> getToscaArtifactByType(toscaArtifacts, typeEnum))
-            .orElseThrow(() -> {
-                    log.debug("Impossible to find a ToscaArtifact with type '{}' for {}", typeEnum.getType(), component);
-                    return new ByResponseFormatComponentException(
-                        componentsUtils.getResponseFormat(ActionStatus.ARTIFACT_NOT_FOUND, typeEnum.name()));
-                });
-    }
-
     private boolean isAbstractResource(Component component) {
-        return component.getComponentType() == ComponentTypeEnum.RESOURCE && ((Resource)component).isAbstract();
+        return component.getComponentType() == ComponentTypeEnum.RESOURCE && ((Resource) component).isAbstract();
     }
 
-    private Either<ArtifactDefinition, Operation> saveToscaArtifactPayload(ArtifactDefinition artifactDefinition, org.openecomp.sdc.be.model.Component component, User user, boolean isInCertificationRequest, boolean shouldLock,
-                                                                                                   boolean inTransaction, boolean fetchTemplatesFromDB) {
-        return artifactsBusinessLogic.generateAndSaveToscaArtifact(artifactDefinition, component, user, isInCertificationRequest, shouldLock, inTransaction, fetchTemplatesFromDB);
+    private Either<ArtifactDefinition, Operation> saveToscaArtifactPayload(ArtifactDefinition artifactDefinition,
+                                                                           org.openecomp.sdc.be.model.Component component, User user,
+                                                                           boolean isInCertificationRequest, boolean shouldLock,
+                                                                           boolean inTransaction, boolean fetchTemplatesFromDB) {
+        return artifactsBusinessLogic
+            .generateAndSaveToscaArtifact(artifactDefinition, component, user, isInCertificationRequest, shouldLock, inTransaction,
+                fetchTemplatesFromDB);
     }
 
-    public ImmutablePair<String, byte[]> getToscaModelByComponentUuid(ComponentTypeEnum componentType, String uuid, ResourceCommonInfo resourceCommonInfo) {
-
+    public ImmutablePair<String, byte[]> getToscaModelByComponentUuid(ComponentTypeEnum componentType, String uuid,
+                                                                      ResourceCommonInfo resourceCommonInfo) {
         Either<List<Component>, StorageOperationStatus> latestVersionEither = toscaOperationFacade.getComponentListByUuid(uuid, null);
-
         if (latestVersionEither.isRight()) {
-            throw new ByActionStatusComponentException(componentsUtils.convertFromStorageResponse(latestVersionEither.right().value(), componentType));
+            throw new ByActionStatusComponentException(
+                componentsUtils.convertFromStorageResponse(latestVersionEither.right().value(), componentType));
         }
-
         List<Component> components = latestVersionEither.left().value();
-
         Component component = components.stream().filter(Component::isHighestVersion).findFirst().orElse(null);
-        if(component == null){
+        if (component == null) {
             component = components.stream().filter(c -> c.getLifecycleState() == LifecycleStateEnum.CERTIFIED).findFirst().orElse(null);
         }
-
-        if(component == null){
-            throw new ByResponseFormatComponentException(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(StorageOperationStatus.NOT_FOUND, componentType)));
+        if (component == null) {
+            throw new ByResponseFormatComponentException(
+                componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(StorageOperationStatus.NOT_FOUND, componentType)));
         }
         resourceCommonInfo.setResourceName(component.getName());
         // TODO remove after migration - handle artifact not found(no
+
         // placeholder)
         if (null == component.getToscaArtifacts() || component.getToscaArtifacts().isEmpty()) {
-            throw new ByResponseFormatComponentException(componentsUtils.getResponseFormat(ActionStatus.ARTIFACT_NOT_FOUND, ArtifactTypeEnum.TOSCA_CSAR.name()));
+            throw new ByResponseFormatComponentException(
+                componentsUtils.getResponseFormat(ActionStatus.ARTIFACT_NOT_FOUND, ArtifactTypeEnum.TOSCA_CSAR.name()));
         }
         ArtifactDefinition csarArtifact = component.getToscaArtifacts().values().stream()
-                .filter(p -> p.getArtifactType().equals(ArtifactTypeEnum.TOSCA_CSAR.getType()))
-                .findAny().get();
+            .filter(p -> p.getArtifactType().equals(ArtifactTypeEnum.TOSCA_CSAR.getType())).findAny().get();
         return artifactsBusinessLogic.handleDownloadToscaModelRequest(component, csarArtifact);
     }
 
     protected StorageOperationStatus markComponentToDelete(Component component) {
-
         ComponentTypeEnum componentType = component.getComponentType();
         String uniqueId = component.getUniqueId();
         if (Boolean.TRUE.equals(component.getIsDeleted())) {
             log.info("component {} already marked as deleted. id= {}, type={}", component.getName(), uniqueId, componentType);
             return StorageOperationStatus.NOT_FOUND;
         }
-
         StorageOperationStatus markResourceToDelete = toscaOperationFacade.markComponentToDelete(component);
         if (StorageOperationStatus.OK != markResourceToDelete) {
             log.debug("failed to mark component {} of type {} for delete. error = {}", uniqueId, componentType, markResourceToDelete);
@@ -596,7 +563,8 @@ public abstract class ComponentBusinessLogic extends BaseBusinessLogic {
         }
     }
 
-    public Either<Boolean, ResponseFormat> validateAndUpdateDescription(User user, Component currentComponent, Component updatedComponent, AuditingActionEnum auditingAction) {
+    public Either<Boolean, ResponseFormat> validateAndUpdateDescription(User user, Component currentComponent, Component updatedComponent,
+                                                                        AuditingActionEnum auditingAction) {
         String descriptionUpdated = updatedComponent.getDescription();
         String descriptionCurrent = currentComponent.getDescription();
         if (descriptionUpdated != null && !descriptionCurrent.equals(descriptionUpdated)) {
@@ -621,7 +589,8 @@ public abstract class ComponentBusinessLogic extends BaseBusinessLogic {
         return Either.left(true);
     }
 
-    public Either<Boolean, ResponseFormat> validateAndUpdateIcon(User user, Component currentComponent, Component updatedComponent, boolean hasBeenCertified) {
+    public Either<Boolean, ResponseFormat> validateAndUpdateIcon(User user, Component currentComponent, Component updatedComponent,
+                                                                 boolean hasBeenCertified) {
         String iconUpdated = updatedComponent.getIcon();
         String iconCurrent = currentComponent.getIcon();
         if (iconUpdated != null && !iconCurrent.equals(iconUpdated)) {
@@ -630,7 +599,8 @@ public abstract class ComponentBusinessLogic extends BaseBusinessLogic {
                 currentComponent.setIcon(updatedComponent.getIcon());
             } else {
                 log.info("icon {} cannot be updated once the component has been certified once.", iconUpdated);
-                ResponseFormat errorResponse = componentsUtils.getResponseFormat(ActionStatus.COMPONENT_PARAMETER_CANNOT_BE_CHANGED, "Icon", currentComponent.getComponentType().name().toLowerCase());
+                ResponseFormat errorResponse = componentsUtils.getResponseFormat(ActionStatus.COMPONENT_PARAMETER_CANNOT_BE_CHANGED, "Icon",
+                    currentComponent.getComponentType().name().toLowerCase());
                 return Either.right(errorResponse);
             }
         }
@@ -638,14 +608,12 @@ public abstract class ComponentBusinessLogic extends BaseBusinessLogic {
     }
 
     protected Either<List<String>, ResponseFormat> deleteMarkedComponents(ComponentTypeEnum componentType) {
-
         log.trace("start deleteMarkedComponents");
         Either<List<String>, StorageOperationStatus> deleteMarkedElements = toscaOperationFacade.deleteMarkedElements(componentType);
-
-
-        if ( deleteMarkedElements.isRight()){
+        if (deleteMarkedElements.isRight()) {
             janusGraphDao.rollback();
-            ResponseFormat responseFormat = componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(deleteMarkedElements.right().value(), componentType));
+            ResponseFormat responseFormat = componentsUtils
+                .getResponseFormat(componentsUtils.convertFromStorageResponse(deleteMarkedElements.right().value(), componentType));
             return Either.right(responseFormat);
         }
         log.trace("end deleteMarkedComponents");
@@ -668,32 +636,27 @@ public abstract class ComponentBusinessLogic extends BaseBusinessLogic {
     }
 
     /**
-     *
      * @param componentId
      * @param user
      * @param dataParamsToReturn - ui list of params to return
      * @return
      */
-
-    public Either<UiComponentDataTransfer, ResponseFormat> getComponentDataFilteredByParams(String componentId, User user, List<String> dataParamsToReturn) {
-
+    public Either<UiComponentDataTransfer, ResponseFormat> getComponentDataFilteredByParams(String componentId, User user,
+                                                                                            List<String> dataParamsToReturn) {
         if (user != null) {
             validateUserExists(user);
         }
-
-        UiComponentDataTransfer result =  new UiComponentDataTransfer();
-
-        if(dataParamsToReturn == null ||  dataParamsToReturn.isEmpty()) {
+        UiComponentDataTransfer result = new UiComponentDataTransfer();
+        if (dataParamsToReturn == null || dataParamsToReturn.isEmpty()) {
             Either.left(result);
-
         } else {
-            Either<UiComponentDataTransfer, ResponseFormat> uiDataTransferEither = getUiComponentDataTransferByComponentId(componentId, dataParamsToReturn);
-            if(uiDataTransferEither.isRight()){
+            Either<UiComponentDataTransfer, ResponseFormat> uiDataTransferEither = getUiComponentDataTransferByComponentId(componentId,
+                dataParamsToReturn);
+            if (uiDataTransferEither.isRight()) {
                 return Either.right(uiDataTransferEither.right().value());
             }
             result = uiDataTransferEither.left().value();
         }
-
         return Either.left(result);
     }
 
@@ -701,7 +664,7 @@ public abstract class ComponentBusinessLogic extends BaseBusinessLogic {
         List<InputDefinition> genericAndComponentInputs = new ArrayList<>();
         List<InputDefinition> genericInputs = genericTypeBusinessLogic.generateInputsFromGenericTypeProperties(genericType);
         genericAndComponentInputs.addAll(genericInputs);
-        if (null != component.getInputs()){
+        if (null != component.getInputs()) {
             List<InputDefinition> nonGenericInputsFromComponent = getAllNonGenericInputsFromComponent(genericInputs, component.getInputs());
             genericAndComponentInputs.addAll(nonGenericInputsFromComponent);
         }
@@ -712,7 +675,6 @@ public abstract class ComponentBusinessLogic extends BaseBusinessLogic {
         if (genericInputs == null) {
             return componentInputs;
         }
-
         Map<String, InputDefinition> inputByNameMap = MapUtil.toMap(genericInputs, InputDefinition::getName);
         List<InputDefinition> componentNonGenericInputs = new ArrayList<>();
         componentInputs.stream().forEach(input -> {
@@ -723,9 +685,9 @@ public abstract class ComponentBusinessLogic extends BaseBusinessLogic {
         return componentNonGenericInputs;
     }
 
-    protected <T extends Component> Resource fetchAndSetDerivedFromGenericType(T component){
+    protected <T extends Component> Resource fetchAndSetDerivedFromGenericType(T component) {
         Either<Resource, ResponseFormat> genericTypeEither = this.genericTypeBusinessLogic.fetchDerivedFromGenericType(component);
-        if(genericTypeEither.isRight()){
+        if (genericTypeEither.isRight()) {
             log.debug("Failed to fetch latest generic type for component {} of type", component.getName(), component.assetType());
             throw new ByActionStatusComponentException(ActionStatus.GENERIC_TYPE_NOT_FOUND, component.assetType());
         }
@@ -734,30 +696,33 @@ public abstract class ComponentBusinessLogic extends BaseBusinessLogic {
         return genericTypeResource;
     }
 
-    public Either<Map<String, List<IComponentInstanceConnectedElement>>, ResponseFormat> getFilteredComponentInstanceProperties(String componentId, Map<FilterKeyEnum, List<String>> filters, String userId) {
+    public Either<Map<String, List<IComponentInstanceConnectedElement>>, ResponseFormat> getFilteredComponentInstanceProperties(String componentId,
+                                                                                                                                Map<FilterKeyEnum, List<String>> filters,
+                                                                                                                                String userId) {
         Either<Map<String, List<IComponentInstanceConnectedElement>>, ResponseFormat> response = null;
         Either<Component, StorageOperationStatus> getResourceRes = null;
-        try{
-            if(!filters.containsKey(FilterKeyEnum.NAME_FRAGMENT) && StringUtils.isEmpty(filters.get(FilterKeyEnum.NAME_FRAGMENT).get(0))){
+        try {
+            if (!filters.containsKey(FilterKeyEnum.NAME_FRAGMENT) && StringUtils.isEmpty(filters.get(FilterKeyEnum.NAME_FRAGMENT).get(0))) {
                 response = Either.right(componentsUtils.getResponseFormat(ActionStatus.INVALID_CONTENT));
             }
             if (userId != null && response == null) {
                 validateUserExists(userId);
             }
-            if(response == null){
+            if (response == null) {
                 getResourceRes = toscaOperationFacade.getToscaElement(componentId);
-                if(getResourceRes.isRight()){
-                    response = Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(getResourceRes.right().value())));
+                if (getResourceRes.isRight()) {
+                    response = Either
+                        .right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(getResourceRes.right().value())));
                 }
             }
-            if(response == null){
+            if (response == null) {
                 response = getFilteredComponentInstancesProperties(getResourceRes.left().value(), filters);
             }
-        } catch(Exception e){
+        } catch (Exception e) {
             log.debug("The exception {} occured during filtered instance properties fetching. the  containing component is {}. ", e, componentId);
             response = Either.right(componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR));
-        } finally{
-            if (response != null && response.isLeft()){
+        } finally {
+            if (response != null && response.isLeft()) {
                 toscaOperationFacade.commit();
             } else {
                 toscaOperationFacade.rollback();
@@ -766,22 +731,25 @@ public abstract class ComponentBusinessLogic extends BaseBusinessLogic {
         return response;
     }
 
-    private Either<Map<String, List<IComponentInstanceConnectedElement>>, ResponseFormat> getFilteredComponentInstancesProperties(Component component, Map<FilterKeyEnum, List<String>> filters) {
-
-        Map<String,  List<IComponentInstanceConnectedElement>> filteredProperties = new HashMap<>();
+    private Either<Map<String, List<IComponentInstanceConnectedElement>>, ResponseFormat> getFilteredComponentInstancesProperties(Component component,
+                                                                                                                                  Map<FilterKeyEnum, List<String>> filters) {
+        Map<String, List<IComponentInstanceConnectedElement>> filteredProperties = new HashMap<>();
         Either<Map<String, List<IComponentInstanceConnectedElement>>, ResponseFormat> result = Either.left(filteredProperties);
         List<ComponentInstance> filteredInstances = getFilteredInstances(component, filters.get(FilterKeyEnum.RESOURCE_TYPE));
-        String propertyNameFragment= filters.get(FilterKeyEnum.NAME_FRAGMENT).get(0);
-        boolean searchByFragment = propertyNameFragment.length() > 3 ;
-        if(CollectionUtils.isNotEmpty(filteredInstances)){
-            for(ComponentInstance instance : filteredInstances){
-                if(component.getComponentInstancesProperties()!=null &&component.getComponentInstancesProperties().containsKey(instance.getUniqueId())){
-                    List<IComponentInstanceConnectedElement> currProperties =  getFilteredComponentInstanceProperties(component.getComponentInstancesProperties().get(instance.getUniqueId()), propertyNameFragment, searchByFragment);
+        String propertyNameFragment = filters.get(FilterKeyEnum.NAME_FRAGMENT).get(0);
+        boolean searchByFragment = propertyNameFragment.length() > 3;
+        if (CollectionUtils.isNotEmpty(filteredInstances)) {
+            for (ComponentInstance instance : filteredInstances) {
+                if (component.getComponentInstancesProperties() != null && component.getComponentInstancesProperties()
+                    .containsKey(instance.getUniqueId())) {
+                    List<IComponentInstanceConnectedElement> currProperties = getFilteredComponentInstanceProperties(
+                        component.getComponentInstancesProperties().get(instance.getUniqueId()), propertyNameFragment, searchByFragment);
                     setFilteredProperties(filteredProperties, instance, currProperties);
                 }
-                if(component.getComponentInstancesInputs()!=null && component.getComponentInstancesInputs().containsKey(instance.getUniqueId())){
-                    List<IComponentInstanceConnectedElement> currInputs =  getFilteredComponentInstanceInputs(component.getComponentInstancesInputs().get(instance.getUniqueId()), propertyNameFragment, searchByFragment);
-                    if(CollectionUtils.isNotEmpty(currInputs)){
+                if (component.getComponentInstancesInputs() != null && component.getComponentInstancesInputs().containsKey(instance.getUniqueId())) {
+                    List<IComponentInstanceConnectedElement> currInputs = getFilteredComponentInstanceInputs(
+                        component.getComponentInstancesInputs().get(instance.getUniqueId()), propertyNameFragment, searchByFragment);
+                    if (CollectionUtils.isNotEmpty(currInputs)) {
                         checkFilteredProperties(filteredProperties, instance, currInputs);
                     }
                 }
@@ -790,34 +758,38 @@ public abstract class ComponentBusinessLogic extends BaseBusinessLogic {
         return result;
     }
 
-    private void setFilteredProperties(Map<String, List<IComponentInstanceConnectedElement>> filteredProperties, ComponentInstance instance, List<IComponentInstanceConnectedElement> currProperties) {
-        if(CollectionUtils.isNotEmpty(currProperties)){
+    private void setFilteredProperties(Map<String, List<IComponentInstanceConnectedElement>> filteredProperties, ComponentInstance instance,
+                                       List<IComponentInstanceConnectedElement> currProperties) {
+        if (CollectionUtils.isNotEmpty(currProperties)) {
             filteredProperties.put(instance.getUniqueId(), currProperties);
         }
     }
 
-    private void checkFilteredProperties(Map<String, List<IComponentInstanceConnectedElement>> filteredProperties, ComponentInstance instance, List<IComponentInstanceConnectedElement> currInputs) {
-        if(filteredProperties.get(instance.getUniqueId())!=null){
+    private void checkFilteredProperties(Map<String, List<IComponentInstanceConnectedElement>> filteredProperties, ComponentInstance instance,
+                                         List<IComponentInstanceConnectedElement> currInputs) {
+        if (filteredProperties.get(instance.getUniqueId()) != null) {
             filteredProperties.get(instance.getUniqueId()).addAll(currInputs);
         } else {
             filteredProperties.put(instance.getUniqueId(), currInputs);
         }
     }
 
-    private List<IComponentInstanceConnectedElement> getFilteredComponentInstanceInputs(List<ComponentInstanceInput> inputs, String propertyNameFragment, boolean searchByFragment) {
+    private List<IComponentInstanceConnectedElement> getFilteredComponentInstanceInputs(List<ComponentInstanceInput> inputs,
+                                                                                        String propertyNameFragment, boolean searchByFragment) {
         return inputs.stream().filter(i -> isMatchingInput(i, propertyNameFragment, searchByFragment)).collect(Collectors.toList());
     }
 
-    private List<IComponentInstanceConnectedElement> getFilteredComponentInstanceProperties(List<ComponentInstanceProperty> instanceProperties, String propertyNameFragment, boolean searchByFragment) {
+    private List<IComponentInstanceConnectedElement> getFilteredComponentInstanceProperties(List<ComponentInstanceProperty> instanceProperties,
+                                                                                            String propertyNameFragment, boolean searchByFragment) {
         return instanceProperties.stream().filter(p -> isMatchingProperty(p, propertyNameFragment, searchByFragment)).collect(Collectors.toList());
     }
 
     private boolean isMatchingInput(ComponentInstanceInput input, String propertyNameFragment, boolean searchByFragment) {
         boolean isMatching = false;
-        if(searchByFragment && input.getName().toLowerCase().contains(propertyNameFragment)){
+        if (searchByFragment && input.getName().toLowerCase().contains(propertyNameFragment)) {
             isMatching = true;
         }
-        if(!searchByFragment && input.getName().equalsIgnoreCase(propertyNameFragment)){
+        if (!searchByFragment && input.getName().equalsIgnoreCase(propertyNameFragment)) {
             isMatching = true;
         }
         return isMatching;
@@ -825,56 +797,50 @@ public abstract class ComponentBusinessLogic extends BaseBusinessLogic {
 
     private boolean isMatchingProperty(ComponentInstanceProperty property, String propertyNameFragment, boolean searchByFragment) {
         boolean isMatching = false;
-        if(searchByFragment && property.getName().toLowerCase().contains(propertyNameFragment)){
+        if (searchByFragment && property.getName().toLowerCase().contains(propertyNameFragment)) {
             isMatching = true;
         }
-        if(!searchByFragment && property.getName().equalsIgnoreCase(propertyNameFragment)){
+        if (!searchByFragment && property.getName().equalsIgnoreCase(propertyNameFragment)) {
             isMatching = true;
         }
-        if (!isMatching && !ToscaPropertyType.isPrimitiveType(property.getType())){
+        if (!isMatching && !ToscaPropertyType.isPrimitiveType(property.getType())) {
             isMatching = isMatchingComplexPropertyByRecursively(property, propertyNameFragment, searchByFragment);
         }
         return isMatching;
     }
 
-    private boolean isMatchingComplexPropertyByRecursively(PropertyDataDefinition property, String propertyNameFragment,  boolean searchByFragment) {
+    private boolean isMatchingComplexPropertyByRecursively(PropertyDataDefinition property, String propertyNameFragment, boolean searchByFragment) {
         String propertyType;
-        List<PropertyDefinition>  dataTypeProperties;
+        List<PropertyDefinition> dataTypeProperties;
         DataTypeDefinition currentProperty;
-        if(searchByFragment && property.getName().toLowerCase().contains(propertyNameFragment.toLowerCase())){
+        if (searchByFragment && property.getName().toLowerCase().contains(propertyNameFragment.toLowerCase())) {
             return true;
         }
-        if(!searchByFragment && property.getName().equalsIgnoreCase(propertyNameFragment)){
+        if (!searchByFragment && property.getName().equalsIgnoreCase(propertyNameFragment)) {
             return true;
         }
-
         propertyType = isEmptyInnerType(property) ? property.getType() : property.getSchema().getProperty().getType();
-
-        if(ToscaPropertyType.isScalarType(propertyType)){
+        if (ToscaPropertyType.isScalarType(propertyType)) {
             return false;
         }
-        Either<DataTypeDefinition, StorageOperationStatus>  getDataTypeByNameRes = propertyOperation.getDataTypeByName(propertyType);
-        if(getDataTypeByNameRes.isRight()){
+        Either<DataTypeDefinition, StorageOperationStatus> getDataTypeByNameRes = propertyOperation.getDataTypeByName(propertyType);
+        if (getDataTypeByNameRes.isRight()) {
             return false;
         }
         currentProperty = getDataTypeByNameRes.left().value();
         dataTypeProperties = currentProperty.getProperties();
-
         boolean dataPropertiesNotNull = CollectionUtils.isNotEmpty(dataTypeProperties);
-        BooleanSupplier dataMatchesComplexProperty = () -> isMatchingComplexProperty(propertyNameFragment,
-            searchByFragment, dataTypeProperties);
-        BooleanSupplier parentPropertiesNotNull = () -> CollectionUtils
-            .isNotEmpty(currentProperty.getDerivedFrom().getProperties());
-        BooleanSupplier parentDataMatchesComplexProperty = () -> isMatchingComplexProperty(propertyNameFragment,
-            searchByFragment, currentProperty.getDerivedFrom().getProperties());
-
-        return ((dataPropertiesNotNull && dataMatchesComplexProperty.getAsBoolean())
-            || (parentPropertiesNotNull.getAsBoolean() && parentDataMatchesComplexProperty.getAsBoolean()));
+        BooleanSupplier dataMatchesComplexProperty = () -> isMatchingComplexProperty(propertyNameFragment, searchByFragment, dataTypeProperties);
+        BooleanSupplier parentPropertiesNotNull = () -> CollectionUtils.isNotEmpty(currentProperty.getDerivedFrom().getProperties());
+        BooleanSupplier parentDataMatchesComplexProperty = () -> isMatchingComplexProperty(propertyNameFragment, searchByFragment,
+            currentProperty.getDerivedFrom().getProperties());
+        return ((dataPropertiesNotNull && dataMatchesComplexProperty.getAsBoolean()) || (parentPropertiesNotNull.getAsBoolean()
+            && parentDataMatchesComplexProperty.getAsBoolean()));
     }
 
     private boolean isMatchingComplexProperty(String propertyNameFragment, boolean searchByFragment, List<PropertyDefinition> dataTypeProperties) {
-        for(PropertyDefinition prop : dataTypeProperties){
-            if(isMatchingComplexPropertyByRecursively(prop, propertyNameFragment, searchByFragment)){
+        for (PropertyDefinition prop : dataTypeProperties) {
+            if (isMatchingComplexPropertyByRecursively(prop, propertyNameFragment, searchByFragment)) {
                 return true;
             }
         }
@@ -882,20 +848,22 @@ public abstract class ComponentBusinessLogic extends BaseBusinessLogic {
     }
 
     private boolean isEmptyInnerType(PropertyDataDefinition property) {
-        return property == null|| property.getSchema() == null || property.getSchema().getProperty() == null || property.getSchema().getProperty().getType() == null;
+        return property == null || property.getSchema() == null || property.getSchema().getProperty() == null
+            || property.getSchema().getProperty().getType() == null;
     }
 
     public Either<Boolean, ResponseFormat> shouldUpgradeToLatestGeneric(Component clonedComponent) {
-
-        if(!clonedComponent.deriveFromGeneric())
+        if (!clonedComponent.deriveFromGeneric()) {
             return Either.left(false);
+        }
         Boolean shouldUpgrade = false;
         String currentGenericType = clonedComponent.getDerivedFromGenericType();
         String currentGenericVersion = clonedComponent.getDerivedFromGenericVersion();
         Resource genericTypeResource = fetchAndSetDerivedFromGenericType(clonedComponent);
-        if(null == currentGenericType || !currentGenericType.equals(genericTypeResource.getToscaResourceName()) || !currentGenericVersion.equals(genericTypeResource.getVersion())){
+        if (null == currentGenericType || !currentGenericType.equals(genericTypeResource.getToscaResourceName()) || !currentGenericVersion
+            .equals(genericTypeResource.getVersion())) {
             shouldUpgrade = upgradeToLatestGeneric(clonedComponent, genericTypeResource);
-            if(!shouldUpgrade) {
+            if (!shouldUpgrade) {
                 reverntUpdateOfGenericVersion(clonedComponent, currentGenericType, currentGenericVersion);
             }
         }
@@ -907,42 +875,45 @@ public abstract class ComponentBusinessLogic extends BaseBusinessLogic {
         clonedComponent.setDerivedFromGenericVersion(currentGenericVersion);
     }
 
-    private <T extends ToscaDataDefinition> Either<Map<String, T>, String> validateNoConflictingProperties(List<T> currentList, List<T> upgradedList) {
+    private <T extends ToscaDataDefinition> Either<Map<String, T>, String> validateNoConflictingProperties(List<T> currentList,
+                                                                                                           List<T> upgradedList) {
         Map<String, T> currentMap = ToscaDataDefinition.listToMapByName(currentList);
         Map<String, T> upgradedMap = ToscaDataDefinition.listToMapByName(upgradedList);
         return ToscaDataDefinition.mergeDataMaps(upgradedMap, currentMap, true);
     }
 
-    private boolean shouldUpgradeNodeType(Component componentToCheckOut, Resource latestGeneric){
-
+    private boolean shouldUpgradeNodeType(Component componentToCheckOut, Resource latestGeneric) {
         List<PropertyDefinition> genericTypeProps = latestGeneric.getProperties();
-        Either<Map<String, PropertyDefinition>, String> validPropertiesMerge = validateNoConflictingProperties(genericTypeProps, ((Resource)componentToCheckOut).getProperties());
+        Either<Map<String, PropertyDefinition>, String> validPropertiesMerge = validateNoConflictingProperties(genericTypeProps,
+            ((Resource) componentToCheckOut).getProperties());
         if (validPropertiesMerge.isRight()) {
-            log.debug("property {} cannot be overriden, check out performed without upgrading to latest generic", validPropertiesMerge.right().value());
+            log.debug("property {} cannot be overriden, check out performed without upgrading to latest generic",
+                validPropertiesMerge.right().value());
             return false;
         }
         List<AttributeDefinition> genericTypeAttributes = latestGeneric.getAttributes();
-        final Either<Map<String, AttributeDefinition>, String> validAttributesMerge = validateNoConflictingProperties(
-            genericTypeAttributes, ((Resource) componentToCheckOut).getAttributes());
+        final Either<Map<String, AttributeDefinition>, String> validAttributesMerge = validateNoConflictingProperties(genericTypeAttributes,
+            ((Resource) componentToCheckOut).getAttributes());
         if (validAttributesMerge.isRight()) {
-            log.debug("attribute {} cannot be overriden, check out performed without upgrading to latest generic", validAttributesMerge.right().value());
+            log.debug("attribute {} cannot be overriden, check out performed without upgrading to latest generic",
+                validAttributesMerge.right().value());
             return false;
         }
         return true;
     }
 
     private boolean upgradeToLatestGeneric(Component componentToCheckOut, Resource latestGeneric) {
-
         if (!componentToCheckOut.shouldGenerateInputs()) {
             //node type - validate properties and attributes
             return shouldUpgradeNodeType(componentToCheckOut, latestGeneric);
         }
         List<PropertyDefinition> genericTypeProps = latestGeneric.getProperties();
-        List<InputDefinition> genericTypeInputs = null == genericTypeProps? null : genericTypeBusinessLogic.convertGenericTypePropertiesToInputsDefintion(genericTypeProps, latestGeneric.getUniqueId());
+        List<InputDefinition> genericTypeInputs = null == genericTypeProps ? null
+            : genericTypeBusinessLogic.convertGenericTypePropertiesToInputsDefintion(genericTypeProps, latestGeneric.getUniqueId());
         List<InputDefinition> currentList = new ArrayList<>();
         // nullify existing ownerId from existing list and merge into updated list
         if (null != componentToCheckOut.getInputs()) {
-            for(InputDefinition input : componentToCheckOut.getInputs()) {
+            for (InputDefinition input : componentToCheckOut.getInputs()) {
                 InputDefinition copy = new InputDefinition(input);
                 copy.setOwnerId(null);
                 currentList.add(copy);
@@ -952,7 +923,6 @@ public abstract class ComponentBusinessLogic extends BaseBusinessLogic {
             componentToCheckOut.setInputs(currentList);
             return true;
         }
-
         Either<Map<String, InputDefinition>, String> eitherMerged = validateNoConflictingProperties(genericTypeInputs, currentList);
         if (eitherMerged.isRight()) {
             log.debug("input {} cannot be overriden, check out performed without upgrading to latest generic", eitherMerged.right().value());
@@ -962,17 +932,15 @@ public abstract class ComponentBusinessLogic extends BaseBusinessLogic {
         return true;
     }
 
-
     private List<ComponentInstance> getFilteredInstances(Component component, List<String> resourceTypes) {
         List<ComponentInstance> filteredInstances = null;
-        if(CollectionUtils.isEmpty(resourceTypes)){
+        if (CollectionUtils.isEmpty(resourceTypes)) {
             filteredInstances = component.getComponentInstances();
+        } else if (CollectionUtils.isNotEmpty(component.getComponentInstances())) {
+            filteredInstances = component.getComponentInstances().stream().filter(i -> isMatchingType(i.getOriginType(), resourceTypes))
+                .collect(Collectors.toList());
         }
-        else if(CollectionUtils.isNotEmpty(component.getComponentInstances())){
-            filteredInstances = component.getComponentInstances()
-                    .stream().filter(i -> isMatchingType(i.getOriginType(), resourceTypes)).collect(Collectors.toList());
-        }
-        if(filteredInstances == null){
+        if (filteredInstances == null) {
             filteredInstances = new ArrayList<>();
         }
         return filteredInstances;
@@ -980,8 +948,8 @@ public abstract class ComponentBusinessLogic extends BaseBusinessLogic {
 
     private boolean isMatchingType(OriginTypeEnum originType, List<String> resourceTypes) {
         boolean isMatchingType = false;
-        for(String resourceType : resourceTypes){
-            if(originType == OriginTypeEnum.findByValue(resourceType.toUpperCase())){
+        for (String resourceType : resourceTypes) {
+            if (originType == OriginTypeEnum.findByValue(resourceType.toUpperCase())) {
                 isMatchingType = true;
                 break;
             }
@@ -994,14 +962,14 @@ public abstract class ComponentBusinessLogic extends BaseBusinessLogic {
         return Either.right(ActionStatus.GENERAL_ERROR);
     }
 
-    protected Either<Component, ResponseFormat>  updateCatalog(Component component, ChangeTypeEnum changeStatus){
-        log.debug("update Catalog start with Component Type {} And Componet Name {} with change status {}", component.getComponentType().name(), component.getName(), changeStatus.name());
-        ActionStatus status =  catalogOperations.updateCatalog(changeStatus,component);
-        if(status != ActionStatus.OK){
-            return Either.right( componentsUtils.getResponseFormat(status));
+    protected Either<Component, ResponseFormat> updateCatalog(Component component, ChangeTypeEnum changeStatus) {
+        log.debug("update Catalog start with Component Type {} And Componet Name {} with change status {}", component.getComponentType().name(),
+            component.getName(), changeStatus.name());
+        ActionStatus status = catalogOperations.updateCatalog(changeStatus, component);
+        if (status != ActionStatus.OK) {
+            return Either.right(componentsUtils.getResponseFormat(status));
         }
-
-       return Either.left(component);
+        return Either.left(component);
     }
 
     public CatalogOperation getCatalogOperations() {
@@ -1016,5 +984,4 @@ public abstract class ComponentBusinessLogic extends BaseBusinessLogic {
     public List<GroupDefinition> throwComponentException(ResponseFormat responseFormat) {
         throw new ByResponseFormatComponentException(responseFormat);
     }
-
 }
index 1e0f686..0a7758d 100644 (file)
@@ -34,7 +34,8 @@ public class ComponentBusinessLogicProvider {
     private final ServiceBusinessLogic serviceBusinessLogic;
     private final ProductBusinessLogic productBusinessLogic;
 
-    public ComponentBusinessLogicProvider(ResourceBusinessLogic resourceBusinessLogic, ServiceBusinessLogic serviceBusinessLogic, ProductBusinessLogic productBusinessLogic) {
+    public ComponentBusinessLogicProvider(ResourceBusinessLogic resourceBusinessLogic, ServiceBusinessLogic serviceBusinessLogic,
+                                          ProductBusinessLogic productBusinessLogic) {
         this.resourceBusinessLogic = resourceBusinessLogic;
         this.serviceBusinessLogic = serviceBusinessLogic;
         this.productBusinessLogic = productBusinessLogic;
@@ -43,16 +44,15 @@ public class ComponentBusinessLogicProvider {
     public ComponentBusinessLogic getInstance(ComponentTypeEnum componentTypeEnum) {
         switch (componentTypeEnum) {
             case SERVICE:
-               return serviceBusinessLogic;
+                return serviceBusinessLogic;
             case PRODUCT:
-               return productBusinessLogic;
+                return productBusinessLogic;
             case RESOURCE:
             case RESOURCE_INSTANCE:
-               return resourceBusinessLogic;
+                return resourceBusinessLogic;
             default:
                 BeEcompErrorManager.getInstance().logBeSystemError("getInstance");
                 throw new ByActionStatusComponentException(ActionStatus.INVALID_CONTENT, componentTypeEnum.getValue());
         }
     }
-
 }
index a18d8dc..8515c5c 100644 (file)
@@ -17,7 +17,6 @@
  * limitations under the License.
  * ============LICENSE_END=========================================================
  */
-
 package org.openecomp.sdc.be.components.impl;
 
 import static org.openecomp.sdc.be.components.attribute.GetOutputUtils.isGetOutputValueForOutput;
@@ -142,7 +141,7 @@ public class ComponentInstanceBusinessLogic extends BaseBusinessLogic {
     private static final String TRY_TO_CREATE_ENTRY_ON_GRAPH = "Try to create entry on graph";
     private static final String CLOUD_SPECIFIC_FIXED_KEY_WORD = "cloudtech";
     private static final String[][] CLOUD_SPECIFIC_KEY_WORDS = {{"k8s", "azure", "aws"}, /* cloud specific technology */
-                                                                {"charts", "day0", "configtemplate"} /*cloud specific sub type*/};
+        {"charts", "day0", "configtemplate"} /*cloud specific sub type*/};
     private static final String FAILED_TO_CREATE_ENTRY_ON_GRAPH_FOR_COMPONENT_INSTANCE = "Failed to create entry on graph for component instance {}";
     private static final String ENTITY_ON_GRAPH_IS_CREATED = "Entity on graph is created.";
     private static final String INVALID_COMPONENT_TYPE = "invalid component type";
@@ -154,28 +153,28 @@ public class ComponentInstanceBusinessLogic extends BaseBusinessLogic {
     private static final String CANNOT_ATTACH_RESOURCE_INSTANCES_TO_CONTAINER_RESOURCE_OF_TYPE = "Cannot attach resource instances to container resource of type {}";
     private static final String SERVICE_PROXY = "serviceProxy";
     private static final String ASSOCIATE_RI_TO_RI = "associateRIToRI";
-
     private ComponentInstanceOperation componentInstanceOperation;
     private ArtifactsBusinessLogic artifactBusinessLogic;
     private ComponentInstanceMergeDataBusinessLogic compInstMergeDataBL;
     private ComponentInstanceChangeOperationOrchestrator onChangeInstanceOperationOrchestrator;
     private ForwardingPathOperation forwardingPathOperation;
     private NodeFilterOperation nodeFilterOperation;
+    @Autowired
+    private CompositionBusinessLogic compositionBusinessLogic;
+    @Autowired
+    private ContainerInstanceTypesData containerInstanceTypesData;
 
     @Autowired
-    public ComponentInstanceBusinessLogic(IElementOperation elementDao,
-        IGroupOperation groupOperation,
-        IGroupInstanceOperation groupInstanceOperation,
-        IGroupTypeOperation groupTypeOperation,
-        InterfaceOperation interfaceOperation,
-        InterfaceLifecycleOperation interfaceLifecycleTypeOperation,
-        ComponentInstanceOperation componentInstanceOperation, ArtifactsBusinessLogic artifactBusinessLogic,
-        ComponentInstanceMergeDataBusinessLogic compInstMergeDataBL,
-        ComponentInstanceChangeOperationOrchestrator onChangeInstanceOperationOrchestrator,
-        ForwardingPathOperation forwardingPathOperation, NodeFilterOperation nodeFilterOperation,
-        ArtifactsOperations artifactToscaOperation) {
-        super(elementDao, groupOperation, groupInstanceOperation, groupTypeOperation,
-            interfaceOperation, interfaceLifecycleTypeOperation, artifactToscaOperation);
+    public ComponentInstanceBusinessLogic(IElementOperation elementDao, IGroupOperation groupOperation,
+                                          IGroupInstanceOperation groupInstanceOperation, IGroupTypeOperation groupTypeOperation,
+                                          InterfaceOperation interfaceOperation, InterfaceLifecycleOperation interfaceLifecycleTypeOperation,
+                                          ComponentInstanceOperation componentInstanceOperation, ArtifactsBusinessLogic artifactBusinessLogic,
+                                          ComponentInstanceMergeDataBusinessLogic compInstMergeDataBL,
+                                          ComponentInstanceChangeOperationOrchestrator onChangeInstanceOperationOrchestrator,
+                                          ForwardingPathOperation forwardingPathOperation, NodeFilterOperation nodeFilterOperation,
+                                          ArtifactsOperations artifactToscaOperation) {
+        super(elementDao, groupOperation, groupInstanceOperation, groupTypeOperation, interfaceOperation, interfaceLifecycleTypeOperation,
+            artifactToscaOperation);
         this.componentInstanceOperation = componentInstanceOperation;
         this.artifactBusinessLogic = artifactBusinessLogic;
         this.compInstMergeDataBL = compInstMergeDataBL;
@@ -184,26 +183,18 @@ public class ComponentInstanceBusinessLogic extends BaseBusinessLogic {
         this.nodeFilterOperation = nodeFilterOperation;
     }
 
-    @Autowired
-    private CompositionBusinessLogic compositionBusinessLogic;
-
-    @Autowired
-    private ContainerInstanceTypesData containerInstanceTypesData;
-
     public ComponentInstance createComponentInstance(String containerComponentParam, String containerComponentId, String userId,
                                                      ComponentInstance resourceInstance) {
         return createComponentInstance(containerComponentParam, containerComponentId, userId, resourceInstance, true);
     }
 
-    public List<ComponentInstanceProperty> getComponentInstancePropertiesByInputId(org.openecomp.sdc.be.model.Component component,
-                                                                                   String inputId) {
+    public List<ComponentInstanceProperty> getComponentInstancePropertiesByInputId(org.openecomp.sdc.be.model.Component component, String inputId) {
         List<ComponentInstanceProperty> resList = new ArrayList<>();
         Map<String, List<ComponentInstanceProperty>> ciPropertiesMap = component.getComponentInstancesProperties();
         if (ciPropertiesMap != null && !ciPropertiesMap.isEmpty()) {
             ciPropertiesMap.forEach((s, ciPropList) -> {
                 String ciName = "";
-                Optional<ComponentInstance> ciOp = component.getComponentInstances().stream().filter(ci -> ci.getUniqueId().equals(s))
-                    .findAny();
+                Optional<ComponentInstance> ciOp = component.getComponentInstances().stream().filter(ci -> ci.getUniqueId().equals(s)).findAny();
                 if (ciOp.isPresent()) {
                     ciName = ciOp.get().getName();
                 }
@@ -216,7 +207,6 @@ public class ComponentInstanceBusinessLogic extends BaseBusinessLogic {
             });
         }
         return resList;
-
     }
 
     public List<ComponentInstanceAttribute> getComponentInstanceAttributesByOutputId(final org.openecomp.sdc.be.model.Component component,
@@ -226,7 +216,8 @@ public class ComponentInstanceBusinessLogic extends BaseBusinessLogic {
         if (org.apache.commons.collections4.MapUtils.isNotEmpty(componentInstancesAttributes)) {
             componentInstancesAttributes.forEach((s, componentInstanceAttributeList) -> {
                 String ciName = "";
-                final Optional<ComponentInstance> ciOp = component.getComponentInstances().stream().filter(ci -> ci.getUniqueId().equals(s)).findAny();
+                final Optional<ComponentInstance> ciOp = component.getComponentInstances().stream().filter(ci -> ci.getUniqueId().equals(s))
+                    .findAny();
                 if (ciOp.isPresent()) {
                     ciName = ciOp.get().getName();
                 }
@@ -239,7 +230,6 @@ public class ComponentInstanceBusinessLogic extends BaseBusinessLogic {
             });
         }
         return resList;
-
     }
 
     private void addCompInstanceProperty(String s, String ciName, ComponentInstanceProperty prop, List<GetInputValueDataDefinition> inputsValues,
@@ -256,11 +246,8 @@ public class ComponentInstanceBusinessLogic extends BaseBusinessLogic {
         }
     }
 
-    private void addCompInstanceAttribute(final String s,
-                                          final String ciName,
-                                          final ComponentInstanceAttribute attribute,
-                                          final List<GetOutputValueDataDefinition> outputsValues,
-                                          final String outputId,
+    private void addCompInstanceAttribute(final String s, final String ciName, final ComponentInstanceAttribute attribute,
+                                          final List<GetOutputValueDataDefinition> outputsValues, final String outputId,
                                           final List<ComponentInstanceAttribute> resList) {
         if (outputsValues != null && !outputsValues.isEmpty()) {
             for (final GetOutputValueDataDefinition outputData : outputsValues) {
@@ -274,30 +261,23 @@ public class ComponentInstanceBusinessLogic extends BaseBusinessLogic {
         }
     }
 
-    public Optional<ComponentInstanceProperty> getComponentInstancePropertyByPolicyId(Component component,
-                                                                                      PolicyDefinition policy) {
-
+    public Optional<ComponentInstanceProperty> getComponentInstancePropertyByPolicyId(Component component, PolicyDefinition policy) {
         Optional<ComponentInstanceProperty> propertyCandidate = getComponentInstancePropertyByPolicy(component, policy);
-
         if (propertyCandidate.isPresent()) {
             ComponentInstanceProperty componentInstanceProperty = propertyCandidate.get();
-            Optional<GetPolicyValueDataDefinition> getPolicyCandidate =
-                getGetPolicyValueDataDefinition(policy, componentInstanceProperty);
-
-            getPolicyCandidate.ifPresent(getPolicyValue ->
-                updateComponentInstancePropertyAfterUndeclaration(componentInstanceProperty, getPolicyValue, policy));
+            Optional<GetPolicyValueDataDefinition> getPolicyCandidate = getGetPolicyValueDataDefinition(policy, componentInstanceProperty);
+            getPolicyCandidate
+                .ifPresent(getPolicyValue -> updateComponentInstancePropertyAfterUndeclaration(componentInstanceProperty, getPolicyValue, policy));
             return Optional.of(componentInstanceProperty);
         }
-
         return Optional.empty();
-
     }
 
     private void updateComponentInstancePropertyAfterUndeclaration(ComponentInstanceProperty componentInstanceProperty,
-            GetPolicyValueDataDefinition getPolicyValue, PolicyDefinition policyDefinition) {
+                                                                   GetPolicyValueDataDefinition getPolicyValue, PolicyDefinition policyDefinition) {
         componentInstanceProperty.setValue(getPolicyValue.getOrigPropertyValue());
         List<GetPolicyValueDataDefinition> getPolicyValues = componentInstanceProperty.getGetPolicyValues();
-        if(CollectionUtils.isNotEmpty(getPolicyValues)) {
+        if (CollectionUtils.isNotEmpty(getPolicyValues)) {
             getPolicyValues.remove(getPolicyValue);
             componentInstanceProperty.setGetPolicyValues(getPolicyValues);
             policyDefinition.setGetPolicyValues(getPolicyValues);
@@ -305,45 +285,30 @@ public class ComponentInstanceBusinessLogic extends BaseBusinessLogic {
     }
 
     private Optional<GetPolicyValueDataDefinition> getGetPolicyValueDataDefinition(PolicyDefinition policy,
-            ComponentInstanceProperty componentInstanceProperty) {
+                                                                                   ComponentInstanceProperty componentInstanceProperty) {
         List<GetPolicyValueDataDefinition> getPolicyValues = policy.getGetPolicyValues();
-        return getPolicyValues.stream()
-                                                                            .filter(getPolicyValue -> getPolicyValue
-                                                                                                              .getPropertyName()
-                                                                                                              .equals(componentInstanceProperty
-                                                                                                                              .getName()))
-                                                                            .findAny();
+        return getPolicyValues.stream().filter(getPolicyValue -> getPolicyValue.getPropertyName().equals(componentInstanceProperty.getName()))
+            .findAny();
     }
 
-    private Optional<ComponentInstanceProperty> getComponentInstancePropertyByPolicy(Component component,
-            PolicyDefinition policy) {
-        Map<String, List<ComponentInstanceProperty>> componentInstancesProperties =
-                component.getComponentInstancesProperties();
-
-        if(MapUtils.isEmpty(componentInstancesProperties)) {
+    private Optional<ComponentInstanceProperty> getComponentInstancePropertyByPolicy(Component component, PolicyDefinition policy) {
+        Map<String, List<ComponentInstanceProperty>> componentInstancesProperties = component.getComponentInstancesProperties();
+        if (MapUtils.isEmpty(componentInstancesProperties)) {
             return Optional.empty();
         }
-
         String instanceUniqueId = policy.getInstanceUniqueId();
-
         List<ComponentInstanceProperty> componentInstanceProperties =
-                componentInstancesProperties.containsKey(instanceUniqueId)
-                        ? componentInstancesProperties.get(instanceUniqueId)
-                        : new ArrayList<>();
-
-        return componentInstanceProperties
-                       .stream().filter(property -> property.getName().equals(policy.getName())).findAny();
+            componentInstancesProperties.containsKey(instanceUniqueId) ? componentInstancesProperties.get(instanceUniqueId) : new ArrayList<>();
+        return componentInstanceProperties.stream().filter(property -> property.getName().equals(policy.getName())).findAny();
     }
 
-    public List<ComponentInstanceInput> getComponentInstanceInputsByInputId(
-            org.openecomp.sdc.be.model.Component component, String inputId) {
+    public List<ComponentInstanceInput> getComponentInstanceInputsByInputId(org.openecomp.sdc.be.model.Component component, String inputId) {
         List<ComponentInstanceInput> resList = new ArrayList<>();
         Map<String, List<ComponentInstanceInput>> ciInputsMap = component.getComponentInstancesInputs();
         if (ciInputsMap != null && !ciInputsMap.isEmpty()) {
             ciInputsMap.forEach((s, ciPropList) -> {
                 String ciName = "";
-                Optional<ComponentInstance> ciOp = component.getComponentInstances().stream().filter(ci -> ci.getUniqueId().equals(s))
-                    .findAny();
+                Optional<ComponentInstance> ciOp = component.getComponentInstances().stream().filter(ci -> ci.getUniqueId().equals(s)).findAny();
                 if (ciOp.isPresent()) {
                     ciName = ciOp.get().getName();
                 }
@@ -351,13 +316,11 @@ public class ComponentInstanceBusinessLogic extends BaseBusinessLogic {
                     for (ComponentInstanceInput prop : ciPropList) {
                         List<GetInputValueDataDefinition> inputsValues = prop.getGetInputValues();
                         addCompInstanceInput(s, ciName, prop, inputsValues, inputId, resList);
-
                     }
                 }
             });
         }
         return resList;
-
     }
 
     public List<ComponentInstanceOutput> getComponentInstanceOutputsByOutputId(final org.openecomp.sdc.be.model.Component component,
@@ -367,7 +330,8 @@ public class ComponentInstanceBusinessLogic extends BaseBusinessLogic {
         if (ciInputsMap != null && !ciInputsMap.isEmpty()) {
             ciInputsMap.forEach((s, ciPropList) -> {
                 String ciName = "";
-                final Optional<ComponentInstance> ciOp = component.getComponentInstances().stream().filter(ci -> ci.getUniqueId().equals(s)).findAny();
+                final Optional<ComponentInstance> ciOp = component.getComponentInstances().stream().filter(ci -> ci.getUniqueId().equals(s))
+                    .findAny();
                 if (ciOp.isPresent()) {
                     ciName = ciOp.get().getName();
                 }
@@ -375,13 +339,11 @@ public class ComponentInstanceBusinessLogic extends BaseBusinessLogic {
                     for (final ComponentInstanceOutput prop : ciPropList) {
                         final List<GetOutputValueDataDefinition> outputValues = prop.getGetOutputValues();
                         addCompInstanceOutput(s, ciName, prop, outputValues, outputId, resList);
-
                     }
                 }
             });
         }
         return resList;
-
     }
 
     private void addCompInstanceInput(String s, String ciName, ComponentInstanceInput prop, List<GetInputValueDataDefinition> inputsValues,
@@ -398,11 +360,8 @@ public class ComponentInstanceBusinessLogic extends BaseBusinessLogic {
         }
     }
 
-    private void addCompInstanceOutput(final String s,
-                                       final String ciName,
-                                       final ComponentInstanceOutput prop,
-                                       final List<GetOutputValueDataDefinition> outputsValues,
-                                       final String outputId,
+    private void addCompInstanceOutput(final String s, final String ciName, final ComponentInstanceOutput prop,
+                                       final List<GetOutputValueDataDefinition> outputsValues, final String outputId,
                                        final List<ComponentInstanceOutput> resList) {
         if (outputsValues != null && !outputsValues.isEmpty()) {
             for (final GetOutputValueDataDefinition outputData : outputsValues) {
@@ -416,25 +375,20 @@ public class ComponentInstanceBusinessLogic extends BaseBusinessLogic {
         }
     }
 
-    public ComponentInstance createComponentInstance(final String containerComponentParam,
-                                                     final String containerComponentId, final String userId,
+    public ComponentInstance createComponentInstance(final String containerComponentParam, final String containerComponentId, final String userId,
                                                      final ComponentInstance resourceInstance, final boolean needLock) {
         final User user = validateUserExists(userId);
         validateUserNotEmpty(user, "Create component instance");
         validateJsonBody(resourceInstance, ComponentInstance.class);
         final ComponentTypeEnum containerComponentType = validateComponentType(containerComponentParam);
-        final org.openecomp.sdc.be.model.Component containerComponent =
-            validateComponentExists(containerComponentId, containerComponentType, null);
-
+        final org.openecomp.sdc.be.model.Component containerComponent = validateComponentExists(containerComponentId, containerComponentType, null);
         if (ModelConverter.isAtomicComponent(containerComponent)) {
             if (log.isDebugEnabled()) {
                 log.debug(CANNOT_ATTACH_RESOURCE_INSTANCES_TO_CONTAINER_RESOURCE_OF_TYPE, containerComponent.assetType());
             }
             throw new ByActionStatusComponentException(ActionStatus.RESOURCE_CANNOT_CONTAIN_RESOURCE_INSTANCES, containerComponent.assetType());
         }
-
         validateCanWorkOnComponent(containerComponent, userId);
-
         Component origComponent = null;
         if (resourceInstance != null && containerComponentType != null) {
             final OriginTypeEnum originType = resourceInstance.getOriginType();
@@ -451,8 +405,7 @@ public class ComponentInstanceBusinessLogic extends BaseBusinessLogic {
             overrideFields(origComponent, resourceInstance);
             compositionBusinessLogic.validateAndSetDefaultCoordinates(resourceInstance);
         }
-            return createComponent(needLock, containerComponent,origComponent, resourceInstance, user);
-
+        return createComponent(needLock, containerComponent, origComponent, resourceInstance, user);
     }
 
     private Component getOrigComponentForServiceProxy(org.openecomp.sdc.be.model.Component containerComponent, ComponentInstance resourceInstance) {
@@ -461,7 +414,6 @@ public class ComponentInstanceBusinessLogic extends BaseBusinessLogic {
             throw new ByActionStatusComponentException(componentsUtils.convertFromStorageResponse(serviceProxyOrigin.right().value()));
         }
         Component origComponent = serviceProxyOrigin.left().value();
-
         StorageOperationStatus fillProxyRes = fillInstanceData(resourceInstance, origComponent);
         if (isFillProxyRes(fillProxyRes)) {
             throw new ByActionStatusComponentException(componentsUtils.convertFromStorageResponse(fillProxyRes));
@@ -471,55 +423,53 @@ public class ComponentInstanceBusinessLogic extends BaseBusinessLogic {
     }
 
     private Component getOrigComponentForServiceSubstitution(ComponentInstance resourceInstance) {
-        final Either<Component, StorageOperationStatus> getServiceResult = toscaOperationFacade.getToscaFullElement(resourceInstance.getComponentUid());
+        final Either<Component, StorageOperationStatus> getServiceResult = toscaOperationFacade
+            .getToscaFullElement(resourceInstance.getComponentUid());
         if (getServiceResult.isRight()) {
             throw new ByActionStatusComponentException(componentsUtils.convertFromStorageResponse(getServiceResult.right().value()));
         }
         final Component service = getServiceResult.left().value();
-
-        final Either<Component, StorageOperationStatus> getServiceDerivedFromTypeResult = toscaOperationFacade.getLatestByToscaResourceName(service.getDerivedFromGenericType());
+        final Either<Component, StorageOperationStatus> getServiceDerivedFromTypeResult = toscaOperationFacade
+            .getLatestByToscaResourceName(service.getDerivedFromGenericType());
         if (getServiceDerivedFromTypeResult.isRight()) {
             throw new ByActionStatusComponentException(componentsUtils.convertFromStorageResponse(getServiceResult.right().value()));
         }
-
         Component origComponent = getServiceDerivedFromTypeResult.left().value();
-
         final StorageOperationStatus fillProxyRes = fillInstanceData(resourceInstance, origComponent);
         if (isFillProxyRes(fillProxyRes)) {
-            throw new ByActionStatusComponentException(
-                componentsUtils.convertFromStorageResponse(fillProxyRes));
+            throw new ByActionStatusComponentException(componentsUtils.convertFromStorageResponse(fillProxyRes));
         }
         return origComponent;
     }
 
-    private ComponentInstance createComponent(boolean needLock, Component containerComponent, Component origComponent, ComponentInstance resourceInstance, User user) {
-
+    private ComponentInstance createComponent(boolean needLock, Component containerComponent, Component origComponent,
+                                              ComponentInstance resourceInstance, User user) {
         boolean failed = false;
         try {
-
             lockIfNeed(needLock, containerComponent);
-
             log.debug(TRY_TO_CREATE_ENTRY_ON_GRAPH);
             return createComponentInstanceOnGraph(containerComponent, origComponent, resourceInstance, user);
-        }catch (ComponentException e){
+        } catch (ComponentException e) {
             failed = true;
             throw e;
-        }finally {
-            if (needLock)
+        } finally {
+            if (needLock) {
                 unlockComponent(failed, containerComponent);
+            }
         }
     }
 
     /**
      * Try using either to make a judgment
+     *
      * @param containerComponentParam
      * @param containerComponentId
      * @param userId
      * @param resourceInstance
      * @return
      */
-
-    public Either<ComponentInstance, ResponseFormat> createRealComponentInstance(String containerComponentParam, String containerComponentId, String userId, ComponentInstance resourceInstance) {
+    public Either<ComponentInstance, ResponseFormat> createRealComponentInstance(String containerComponentParam, String containerComponentId,
+                                                                                 String userId, ComponentInstance resourceInstance) {
         log.debug("enter createRealComponentInstance");
         return createRealComponentInstance(containerComponentParam, containerComponentId, userId, resourceInstance, true);
     }
@@ -534,11 +484,9 @@ public class ComponentInstanceBusinessLogic extends BaseBusinessLogic {
      * @param resourceInstance
      * @return
      */
-    public Either<ComponentInstance, ResponseFormat> createRealComponentInstance(String containerComponentParam,
-                                                                                 String containerComponentId, String userId,
-                                                                                 ComponentInstance resourceInstance,
+    public Either<ComponentInstance, ResponseFormat> createRealComponentInstance(String containerComponentParam, String containerComponentId,
+                                                                                 String userId, ComponentInstance resourceInstance,
                                                                                  boolean needLock) {
-
         log.debug("enter createRealComponentInstance");
         Component origComponent = null;
         User user;
@@ -550,29 +498,24 @@ public class ComponentInstanceBusinessLogic extends BaseBusinessLogic {
             validateJsonBody(resourceInstance, ComponentInstance.class);
             containerComponentType = validateComponentType(containerComponentParam);
             containerComponent = validateComponentExists(containerComponentId, containerComponentType, null);
-
             log.debug("enter createRealComponentInstance,validate user json success");
             if (ModelConverter.isAtomicComponent(containerComponent)) {
                 log.debug(CANNOT_ATTACH_RESOURCE_INSTANCES_TO_CONTAINER_RESOURCE_OF_TYPE, containerComponent.assetType());
                 throw new ByActionStatusComponentException(ActionStatus.RESOURCE_CANNOT_CONTAIN_RESOURCE_INSTANCES, containerComponent.assetType());
             }
-
             validateCanWorkOnComponent(containerComponent, userId);
             log.debug("enter createRealComponentInstance,validateCanWorkOnComponent success");
-
             if (resourceInstance != null && containerComponentType != null) {
                 log.debug("enter createRealComponentInstance,start create ComponentInstance");
                 OriginTypeEnum originType = resourceInstance.getOriginType();
                 validateInstanceName(resourceInstance);
                 if (originType == OriginTypeEnum.ServiceProxy) {
-
                     log.debug("enter createRealComponentInstance,originType equals ServiceProxy");
                     Either<Component, StorageOperationStatus> serviceProxyOrigin = toscaOperationFacade.getLatestByName(SERVICE_PROXY);
                     if (isServiceProxyOrigin(serviceProxyOrigin)) {
                         throw new ByActionStatusComponentException(componentsUtils.convertFromStorageResponse(serviceProxyOrigin.right().value()));
                     }
                     origComponent = serviceProxyOrigin.left().value();
-
                     StorageOperationStatus fillProxyRes = fillInstanceData(resourceInstance, origComponent);
                     if (isFillProxyRes(fillProxyRes)) {
                         throw new ByActionStatusComponentException(componentsUtils.convertFromStorageResponse(fillProxyRes));
@@ -588,52 +531,50 @@ public class ComponentInstanceBusinessLogic extends BaseBusinessLogic {
                 log.debug("enter createRealComponentInstance,final validate success");
             }
             return createRealComponent(needLock, containerComponent, origComponent, resourceInstance, user);
-
         } catch (ComponentException e) {
             log.debug("create Real Component Instance failed");
             throw e;
         }
     }
 
-    private Either<ComponentInstance, ResponseFormat> createRealComponent(boolean needLock, Component containerComponent, Component origComponent, ComponentInstance resourceInstance, User user) {
-
+    private Either<ComponentInstance, ResponseFormat> createRealComponent(boolean needLock, Component containerComponent, Component origComponent,
+                                                                          ComponentInstance resourceInstance, User user) {
         log.debug("enter createRealComponent");
         boolean failed = false;
         try {
-
             lockIfNeed(needLock, containerComponent);
-
             log.debug(TRY_TO_CREATE_ENTRY_ON_GRAPH);
             return createRealComponentInstanceOnGraph(containerComponent, origComponent, resourceInstance, user);
         } catch (ComponentException e) {
             failed = true;
             throw e;
         } finally {
-            if (needLock)
+            if (needLock) {
                 unlockComponent(failed, containerComponent);
+            }
         }
     }
 
-    private Either<ComponentInstance, ResponseFormat> createRealComponentInstanceOnGraph(org.openecomp.sdc.be.model.Component containerComponent, Component originComponent, ComponentInstance componentInstance, User user) {
+    private Either<ComponentInstance, ResponseFormat> createRealComponentInstanceOnGraph(org.openecomp.sdc.be.model.Component containerComponent,
+                                                                                         Component originComponent,
+                                                                                         ComponentInstance componentInstance, User user) {
         log.debug("enter createRealComponentInstanceOnGraph");
-
-        Either<ImmutablePair<Component, String>, StorageOperationStatus> result = toscaOperationFacade.addComponentInstanceToTopologyTemplate(containerComponent, originComponent, componentInstance, false, user);
-
+        Either<ImmutablePair<Component, String>, StorageOperationStatus> result = toscaOperationFacade
+            .addComponentInstanceToTopologyTemplate(containerComponent, originComponent, componentInstance, false, user);
         if (result.isRight()) {
             log.debug("enter createRealComponentInstanceOnGraph,result is right");
             ActionStatus status = componentsUtils.convertFromStorageResponse(result.right().value());
             log.debug(FAILED_TO_CREATE_ENTRY_ON_GRAPH_FOR_COMPONENT_INSTANCE, componentInstance.getName());
             return Either.right(componentsUtils.getResponseFormat(status));
         }
-
         log.debug(ENTITY_ON_GRAPH_IS_CREATED);
         log.debug("enter createRealComponentInstanceOnGraph,Entity on graph is created.");
         Component updatedComponent = result.left().value().getLeft();
         Map<String, String> existingEnvVersions = new HashMap<>();
         // TODO existingEnvVersions ??
         addComponentInstanceArtifacts(updatedComponent, componentInstance, originComponent, user, existingEnvVersions);
-
-        Optional<ComponentInstance> updatedInstanceOptional = updatedComponent.getComponentInstances().stream().filter(ci -> ci.getUniqueId().equals(result.left().value().getRight())).findFirst();
+        Optional<ComponentInstance> updatedInstanceOptional = updatedComponent.getComponentInstances().stream()
+            .filter(ci -> ci.getUniqueId().equals(result.left().value().getRight())).findFirst();
         if (!updatedInstanceOptional.isPresent()) {
             log.debug("Failed to fetch new added component instance {} from component {}", componentInstance.getName(), containerComponent.getName());
             throw new ByActionStatusComponentException(ActionStatus.COMPONENT_INSTANCE_NOT_FOUND_ON_CONTAINER, componentInstance.getName());
@@ -648,18 +589,15 @@ public class ComponentInstanceBusinessLogic extends BaseBusinessLogic {
     }
 
     private void validateInstanceName(ComponentInstance resourceInstance) {
-
         String resourceInstanceName = resourceInstance.getName();
         if (StringUtils.isEmpty(resourceInstanceName)) {
             log.debug("ComponentInstance name is empty");
             throw new ByActionStatusComponentException(ActionStatus.INVALID_COMPONENT_NAME, resourceInstance.getName());
         }
-
         if (!ValidationUtils.validateComponentNameLength(resourceInstanceName)) {
             log.debug("ComponentInstance name exceeds max length {} ", ValidationUtils.COMPONENT_NAME_MAX_LENGTH);
             throw new ByActionStatusComponentException(ActionStatus.INVALID_COMPONENT_NAME, resourceInstance.getName());
         }
-
         if (!ValidationUtils.validateComponentNamePattern(resourceInstanceName)) {
             log.debug("ComponentInstance name {} has invalid format", resourceInstanceName);
             throw new ByActionStatusComponentException(ActionStatus.INVALID_COMPONENT_NAME, resourceInstance.getName());
@@ -667,14 +605,13 @@ public class ComponentInstanceBusinessLogic extends BaseBusinessLogic {
     }
 
     private void validateResourceInstanceState(Component containerComponent, Component origComponent) {
-        if (origComponent.getLifecycleState() == LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT){
+        if (origComponent.getLifecycleState() == LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT) {
             throw new ByActionStatusComponentException(ActionStatus.CONTAINER_CANNOT_CONTAIN_INSTANCE,
-                    containerComponent.getComponentType().getValue(), origComponent.getLifecycleState().toString());
+                containerComponent.getComponentType().getValue(), origComponent.getLifecycleState().toString());
         }
     }
 
-    private void validateOriginAndResourceInstanceTypes(final Component containerComponent,
-                                                        final Component origComponent,
+    private void validateOriginAndResourceInstanceTypes(final Component containerComponent, final Component origComponent,
                                                         final OriginTypeEnum originType) {
         final ResourceTypeEnum resourceType = getResourceTypeEnumFromOriginComponent(origComponent);
         validateOriginType(originType, resourceType);
@@ -686,14 +623,14 @@ public class ComponentInstanceBusinessLogic extends BaseBusinessLogic {
             case SERVICE:
                 if (!containerInstanceTypesData.isAllowedForServiceComponent(resourceType)) {
                     throw new ByActionStatusComponentException(ActionStatus.CONTAINER_CANNOT_CONTAIN_INSTANCE,
-                            containerComponent.getComponentType().toString(), resourceType.name());
+                        containerComponent.getComponentType().toString(), resourceType.name());
                 }
                 break;
             case RESOURCE:
                 final ResourceTypeEnum componentResourceType = ((Resource) containerComponent).getResourceType();
                 if (!containerInstanceTypesData.isAllowedForResourceComponent(componentResourceType, resourceType)) {
                     throw new ByActionStatusComponentException(ActionStatus.CONTAINER_CANNOT_CONTAIN_INSTANCE,
-                            containerComponent.getComponentType().toString(), resourceType.name());
+                        containerComponent.getComponentType().toString(), resourceType.name());
                 }
                 break;
             default:
@@ -705,12 +642,12 @@ public class ComponentInstanceBusinessLogic extends BaseBusinessLogic {
         ResourceTypeEnum convertedOriginType;
         try {
             convertedOriginType = ResourceTypeEnum.getTypeIgnoreCase(originType.name());
+        } catch (Exception e) {
+            throw new ByActionStatusComponentException(ActionStatus.INVALID_CONTENT);
         }
-        catch (Exception e){
+        if (resourceType != convertedOriginType) {
             throw new ByActionStatusComponentException(ActionStatus.INVALID_CONTENT);
         }
-
-        if (resourceType != convertedOriginType)  throw new ByActionStatusComponentException(ActionStatus.INVALID_CONTENT);
     }
 
     private ResourceTypeEnum getResourceTypeEnumFromOriginComponent(final Component origComponent) {
@@ -748,8 +685,7 @@ public class ComponentInstanceBusinessLogic extends BaseBusinessLogic {
         filter.setIgnoreProperties(false);
         filter.setIgnoreAttributes(false);
         filter.setIgnoreInputs(false);
-        Either<Component, StorageOperationStatus> serviceRes =
-                toscaOperationFacade.getToscaElement(resourceInstance.getComponentUid(), filter);
+        Either<Component, StorageOperationStatus> serviceRes = toscaOperationFacade.getToscaElement(resourceInstance.getComponentUid(), filter);
         if (serviceRes.isRight()) {
             return serviceRes.right().value();
         }
@@ -759,12 +695,11 @@ public class ComponentInstanceBusinessLogic extends BaseBusinessLogic {
         final Map<String, List<RequirementDefinition>> req = service.getRequirements();
         resourceInstance.setRequirements(req);
         final Map<String, InterfaceDefinition> serviceInterfaces = service.getInterfaces();
-        if(MapUtils.isNotEmpty(serviceInterfaces)) {
+        if (MapUtils.isNotEmpty(serviceInterfaces)) {
             serviceInterfaces.forEach(resourceInstance::addInterface);
         }
         resourceInstance.setProperties(PropertiesUtils.getProperties(service));
         resourceInstance.setAttributes(service.getAttributes());
-
         final List<InputDefinition> serviceInputs = service.getInputs();
         resourceInstance.setInputs(serviceInputs);
         resourceInstance.setSourceModelInvariant(service.getInvariantUUID());
@@ -773,18 +708,18 @@ public class ComponentInstanceBusinessLogic extends BaseBusinessLogic {
         resourceInstance.setSourceModelUid(service.getUniqueId());
         resourceInstance.setComponentUid(origComponent.getUniqueId());
         resourceInstance.setComponentVersion(service.getVersion());
-
-        switch(resourceInstance.getOriginType()) {
-        case ServiceProxy:
-               return fillProxyInstanceData(resourceInstance, origComponent, service);
-        case ServiceSubstitution:
-               return fillServiceSubstitutableNodeTypeData(resourceInstance, service);
-        default:
-               return StorageOperationStatus.OK;
+        switch (resourceInstance.getOriginType()) {
+            case ServiceProxy:
+                return fillProxyInstanceData(resourceInstance, origComponent, service);
+            case ServiceSubstitution:
+                return fillServiceSubstitutableNodeTypeData(resourceInstance, service);
+            default:
+                return StorageOperationStatus.OK;
         }
     }
 
-    private StorageOperationStatus fillProxyInstanceData(final ComponentInstance resourceInstance, final Component origComponent, final Component service) {
+    private StorageOperationStatus fillProxyInstanceData(final ComponentInstance resourceInstance, final Component origComponent,
+                                                         final Component service) {
         final String name = ValidationUtils.normalizeComponentInstanceName(service.getName()) + ToscaOperationFacade.PROXY_SUFFIX;
         final String toscaResourceName = ((Resource) origComponent).getToscaResourceName();
         final int lastIndexOf = toscaResourceName.lastIndexOf('.');
@@ -799,39 +734,32 @@ public class ComponentInstanceBusinessLogic extends BaseBusinessLogic {
     }
 
     private StorageOperationStatus fillServiceSubstitutableNodeTypeData(final ComponentInstance resourceInstance, final Component service) {
-       resourceInstance.setToscaComponentName("org.openecomp.service." + ValidationUtils.convertToSystemName(service.getName()));
+        resourceInstance.setToscaComponentName("org.openecomp.service." + ValidationUtils.convertToSystemName(service.getName()));
         resourceInstance.setName(ValidationUtils.normalizeComponentInstanceName(service.getName()));
         resourceInstance.setIsProxy(false);
         resourceInstance.setDescription("A substitutable node type for service " + service.getName());
-
         return StorageOperationStatus.OK;
     }
 
-    public Either<CreateAndAssotiateInfo, ResponseFormat> createAndAssociateRIToRI(String containerComponentParam, String containerComponentId, String userId, CreateAndAssotiateInfo createAndAssotiateInfo) {
-
+    public Either<CreateAndAssotiateInfo, ResponseFormat> createAndAssociateRIToRI(String containerComponentParam, String containerComponentId,
+                                                                                   String userId, CreateAndAssotiateInfo createAndAssotiateInfo) {
         Either<CreateAndAssotiateInfo, ResponseFormat> resultOp = null;
         ComponentInstance resourceInstance = createAndAssotiateInfo.getNode();
         RequirementCapabilityRelDef associationInfo = createAndAssotiateInfo.getAssociate();
-
         User user = validateUserExists(userId);
-
         final ComponentTypeEnum containerComponentType = validateComponentType(containerComponentParam);
-
         org.openecomp.sdc.be.model.Component containerComponent = validateComponentExists(containerComponentId, containerComponentType, null);
-
         if (ModelConverter.isAtomicComponent(containerComponent)) {
             log.debug(CANNOT_ATTACH_RESOURCE_INSTANCES_TO_CONTAINER_RESOURCE_OF_TYPE, containerComponent.assetType());
-            return Either.right(componentsUtils.getResponseFormat(ActionStatus.RESOURCE_CANNOT_CONTAIN_RESOURCE_INSTANCES, containerComponent.assetType()));
+            return Either
+                .right(componentsUtils.getResponseFormat(ActionStatus.RESOURCE_CANNOT_CONTAIN_RESOURCE_INSTANCES, containerComponent.assetType()));
         }
-
         validateCanWorkOnComponent(containerComponent, userId);
-
         boolean failed = false;
         try {
             lockComponent(containerComponent, "createAndAssociateRIToRI");
             log.debug(TRY_TO_CREATE_ENTRY_ON_GRAPH);
             Component origComponent = getOriginComponentFromComponentInstance(resourceInstance);
-
             log.debug(ENTITY_ON_GRAPH_IS_CREATED);
             ComponentInstance resResourceInfo = createComponentInstanceOnGraph(containerComponent, origComponent, resourceInstance, user);
             if (associationInfo.getFromNode() == null || associationInfo.getFromNode().isEmpty()) {
@@ -839,25 +767,24 @@ public class ComponentInstanceBusinessLogic extends BaseBusinessLogic {
             } else {
                 associationInfo.setToNode(resResourceInfo.getUniqueId());
             }
-
-            Either<RequirementCapabilityRelDef, StorageOperationStatus> resultReqCapDef = toscaOperationFacade.associateResourceInstances(containerComponent, containerComponentId, associationInfo);
+            Either<RequirementCapabilityRelDef, StorageOperationStatus> resultReqCapDef = toscaOperationFacade
+                .associateResourceInstances(containerComponent, containerComponentId, associationInfo);
             if (resultReqCapDef.isLeft()) {
                 log.debug(ENTITY_ON_GRAPH_IS_CREATED);
                 RequirementCapabilityRelDef resReqCapabilityRelDef = resultReqCapDef.left().value();
                 CreateAndAssotiateInfo resInfo = new CreateAndAssotiateInfo(resResourceInfo, resReqCapabilityRelDef);
                 resultOp = Either.left(resInfo);
                 return resultOp;
-
             } else {
                 log.info("Failed to associate node {} with node {}", associationInfo.getFromNode(), associationInfo.getToNode());
-                resultOp = Either.right(componentsUtils.getResponseFormatForResourceInstance(componentsUtils.convertFromStorageResponseForResourceInstance(resultReqCapDef.right().value(), true), "", null));
+                resultOp = Either.right(componentsUtils.getResponseFormatForResourceInstance(
+                    componentsUtils.convertFromStorageResponseForResourceInstance(resultReqCapDef.right().value(), true), "", null));
                 return resultOp;
             }
-
-        }catch (ComponentException e){
+        } catch (ComponentException e) {
             failed = true;
             throw e;
-        }finally {
+        } finally {
             unlockComponent(failed, containerComponent);
         }
     }
@@ -874,27 +801,29 @@ public class ComponentInstanceBusinessLogic extends BaseBusinessLogic {
         Either<Component, StorageOperationStatus> eitherComponent = toscaOperationFacade.getToscaFullElement(origComponetId);
         if (eitherComponent.isRight()) {
             log.debug("Failed to get origin component with id {} for component instance {} ", origComponetId, componentInstanceName);
-            throw new ByActionStatusComponentException(componentsUtils.convertFromStorageResponse(eitherComponent.right().value(), ComponentTypeEnum.RESOURCE), "", null);
+            throw new ByActionStatusComponentException(
+                componentsUtils.convertFromStorageResponse(eitherComponent.right().value(), ComponentTypeEnum.RESOURCE), "", null);
         }
         return eitherComponent.left().value();
     }
 
-    private ComponentInstance createComponentInstanceOnGraph(org.openecomp.sdc.be.model.Component containerComponent, Component originComponent, ComponentInstance componentInstance, User user) {
-
-        Either<ImmutablePair<Component, String>, StorageOperationStatus> result = toscaOperationFacade.addComponentInstanceToTopologyTemplate(containerComponent, originComponent, componentInstance, false, user);
-
+    private ComponentInstance createComponentInstanceOnGraph(org.openecomp.sdc.be.model.Component containerComponent, Component originComponent,
+                                                             ComponentInstance componentInstance, User user) {
+        Either<ImmutablePair<Component, String>, StorageOperationStatus> result = toscaOperationFacade
+            .addComponentInstanceToTopologyTemplate(containerComponent, originComponent, componentInstance, false, user);
         if (result.isRight()) {
             log.debug(FAILED_TO_CREATE_ENTRY_ON_GRAPH_FOR_COMPONENT_INSTANCE, componentInstance.getName());
-            throw new ByResponseFormatComponentException(componentsUtils.getResponseFormatForResourceInstance(componentsUtils.convertFromStorageResponseForResourceInstance(result.right().value(), true), "", null));
+            throw new ByResponseFormatComponentException(componentsUtils
+                .getResponseFormatForResourceInstance(componentsUtils.convertFromStorageResponseForResourceInstance(result.right().value(), true), "",
+                    null));
         }
-
         log.debug(ENTITY_ON_GRAPH_IS_CREATED);
         Component updatedComponent = result.left().value().getLeft();
         Map<String, String> existingEnvVersions = new HashMap<>();
         // TODO existingEnvVersions ??
         addComponentInstanceArtifacts(updatedComponent, componentInstance, originComponent, user, existingEnvVersions);
-
-        Optional<ComponentInstance> updatedInstanceOptional = updatedComponent.getComponentInstances().stream().filter(ci -> ci.getUniqueId().equals(result.left().value().getRight())).findFirst();
+        Optional<ComponentInstance> updatedInstanceOptional = updatedComponent.getComponentInstances().stream()
+            .filter(ci -> ci.getUniqueId().equals(result.left().value().getRight())).findFirst();
         if (!updatedInstanceOptional.isPresent()) {
             log.debug("Failed to fetch new added component instance {} from component {}", componentInstance.getName(), containerComponent.getName());
             throw new ByActionStatusComponentException(ActionStatus.COMPONENT_INSTANCE_NOT_FOUND_ON_CONTAINER, componentInstance.getName());
@@ -902,21 +831,23 @@ public class ComponentInstanceBusinessLogic extends BaseBusinessLogic {
         return updatedInstanceOptional.get();
     }
 
-  public boolean isCloudSpecificArtifact(String artifact) {
-      if (artifact.contains(CLOUD_SPECIFIC_FIXED_KEY_WORD)) {
-          for (int i = 0; i < CLOUD_SPECIFIC_KEY_WORDS.length; i++) {
-              if (Arrays.stream(CLOUD_SPECIFIC_KEY_WORDS[i]).noneMatch(artifact::contains)) {
-                  return false;
-              }
-          }
-          return true;
-      } else {
-          return false;
-      }
-  }
+    public boolean isCloudSpecificArtifact(String artifact) {
+        if (artifact.contains(CLOUD_SPECIFIC_FIXED_KEY_WORD)) {
+            for (int i = 0; i < CLOUD_SPECIFIC_KEY_WORDS.length; i++) {
+                if (Arrays.stream(CLOUD_SPECIFIC_KEY_WORDS[i]).noneMatch(artifact::contains)) {
+                    return false;
+                }
+            }
+            return true;
+        } else {
+            return false;
+        }
+    }
 
     /**
-     * addResourceInstanceArtifacts - add artifacts (HEAT_ENV) to resource instance The instance artifacts are generated from the resource's artifacts
+     * addResourceInstanceArtifacts - add artifacts (HEAT_ENV) to resource instance The instance artifacts are generated from the resource's
+     * artifacts
+     *
      * @param containerComponent
      * @param componentInstance
      * @param originComponent
@@ -924,8 +855,9 @@ public class ComponentInstanceBusinessLogic extends BaseBusinessLogic {
      * @param existingEnvVersions
      * @return
      */
-    protected ActionStatus addComponentInstanceArtifacts(org.openecomp.sdc.be.model.Component containerComponent, ComponentInstance componentInstance, org.openecomp.sdc.be.model.Component originComponent, User user,    Map<String, String> existingEnvVersions) {
-
+    protected ActionStatus addComponentInstanceArtifacts(org.openecomp.sdc.be.model.Component containerComponent, ComponentInstance componentInstance,
+                                                         org.openecomp.sdc.be.model.Component originComponent, User user,
+                                                         Map<String, String> existingEnvVersions) {
         log.debug("add artifacts to resource instance");
         List<GroupDefinition> filteredGroups = new ArrayList<>();
         ActionStatus status = setResourceArtifactsOnResourceInstance(componentInstance);
@@ -936,30 +868,29 @@ public class ComponentInstanceBusinessLogic extends BaseBusinessLogic {
         // generate heat_env if necessary
         Map<String, ArtifactDefinition> componentDeploymentArtifacts = componentInstance.getDeploymentArtifacts();
         if (MapUtils.isNotEmpty(componentDeploymentArtifacts)) {
-
             Map<String, ArtifactDefinition> finalDeploymentArtifacts = new HashMap<>();
             Map<String, List<ArtifactDefinition>> groupInstancesArtifacts = new HashMap<>();
-            Integer defaultHeatTimeout = ConfigurationManager.getConfigurationManager().getConfiguration()
-                    .getHeatArtifactDeploymentTimeout().getDefaultMinutes();
+            Integer defaultHeatTimeout = ConfigurationManager.getConfigurationManager().getConfiguration().getHeatArtifactDeploymentTimeout()
+                .getDefaultMinutes();
             List<ArtifactDefinition> listOfCloudSpecificArts = new ArrayList<>();
             for (ArtifactDefinition artifact : componentDeploymentArtifacts.values()) {
                 String type = artifact.getArtifactType();
                 if (!type.equalsIgnoreCase(ArtifactTypeEnum.HEAT_ENV.getType())) {
                     finalDeploymentArtifacts.put(artifact.getArtifactLabel(), artifact);
                 }
-                if (type.equalsIgnoreCase(ArtifactTypeEnum.HEAT.getType()) || type.equalsIgnoreCase(ArtifactTypeEnum.HELM.getType())|| type.equalsIgnoreCase(ArtifactTypeEnum.HEAT_NET.getType()) || type.equalsIgnoreCase(ArtifactTypeEnum.HEAT_VOL.getType()) || type.equalsIgnoreCase(ArtifactTypeEnum.CLOUD_TECHNOLOGY_SPECIFIC_ARTIFACT.getType())) {
+                if (type.equalsIgnoreCase(ArtifactTypeEnum.HEAT.getType()) || type.equalsIgnoreCase(ArtifactTypeEnum.HELM.getType()) || type
+                    .equalsIgnoreCase(ArtifactTypeEnum.HEAT_NET.getType()) || type.equalsIgnoreCase(ArtifactTypeEnum.HEAT_VOL.getType()) || type
+                    .equalsIgnoreCase(ArtifactTypeEnum.CLOUD_TECHNOLOGY_SPECIFIC_ARTIFACT.getType())) {
                     artifact.setTimeout(defaultHeatTimeout);
                 } else {
                     continue;
                 }
                 if (artifact.checkEsIdExist()) {
-                    ArtifactDefinition artifactDefinition = artifactBusinessLogic.createHeatEnvPlaceHolder(new ArrayList<>(),
-                            artifact, ArtifactsBusinessLogic.HEAT_ENV_NAME, componentInstance.getUniqueId(),
-                            NodeTypeEnum.ResourceInstance, componentInstance.getName(), user, containerComponent,
-                            existingEnvVersions);
+                    ArtifactDefinition artifactDefinition = artifactBusinessLogic
+                        .createHeatEnvPlaceHolder(new ArrayList<>(), artifact, ArtifactsBusinessLogic.HEAT_ENV_NAME, componentInstance.getUniqueId(),
+                            NodeTypeEnum.ResourceInstance, componentInstance.getName(), user, containerComponent, existingEnvVersions);
                     // put env
                     finalDeploymentArtifacts.put(artifactDefinition.getArtifactLabel(), artifactDefinition);
-
                     if (CollectionUtils.isNotEmpty(originComponent.getGroups())) {
                         filteredGroups = originComponent.getGroups().stream().filter(g -> g.getType().equals(VF_MODULE)).collect(Collectors.toList());
                     }
@@ -967,45 +898,47 @@ public class ComponentInstanceBusinessLogic extends BaseBusinessLogic {
                         listOfCloudSpecificArts.add(artifact);
                     }
                     if (CollectionUtils.isNotEmpty(filteredGroups)) {
-                        filteredGroups.stream().filter(g ->
-                                g.getArtifacts()
-                                        .stream()
-                                        .anyMatch(p -> p.equals(artifactDefinition.getGeneratedFromId())))
-                                .findFirst()
-                                .ifPresent(g -> fillInstanceArtifactMap(groupInstancesArtifacts, artifactDefinition, g));
+                        filteredGroups.stream()
+                            .filter(g -> g.getArtifacts().stream().anyMatch(p -> p.equals(artifactDefinition.getGeneratedFromId()))).findFirst()
+                            .ifPresent(g -> fillInstanceArtifactMap(groupInstancesArtifacts, artifactDefinition, g));
                     }
                 }
             }
-            groupInstancesArtifacts.forEach((k,v) -> v.addAll(listOfCloudSpecificArts));
+            groupInstancesArtifacts.forEach((k, v) -> v.addAll(listOfCloudSpecificArts));
             filteredGroups.forEach(g -> listOfCloudSpecificArts.forEach(e -> {
                 g.getArtifactsUuid().add(e.getArtifactUUID());
                 g.getArtifacts().add(e.getUniqueId());
             }));
-            artStatus = toscaOperationFacade.addDeploymentArtifactsToInstance(containerComponent.getUniqueId(), componentInstance, finalDeploymentArtifacts);
+            artStatus = toscaOperationFacade
+                .addDeploymentArtifactsToInstance(containerComponent.getUniqueId(), componentInstance, finalDeploymentArtifacts);
             if (artStatus != StorageOperationStatus.OK) {
-                log.debug("Failed to add instance deployment artifacts for instance {} in conatiner {} error {}", componentInstance.getUniqueId(), containerComponent.getUniqueId(), artStatus);
-                throw new ByResponseFormatComponentException(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponseForResourceInstance(artStatus, false)));
-
+                log.debug("Failed to add instance deployment artifacts for instance {} in conatiner {} error {}", componentInstance.getUniqueId(),
+                    containerComponent.getUniqueId(), artStatus);
+                throw new ByResponseFormatComponentException(
+                    componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponseForResourceInstance(artStatus, false)));
             }
-            StorageOperationStatus result = toscaOperationFacade.addGroupInstancesToComponentInstance(containerComponent, componentInstance, filteredGroups, groupInstancesArtifacts);
+            StorageOperationStatus result = toscaOperationFacade
+                .addGroupInstancesToComponentInstance(containerComponent, componentInstance, filteredGroups, groupInstancesArtifacts);
             if (result != StorageOperationStatus.OK) {
                 log.debug("failed to update group instance for component instance {}", componentInstance.getUniqueId());
                 throw new ByResponseFormatComponentException(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(result)));
             }
             componentInstance.setDeploymentArtifacts(finalDeploymentArtifacts);
         }
-
-        artStatus = toscaOperationFacade.addInformationalArtifactsToInstance(containerComponent.getUniqueId(), componentInstance, originComponent.getArtifacts());
+        artStatus = toscaOperationFacade
+            .addInformationalArtifactsToInstance(containerComponent.getUniqueId(), componentInstance, originComponent.getArtifacts());
         if (artStatus != StorageOperationStatus.OK) {
-            log.debug("Failed to add informational artifacts to the instance {} belonging to the conatiner {}. Status is {}", componentInstance.getUniqueId(), containerComponent.getUniqueId(), artStatus);
-            throw new ByResponseFormatComponentException(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponseForResourceInstance(artStatus, false)));
-
+            log.debug("Failed to add informational artifacts to the instance {} belonging to the conatiner {}. Status is {}",
+                componentInstance.getUniqueId(), containerComponent.getUniqueId(), artStatus);
+            throw new ByResponseFormatComponentException(
+                componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponseForResourceInstance(artStatus, false)));
         }
         componentInstance.setArtifacts(originComponent.getArtifacts());
         return ActionStatus.OK;
     }
 
-    private void fillInstanceArtifactMap(Map<String, List<ArtifactDefinition>> groupInstancesArtifacts, ArtifactDefinition artifactDefinition, GroupDefinition groupInstance) {
+    private void fillInstanceArtifactMap(Map<String, List<ArtifactDefinition>> groupInstancesArtifacts, ArtifactDefinition artifactDefinition,
+                                         GroupDefinition groupInstance) {
         List<ArtifactDefinition> artifactsUid;
         if (groupInstancesArtifacts.containsKey(groupInstance.getUniqueId())) {
             artifactsUid = groupInstancesArtifacts.get(groupInstance.getUniqueId());
@@ -1017,9 +950,8 @@ public class ComponentInstanceBusinessLogic extends BaseBusinessLogic {
     }
 
     private ActionStatus setResourceArtifactsOnResourceInstance(ComponentInstance resourceInstance) {
-        Either<Map<String, ArtifactDefinition>, StorageOperationStatus> getResourceDeploymentArtifacts =
-                artifactBusinessLogic.getArtifacts(resourceInstance.getComponentUid(), NodeTypeEnum.Resource, ArtifactGroupTypeEnum.DEPLOYMENT, null);
-
+        Either<Map<String, ArtifactDefinition>, StorageOperationStatus> getResourceDeploymentArtifacts = artifactBusinessLogic
+            .getArtifacts(resourceInstance.getComponentUid(), NodeTypeEnum.Resource, ArtifactGroupTypeEnum.DEPLOYMENT, null);
         Map<String, ArtifactDefinition> deploymentArtifacts = new HashMap<>();
         if (getResourceDeploymentArtifacts.isRight()) {
             StorageOperationStatus status = getResourceDeploymentArtifacts.right().value();
@@ -1030,7 +962,6 @@ public class ComponentInstanceBusinessLogic extends BaseBusinessLogic {
         } else {
             deploymentArtifacts = getResourceDeploymentArtifacts.left().value();
         }
-
         if (!deploymentArtifacts.isEmpty()) {
             Map<String, ArtifactDefinition> tempDeploymentArtifacts = new HashMap<>(deploymentArtifacts);
             for (Entry<String, ArtifactDefinition> artifact : deploymentArtifacts.entrySet()) {
@@ -1038,42 +969,37 @@ public class ComponentInstanceBusinessLogic extends BaseBusinessLogic {
                     tempDeploymentArtifacts.remove(artifact.getKey());
                 }
             }
-
             resourceInstance.setDeploymentArtifacts(tempDeploymentArtifacts);
         }
-
         return ActionStatus.OK;
     }
 
-    public Either<ComponentInstance, ResponseFormat> updateComponentInstanceMetadata(String containerComponentParam, String containerComponentId, String componentInstanceId, String userId, ComponentInstance componentInstance) {
+    public Either<ComponentInstance, ResponseFormat> updateComponentInstanceMetadata(String containerComponentParam, String containerComponentId,
+                                                                                     String componentInstanceId, String userId,
+                                                                                     ComponentInstance componentInstance) {
         return updateComponentInstanceMetadata(containerComponentParam, containerComponentId, componentInstanceId, userId, componentInstance, true);
     }
 
-    public Either<ComponentInstance, ResponseFormat> updateComponentInstanceMetadata(
-        final String containerComponentParam,
-        final String containerComponentId,
-        final String componentInstanceId,
-        final String userId,
-        ComponentInstance componentInstance,
-        boolean needLock) {
-
+    public Either<ComponentInstance, ResponseFormat> updateComponentInstanceMetadata(final String containerComponentParam,
+                                                                                     final String containerComponentId,
+                                                                                     final String componentInstanceId, final String userId,
+                                                                                     ComponentInstance componentInstance, boolean needLock) {
         validateUserExists(userId);
-
         final ComponentTypeEnum containerComponentType = validateComponentType(containerComponentParam);
-
         final Component containerComponent = validateComponentExists(containerComponentId, containerComponentType, null);
-
         validateCanWorkOnComponent(containerComponent, userId);
         ComponentTypeEnum instanceType = getComponentType(containerComponentType);
-        Either<Boolean, StorageOperationStatus> validateParentStatus = toscaOperationFacade.validateComponentExists(componentInstance.getComponentUid());
+        Either<Boolean, StorageOperationStatus> validateParentStatus = toscaOperationFacade
+            .validateComponentExists(componentInstance.getComponentUid());
         if (validateParentStatus.isRight()) {
             log.debug("Failed to get component instance {} on service {}", componentInstanceId, containerComponentId);
-            throw new ByActionStatusComponentException(ActionStatus.COMPONENT_INSTANCE_NOT_FOUND, componentInstance.getName(), instanceType.getValue().toLowerCase());
+            throw new ByActionStatusComponentException(ActionStatus.COMPONENT_INSTANCE_NOT_FOUND, componentInstance.getName(),
+                instanceType.getValue().toLowerCase());
         }
         if (!validateParentStatus.left().value()) {
-            throw new ByActionStatusComponentException(ActionStatus.COMPONENT_INSTANCE_NOT_FOUND_ON_CONTAINER, componentInstance.getName(), instanceType.getValue().toLowerCase(), containerComponentType.getValue().toLowerCase(), containerComponentId);
+            throw new ByActionStatusComponentException(ActionStatus.COMPONENT_INSTANCE_NOT_FOUND_ON_CONTAINER, componentInstance.getName(),
+                instanceType.getValue().toLowerCase(), containerComponentType.getValue().toLowerCase(), containerComponentId);
         }
-
         if (needLock) {
             lockComponent(containerComponent, "updateComponentInstance");
         }
@@ -1081,11 +1007,12 @@ public class ComponentInstanceBusinessLogic extends BaseBusinessLogic {
         boolean failed = false;
         try {
             origComponent = getOriginComponentFromComponentInstance(componentInstance);
-            componentInstance = updateComponentInstanceMetadata(containerComponent, containerComponentType, origComponent, componentInstanceId, componentInstance);
-        }catch (ComponentException e) {
+            componentInstance = updateComponentInstanceMetadata(containerComponent, containerComponentType, origComponent, componentInstanceId,
+                componentInstance);
+        } catch (ComponentException e) {
             failed = true;
             throw e;
-        }finally {
+        } finally {
             if (needLock) {
                 unlockComponent(failed, containerComponent);
             }
@@ -1094,12 +1021,11 @@ public class ComponentInstanceBusinessLogic extends BaseBusinessLogic {
     }
 
     // New Multiple Instance Update API
-    public List<ComponentInstance> updateComponentInstance(String containerComponentParam, Component containerComponent, String containerComponentId, String userId, List<ComponentInstance> componentInstanceList, boolean needLock) {
-
+    public List<ComponentInstance> updateComponentInstance(String containerComponentParam, Component containerComponent, String containerComponentId,
+                                                           String userId, List<ComponentInstance> componentInstanceList, boolean needLock) {
         boolean failed = false;
         try {
             validateUserExists(userId);
-
             final ComponentTypeEnum containerComponentType = validateComponentType(containerComponentParam);
             ComponentParametersView componentFilter = new ComponentParametersView();
             componentFilter.disableAll();
@@ -1109,65 +1035,67 @@ public class ComponentInstanceBusinessLogic extends BaseBusinessLogic {
                 containerComponent = validateComponentExistsByFilter(containerComponentId, containerComponentType, componentFilter);
             }
             validateCanWorkOnComponent(containerComponent, userId);
-
             ComponentTypeEnum instanceType = getComponentType(containerComponentType);
-
             for (ComponentInstance componentInstance : componentInstanceList) {
                 boolean validateParent = validateParent(containerComponent, componentInstance.getUniqueId());
                 if (!validateParent) {
                     throw new ByActionStatusComponentException(ActionStatus.COMPONENT_INSTANCE_NOT_FOUND_ON_CONTAINER, componentInstance.getName(),
-                            instanceType.getValue().toLowerCase(), containerComponentType.getValue().toLowerCase(),
-                            containerComponentId);
+                        instanceType.getValue().toLowerCase(), containerComponentType.getValue().toLowerCase(), containerComponentId);
                 }
             }
-
             if (needLock) {
                 lockComponent(containerComponent, "updateComponentInstance");
             }
-
             List<ComponentInstance> updatedList = new ArrayList<>();
             List<ComponentInstance> instancesFromContainerComponent = containerComponent.getComponentInstances();
             List<ComponentInstance> listForUpdate = new ArrayList<>();
-            if (instancesFromContainerComponent == null || instancesFromContainerComponent.isEmpty())
+            if (instancesFromContainerComponent == null || instancesFromContainerComponent.isEmpty()) {
                 containerComponent.setComponentInstances(componentInstanceList);
-            else {
+            else {
                 Iterator<ComponentInstance> iterator = instancesFromContainerComponent.iterator();
                 while (iterator.hasNext()) {
                     ComponentInstance origInst = iterator.next();
-                    Optional<ComponentInstance> op = componentInstanceList.stream().filter(ci -> ci.getUniqueId().equals(origInst.getUniqueId())).findAny();
+                    Optional<ComponentInstance> op = componentInstanceList.stream().filter(ci -> ci.getUniqueId().equals(origInst.getUniqueId()))
+                        .findAny();
                     if (op.isPresent()) {
                         ComponentInstance updatedCi = op.get();
                         updatedCi = buildComponentInstance(updatedCi, origInst);
-
                         Boolean isUniqueName = validateInstanceNameUniquenessUponUpdate(containerComponent, origInst, updatedCi.getName());
                         if (!isUniqueName) {
-                            CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to update the name of the component instance {} to {}. A component instance with the same name already exists. ", origInst.getName(), updatedCi.getName());
-                            throw new ByResponseFormatComponentException(componentsUtils.getResponseFormat(ActionStatus.COMPONENT_NAME_ALREADY_EXIST, containerComponentType.getValue(), origInst.getName()));
+                            CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG,
+                                "Failed to update the name of the component instance {} to {}. A component instance with the same name already exists. ",
+                                origInst.getName(), updatedCi.getName());
+                            throw new ByResponseFormatComponentException(componentsUtils
+                                .getResponseFormat(ActionStatus.COMPONENT_NAME_ALREADY_EXIST, containerComponentType.getValue(), origInst.getName()));
                         }
                         listForUpdate.add(updatedCi);
-                    } else
+                    } else {
                         listForUpdate.add(origInst);
+                    }
                 }
                 containerComponent.setComponentInstances(listForUpdate);
-
-                Either<Component, StorageOperationStatus> updateStatus = toscaOperationFacade.updateComponentInstanceMetadataOfTopologyTemplate(containerComponent, componentFilter);
+                Either<Component, StorageOperationStatus> updateStatus = toscaOperationFacade
+                    .updateComponentInstanceMetadataOfTopologyTemplate(containerComponent, componentFilter);
                 if (updateStatus.isRight()) {
-                    CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to update metadata belonging to container component {}. Status is {}. ", containerComponent.getName(), updateStatus.right().value());
-                    throw new ByResponseFormatComponentException(componentsUtils.getResponseFormatForResourceInstance(componentsUtils.convertFromStorageResponseForResourceInstance(updateStatus.right().value(), true), "", null));
+                    CommonUtility
+                        .addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to update metadata belonging to container component {}. Status is {}. ",
+                            containerComponent.getName(), updateStatus.right().value());
+                    throw new ByResponseFormatComponentException(componentsUtils.getResponseFormatForResourceInstance(
+                        componentsUtils.convertFromStorageResponseForResourceInstance(updateStatus.right().value(), true), "", null));
                 }
-
                 for (ComponentInstance updatedInstance : updateStatus.left().value().getComponentInstances()) {
-                    Optional<ComponentInstance> op = componentInstanceList.stream().filter(ci -> ci.getName().equals(updatedInstance.getName())).findAny();
+                    Optional<ComponentInstance> op = componentInstanceList.stream().filter(ci -> ci.getName().equals(updatedInstance.getName()))
+                        .findAny();
                     if (op.isPresent()) {
                         updatedList.add(updatedInstance);
                     }
                 }
             }
             return updatedList;
-        }catch (ComponentException e){
+        } catch (ComponentException e) {
             failed = true;
             throw e;
-        }finally {
+        } finally {
             if (needLock) {
                 unlockComponent(failed, containerComponent);
             }
@@ -1186,127 +1114,131 @@ public class ComponentInstanceBusinessLogic extends BaseBusinessLogic {
         }
     }
 
-    private ComponentInstance updateComponentInstanceMetadata(Component containerComponent, ComponentTypeEnum containerComponentType, org.openecomp.sdc.be.model.Component origComponent, String componentInstanceId,
+    private ComponentInstance updateComponentInstanceMetadata(Component containerComponent, ComponentTypeEnum containerComponentType,
+                                                              org.openecomp.sdc.be.model.Component origComponent, String componentInstanceId,
                                                               ComponentInstance componentInstance) {
-
         Optional<ComponentInstance> componentInstanceOptional;
         Either<ImmutablePair<Component, String>, StorageOperationStatus> updateRes = null;
         ComponentInstance oldComponentInstance = null;
         boolean isNameChanged = false;
-
-        componentInstanceOptional = containerComponent.getComponentInstances().stream().filter(ci -> ci.getUniqueId().equals(componentInstance.getUniqueId())).findFirst();
+        componentInstanceOptional = containerComponent.getComponentInstances().stream()
+            .filter(ci -> ci.getUniqueId().equals(componentInstance.getUniqueId())).findFirst();
         if (!componentInstanceOptional.isPresent()) {
-            CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to find the component instance {} in container component {}. ", componentInstance.getName(), containerComponent.getName());
+            CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to find the component instance {} in container component {}. ",
+                componentInstance.getName(), containerComponent.getName());
             throw new ByActionStatusComponentException(ActionStatus.COMPONENT_INSTANCE_NOT_FOUND_ON_CONTAINER, componentInstance.getName());
         }
         String oldComponentName;
         oldComponentInstance = componentInstanceOptional.get();
         oldComponentName = oldComponentInstance.getName();
         String newInstanceName = componentInstance.getName();
-        if (oldComponentName != null && !oldComponentInstance.getName().equals(newInstanceName))
+        if (oldComponentName != null && !oldComponentInstance.getName().equals(newInstanceName)) {
             isNameChanged = true;
+        }
         Boolean isUniqueName = validateInstanceNameUniquenessUponUpdate(containerComponent, oldComponentInstance, newInstanceName);
         if (!isUniqueName) {
-            CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to update the name of the component instance {} to {}. A component instance with the same name already exists. ", oldComponentInstance.getName(), newInstanceName);
-            throw new ByActionStatusComponentException(ActionStatus.COMPONENT_NAME_ALREADY_EXIST, containerComponentType.getValue(), componentInstance.getName());
+            CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG,
+                "Failed to update the name of the component instance {} to {}. A component instance with the same name already exists. ",
+                oldComponentInstance.getName(), newInstanceName);
+            throw new ByActionStatusComponentException(ActionStatus.COMPONENT_NAME_ALREADY_EXIST, containerComponentType.getValue(),
+                componentInstance.getName());
         }
-        if(!DirectivesUtil.isValid(componentInstance.getDirectives())) {
-            final String directivesStr =
-                    componentInstance.getDirectives().stream().collect(Collectors.joining(" , ", " [ ", " ] "));
+        if (!DirectivesUtil.isValid(componentInstance.getDirectives())) {
+            final String directivesStr = componentInstance.getDirectives().stream().collect(Collectors.joining(" , ", " [ ", " ] "));
             CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG,
-                    "Failed to update the directives of the component instance {} to {}. Directives data {} is invalid. ",
-                    oldComponentInstance.getName(), newInstanceName ,
-                    directivesStr);
-            throw new ByActionStatusComponentException(ActionStatus.DIRECTIVES_INVALID_VALUE, containerComponentType.getValue(), componentInstance.getName());
+                "Failed to update the directives of the component instance {} to {}. Directives data {} is invalid. ", oldComponentInstance.getName(),
+                newInstanceName, directivesStr);
+            throw new ByActionStatusComponentException(ActionStatus.DIRECTIVES_INVALID_VALUE, containerComponentType.getValue(),
+                componentInstance.getName());
         }
-        updateRes = toscaOperationFacade.updateComponentInstanceMetadataOfTopologyTemplate(containerComponent, origComponent, updateComponentInstanceMetadata(oldComponentInstance, componentInstance));
+        updateRes = toscaOperationFacade.updateComponentInstanceMetadataOfTopologyTemplate(containerComponent, origComponent,
+            updateComponentInstanceMetadata(oldComponentInstance, componentInstance));
         if (updateRes.isRight()) {
-            CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to update metadata of component instance {} belonging to container component {}. Status is {}. ", componentInstance.getName(), containerComponent.getName(),
-                    updateRes.right().value());
-            throw new ByResponseFormatComponentException(componentsUtils.getResponseFormatForResourceInstance(componentsUtils.convertFromStorageResponseForResourceInstance(updateRes.right().value(), true), "", null));
+            CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG,
+                "Failed to update metadata of component instance {} belonging to container component {}. Status is {}. ", componentInstance.getName(),
+                containerComponent.getName(), updateRes.right().value());
+            throw new ByResponseFormatComponentException(componentsUtils
+                .getResponseFormatForResourceInstance(componentsUtils.convertFromStorageResponseForResourceInstance(updateRes.right().value(), true),
+                    "", null));
         } else {
             // region - Update instance Groups
             if (isNameChanged) {
-                Either<StorageOperationStatus, StorageOperationStatus> result =
-                        toscaOperationFacade.cleanAndAddGroupInstancesToComponentInstance(containerComponent, oldComponentInstance, componentInstanceId);
-                if (result.isRight())
-                    CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to rename group instances for container {}. error {} ", componentInstanceId, result.right().value());
-
-                if (containerComponent instanceof Service){
-                    Either<ComponentInstance, ResponseFormat> renameEither =
-                            renameServiceFilter((Service) containerComponent, newInstanceName,
-                                oldComponentInstance.getName());
+                Either<StorageOperationStatus, StorageOperationStatus> result = toscaOperationFacade
+                    .cleanAndAddGroupInstancesToComponentInstance(containerComponent, oldComponentInstance, componentInstanceId);
+                if (result.isRight()) {
+                    CommonUtility
+                        .addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to rename group instances for container {}. error {} ", componentInstanceId,
+                            result.right().value());
+                }
+                if (containerComponent instanceof Service) {
+                    Either<ComponentInstance, ResponseFormat> renameEither = renameServiceFilter((Service) containerComponent, newInstanceName,
+                        oldComponentInstance.getName());
                     if (renameEither.isRight()) {
                         throw new ByResponseFormatComponentException(renameEither.right().value());
                     }
-
                     updateForwardingPathDefinition(containerComponent, componentInstance, oldComponentName);
                 }
             }
             // endregion
         }
         String newInstanceId = updateRes.left().value().getRight();
-        Optional<ComponentInstance> updatedInstanceOptional = updateRes.left().value().getLeft().getComponentInstances().stream().filter(ci -> ci.getUniqueId().equals(newInstanceId)).findFirst();
-
+        Optional<ComponentInstance> updatedInstanceOptional = updateRes.left().value().getLeft().getComponentInstances().stream()
+            .filter(ci -> ci.getUniqueId().equals(newInstanceId)).findFirst();
         if (!updatedInstanceOptional.isPresent()) {
-            log.debug("Failed to update metadata of component instance {} of container component {}", componentInstance.getName(), containerComponent.getName());
-            throw new ByResponseFormatComponentException(componentsUtils.getResponseFormat(ActionStatus.COMPONENT_INSTANCE_NOT_FOUND_ON_CONTAINER, componentInstance.getName()));
+            log.debug("Failed to update metadata of component instance {} of container component {}", componentInstance.getName(),
+                containerComponent.getName());
+            throw new ByResponseFormatComponentException(
+                componentsUtils.getResponseFormat(ActionStatus.COMPONENT_INSTANCE_NOT_FOUND_ON_CONTAINER, componentInstance.getName()));
         }
-
         return componentInstanceOptional.get();
     }
 
     private void updateForwardingPathDefinition(Component containerComponent, ComponentInstance componentInstance, String oldComponentName) {
         Collection<ForwardingPathDataDefinition> forwardingPathDataDefinitions = getForwardingPathDataDefinitions(containerComponent.getUniqueId());
         Set<ForwardingPathDataDefinition> updated = new ForwardingPathUtils()
-                .updateComponentInstanceName(forwardingPathDataDefinitions, oldComponentName,
-                        componentInstance.getName());
+            .updateComponentInstanceName(forwardingPathDataDefinitions, oldComponentName, componentInstance.getName());
         updated.forEach(fp -> {
             Either<ForwardingPathDataDefinition, StorageOperationStatus> resultEither = forwardingPathOperation
-                    .updateForwardingPath(containerComponent.getUniqueId(), fp);
-            if (resultEither.isRight()){
-                CommonUtility.addRecordToLog(log, LogLevelEnum.ERROR, "Failed to rename forwarding path for container {}. error {} ",containerComponent.getName(), resultEither.right().value());
+                .updateForwardingPath(containerComponent.getUniqueId(), fp);
+            if (resultEither.isRight()) {
+                CommonUtility.addRecordToLog(log, LogLevelEnum.ERROR, "Failed to rename forwarding path for container {}. error {} ",
+                    containerComponent.getName(), resultEither.right().value());
             }
         });
     }
 
-
-    public Either<ComponentInstance, ResponseFormat> renameServiceFilter(final Service containerComponent,
-                                                                         final String newInstanceName,
+    public Either<ComponentInstance, ResponseFormat> renameServiceFilter(final Service containerComponent, final String newInstanceName,
                                                                          final String oldInstanceName) {
-
-        Map<String, CINodeFilterDataDefinition> renamedNodesFilter =
-            ServiceFilterUtils.getRenamedNodesFilter(containerComponent, oldInstanceName, newInstanceName);
-        for( Entry<String, CINodeFilterDataDefinition> entry :  renamedNodesFilter.entrySet()){
-            Either<CINodeFilterDataDefinition, StorageOperationStatus>
-                    renameEither = nodeFilterOperation.updateNodeFilter(
-                    containerComponent.getUniqueId(),entry.getKey(),entry.getValue());
-            if (renameEither.isRight()){
-                return  Either.right(componentsUtils.getResponseFormatForResourceInstance(
-                        componentsUtils.convertFromStorageResponse(renameEither.right().value(), ComponentTypeEnum.SERVICE),
-                        containerComponent.getName(), null));
+        Map<String, CINodeFilterDataDefinition> renamedNodesFilter = ServiceFilterUtils
+            .getRenamedNodesFilter(containerComponent, oldInstanceName, newInstanceName);
+        for (Entry<String, CINodeFilterDataDefinition> entry : renamedNodesFilter.entrySet()) {
+            Either<CINodeFilterDataDefinition, StorageOperationStatus> renameEither = nodeFilterOperation
+                .updateNodeFilter(containerComponent.getUniqueId(), entry.getKey(), entry.getValue());
+            if (renameEither.isRight()) {
+                return Either.right(componentsUtils.getResponseFormatForResourceInstance(
+                    componentsUtils.convertFromStorageResponse(renameEither.right().value(), ComponentTypeEnum.SERVICE), containerComponent.getName(),
+                    null));
             }
-
         }
         return Either.left(null);
     }
 
     /**
-     * @param oldPrefix-
-     *            The normalized old vf name
-     * @param newNormailzedPrefix-
-     *            The normalized new vf name
-     * @param qualifiedGroupInstanceName-
-     *            old Group Instance Name
+     * @param oldPrefix-                  The normalized old vf name
+     * @param newNormailzedPrefix-        The normalized new vf name
+     * @param qualifiedGroupInstanceName- old Group Instance Name
      **/
+
     // modify group names
     private String getNewGroupName(String oldPrefix, String newNormailzedPrefix, String qualifiedGroupInstanceName) {
         if (qualifiedGroupInstanceName == null) {
             log.info("CANNOT change group name ");
             return null;
         }
-        if (qualifiedGroupInstanceName.startsWith(oldPrefix) || qualifiedGroupInstanceName.startsWith(ValidationUtils.normalizeComponentInstanceName(oldPrefix)))
+        if (qualifiedGroupInstanceName.startsWith(oldPrefix) || qualifiedGroupInstanceName
+            .startsWith(ValidationUtils.normalizeComponentInstanceName(oldPrefix))) {
             return qualifiedGroupInstanceName.replaceFirst(oldPrefix, newNormailzedPrefix);
+        }
         return qualifiedGroupInstanceName;
     }
 
@@ -1315,42 +1247,37 @@ public class ComponentInstanceBusinessLogic extends BaseBusinessLogic {
         oldComponentInstance.setModificationTime(System.currentTimeMillis());
         oldComponentInstance.setCustomizationUUID(UUID.randomUUID().toString());
         oldComponentInstance.setDirectives(newComponentInstance.getDirectives());
-        if (oldComponentInstance.getGroupInstances() != null)
-            oldComponentInstance.getGroupInstances().forEach(group -> group.setName(getNewGroupName(oldComponentInstance.getNormalizedName(), ValidationUtils.normalizeComponentInstanceName(newComponentInstance.getName()), group.getName())));
+        if (oldComponentInstance.getGroupInstances() != null) {
+            oldComponentInstance.getGroupInstances().forEach(group -> group.setName(getNewGroupName(oldComponentInstance.getNormalizedName(),
+                ValidationUtils.normalizeComponentInstanceName(newComponentInstance.getName()), group.getName())));
+        }
         return oldComponentInstance;
     }
 
-    public ComponentInstance deleteComponentInstance(final String containerComponentParam,
-                                                     final String containerComponentId,
-                                                     final String componentInstanceId, String userId)
-        throws BusinessLogicException {
-
+    public ComponentInstance deleteComponentInstance(final String containerComponentParam, final String containerComponentId,
+                                                     final String componentInstanceId, String userId) throws BusinessLogicException {
         validateUserExists(userId);
         final ComponentTypeEnum containerComponentType = validateComponentType(containerComponentParam);
-
         final Component containerComponent = validateComponentExists(containerComponentId, containerComponentType, null);
         validateCanWorkOnComponent(containerComponent, userId);
-
         boolean failed = false;
         final Optional<ComponentInstance> componentInstanceOptional = containerComponent.getComponentInstanceById(componentInstanceId);
         if (!componentInstanceOptional.isPresent()) {
-            throw new BusinessLogicException(componentsUtils
-                .getResponseFormat(ActionStatus.COMPONENT_INSTANCE_NOT_FOUND));
+            throw new BusinessLogicException(componentsUtils.getResponseFormat(ActionStatus.COMPONENT_INSTANCE_NOT_FOUND));
         }
         ComponentInstance componentInstance = componentInstanceOptional.get();
-
         try {
             if (containerComponent instanceof Service || containerComponent instanceof Resource) {
-                final Either<String, StorageOperationStatus> deleteServiceFilterEither =
-                        nodeFilterOperation.deleteNodeFilter(containerComponent, componentInstanceId);
+                final Either<String, StorageOperationStatus> deleteServiceFilterEither = nodeFilterOperation
+                    .deleteNodeFilter(containerComponent, componentInstanceId);
                 if (deleteServiceFilterEither.isRight()) {
-                    final ActionStatus status = componentsUtils.convertFromStorageResponse(deleteServiceFilterEither.right().value(),
-                            containerComponentType);
+                    final ActionStatus status = componentsUtils
+                        .convertFromStorageResponse(deleteServiceFilterEither.right().value(), containerComponentType);
                     janusGraphDao.rollback();
                     throw new ByResponseFormatComponentException(componentsUtils.getResponseFormat(status, componentInstanceId));
                 }
-                final Either<ComponentInstance, ResponseFormat> resultOp = deleteNodeFiltersFromComponentInstance(
-                    containerComponent, componentInstance, containerComponentType, userId);
+                final Either<ComponentInstance, ResponseFormat> resultOp = deleteNodeFiltersFromComponentInstance(containerComponent,
+                    componentInstance, containerComponentType, userId);
                 if (resultOp.isRight()) {
                     janusGraphDao.rollback();
                     throw new ByResponseFormatComponentException(resultOp.right().value());
@@ -1358,24 +1285,23 @@ public class ComponentInstanceBusinessLogic extends BaseBusinessLogic {
             }
             lockComponent(containerComponent, "deleteComponentInstance");
             final ComponentInstance deletedCompInstance = deleteComponentInstance(containerComponent, componentInstanceId, containerComponentType);
-
-            componentInstance = deleteForwardingPathsRelatedTobeDeletedComponentInstance(containerComponentId,
-                    containerComponentType, deletedCompInstance);
-            final ActionStatus onDeleteOperationsStatus = onChangeInstanceOperationOrchestrator.doOnDeleteInstanceOperations(containerComponent, componentInstanceId);
+            componentInstance = deleteForwardingPathsRelatedTobeDeletedComponentInstance(containerComponentId, containerComponentType,
+                deletedCompInstance);
+            final ActionStatus onDeleteOperationsStatus = onChangeInstanceOperationOrchestrator
+                .doOnDeleteInstanceOperations(containerComponent, componentInstanceId);
             if (ActionStatus.OK != onDeleteOperationsStatus) {
                 throw new ByActionStatusComponentException(onDeleteOperationsStatus);
             }
         } catch (final ComponentException e) {
             failed = true;
             throw e;
-        }
-        finally {
+        } finally {
             unlockComponent(failed, containerComponent);
         }
         return componentInstance;
     }
 
-        /**
+    /**
      * Try to modify the delete and return two cases
      *
      * @param containerComponentParam
@@ -1384,15 +1310,13 @@ public class ComponentInstanceBusinessLogic extends BaseBusinessLogic {
      * @param userId
      * @return
      */
-    public Either<ComponentInstance, ResponseFormat> deleteAbstractComponentInstance(String containerComponentParam, String containerComponentId, String componentInstanceId, String userId) {
+    public Either<ComponentInstance, ResponseFormat> deleteAbstractComponentInstance(String containerComponentParam, String containerComponentId,
+                                                                                     String componentInstanceId, String userId) {
         log.debug("enter deleteAbstractComponentInstance");
         validateUserExists(userId);
-
         final ComponentTypeEnum containerComponentType = validateComponentType(containerComponentParam);
-
         org.openecomp.sdc.be.model.Component containerComponent = validateComponentExists(containerComponentId, containerComponentType, null);
         validateCanWorkOnComponent(containerComponent, userId);
-
         boolean failed = false;
         ComponentInstance deletedRelatedInst;
         try {
@@ -1400,17 +1324,17 @@ public class ComponentInstanceBusinessLogic extends BaseBusinessLogic {
                 final Optional<ComponentInstance> componentInstanceById = containerComponent.getComponentInstanceById(componentInstanceId);
                 if (componentInstanceById.isPresent()) {
                     ComponentInstance componentInstance = componentInstanceById.get();
-                    Either<String, StorageOperationStatus> deleteServiceFilterEither =
-                        nodeFilterOperation.deleteNodeFilter(containerComponent, componentInstanceId);
+                    Either<String, StorageOperationStatus> deleteServiceFilterEither = nodeFilterOperation
+                        .deleteNodeFilter(containerComponent, componentInstanceId);
                     if (deleteServiceFilterEither.isRight()) {
                         log.debug("enter deleteAbstractComponentInstance:deleteServiceFilterEither is right, filed");
-                        ActionStatus status = componentsUtils.convertFromStorageResponse(deleteServiceFilterEither.right().value(),
-                            containerComponentType);
+                        ActionStatus status = componentsUtils
+                            .convertFromStorageResponse(deleteServiceFilterEither.right().value(), containerComponentType);
                         janusGraphDao.rollback();
                         return Either.right(componentsUtils.getResponseFormat(status, componentInstance.getName()));
                     }
-                    Either<ComponentInstance, ResponseFormat> resultOp = deleteNodeFiltersFromComponentInstance(containerComponent,
-                        componentInstance, ComponentTypeEnum.SERVICE, userId);
+                    Either<ComponentInstance, ResponseFormat> resultOp = deleteNodeFiltersFromComponentInstance(containerComponent, componentInstance,
+                        ComponentTypeEnum.SERVICE, userId);
                     if (resultOp.isRight()) {
                         log.debug("enter deleteAbstractComponentInstance:resultOp is right, filed");
                         janusGraphDao.rollback();
@@ -1421,11 +1345,11 @@ public class ComponentInstanceBusinessLogic extends BaseBusinessLogic {
             log.debug("enter deleteAbstractComponentInstance:");
             lockComponent(containerComponent, "deleteComponentInstance");
             ComponentInstance deletedCompInstance = deleteComponentInstance(containerComponent, componentInstanceId, containerComponentType);
-
-            deletedRelatedInst = deleteForwardingPathsRelatedTobeDeletedComponentInstance(containerComponentId,
-                    containerComponentType, deletedCompInstance);
-            ActionStatus onDeleteOperationsStatus = onChangeInstanceOperationOrchestrator.doOnDeleteInstanceOperations(containerComponent, componentInstanceId);
-            log.debug("enter deleteAbstractComponentInstance,get onDeleteOperationsStatus:{}",onDeleteOperationsStatus);
+            deletedRelatedInst = deleteForwardingPathsRelatedTobeDeletedComponentInstance(containerComponentId, containerComponentType,
+                deletedCompInstance);
+            ActionStatus onDeleteOperationsStatus = onChangeInstanceOperationOrchestrator
+                .doOnDeleteInstanceOperations(containerComponent, componentInstanceId);
+            log.debug("enter deleteAbstractComponentInstance,get onDeleteOperationsStatus:{}", onDeleteOperationsStatus);
             if (ActionStatus.OK != onDeleteOperationsStatus) {
                 throw new ByActionStatusComponentException(onDeleteOperationsStatus);
             }
@@ -1439,24 +1363,19 @@ public class ComponentInstanceBusinessLogic extends BaseBusinessLogic {
         return Either.left(deletedRelatedInst);
     }
 
-    public Either<ComponentInstance, ResponseFormat> deleteNodeFiltersFromComponentInstance(
-        final Component component,
-        final ComponentInstance componentInstance,
-        final ComponentTypeEnum containerComponentType,
-        final String userId) {
-
-        final Set<String> componentFiltersIDsToBeDeleted =
-            getComponentFiltersRelatedToComponentInstance(component.getUniqueId(), componentInstance);
+    public Either<ComponentInstance, ResponseFormat> deleteNodeFiltersFromComponentInstance(final Component component,
+                                                                                            final ComponentInstance componentInstance,
+                                                                                            final ComponentTypeEnum containerComponentType,
+                                                                                            final String userId) {
+        final Set<String> componentFiltersIDsToBeDeleted = getComponentFiltersRelatedToComponentInstance(component.getUniqueId(), componentInstance);
         if (!componentFiltersIDsToBeDeleted.isEmpty()) {
-            final Set<String> ids = component.getComponentInstances().stream()
-                .filter(ci -> componentFiltersIDsToBeDeleted.contains(ci.getName()))
+            final Set<String> ids = component.getComponentInstances().stream().filter(ci -> componentFiltersIDsToBeDeleted.contains(ci.getName()))
                 .map(ComponentInstance::getUniqueId).collect(Collectors.toSet());
-            final Either<Set<String>, StorageOperationStatus> deleteComponentNodeFiltersEither =
-                nodeFilterOperation.deleteNodeFilters(component, ids);
+            final Either<Set<String>, StorageOperationStatus> deleteComponentNodeFiltersEither = nodeFilterOperation
+                .deleteNodeFilters(component, ids);
             if (deleteComponentNodeFiltersEither.isRight()) {
                 final ActionStatus status = componentsUtils
-                    .convertFromStorageResponse(deleteComponentNodeFiltersEither.right().value(),
-                        containerComponentType);
+                    .convertFromStorageResponse(deleteComponentNodeFiltersEither.right().value(), containerComponentType);
                 return Either.right(componentsUtils.getResponseFormat(status, componentInstance.getName()));
             }
             for (final String id : ids) {
@@ -1465,11 +1384,10 @@ public class ComponentInstanceBusinessLogic extends BaseBusinessLogic {
                     return Either.right(componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR));
                 }
                 final ComponentInstance componentInstanceToBeUpdated = componentInstanceById.get();
-
                 componentInstanceToBeUpdated.setDirectives(Collections.emptyList());
-                final Either<ComponentInstance, ResponseFormat> componentInstanceResponseFormatEither =
-                    updateComponentInstanceMetadata(containerComponentType.getValue(), component.getUniqueId(),
-                        componentInstanceToBeUpdated.getUniqueId(), userId, componentInstanceToBeUpdated, false);
+                final Either<ComponentInstance, ResponseFormat> componentInstanceResponseFormatEither = updateComponentInstanceMetadata(
+                    containerComponentType.getValue(), component.getUniqueId(), componentInstanceToBeUpdated.getUniqueId(), userId,
+                    componentInstanceToBeUpdated, false);
                 if (componentInstanceResponseFormatEither.isRight()) {
                     return componentInstanceResponseFormatEither;
                 }
@@ -1478,19 +1396,17 @@ public class ComponentInstanceBusinessLogic extends BaseBusinessLogic {
         return Either.left(componentInstance);
     }
 
-    private Set<String> getComponentFiltersRelatedToComponentInstance(String containerComponentId,
-                                                                      ComponentInstance componentInstance) {
+    private Set<String> getComponentFiltersRelatedToComponentInstance(String containerComponentId, ComponentInstance componentInstance) {
         ComponentParametersView filter = new ComponentParametersView(true);
         filter.setIgnoreComponentInstances(false);
-        Either<Component, StorageOperationStatus> componentFilterOrigin =
-                toscaOperationFacade.getToscaElement(containerComponentId, filter);
+        Either<Component, StorageOperationStatus> componentFilterOrigin = toscaOperationFacade.getToscaElement(containerComponentId, filter);
         final Component component = componentFilterOrigin.left().value();
         return ComponentsUtils.getNodesFiltersToBeDeleted(component, componentInstance);
     }
 
-    ComponentInstance deleteForwardingPathsRelatedTobeDeletedComponentInstance(String containerComponentId,
-                                                                               ComponentTypeEnum containerComponentType, ComponentInstance componentInstance) {
-        if(containerComponentType == ComponentTypeEnum.SERVICE){
+    ComponentInstance deleteForwardingPathsRelatedTobeDeletedComponentInstance(String containerComponentId, ComponentTypeEnum containerComponentType,
+                                                                               ComponentInstance componentInstance) {
+        if (containerComponentType == ComponentTypeEnum.SERVICE) {
             List<String> pathIDsToBeDeleted = getForwardingPathsRelatedToComponentInstance(containerComponentId, componentInstance.getName());
             if (!pathIDsToBeDeleted.isEmpty()) {
                 deleteForwardingPaths(containerComponentId, pathIDsToBeDeleted);
@@ -1499,48 +1415,43 @@ public class ComponentInstanceBusinessLogic extends BaseBusinessLogic {
         return componentInstance;
     }
 
-    private void deleteForwardingPaths(String serviceId,  List<String> pathIdsToDelete){
-
+    private void deleteForwardingPaths(String serviceId, List<String> pathIdsToDelete) {
         Either<Service, StorageOperationStatus> storageStatus = toscaOperationFacade.getToscaElement(serviceId);
-        if(storageStatus.isRight()) {
+        if (storageStatus.isRight()) {
             throw new ByActionStatusComponentException(componentsUtils.convertFromStorageResponse(storageStatus.right().value()));
         }
-        Either<Set<String>, StorageOperationStatus> result = forwardingPathOperation.deleteForwardingPath(storageStatus.left().value(),
-                Sets.newHashSet(pathIdsToDelete));
-
-        if(result.isRight()) {
+        Either<Set<String>, StorageOperationStatus> result = forwardingPathOperation
+            .deleteForwardingPath(storageStatus.left().value(), Sets.newHashSet(pathIdsToDelete));
+        if (result.isRight()) {
             throw new ByActionStatusComponentException(componentsUtils.convertFromStorageResponse(result.right().value()));
         }
     }
 
-    private List<String> getForwardingPathsRelatedToComponentInstance(String containerComponentId, String componentInstanceId){
+    private List<String> getForwardingPathsRelatedToComponentInstance(String containerComponentId, String componentInstanceId) {
         Collection<ForwardingPathDataDefinition> allPaths = getForwardingPathDataDefinitions(containerComponentId);
         List<String> pathIDsToBeDeleted = new ArrayList<>();
-
-        allPaths.stream().filter(path -> isPathRelatedToComponent(path,componentInstanceId ))
-                .forEach(path -> pathIDsToBeDeleted.add(path.getUniqueId()));
-
+        allPaths.stream().filter(path -> isPathRelatedToComponent(path, componentInstanceId))
+            .forEach(path -> pathIDsToBeDeleted.add(path.getUniqueId()));
         return pathIDsToBeDeleted;
     }
 
     private Collection<ForwardingPathDataDefinition> getForwardingPathDataDefinitions(String containerComponentId) {
         ComponentParametersView filter = new ComponentParametersView(true);
         filter.setIgnoreServicePath(false);
-        Either<Service, StorageOperationStatus> forwardingPathOrigin = toscaOperationFacade
-                .getToscaElement(containerComponentId, filter);
+        Either<Service, StorageOperationStatus> forwardingPathOrigin = toscaOperationFacade.getToscaElement(containerComponentId, filter);
         return forwardingPathOrigin.left().value().getForwardingPaths().values();
     }
 
-    private boolean isPathRelatedToComponent(ForwardingPathDataDefinition pathDataDefinition,
-                                             String componentInstanceId){
-        return pathDataDefinition.getPathElements().getListToscaDataDefinition()
-                .stream().anyMatch(elementDataDefinition -> elementDataDefinition.getFromNode().equalsIgnoreCase(componentInstanceId) ||
-                        elementDataDefinition.getToNode()
-                                .equalsIgnoreCase(componentInstanceId));
+    private boolean isPathRelatedToComponent(ForwardingPathDataDefinition pathDataDefinition, String componentInstanceId) {
+        return pathDataDefinition.getPathElements().getListToscaDataDefinition().stream().anyMatch(
+            elementDataDefinition -> elementDataDefinition.getFromNode().equalsIgnoreCase(componentInstanceId) || elementDataDefinition.getToNode()
+                .equalsIgnoreCase(componentInstanceId));
     }
 
-    private ComponentInstance deleteComponentInstance(Component containerComponent, String componentInstanceId, ComponentTypeEnum containerComponentType) {
-        Either<ImmutablePair<Component, String>, StorageOperationStatus> deleteRes = toscaOperationFacade.deleteComponentInstanceFromTopologyTemplate(containerComponent, componentInstanceId);
+    private ComponentInstance deleteComponentInstance(Component containerComponent, String componentInstanceId,
+                                                      ComponentTypeEnum containerComponentType) {
+        Either<ImmutablePair<Component, String>, StorageOperationStatus> deleteRes = toscaOperationFacade
+            .deleteComponentInstanceFromTopologyTemplate(containerComponent, componentInstanceId);
         if (deleteRes.isRight()) {
             log.debug("Failed to delete entry on graph for resourceInstance {}", componentInstanceId);
             ActionStatus status = componentsUtils.convertFromStorageResponse(deleteRes.right().value(), containerComponentType);
@@ -1548,26 +1459,29 @@ public class ComponentInstanceBusinessLogic extends BaseBusinessLogic {
         }
         log.debug("The component instance {} has been removed from container component {}. ", componentInstanceId, containerComponent);
         ComponentInstance deletedInstance = findAndRemoveComponentInstanceFromContainerComponent(componentInstanceId, containerComponent);
-
         if (CollectionUtils.isNotEmpty(containerComponent.getInputs())) {
-            List<InputDefinition> inputsToDelete = containerComponent.getInputs().stream().filter(i -> i.getInstanceUniqueId() != null && i.getInstanceUniqueId().equals(componentInstanceId)).collect(Collectors.toList());
+            List<InputDefinition> inputsToDelete = containerComponent.getInputs().stream()
+                .filter(i -> i.getInstanceUniqueId() != null && i.getInstanceUniqueId().equals(componentInstanceId)).collect(Collectors.toList());
             if (CollectionUtils.isNotEmpty(inputsToDelete)) {
-                StorageOperationStatus deleteInputsRes = toscaOperationFacade.deleteComponentInstanceInputsFromTopologyTemplate(containerComponent, inputsToDelete);
+                StorageOperationStatus deleteInputsRes = toscaOperationFacade
+                    .deleteComponentInstanceInputsFromTopologyTemplate(containerComponent, inputsToDelete);
                 if (deleteInputsRes != StorageOperationStatus.OK) {
                     log.debug("Failed to delete inputs of the component instance {} from container component. ", componentInstanceId);
-                    throw new ByActionStatusComponentException(
-                            componentsUtils.convertFromStorageResponse(deleteInputsRes, containerComponentType), componentInstanceId);
+                    throw new ByActionStatusComponentException(componentsUtils.convertFromStorageResponse(deleteInputsRes, containerComponentType),
+                        componentInstanceId);
                 }
             }
         }
         if (CollectionUtils.isNotEmpty(containerComponent.getOutputs())) {
-            final List<OutputDefinition> outputsToDelete = containerComponent.getOutputs().stream().filter(i -> i.getInstanceUniqueId() != null && i.getInstanceUniqueId().equals(componentInstanceId)).collect(Collectors.toList());
+            final List<OutputDefinition> outputsToDelete = containerComponent.getOutputs().stream()
+                .filter(i -> i.getInstanceUniqueId() != null && i.getInstanceUniqueId().equals(componentInstanceId)).collect(Collectors.toList());
             if (CollectionUtils.isNotEmpty(outputsToDelete)) {
-                final StorageOperationStatus deleteOutputsRes = toscaOperationFacade.deleteComponentInstanceOutputsFromTopologyTemplate(containerComponent, outputsToDelete);
+                final StorageOperationStatus deleteOutputsRes = toscaOperationFacade
+                    .deleteComponentInstanceOutputsFromTopologyTemplate(containerComponent, outputsToDelete);
                 if (deleteOutputsRes != StorageOperationStatus.OK) {
                     log.debug("Failed to delete outputs of the component instance {} from container component. ", componentInstanceId);
-                    throw new ByActionStatusComponentException(
-                            componentsUtils.convertFromStorageResponse(deleteOutputsRes, containerComponentType), componentInstanceId);
+                    throw new ByActionStatusComponentException(componentsUtils.convertFromStorageResponse(deleteOutputsRes, containerComponentType),
+                        componentInstanceId);
                 }
             }
         }
@@ -1588,8 +1502,10 @@ public class ComponentInstanceBusinessLogic extends BaseBusinessLogic {
     }
 
     private void findAndRemoveComponentInstanceRelations(String componentInstanceId, Component containerComponent) {
-        if(CollectionUtils.isNotEmpty(containerComponent.getComponentInstancesRelations())){
-            containerComponent.setComponentInstancesRelations(containerComponent.getComponentInstancesRelations().stream().filter(r -> isNotBelongingRelation(componentInstanceId, r)).collect(Collectors.toList()));
+        if (CollectionUtils.isNotEmpty(containerComponent.getComponentInstancesRelations())) {
+            containerComponent.setComponentInstancesRelations(
+                containerComponent.getComponentInstancesRelations().stream().filter(r -> isNotBelongingRelation(componentInstanceId, r))
+                    .collect(Collectors.toList()));
         }
     }
 
@@ -1597,19 +1513,16 @@ public class ComponentInstanceBusinessLogic extends BaseBusinessLogic {
         return !relation.getToNode().equals(componentInstanceId) && !relation.getFromNode().equals(componentInstanceId);
     }
 
-    public RequirementCapabilityRelDef associateRIToRI(String componentId, String userId, RequirementCapabilityRelDef requirementDef, ComponentTypeEnum componentTypeEnum) {
+    public RequirementCapabilityRelDef associateRIToRI(String componentId, String userId, RequirementCapabilityRelDef requirementDef,
+                                                       ComponentTypeEnum componentTypeEnum) {
         return associateRIToRI(componentId, userId, requirementDef, componentTypeEnum, true);
     }
 
     public RequirementCapabilityRelDef associateRIToRI(String componentId, String userId, RequirementCapabilityRelDef requirementDef,
                                                        ComponentTypeEnum componentTypeEnum, boolean needLock) {
-
         validateUserExists(userId);
-
         RequirementCapabilityRelDef requirementCapabilityRelDef;
-
         org.openecomp.sdc.be.model.Component containerComponent = validateComponentExists(componentId, componentTypeEnum, null);
-
         validateCanWorkOnComponent(containerComponent, userId);
         boolean failed = false;
         try {
@@ -1617,22 +1530,21 @@ public class ComponentInstanceBusinessLogic extends BaseBusinessLogic {
                 lockComponent(containerComponent, ASSOCIATE_RI_TO_RI);
             }
             requirementCapabilityRelDef = associateRIToRIOnGraph(containerComponent, requirementDef);
-        }catch (ComponentException e){
+        } catch (ComponentException e) {
             failed = true;
             throw e;
-        }finally {
-            if (needLock)
+        } finally {
+            if (needLock) {
                 unlockComponent(failed, containerComponent);
+            }
         }
         return requirementCapabilityRelDef;
     }
 
     public RequirementCapabilityRelDef associateRIToRIOnGraph(Component containerComponent, RequirementCapabilityRelDef requirementDef) {
-
         log.debug(TRY_TO_CREATE_ENTRY_ON_GRAPH);
-
-        Either<RequirementCapabilityRelDef, StorageOperationStatus> result = toscaOperationFacade.associateResourceInstances(null, containerComponent.getUniqueId(), requirementDef);
-
+        Either<RequirementCapabilityRelDef, StorageOperationStatus> result = toscaOperationFacade
+            .associateResourceInstances(null, containerComponent.getUniqueId(), requirementDef);
         if (result.isLeft()) {
             log.debug(ENTITY_ON_GRAPH_IS_CREATED);
             return result.left().value();
@@ -1642,7 +1554,6 @@ public class ComponentInstanceBusinessLogic extends BaseBusinessLogic {
             String toNameOrId = "";
             Either<ComponentInstance, StorageOperationStatus> fromResult = getResourceInstanceById(containerComponent, requirementDef.getFromNode());
             Either<ComponentInstance, StorageOperationStatus> toResult = getResourceInstanceById(containerComponent, requirementDef.getToNode());
-
             toNameOrId = requirementDef.getFromNode();
             fromNameOrId = requirementDef.getFromNode();
             if (fromResult.isLeft()) {
@@ -1651,12 +1562,9 @@ public class ComponentInstanceBusinessLogic extends BaseBusinessLogic {
             if (toResult.isLeft()) {
                 toNameOrId = toResult.left().value().getName();
             }
-
-            throw new ByActionStatusComponentException(componentsUtils.convertFromStorageResponseForResourceInstance
-                    (result.right().value(), true), fromNameOrId, toNameOrId,
-                    requirementDef.getRelationships().get(0).getRelation().getRequirement());
+            throw new ByActionStatusComponentException(componentsUtils.convertFromStorageResponseForResourceInstance(result.right().value(), true),
+                fromNameOrId, toNameOrId, requirementDef.getRelationships().get(0).getRelation().getRequirement());
         }
-
     }
 
     /**
@@ -1666,12 +1574,9 @@ public class ComponentInstanceBusinessLogic extends BaseBusinessLogic {
      * @param componentTypeEnum
      * @return
      */
-    public List<RequirementCapabilityRelDef> batchDissociateRIFromRI(
-            String componentId,
-            String userId,
-            List<RequirementCapabilityRelDef> requirementDefList,
-            ComponentTypeEnum componentTypeEnum) {
-
+    public List<RequirementCapabilityRelDef> batchDissociateRIFromRI(String componentId, String userId,
+                                                                     List<RequirementCapabilityRelDef> requirementDefList,
+                                                                     ComponentTypeEnum componentTypeEnum) {
         validateUserExists(userId);
         org.openecomp.sdc.be.model.Component containerComponent = validateComponentExists(componentId, componentTypeEnum, null);
         validateCanWorkOnComponent(containerComponent, userId);
@@ -1680,41 +1585,40 @@ public class ComponentInstanceBusinessLogic extends BaseBusinessLogic {
         try {
             lockComponent(containerComponent, ASSOCIATE_RI_TO_RI);
             for (RequirementCapabilityRelDef requirementDef : requirementDefList) {
-                RequirementCapabilityRelDef requirementCapabilityRelDef = dissociateRIFromRI(
-                        componentId, userId, requirementDef, containerComponent.getComponentType());
+                RequirementCapabilityRelDef requirementCapabilityRelDef = dissociateRIFromRI(componentId, userId, requirementDef,
+                    containerComponent.getComponentType());
                 delOkResult.add(requirementCapabilityRelDef);
             }
-        }catch (ComponentException e){
+        } catch (ComponentException e) {
             failed = true;
             throw e;
-        }finally {
+        } finally {
             unlockComponent(failed, containerComponent);
         }
         return delOkResult;
     }
 
-    public RequirementCapabilityRelDef dissociateRIFromRI(String componentId, String userId, RequirementCapabilityRelDef requirementDef, ComponentTypeEnum componentTypeEnum) {
+    public RequirementCapabilityRelDef dissociateRIFromRI(String componentId, String userId, RequirementCapabilityRelDef requirementDef,
+                                                          ComponentTypeEnum componentTypeEnum) {
         validateUserExists(userId);
-
         org.openecomp.sdc.be.model.Component containerComponent = validateComponentExists(componentId, componentTypeEnum, null);
-
         validateCanWorkOnComponent(containerComponent, userId);
         boolean failed = false;
         try {
             lockComponent(containerComponent, ASSOCIATE_RI_TO_RI);
             log.debug(TRY_TO_CREATE_ENTRY_ON_GRAPH);
-            Either<RequirementCapabilityRelDef, StorageOperationStatus> result = toscaOperationFacade.dissociateResourceInstances(componentId, requirementDef);
+            Either<RequirementCapabilityRelDef, StorageOperationStatus> result = toscaOperationFacade
+                .dissociateResourceInstances(componentId, requirementDef);
             if (result.isLeft()) {
                 log.debug(ENTITY_ON_GRAPH_IS_CREATED);
                 return result.left().value();
             } else {
-
                 log.debug("Failed to dissocaite node  {} from node {}", requirementDef.getFromNode(), requirementDef.getToNode());
                 String fromNameOrId = "";
                 String toNameOrId = "";
-                Either<ComponentInstance, StorageOperationStatus> fromResult = getResourceInstanceById(containerComponent, requirementDef.getFromNode());
+                Either<ComponentInstance, StorageOperationStatus> fromResult = getResourceInstanceById(containerComponent,
+                    requirementDef.getFromNode());
                 Either<ComponentInstance, StorageOperationStatus> toResult = getResourceInstanceById(containerComponent, requirementDef.getToNode());
-
                 toNameOrId = requirementDef.getFromNode();
                 fromNameOrId = requirementDef.getFromNode();
                 if (fromResult.isLeft()) {
@@ -1723,57 +1627,57 @@ public class ComponentInstanceBusinessLogic extends BaseBusinessLogic {
                 if (toResult.isLeft()) {
                     toNameOrId = toResult.left().value().getName();
                 }
-
                 throw new ByActionStatusComponentException(
-                        componentsUtils.convertFromStorageResponseForResourceInstance(result.right().value(), true),
-                        fromNameOrId, toNameOrId, requirementDef.getRelationships().get(0).getRelation().getRequirement());
+                    componentsUtils.convertFromStorageResponseForResourceInstance(result.right().value(), true), fromNameOrId, toNameOrId,
+                    requirementDef.getRelationships().get(0).getRelation().getRequirement());
             }
-        }catch (ComponentException e){
+        } catch (ComponentException e) {
             failed = true;
             throw e;
-        }finally {
+        } finally {
             unlockComponent(failed, containerComponent);
         }
     }
+
     /**
      * Allows to get relation contained in specified component according to received Id
+     *
      * @param componentId
      * @param relationId
      * @param userId
      * @param componentTypeEnum
      * @return
      */
-    public Either<RequirementCapabilityRelDef, ResponseFormat> getRelationById(String componentId, String relationId, String userId, ComponentTypeEnum componentTypeEnum) {
-
+    public Either<RequirementCapabilityRelDef, ResponseFormat> getRelationById(String componentId, String relationId, String userId,
+                                                                               ComponentTypeEnum componentTypeEnum) {
         Either<RequirementCapabilityRelDef, ResponseFormat> resultOp = null;
         try {
             org.openecomp.sdc.be.model.Component containerComponent = null;
             RequirementCapabilityRelDef foundRelation = null;
-
             validateUserExists(userId);
             containerComponent = validateComponentExists(componentId, componentTypeEnum, null);
             List<RequirementCapabilityRelDef> requirementCapabilityRelations = containerComponent.getComponentInstancesRelations();
             foundRelation = findRelation(relationId, requirementCapabilityRelations);
-            if(foundRelation == null){
+            if (foundRelation == null) {
                 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.RELATION_NOT_FOUND, relationId, componentId);
                 log.debug("Relation with id {} was not found on the component", relationId, componentId);
                 resultOp = Either.right(responseFormat);
             }
-            if(resultOp == null){
+            if (resultOp == null) {
                 resultOp = setRelatedCapability(foundRelation, containerComponent);
             }
-            if(resultOp.isLeft()){
+            if (resultOp.isLeft()) {
                 resultOp = setRelatedRequirement(foundRelation, containerComponent);
             }
         } catch (Exception e) {
             log.error("The exception {} occured upon get relation {} of the component {} ", e, relationId, componentId);
-            resultOp =  Either.right(componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR));
+            resultOp = Either.right(componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR));
         }
         return resultOp;
     }
 
     private RequirementCapabilityRelDef findRelation(String relationId, List<RequirementCapabilityRelDef> requirementCapabilityRelations) {
-        for(RequirementCapabilityRelDef relationship : requirementCapabilityRelations){
+        for (RequirementCapabilityRelDef relationship : requirementCapabilityRelations) {
             if (relationship.getRelationships().stream().anyMatch(r -> r.getRelation().getId().equals(relationId))) {
                 return relationship;
             }
@@ -1781,13 +1685,14 @@ public class ComponentInstanceBusinessLogic extends BaseBusinessLogic {
         return null;
     }
 
-    private Either<RequirementCapabilityRelDef, ResponseFormat> setRelatedRequirement(RequirementCapabilityRelDef foundRelation, Component containerComponent) {
+    private Either<RequirementCapabilityRelDef, ResponseFormat> setRelatedRequirement(RequirementCapabilityRelDef foundRelation,
+                                                                                      Component containerComponent) {
         Either<RequirementCapabilityRelDef, ResponseFormat> result = null;
         RelationshipInfo relationshipInfo = foundRelation.resolveSingleRelationship().getRelation();
         String instanceId = foundRelation.getFromNode();
         Optional<RequirementDefinition> foundRequirement;
-        Optional<ComponentInstance> instance = containerComponent.getComponentInstances().stream()
-            .filter(i -> i.getUniqueId().equals(instanceId)).findFirst();
+        Optional<ComponentInstance> instance = containerComponent.getComponentInstances().stream().filter(i -> i.getUniqueId().equals(instanceId))
+            .findFirst();
         if (!instance.isPresent()) {
             ResponseFormat responseFormat = componentsUtils
                 .getResponseFormat(ActionStatus.COMPONENT_INSTANCE_NOT_FOUND_ON_CONTAINER, instanceId, "instance",
@@ -1807,12 +1712,11 @@ public class ComponentInstanceBusinessLogic extends BaseBusinessLogic {
         }
         if (result == null) {
             Either<RequirementDataDefinition, StorageOperationStatus> getfulfilledRequirementRes = toscaOperationFacade
-                .getFulfilledRequirementByRelation(containerComponent.getUniqueId(), instanceId, foundRelation,
-                    this::isBelongingFullRequirement);
+                .getFulfilledRequirementByRelation(containerComponent.getUniqueId(), instanceId, foundRelation, this::isBelongingFullRequirement);
             if (getfulfilledRequirementRes.isRight()) {
                 ResponseFormat responseFormat = componentsUtils
-                    .getResponseFormat(ActionStatus.REQUIREMENT_OF_INSTANCE_NOT_FOUND_ON_CONTAINER, relationshipInfo.getRequirement(),
-                        instanceId, containerComponent.getUniqueId());
+                    .getResponseFormat(ActionStatus.REQUIREMENT_OF_INSTANCE_NOT_FOUND_ON_CONTAINER, relationshipInfo.getRequirement(), instanceId,
+                        containerComponent.getUniqueId());
                 log.debug("Requirement {} of instance {} was not found on the container {}. ", relationshipInfo.getCapability(), instanceId,
                     containerComponent.getUniqueId());
                 result = Either.right(responseFormat);
@@ -1827,24 +1731,23 @@ public class ComponentInstanceBusinessLogic extends BaseBusinessLogic {
     }
 
     private boolean isBelongingFullRequirement(RelationshipInfo relationshipInfo, RequirementDataDefinition req) {
-        return  req.getName().equals(relationshipInfo.getRequirement()) &&
-                req.getUniqueId().equals(relationshipInfo.getRequirementUid()) &&
-                req.getOwnerId().equals(relationshipInfo.getRequirementOwnerId());
+        return req.getName().equals(relationshipInfo.getRequirement()) && req.getUniqueId().equals(relationshipInfo.getRequirementUid()) && req
+            .getOwnerId().equals(relationshipInfo.getRequirementOwnerId());
     }
 
     private boolean isBelongingCalcRequirement(RelationshipInfo relationshipInfo, RequirementDataDefinition req, LifecycleStateEnum state) {
-        return  nameMatches(relationshipInfo.getRequirement(), req.getName(), req.getPreviousName(), state) &&
-                req.getUniqueId().equals(relationshipInfo.getRequirementUid()) &&
-                req.getOwnerId().equals(relationshipInfo.getRequirementOwnerId());
+        return nameMatches(relationshipInfo.getRequirement(), req.getName(), req.getPreviousName(), state) && req.getUniqueId()
+            .equals(relationshipInfo.getRequirementUid()) && req.getOwnerId().equals(relationshipInfo.getRequirementOwnerId());
     }
 
-    private Either<RequirementCapabilityRelDef, ResponseFormat> setRelatedCapability(RequirementCapabilityRelDef foundRelation, Component containerComponent) {
+    private Either<RequirementCapabilityRelDef, ResponseFormat> setRelatedCapability(RequirementCapabilityRelDef foundRelation,
+                                                                                     Component containerComponent) {
         Either<RequirementCapabilityRelDef, ResponseFormat> result = null;
         RelationshipInfo relationshipInfo = foundRelation.resolveSingleRelationship().getRelation();
         String instanceId = foundRelation.getToNode();
         Optional<CapabilityDefinition> foundCapability;
-        Optional<ComponentInstance> instance = containerComponent.getComponentInstances().stream()
-            .filter(i -> i.getUniqueId().equals(instanceId)).findFirst();
+        Optional<ComponentInstance> instance = containerComponent.getComponentInstances().stream().filter(i -> i.getUniqueId().equals(instanceId))
+            .findFirst();
         if (!instance.isPresent()) {
             ResponseFormat responseFormat = componentsUtils
                 .getResponseFormat(ActionStatus.COMPONENT_INSTANCE_NOT_FOUND_ON_CONTAINER, instanceId, "instance",
@@ -1863,13 +1766,12 @@ public class ComponentInstanceBusinessLogic extends BaseBusinessLogic {
             }
         }
         if (result == null) {
-            Either<CapabilityDataDefinition, StorageOperationStatus> getfulfilledRequirementRes =
-                toscaOperationFacade.getFulfilledCapabilityByRelation(containerComponent.getUniqueId(), instanceId, foundRelation,
-                    this::isBelongingFullCapability);
+            Either<CapabilityDataDefinition, StorageOperationStatus> getfulfilledRequirementRes = toscaOperationFacade
+                .getFulfilledCapabilityByRelation(containerComponent.getUniqueId(), instanceId, foundRelation, this::isBelongingFullCapability);
             if (getfulfilledRequirementRes.isRight()) {
                 ResponseFormat responseFormat = componentsUtils
-                    .getResponseFormat(ActionStatus.CAPABILITY_OF_INSTANCE_NOT_FOUND_ON_CONTAINER, relationshipInfo.getCapability(),
-                        instanceId, containerComponent.getUniqueId());
+                    .getResponseFormat(ActionStatus.CAPABILITY_OF_INSTANCE_NOT_FOUND_ON_CONTAINER, relationshipInfo.getCapability(), instanceId,
+                        containerComponent.getUniqueId());
                 log.debug("Capability {} of instance {} was not found on the container {}. ", relationshipInfo.getCapability(), instanceId,
                     containerComponent.getUniqueId());
                 result = Either.right(responseFormat);
@@ -1877,73 +1779,61 @@ public class ComponentInstanceBusinessLogic extends BaseBusinessLogic {
                 foundRelation.resolveSingleRelationship().setCapability(getfulfilledRequirementRes.left().value());
             }
         }
-        if(result == null){
+        if (result == null) {
             result = Either.left(foundRelation);
         }
         return result;
     }
 
     private boolean isBelongingFullCapability(RelationshipInfo relationshipInfo, CapabilityDataDefinition cap) {
-        return     cap.getName().equals(relationshipInfo.getCapability()) &&
-                cap.getUniqueId().equals(relationshipInfo.getCapabilityUid()) &&
-                cap.getOwnerId().equals(relationshipInfo.getCapabilityOwnerId());
+        return cap.getName().equals(relationshipInfo.getCapability()) && cap.getUniqueId().equals(relationshipInfo.getCapabilityUid()) && cap
+            .getOwnerId().equals(relationshipInfo.getCapabilityOwnerId());
     }
 
     private boolean isBelongingCalcCapability(RelationshipInfo relationshipInfo, CapabilityDataDefinition cap, LifecycleStateEnum state) {
-        return  nameMatches(relationshipInfo.getCapability(), cap.getName(), cap.getPreviousName(), state) &&
-                cap.getUniqueId().equals(relationshipInfo.getCapabilityUid()) &&
-                cap.getOwnerId().equals(relationshipInfo.getCapabilityOwnerId());
+        return nameMatches(relationshipInfo.getCapability(), cap.getName(), cap.getPreviousName(), state) && cap.getUniqueId()
+            .equals(relationshipInfo.getCapabilityUid()) && cap.getOwnerId().equals(relationshipInfo.getCapabilityOwnerId());
     }
 
     private boolean nameMatches(String nameFromRelationship, String currName, String previousName, LifecycleStateEnum state) {
-        return state == LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT ?
-                currName.equals(nameFromRelationship):
-                previousName!= null && previousName.equals(nameFromRelationship);
+        return state == LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT ? currName.equals(nameFromRelationship)
+            : previousName != null && previousName.equals(nameFromRelationship);
     }
 
     private Either<ComponentInstanceProperty, ResponseFormat> updateAttributeValue(ComponentInstanceProperty attribute, String resourceInstanceId) {
-        Either<ComponentInstanceProperty, StorageOperationStatus> eitherAttribute = componentInstanceOperation.updateAttributeValueInResourceInstance(attribute, resourceInstanceId, true);
+        Either<ComponentInstanceProperty, StorageOperationStatus> eitherAttribute = componentInstanceOperation
+            .updateAttributeValueInResourceInstance(attribute, resourceInstanceId, true);
         Either<ComponentInstanceProperty, ResponseFormat> result;
         if (eitherAttribute.isLeft()) {
             log.debug("Attribute value {} was updated on graph.", attribute.getValueUniqueUid());
             ComponentInstanceProperty instanceAttribute = eitherAttribute.left().value();
-
             result = Either.left(instanceAttribute);
-
         } else {
             log.debug("Failed to update attribute value {} in resource instance {}", attribute, resourceInstanceId);
-
             ActionStatus actionStatus = componentsUtils.convertFromStorageResponseForResourceInstanceProperty(eitherAttribute.right().value());
-
             result = Either.right(componentsUtils.getResponseFormat(actionStatus, ""));
-
         }
         return result;
     }
 
     private Either<ComponentInstanceProperty, ResponseFormat> createAttributeValue(ComponentInstanceProperty attribute, String resourceInstanceId) {
-
         Either<ComponentInstanceProperty, ResponseFormat> result;
-
         Wrapper<Integer> indexCounterWrapper = new Wrapper<>();
         Wrapper<ResponseFormat> errorWrapper = new Wrapper<>();
         validateIncrementCounter(resourceInstanceId, GraphPropertiesDictionary.ATTRIBUTE_COUNTER, indexCounterWrapper, errorWrapper);
-
         if (!errorWrapper.isEmpty()) {
             result = Either.right(errorWrapper.getInnerElement());
         } else {
-            Either<ComponentInstanceProperty, StorageOperationStatus> eitherAttribute = componentInstanceOperation.addAttributeValueToResourceInstance(attribute, resourceInstanceId, indexCounterWrapper.getInnerElement(), true);
+            Either<ComponentInstanceProperty, StorageOperationStatus> eitherAttribute = componentInstanceOperation
+                .addAttributeValueToResourceInstance(attribute, resourceInstanceId, indexCounterWrapper.getInnerElement(), true);
             if (eitherAttribute.isLeft()) {
                 log.debug("Attribute value was added to resource instance {}", resourceInstanceId);
                 ComponentInstanceProperty instanceAttribute = eitherAttribute.left().value();
                 result = Either.left(instanceAttribute);
-
             } else {
                 log.debug("Failed to add attribute value {}  to resource instance {}", attribute, resourceInstanceId);
-
                 ActionStatus actionStatus = componentsUtils.convertFromStorageResponseForResourceInstanceProperty(eitherAttribute.right().value());
                 result = Either.right(componentsUtils.getResponseFormatForResourceInstanceProperty(actionStatus, ""));
-
             }
         }
         return result;
@@ -1959,10 +1849,11 @@ public class ComponentInstanceBusinessLogic extends BaseBusinessLogic {
      * @param userId
      * @return
      */
-    public Either<ComponentInstanceProperty, ResponseFormat> createOrUpdateAttributeValue(ComponentTypeEnum componentTypeEnum, String componentId, String resourceInstanceId, ComponentInstanceProperty attribute, String userId) {
+    public Either<ComponentInstanceProperty, ResponseFormat> createOrUpdateAttributeValue(ComponentTypeEnum componentTypeEnum, String componentId,
+                                                                                          String resourceInstanceId,
+                                                                                          ComponentInstanceProperty attribute, String userId) {
         Either<ComponentInstanceProperty, ResponseFormat> result = null;
         Wrapper<ResponseFormat> errorWrapper = new Wrapper<>();
-
         validateUserExists(userId);
         if (errorWrapper.isEmpty()) {
             validateComponentTypeEnum(componentTypeEnum, "CreateOrUpdateAttributeValue", errorWrapper);
@@ -1973,7 +1864,6 @@ public class ComponentInstanceBusinessLogic extends BaseBusinessLogic {
         if (errorWrapper.isEmpty()) {
             validateComponentLock(componentId, componentTypeEnum, errorWrapper);
         }
-
         try {
             if (errorWrapper.isEmpty()) {
                 final boolean isCreate = Objects.isNull(attribute.getValueUniqueUid());
@@ -1986,9 +1876,7 @@ public class ComponentInstanceBusinessLogic extends BaseBusinessLogic {
                 result = Either.right(errorWrapper.getInnerElement());
             }
             return result;
-        }
-
-        finally {
+        } finally {
             if (result == null || result.isRight()) {
                 janusGraphDao.rollback();
             } else {
@@ -1999,10 +1887,11 @@ public class ComponentInstanceBusinessLogic extends BaseBusinessLogic {
         }
     }
 
-    public Either<List<ComponentInstanceProperty>, ResponseFormat> createOrUpdatePropertiesValues(ComponentTypeEnum componentTypeEnum, String componentId, String resourceInstanceId, List<ComponentInstanceProperty> properties, String userId) {
-
+    public Either<List<ComponentInstanceProperty>, ResponseFormat> createOrUpdatePropertiesValues(ComponentTypeEnum componentTypeEnum,
+                                                                                                  String componentId, String resourceInstanceId,
+                                                                                                  List<ComponentInstanceProperty> properties,
+                                                                                                  String userId) {
         Either<List<ComponentInstanceProperty>, ResponseFormat> resultOp = null;
-
         /*-------------------------------Validations---------------------------------*/
         validateUserExists(userId);
 
@@ -2032,7 +1921,7 @@ public class ComponentInstanceBusinessLogic extends BaseBusinessLogic {
         Either<ComponentInstance, StorageOperationStatus> resourceInstanceStatus = getResourceInstanceById(containerComponent, resourceInstanceId);
         if (resourceInstanceStatus.isRight()) {
             return Either.right(componentsUtils.getResponseFormat(ActionStatus.COMPONENT_INSTANCE_NOT_FOUND_ON_CONTAINER,
-                    resourceInstanceId, "resource instance", "service", componentId));
+                resourceInstanceId, "resource instance", "service", componentId));
         }
         ComponentInstance foundResourceInstance = resourceInstanceStatus.left().value();
 
@@ -2042,37 +1931,39 @@ public class ComponentInstanceBusinessLogic extends BaseBusinessLogic {
             log.debug(FAILED_TO_LOCK_SERVICE, componentId);
             return Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(lockStatus)));
         }
-        List <ComponentInstanceProperty> updatedProperties = new ArrayList<>();
+        List<ComponentInstanceProperty> updatedProperties = new ArrayList<>();
         try {
-            for (ComponentInstanceProperty property: properties) {
+            for (ComponentInstanceProperty property : properties) {
                 validateMandatoryFields(property);
-                ComponentInstanceProperty componentInstanceProperty = validatePropertyExistsOnComponent(property, containerComponent, foundResourceInstance);
+                ComponentInstanceProperty componentInstanceProperty = validatePropertyExistsOnComponent(property, containerComponent,
+                    foundResourceInstance);
                 String propertyParentUniqueId = property.getParentUniqueId();
                 Either<String, ResponseFormat> updatedPropertyValue = updatePropertyObjectValue(property, false);
                 if (updatedPropertyValue.isRight()) {
                     log.error("Failed to update property object value of property: {}",
-                            property);
+                        property);
                     throw new ByResponseFormatComponentException(updatedPropertyValue.right().value());
                 }
                 Optional<CapabilityDefinition>
-                        capPropDefinition = getPropertyCapabilityOfChildInstance(propertyParentUniqueId, foundResourceInstance.getCapabilities());
+                    capPropDefinition = getPropertyCapabilityOfChildInstance(propertyParentUniqueId, foundResourceInstance.getCapabilities());
                 if (capPropDefinition.isPresent()) {
                     updatedPropertyValue
-                            .bimap(updatedValue -> updateCapabilityPropFromUpdateInstProp(property, updatedValue,
-                                    containerComponent, foundResourceInstance, capPropDefinition.get().getType(),
-                                    capPropDefinition.get().getName()), Either::right);
+                        .bimap(updatedValue -> updateCapabilityPropFromUpdateInstProp(property, updatedValue,
+                            containerComponent, foundResourceInstance, capPropDefinition.get().getType(),
+                            capPropDefinition.get().getName()), Either::right);
                 } else {
                     updatedPropertyValue.bimap(
-                            updatedValue -> {
-                                componentInstanceProperty.setValue(updatedValue);
-                                return updatePropertyOnContainerComponent(property, updatedValue,
-                                        containerComponent, foundResourceInstance);
-                            }, Either::right);
+                        updatedValue -> {
+                            componentInstanceProperty.setValue(updatedValue);
+                            return updatePropertyOnContainerComponent(property, updatedValue,
+                                containerComponent, foundResourceInstance);
+                        }, Either::right);
                     updatedProperties.add(componentInstanceProperty);
                 }
             }
 
-            Either<Component, StorageOperationStatus> updateContainerRes = toscaOperationFacade.updateComponentInstanceMetadataOfTopologyTemplate(containerComponent);
+            Either<Component, StorageOperationStatus> updateContainerRes = toscaOperationFacade
+                .updateComponentInstanceMetadataOfTopologyTemplate(containerComponent);
             if (updateContainerRes.isRight()) {
                 ActionStatus actionStatus = componentsUtils.convertFromStorageResponseForResourceInstanceProperty(updateContainerRes.right().value());
                 resultOp = Either.right(componentsUtils.getResponseFormatForResourceInstanceProperty(actionStatus, ""));
@@ -2094,13 +1985,16 @@ public class ComponentInstanceBusinessLogic extends BaseBusinessLogic {
 
     private void validateMandatoryFields(PropertyDataDefinition property) {
         if (StringUtils.isEmpty(property.getName())) {
-            throw new ByActionStatusComponentException (ActionStatus.MISSING_PROPERTY_NAME);
+            throw new ByActionStatusComponentException(ActionStatus.MISSING_PROPERTY_NAME);
         }
     }
 
-    private ComponentInstanceProperty validatePropertyExistsOnComponent(ComponentInstanceProperty property, Component containerComponent, ComponentInstance foundResourceInstance) {
-        List<ComponentInstanceProperty> instanceProperties = containerComponent.getComponentInstancesProperties().get(foundResourceInstance.getUniqueId());
-        Optional<ComponentInstanceProperty> instanceProperty = instanceProperties.stream().filter(p -> p.getName().equals(property.getName())).findAny();
+    private ComponentInstanceProperty validatePropertyExistsOnComponent(ComponentInstanceProperty property, Component containerComponent,
+                                                                        ComponentInstance foundResourceInstance) {
+        List<ComponentInstanceProperty> instanceProperties = containerComponent.getComponentInstancesProperties()
+            .get(foundResourceInstance.getUniqueId());
+        Optional<ComponentInstanceProperty> instanceProperty = instanceProperties.stream().filter(p -> p.getName().equals(property.getName()))
+            .findAny();
         if (!instanceProperty.isPresent()) {
             throw new ByActionStatusComponentException(ActionStatus.PROPERTY_NOT_FOUND, property.getName());
         }
@@ -2108,11 +2002,12 @@ public class ComponentInstanceBusinessLogic extends BaseBusinessLogic {
     }
 
     private ResponseFormat updateCapabilityPropertyOnContainerComponent(ComponentInstanceProperty property,
-                                                                        String newValue, Component containerComponent, ComponentInstance foundResourceInstance,
+                                                                        String newValue, Component containerComponent,
+                                                                        ComponentInstance foundResourceInstance,
                                                                         String capabilityType, String capabilityName) {
         String componentInstanceUniqueId = foundResourceInstance.getUniqueId();
         ResponseFormat actionStatus = updateCapPropOnContainerComponent(property, newValue, containerComponent,
-                foundResourceInstance, capabilityType, capabilityName, componentInstanceUniqueId);
+            foundResourceInstance, capabilityType, capabilityName, componentInstanceUniqueId);
         if (actionStatus != null) {
             return actionStatus;
         }
@@ -2126,13 +2021,13 @@ public class ComponentInstanceBusinessLogic extends BaseBusinessLogic {
                                                                   String capabilityType, String capabilityName) {
         String componentInstanceUniqueId = foundResourceInstance.getUniqueId();
         Either<Component, StorageOperationStatus> getComponentRes =
-                toscaOperationFacade.getToscaFullElement(foundResourceInstance.getComponentUid());
-        if(getComponentRes.isRight()) {
+            toscaOperationFacade.getToscaFullElement(foundResourceInstance.getComponentUid());
+        if (getComponentRes.isRight()) {
             return componentsUtils.getResponseFormat(getComponentRes.right().value());
         }
 
         ResponseFormat actionStatus = updateCapPropOnContainerComponent(property, newValue, containerComponent,
-                foundResourceInstance, capabilityType, capabilityName, componentInstanceUniqueId);
+            foundResourceInstance, capabilityType, capabilityName, componentInstanceUniqueId);
         if (actionStatus != null) {
             return actionStatus;
         }
@@ -2155,20 +2050,22 @@ public class ComponentInstanceBusinessLogic extends BaseBusinessLogic {
             List<ComponentInstanceProperty> capProperties = cap.get().getProperties();
             if (capProperties != null) {
                 Optional<ComponentInstanceProperty> instanceProperty =
-                        capProperties.stream().filter(p -> p.getUniqueId().equals(property.getUniqueId())).findAny();
+                    capProperties.stream().filter(p -> p.getUniqueId().equals(property.getUniqueId())).findAny();
                 StorageOperationStatus status;
                 if (instanceProperty.isPresent()) {
-                    String capKey = ModelConverter.buildCapabilityPropertyKey(foundResourceInstance.getOriginType().isAtomicType(), capabilityType, capabilityName, componentInstanceUniqueId, cap.get());
+                    String capKey = ModelConverter
+                        .buildCapabilityPropertyKey(foundResourceInstance.getOriginType().isAtomicType(), capabilityType, capabilityName,
+                            componentInstanceUniqueId, cap.get());
                     instanceProperty.get().setValue(newValue);
                     List<String> path = new ArrayList<>();
                     path.add(componentInstanceUniqueId);
                     path.add(capKey);
                     instanceProperty.get().setPath(path);
                     status = toscaOperationFacade.updateComponentInstanceCapabiltyProperty(containerComponent,
-                            componentInstanceUniqueId, capKey, instanceProperty.get());
+                        componentInstanceUniqueId, capKey, instanceProperty.get());
                     if (status != StorageOperationStatus.OK) {
                         ActionStatus actionStatus =
-                                componentsUtils.convertFromStorageResponseForResourceInstanceProperty(status);
+                            componentsUtils.convertFromStorageResponseForResourceInstanceProperty(status);
                         return componentsUtils.getResponseFormatForResourceInstanceProperty(actionStatus, "");
 
                     }
@@ -2179,7 +2076,8 @@ public class ComponentInstanceBusinessLogic extends BaseBusinessLogic {
         return null;
     }
 
-    private ResponseFormat updatePropertyOnContainerComponent(ComponentInstanceProperty instanceProperty, String newValue, Component containerComponent, ComponentInstance foundResourceInstance) {
+    private ResponseFormat updatePropertyOnContainerComponent(ComponentInstanceProperty instanceProperty, String newValue,
+                                                              Component containerComponent, ComponentInstance foundResourceInstance) {
         StorageOperationStatus status;
         instanceProperty.setValue(newValue);
         status = toscaOperationFacade.updateComponentInstanceProperty(containerComponent, foundResourceInstance.getUniqueId(), instanceProperty);
@@ -2191,19 +2089,23 @@ public class ComponentInstanceBusinessLogic extends BaseBusinessLogic {
         return componentsUtils.getResponseFormat(ActionStatus.OK);
     }
 
-    private <T extends PropertyDefinition> Either<String,ResponseFormat> validatePropertyObjectValue(T property, String newValue, boolean isInput) {
+    private <T extends PropertyDefinition> Either<String, ResponseFormat> validatePropertyObjectValue(T property, String newValue, boolean isInput) {
         Either<Map<String, DataTypeDefinition>, JanusGraphOperationStatus> allDataTypesEither = dataTypeCache.getAll();
         if (allDataTypesEither.isRight()) {
             JanusGraphOperationStatus status = allDataTypesEither.right().value();
-            BeEcompErrorManager.getInstance().logInternalFlowError("UpdatePropertyValueOnComponentInstance", "Failed to update property value on instance. Status is " + status, ErrorSeverity.ERROR);
-            return Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(DaoStatusConverter.convertJanusGraphStatusToStorageStatus(status))));
+            BeEcompErrorManager.getInstance()
+                .logInternalFlowError("UpdatePropertyValueOnComponentInstance", "Failed to update property value on instance. Status is " + status,
+                    ErrorSeverity.ERROR);
+            return Either.right(componentsUtils
+                .getResponseFormat(componentsUtils.convertFromStorageResponse(DaoStatusConverter.convertJanusGraphStatusToStorageStatus(status))));
         }
         Map<String, DataTypeDefinition> allDataTypes = allDataTypesEither.left().value();
         String propertyType = property.getType();
         String innerType = getInnerType(property);
 
         // Specific Update Logic
-        Either<Object, Boolean> isValid = propertyOperation.validateAndUpdatePropertyValue(property.getType(), newValue, true, innerType, allDataTypes);
+        Either<Object, Boolean> isValid = propertyOperation
+            .validateAndUpdatePropertyValue(property.getType(), newValue, true, innerType, allDataTypes);
         if (isValid.isRight()) {
             Boolean res = isValid.right().value();
             if (!res) {
@@ -2216,14 +2118,18 @@ public class ComponentInstanceBusinessLogic extends BaseBusinessLogic {
                 newValue = object.toString();
             }
         }
-        if (validateAndUpdateRules(property, isInput, allDataTypes, innerType, propertyType))
-            return Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(DaoStatusConverter.convertJanusGraphStatusToStorageStatus(JanusGraphOperationStatus.ILLEGAL_ARGUMENT))));
+        if (validateAndUpdateRules(property, isInput, allDataTypes, innerType, propertyType)) {
+            return Either.right(componentsUtils.getResponseFormat(componentsUtils
+                .convertFromStorageResponse(DaoStatusConverter.convertJanusGraphStatusToStorageStatus(JanusGraphOperationStatus.ILLEGAL_ARGUMENT))));
+        }
         return Either.left(newValue);
     }
 
-    private <T extends PropertyDefinition> boolean validateAndUpdateRules(T property, boolean isInput, Map<String, DataTypeDefinition> allDataTypes, String innerType, String propertyType) {
+    private <T extends PropertyDefinition> boolean validateAndUpdateRules(T property, boolean isInput, Map<String, DataTypeDefinition> allDataTypes,
+                                                                          String innerType, String propertyType) {
         if (!isInput) {
-            ImmutablePair<String, Boolean> pair = propertyOperation.validateAndUpdateRules(propertyType, ((ComponentInstanceProperty) property).getRules(), innerType, allDataTypes, true);
+            ImmutablePair<String, Boolean> pair = propertyOperation
+                .validateAndUpdateRules(propertyType, ((ComponentInstanceProperty) property).getRules(), innerType, allDataTypes, true);
             if (pair.getRight() != null && !pair.getRight()) {
                 BeEcompErrorManager.getInstance().logBeInvalidValueError("Add property value", pair.getLeft(), property.getName(), propertyType);
                 return true;
@@ -2232,12 +2138,15 @@ public class ComponentInstanceBusinessLogic extends BaseBusinessLogic {
         return false;
     }
 
-    private <T extends PropertyDefinition> Either<String,ResponseFormat> updatePropertyObjectValue(T property, boolean isInput) {
+    private <T extends PropertyDefinition> Either<String, ResponseFormat> updatePropertyObjectValue(T property, boolean isInput) {
         Either<Map<String, DataTypeDefinition>, JanusGraphOperationStatus> allDataTypesEither = dataTypeCache.getAll();
         if (allDataTypesEither.isRight()) {
             JanusGraphOperationStatus status = allDataTypesEither.right().value();
-            BeEcompErrorManager.getInstance().logInternalFlowError("UpdatePropertyValueOnComponentInstance", "Failed to update property value on instance. Status is " + status, ErrorSeverity.ERROR);
-            return Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(DaoStatusConverter.convertJanusGraphStatusToStorageStatus(status))));
+            BeEcompErrorManager.getInstance()
+                .logInternalFlowError("UpdatePropertyValueOnComponentInstance", "Failed to update property value on instance. Status is " + status,
+                    ErrorSeverity.ERROR);
+            return Either.right(componentsUtils
+                .getResponseFormat(componentsUtils.convertFromStorageResponse(DaoStatusConverter.convertJanusGraphStatusToStorageStatus(status))));
         }
         Map<String, DataTypeDefinition> allDataTypes = allDataTypesEither.left().value();
         String innerType = null;
@@ -2249,23 +2158,27 @@ public class ComponentInstanceBusinessLogic extends BaseBusinessLogic {
             SchemaDefinition def = property.getSchema();
             if (def == null) {
                 log.debug("Schema doesn't exists for property of type {}", type);
-                return Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(StorageOperationStatus.INVALID_VALUE)));
+                return Either
+                    .right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(StorageOperationStatus.INVALID_VALUE)));
             }
             PropertyDataDefinition propDef = def.getProperty();
             if (propDef == null) {
                 log.debug("Property in Schema Definition inside property of type {} doesn't exist", type);
-                return Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(StorageOperationStatus.INVALID_VALUE)));
+                return Either
+                    .right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(StorageOperationStatus.INVALID_VALUE)));
             }
             innerType = propDef.getType();
         }
         // Specific Update Logic
-        Either<Object, Boolean> isValid = propertyOperation.validateAndUpdatePropertyValue(propertyType, property.getValue(), true, innerType, allDataTypes);
+        Either<Object, Boolean> isValid = propertyOperation
+            .validateAndUpdatePropertyValue(propertyType, property.getValue(), true, innerType, allDataTypes);
         String newValue = property.getValue();
         if (isValid.isRight()) {
             Boolean res = isValid.right().value();
             if (!res) {
                 log.debug("validate and update property value has failed with value: {}", property.getValue());
-                throw new ByActionStatusComponentException(componentsUtils.convertFromStorageResponse(DaoStatusConverter.convertJanusGraphStatusToStorageStatus(JanusGraphOperationStatus.ILLEGAL_ARGUMENT)));
+                throw new ByActionStatusComponentException(componentsUtils.convertFromStorageResponse(
+                    DaoStatusConverter.convertJanusGraphStatusToStorageStatus(JanusGraphOperationStatus.ILLEGAL_ARGUMENT)));
             }
         } else {
             Object object = isValid.left().value();
@@ -2274,16 +2187,19 @@ public class ComponentInstanceBusinessLogic extends BaseBusinessLogic {
             }
         }
         if (!isInput) {
-            ImmutablePair<String, Boolean> pair = propertyOperation.validateAndUpdateRules(propertyType, ((ComponentInstanceProperty) property).getRules(), innerType, allDataTypes, true);
+            ImmutablePair<String, Boolean> pair = propertyOperation
+                .validateAndUpdateRules(propertyType, ((ComponentInstanceProperty) property).getRules(), innerType, allDataTypes, true);
             if (pair.getRight() != null && pair.getRight() == false) {
                 BeEcompErrorManager.getInstance().logBeInvalidValueError("Add property value", pair.getLeft(), property.getName(), propertyType);
-                return Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(DaoStatusConverter.convertJanusGraphStatusToStorageStatus(JanusGraphOperationStatus.ILLEGAL_ARGUMENT))));
+                return Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(
+                    DaoStatusConverter.convertJanusGraphStatusToStorageStatus(JanusGraphOperationStatus.ILLEGAL_ARGUMENT))));
             }
         }
         return Either.left(newValue);
     }
 
-    private ResponseFormat updateInputOnContainerComponent(ComponentInstanceInput input, String newValue, Component containerComponent, ComponentInstance foundResourceInstance) {
+    private ResponseFormat updateInputOnContainerComponent(ComponentInstanceInput input, String newValue, Component containerComponent,
+                                                           ComponentInstance foundResourceInstance) {
         StorageOperationStatus status;
         input.setValue(newValue);
         status = toscaOperationFacade.updateComponentInstanceInput(containerComponent, foundResourceInstance.getUniqueId(), input);
@@ -2295,7 +2211,10 @@ public class ComponentInstanceBusinessLogic extends BaseBusinessLogic {
         return componentsUtils.getResponseFormat(ActionStatus.OK);
     }
 
-    public Either<List<ComponentInstanceInput>, ResponseFormat> createOrUpdateInstanceInputValues(ComponentTypeEnum componentTypeEnum, String componentId, String resourceInstanceId, List<ComponentInstanceInput> inputs, String userId) {
+    public Either<List<ComponentInstanceInput>, ResponseFormat> createOrUpdateInstanceInputValues(ComponentTypeEnum componentTypeEnum,
+                                                                                                  String componentId, String resourceInstanceId,
+                                                                                                  List<ComponentInstanceInput> inputs,
+                                                                                                  String userId) {
 
         Either<List<ComponentInstanceInput>, ResponseFormat> resultOp = null;
 
@@ -2327,7 +2246,7 @@ public class ComponentInstanceBusinessLogic extends BaseBusinessLogic {
         Either<ComponentInstance, StorageOperationStatus> resourceInstanceStatus = getResourceInstanceById(containerComponent, resourceInstanceId);
         if (resourceInstanceStatus.isRight()) {
             return Either.right(componentsUtils.getResponseFormat(ActionStatus.COMPONENT_INSTANCE_NOT_FOUND_ON_CONTAINER,
-                    resourceInstanceId, "resource instance", "service", componentId));
+                resourceInstanceId, "resource instance", "service", componentId));
         }
 
         ComponentInstance foundResourceInstance = resourceInstanceStatus.left().value();
@@ -2338,19 +2257,21 @@ public class ComponentInstanceBusinessLogic extends BaseBusinessLogic {
             log.debug(FAILED_TO_LOCK_SERVICE, componentId);
             return Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(lockStatus)));
         }
-        List <ComponentInstanceInput> updatedInputs = new ArrayList<>();
+        List<ComponentInstanceInput> updatedInputs = new ArrayList<>();
         try {
-            for (ComponentInstanceInput input: inputs) {
+            for (ComponentInstanceInput input : inputs) {
                 validateMandatoryFields(input);
                 ComponentInstanceInput componentInstanceInput = validateInputExistsOnComponent(input, containerComponent, foundResourceInstance);
                 Either<String, ResponseFormat> validatedInputValue = validatePropertyObjectValue(componentInstanceInput, input.getValue(), true);
-                if (validatedInputValue.isRight()){
+                if (validatedInputValue.isRight()) {
                     throw new ByActionStatusComponentException(ActionStatus.INVALID_CONTENT, input.getName());
                 }
-                updateInputOnContainerComponent(componentInstanceInput, validatedInputValue.left().value(), containerComponent, foundResourceInstance);
+                updateInputOnContainerComponent(componentInstanceInput, validatedInputValue.left().value(), containerComponent,
+                    foundResourceInstance);
                 updatedInputs.add(componentInstanceInput);
             }
-            Either<Component, StorageOperationStatus> updateContainerRes = toscaOperationFacade.updateComponentInstanceMetadataOfTopologyTemplate(containerComponent);
+            Either<Component, StorageOperationStatus> updateContainerRes = toscaOperationFacade
+                .updateComponentInstanceMetadataOfTopologyTemplate(containerComponent);
             if (updateContainerRes.isRight()) {
                 ActionStatus actionStatus = componentsUtils.convertFromStorageResponseForResourceInstanceProperty(updateContainerRes.right().value());
                 resultOp = Either.right(componentsUtils.getResponseFormatForResourceInstanceProperty(actionStatus, ""));
@@ -2371,7 +2292,8 @@ public class ComponentInstanceBusinessLogic extends BaseBusinessLogic {
 
     }
 
-    private ComponentInstanceInput validateInputExistsOnComponent(ComponentInstanceInput input, Component containerComponent, ComponentInstance foundResourceInstance) {
+    private ComponentInstanceInput validateInputExistsOnComponent(ComponentInstanceInput input, Component containerComponent,
+                                                                  ComponentInstance foundResourceInstance) {
         List<ComponentInstanceInput> instanceProperties = containerComponent.getComponentInstancesInputs().get(foundResourceInstance.getUniqueId());
         Optional<ComponentInstanceInput> instanceInput = instanceProperties.stream().filter(p -> p.getName().equals(input.getName())).findAny();
         if (!instanceInput.isPresent()) {
@@ -2380,7 +2302,11 @@ public class ComponentInstanceBusinessLogic extends BaseBusinessLogic {
         return instanceInput.get();
     }
 
-    public Either<ComponentInstanceProperty, ResponseFormat> createOrUpdateGroupInstancePropertyValue(ComponentTypeEnum componentTypeEnum, String componentId, String resourceInstanceId, String groupInstanceId, ComponentInstanceProperty property, String userId) {
+    public Either<ComponentInstanceProperty, ResponseFormat> createOrUpdateGroupInstancePropertyValue(ComponentTypeEnum componentTypeEnum,
+                                                                                                      String componentId, String resourceInstanceId,
+                                                                                                      String groupInstanceId,
+                                                                                                      ComponentInstanceProperty property,
+                                                                                                      String userId) {
 
         Either<ComponentInstanceProperty, ResponseFormat> resultOp = null;
 
@@ -2409,7 +2335,8 @@ public class ComponentInstanceBusinessLogic extends BaseBusinessLogic {
 
             if (propertyValueUid == null) {
 
-                Either<Integer, StorageOperationStatus> counterRes = groupInstanceOperation.increaseAndGetGroupInstancePropertyCounter(groupInstanceId);
+                Either<Integer, StorageOperationStatus> counterRes = groupInstanceOperation
+                    .increaseAndGetGroupInstancePropertyCounter(groupInstanceId);
 
                 if (counterRes.isRight()) {
                     log.debug("increaseAndGetResourcePropertyCounter failed resource instance: {} property: {}", resourceInstanceId, property);
@@ -2418,7 +2345,8 @@ public class ComponentInstanceBusinessLogic extends BaseBusinessLogic {
                     resultOp = Either.right(componentsUtils.getResponseFormat(actionStatus));
                 }
                 Integer index = counterRes.left().value();
-                Either<ComponentInstanceProperty, StorageOperationStatus> result = groupInstanceOperation.addPropertyValueToGroupInstance(property, resourceInstanceId, index, true);
+                Either<ComponentInstanceProperty, StorageOperationStatus> result = groupInstanceOperation
+                    .addPropertyValueToGroupInstance(property, resourceInstanceId, index, true);
 
                 if (result.isLeft()) {
                     log.trace("Property value was added to resource instance {}", resourceInstanceId);
@@ -2435,7 +2363,8 @@ public class ComponentInstanceBusinessLogic extends BaseBusinessLogic {
                 }
 
             } else {
-                Either<ComponentInstanceProperty, StorageOperationStatus> result = groupInstanceOperation.updatePropertyValueInGroupInstance(property, resourceInstanceId, true);
+                Either<ComponentInstanceProperty, StorageOperationStatus> result = groupInstanceOperation
+                    .updatePropertyValueInGroupInstance(property, resourceInstanceId, true);
 
                 if (result.isLeft()) {
                     log.debug("Property value {} was updated on graph.", property.getValueUniqueUid());
@@ -2474,7 +2403,8 @@ public class ComponentInstanceBusinessLogic extends BaseBusinessLogic {
 
     }
 
-    public Either<ComponentInstanceProperty, ResponseFormat> deletePropertyValue(ComponentTypeEnum componentTypeEnum, String serviceId, String resourceInstanceId, String propertyValueId, String userId) {
+    public Either<ComponentInstanceProperty, ResponseFormat> deletePropertyValue(ComponentTypeEnum componentTypeEnum, String serviceId,
+                                                                                 String resourceInstanceId, String propertyValueId, String userId) {
 
         validateUserExists(userId);
 
@@ -2499,7 +2429,8 @@ public class ComponentInstanceBusinessLogic extends BaseBusinessLogic {
             return resultOp;
         }
         try {
-            Either<ComponentInstanceProperty, StorageOperationStatus> result = propertyOperation.removePropertyValueFromResourceInstance(propertyValueId, resourceInstanceId, true);
+            Either<ComponentInstanceProperty, StorageOperationStatus> result = propertyOperation
+                .removePropertyValueFromResourceInstance(propertyValueId, resourceInstanceId, true);
 
             if (result.isLeft()) {
                 log.debug("Property value {} was removed from graph.", propertyValueId);
@@ -2536,7 +2467,8 @@ public class ComponentInstanceBusinessLogic extends BaseBusinessLogic {
         Component component;
         Either<Component, StorageOperationStatus> getComponentRes = toscaOperationFacade.getToscaFullElement(componentInstance.getComponentUid());
         if (getComponentRes.isRight()) {
-            log.debug("Failed to get the component with id {} for component instance {} creation. ", componentInstance.getComponentUid(), componentInstance.getName());
+            log.debug("Failed to get the component with id {} for component instance {} creation. ", componentInstance.getComponentUid(),
+                componentInstance.getName());
             ActionStatus actionStatus = componentsUtils.convertFromStorageResponse(getComponentRes.right().value(), componentType);
             throw new ByActionStatusComponentException(actionStatus, Constants.EMPTY_STRING);
         }
@@ -2544,14 +2476,14 @@ public class ComponentInstanceBusinessLogic extends BaseBusinessLogic {
         LifecycleStateEnum resourceCurrState = component.getLifecycleState();
         if (resourceCurrState == LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT) {
             ActionStatus actionStatus = ActionStatus.CONTAINER_CANNOT_CONTAIN_COMPONENT_IN_STATE;
-            throw new ByActionStatusComponentException(actionStatus, containerComponent.getComponentType().toString(),  resourceCurrState.toString());
+            throw new ByActionStatusComponentException(actionStatus, containerComponent.getComponentType().toString(), resourceCurrState.toString());
         }
-        if (component.isArchived() == true){
+        if (component.isArchived() == true) {
             ActionStatus actionStatus = ActionStatus.COMPONENT_IS_ARCHIVED;
             throw new ByActionStatusComponentException(actionStatus, component.getName());
         }
         final Map<String, InterfaceDefinition> componentInterfaces = component.getInterfaces();
-        if(MapUtils.isNotEmpty(componentInterfaces)) {
+        if (MapUtils.isNotEmpty(componentInterfaces)) {
             componentInterfaces.forEach(componentInstance::addInterface);
         }
         return component;
@@ -2570,10 +2502,10 @@ public class ComponentInstanceBusinessLogic extends BaseBusinessLogic {
 
         //Fetch current component instance
         Either<ComponentInstance, StorageOperationStatus> eitherResourceInstance =
-                getResourceInstanceById(containerComponent, componentInstanceId);
+            getResourceInstanceById(containerComponent, componentInstanceId);
         if (eitherResourceInstance.isRight()) {
             resultOp = Either.right(componentsUtils.getResponseFormat(
-                    ActionStatus.RESOURCE_INSTANCE_NOT_FOUND_ON_SERVICE, componentInstanceId, containerComponentId));
+                ActionStatus.RESOURCE_INSTANCE_NOT_FOUND_ON_SERVICE, componentInstanceId, containerComponentId));
             return resultOp;
         }
         ComponentInstance currentResourceInstance = eitherResourceInstance.left().value();
@@ -2584,7 +2516,7 @@ public class ComponentInstanceBusinessLogic extends BaseBusinessLogic {
         if (componentExistsRes.isRight()) {
             log.debug("Failed to find resource {}", resourceId);
             resultOp = Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse
-                    (componentExistsRes.right().value()), resourceId));
+                (componentExistsRes.right().value()), resourceId));
             return resultOp;
         } else if (!componentExistsRes.left().value()) {
             log.debug("The resource {} not found ", resourceId);
@@ -2593,24 +2525,24 @@ public class ComponentInstanceBusinessLogic extends BaseBusinessLogic {
         }
 
         //Fetch component using new component instance uid
-        Component updatedContainerComponent=getOriginComponentFromComponentInstance(newComponentInstance);
+        Component updatedContainerComponent = getOriginComponentFromComponentInstance(newComponentInstance);
         Set<String> toDeleteForwardingPaths = getForwardingPaths(containerComponent,
-                currentResourceInstance, updatedContainerComponent);
-        resultOp=Either.left(toDeleteForwardingPaths);
+            currentResourceInstance, updatedContainerComponent);
+        resultOp = Either.left(toDeleteForwardingPaths);
 
         return resultOp;
     }
 
     private Set<String> getForwardingPaths(Component containerComponent, ComponentInstance currentResourceInstance,
                                            Component updatedContainerComponent) {
-        DataForMergeHolder dataForMergeHolder=new DataForMergeHolder();
+        DataForMergeHolder dataForMergeHolder = new DataForMergeHolder();
         dataForMergeHolder.setOrigComponentInstId(currentResourceInstance.getName());
 
         Service service = (Service) containerComponent;
         ForwardingPathUtils forwardingPathUtils = new ForwardingPathUtils();
 
         return forwardingPathUtils.
-                getForwardingPathsToBeDeletedOnVersionChange(service,dataForMergeHolder,updatedContainerComponent);
+            getForwardingPathsToBeDeletedOnVersionChange(service, dataForMergeHolder, updatedContainerComponent);
     }
 
     private ComponentParametersView getComponentParametersViewForForwardingPath() {
@@ -2620,32 +2552,35 @@ public class ComponentInstanceBusinessLogic extends BaseBusinessLogic {
         return componentParametersView;
     }
 
-    public ComponentInstance changeComponentInstanceVersion(String containerComponentParam, String containerComponentId, String componentInstanceId, String userId, ComponentInstance newComponentInstance) {
+    public ComponentInstance changeComponentInstanceVersion(String containerComponentParam, String containerComponentId, String componentInstanceId,
+                                                            String userId, ComponentInstance newComponentInstance) {
 
         User user = validateUserExists(userId);
         final ComponentTypeEnum containerComponentType = validateComponentType(containerComponentParam);
         ComponentParametersView componentParametersView = new ComponentParametersView();
         componentParametersView.setIgnoreCapabiltyProperties(false);
 
-        org.openecomp.sdc.be.model.Component containerComponent = validateComponentExists(containerComponentId, containerComponentType, componentParametersView);
+        org.openecomp.sdc.be.model.Component containerComponent = validateComponentExists(containerComponentId, containerComponentType,
+            componentParametersView);
 
         validateCanWorkOnComponent(containerComponent, userId);
 
         Either<ComponentInstance, StorageOperationStatus> resourceInstanceStatus = getResourceInstanceById(containerComponent, componentInstanceId);
         if (resourceInstanceStatus.isRight()) {
-            throw new ByActionStatusComponentException(ActionStatus.RESOURCE_INSTANCE_NOT_FOUND_ON_SERVICE, componentInstanceId, containerComponentId);
+            throw new ByActionStatusComponentException(ActionStatus.RESOURCE_INSTANCE_NOT_FOUND_ON_SERVICE, componentInstanceId,
+                containerComponentId);
         }
 
         ComponentInstance currentResourceInstance = resourceInstanceStatus.left().value();
 
-        return changeInstanceVersion(containerComponent, currentResourceInstance, newComponentInstance, user, containerComponentType );
+        return changeInstanceVersion(containerComponent, currentResourceInstance, newComponentInstance, user, containerComponentType);
     }
 
     public ComponentInstance changeInstanceVersion(org.openecomp.sdc.be.model.Component containerComponent,
-        ComponentInstance currentResourceInstance,
-        ComponentInstance newComponentInstance,
-        User user,
-        final ComponentTypeEnum containerComponentType) {
+                                                   ComponentInstance currentResourceInstance,
+                                                   ComponentInstance newComponentInstance,
+                                                   User user,
+                                                   final ComponentTypeEnum containerComponentType) {
         boolean failed = false;
         Either<ComponentInstance, StorageOperationStatus> resourceInstanceStatus;
 
@@ -2699,17 +2634,19 @@ public class ComponentInstanceBusinessLogic extends BaseBusinessLogic {
                         throw new ByActionStatusComponentException(
                             componentsUtils.convertFromStorageResponse(fillProxyRes));
                     }
-                } else if (originType == OriginTypeEnum.ServiceSubstitution){
-                       final Either<Component, StorageOperationStatus> getServiceResult = toscaOperationFacade.getToscaFullElement(newComponentInstance.getComponentUid());
-                       if (getServiceResult.isRight()) {
-                               throw new ByActionStatusComponentException(componentsUtils.convertFromStorageResponse(getServiceResult.right().value()));
-                       }
-                       final Component service = getServiceResult.left().value();
-
-                       final Either<Component, StorageOperationStatus> getServiceDerivedFromTypeResult = toscaOperationFacade.getLatestByToscaResourceName(service.getDerivedFromGenericType());
-                       if (getServiceDerivedFromTypeResult.isRight()) {
-                               throw new ByActionStatusComponentException(componentsUtils.convertFromStorageResponse(getServiceResult.right().value()));
-                       }
+                } else if (originType == OriginTypeEnum.ServiceSubstitution) {
+                    final Either<Component, StorageOperationStatus> getServiceResult = toscaOperationFacade
+                        .getToscaFullElement(newComponentInstance.getComponentUid());
+                    if (getServiceResult.isRight()) {
+                        throw new ByActionStatusComponentException(componentsUtils.convertFromStorageResponse(getServiceResult.right().value()));
+                    }
+                    final Component service = getServiceResult.left().value();
+
+                    final Either<Component, StorageOperationStatus> getServiceDerivedFromTypeResult = toscaOperationFacade
+                        .getLatestByToscaResourceName(service.getDerivedFromGenericType());
+                    if (getServiceDerivedFromTypeResult.isRight()) {
+                        throw new ByActionStatusComponentException(componentsUtils.convertFromStorageResponse(getServiceResult.right().value()));
+                    }
 
                     origComponent = getServiceDerivedFromTypeResult.left().value();
 
@@ -2775,7 +2712,8 @@ public class ComponentInstanceBusinessLogic extends BaseBusinessLogic {
     }
 
     // US831698
-    public List<ComponentInstanceProperty> getComponentInstancePropertiesById(String containerComponentTypeParam, String containerComponentId, String componentInstanceUniqueId, String userId) {
+    public List<ComponentInstanceProperty> getComponentInstancePropertiesById(String containerComponentTypeParam, String containerComponentId,
+                                                                              String componentInstanceUniqueId, String userId) {
         Component containerComponent = null;
 
         boolean failed = false;
@@ -2785,13 +2723,16 @@ public class ComponentInstanceBusinessLogic extends BaseBusinessLogic {
 
             Either<Component, StorageOperationStatus> validateContainerComponentExists = toscaOperationFacade.getToscaElement(containerComponentId);
             if (validateContainerComponentExists.isRight()) {
-                throw new ByActionStatusComponentException(componentsUtils.convertFromStorageResponse(validateContainerComponentExists.right().value()));
+                throw new ByActionStatusComponentException(
+                    componentsUtils.convertFromStorageResponse(validateContainerComponentExists.right().value()));
             }
             containerComponent = validateContainerComponentExists.left().value();
 
-            Either<ComponentInstance, StorageOperationStatus> resourceInstanceStatus = getResourceInstanceById(containerComponent, componentInstanceUniqueId);
+            Either<ComponentInstance, StorageOperationStatus> resourceInstanceStatus = getResourceInstanceById(containerComponent,
+                componentInstanceUniqueId);
             if (resourceInstanceStatus.isRight()) {
-                throw new ByActionStatusComponentException(ActionStatus.RESOURCE_INSTANCE_NOT_FOUND_ON_SERVICE, componentInstanceUniqueId, containerComponentId);
+                throw new ByActionStatusComponentException(ActionStatus.RESOURCE_INSTANCE_NOT_FOUND_ON_SERVICE, componentInstanceUniqueId,
+                    containerComponentId);
             }
 
             List<ComponentInstanceProperty> instanceProperties = containerComponent.getComponentInstancesProperties().get(componentInstanceUniqueId);
@@ -2868,13 +2809,17 @@ public class ComponentInstanceBusinessLogic extends BaseBusinessLogic {
      * @param inTransaction
      * @return
      */
-    public Either<ComponentInstanceData, ResponseFormat> updateComponentInstanceModificationTimeAndCustomizationUuid(ComponentInstance componentInstance, NodeTypeEnum componentInstanceType, Long modificationTime, boolean inTransaction) {
+    public Either<ComponentInstanceData, ResponseFormat> updateComponentInstanceModificationTimeAndCustomizationUuid(
+        ComponentInstance componentInstance, NodeTypeEnum componentInstanceType, Long modificationTime, boolean inTransaction) {
         Either<ComponentInstanceData, ResponseFormat> result;
-        Either<ComponentInstanceData, StorageOperationStatus> updateComponentInstanceRes = componentInstanceOperation.updateComponentInstanceModificationTimeAndCustomizationUuidOnGraph(componentInstance, componentInstanceType, modificationTime,
+        Either<ComponentInstanceData, StorageOperationStatus> updateComponentInstanceRes = componentInstanceOperation
+            .updateComponentInstanceModificationTimeAndCustomizationUuidOnGraph(componentInstance, componentInstanceType, modificationTime,
                 inTransaction);
         if (updateComponentInstanceRes.isRight()) {
-            log.debug("Failed to update component instance {} with new last update date and mofifier. Status is {}. ", componentInstance.getName(), updateComponentInstanceRes.right().value());
-            result = Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(updateComponentInstanceRes.right().value())));
+            log.debug("Failed to update component instance {} with new last update date and mofifier. Status is {}. ", componentInstance.getName(),
+                updateComponentInstanceRes.right().value());
+            result = Either
+                .right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(updateComponentInstanceRes.right().value())));
         } else {
             result = Either.left(updateComponentInstanceRes.left().value());
         }
@@ -2896,12 +2841,12 @@ public class ComponentInstanceBusinessLogic extends BaseBusinessLogic {
         return Either.left(new ComponentInstance());
     }
 
-    private Boolean validateInstanceNameUniquenessUponUpdate(Component containerComponent, ComponentInstance oldComponentInstance, String newInstanceName) {
+    private Boolean validateInstanceNameUniquenessUponUpdate(Component containerComponent, ComponentInstance oldComponentInstance,
+                                                             String newInstanceName) {
         return ComponentValidations.validateNameIsUniqueInComponent(oldComponentInstance.getName(), newInstanceName, containerComponent);
     }
 
     private Either<ComponentInstance, StorageOperationStatus> getResourceInstanceById(Component containerComponent, String instanceId) {
-
         Either<ComponentInstance, StorageOperationStatus> result = Either.right(StorageOperationStatus.NOT_FOUND);
         List<ComponentInstance> instances = containerComponent.getComponentInstances();
         Optional<ComponentInstance> foundInstance = Optional.empty();
@@ -2920,38 +2865,33 @@ public class ComponentInstanceBusinessLogic extends BaseBusinessLogic {
     }
 
     private ComponentInstance buildComponentInstance(ComponentInstance resourceInstanceForUpdate, ComponentInstance origInstanceForUpdate) {
-
         Long creationDate = origInstanceForUpdate.getCreationTime();
-
         Long modificationTime = System.currentTimeMillis();
         resourceInstanceForUpdate.setCreationTime(creationDate);
         resourceInstanceForUpdate.setModificationTime(modificationTime);
-
         resourceInstanceForUpdate.setCustomizationUUID(origInstanceForUpdate.getCustomizationUUID());
-
         if (StringUtils.isEmpty(resourceInstanceForUpdate.getName()) && StringUtils.isNotEmpty(origInstanceForUpdate.getName())) {
             resourceInstanceForUpdate.setName(origInstanceForUpdate.getName());
         }
-
         resourceInstanceForUpdate.setNormalizedName(ValidationUtils.normalizeComponentInstanceName(resourceInstanceForUpdate.getName()));
-
-        if (StringUtils.isEmpty(resourceInstanceForUpdate.getIcon()))
+        if (StringUtils.isEmpty(resourceInstanceForUpdate.getIcon())) {
             resourceInstanceForUpdate.setIcon(origInstanceForUpdate.getIcon());
-
-        if (StringUtils.isEmpty(resourceInstanceForUpdate.getComponentVersion()))
+        }
+        if (StringUtils.isEmpty(resourceInstanceForUpdate.getComponentVersion())) {
             resourceInstanceForUpdate.setComponentVersion(origInstanceForUpdate.getComponentVersion());
-
-        if (StringUtils.isEmpty(resourceInstanceForUpdate.getComponentName()))
+        }
+        if (StringUtils.isEmpty(resourceInstanceForUpdate.getComponentName())) {
             resourceInstanceForUpdate.setComponentName(origInstanceForUpdate.getComponentName());
-
-        if (StringUtils.isEmpty(resourceInstanceForUpdate.getToscaComponentName()))
+        }
+        if (StringUtils.isEmpty(resourceInstanceForUpdate.getToscaComponentName())) {
             resourceInstanceForUpdate.setToscaComponentName(origInstanceForUpdate.getToscaComponentName());
-
+        }
         if (resourceInstanceForUpdate.getOriginType() == null) {
             resourceInstanceForUpdate.setOriginType(origInstanceForUpdate.getOriginType());
         }
-        if(resourceInstanceForUpdate.getOriginType()  == OriginTypeEnum.ServiceProxy)
+        if (resourceInstanceForUpdate.getOriginType() == OriginTypeEnum.ServiceProxy) {
             resourceInstanceForUpdate.setIsProxy(true);
+        }
         if (resourceInstanceForUpdate.getSourceModelInvariant() == null) {
             resourceInstanceForUpdate.setSourceModelInvariant(origInstanceForUpdate.getSourceModelInvariant());
         }
@@ -2969,8 +2909,10 @@ public class ComponentInstanceBusinessLogic extends BaseBusinessLogic {
         }
         return resourceInstanceForUpdate;
     }
+
     /**
      * Returns list of ComponentInstanceProperty belonging to component instance capability specified by name, type and ownerId
+     *
      * @param containerComponentType
      * @param containerComponentId
      * @param componentInstanceUniqueId
@@ -2980,10 +2922,10 @@ public class ComponentInstanceBusinessLogic extends BaseBusinessLogic {
      * @param ownerId
      * @return
      */
-    public List<ComponentInstanceProperty> getComponentInstanceCapabilityPropertiesById(String containerComponentType, String containerComponentId, String componentInstanceUniqueId, String capabilityType, String capabilityName, String ownerId, String userId) {
-
+    public List<ComponentInstanceProperty> getComponentInstanceCapabilityPropertiesById(String containerComponentType, String containerComponentId,
+                                                                                        String componentInstanceUniqueId, String capabilityType,
+                                                                                        String capabilityName, String ownerId, String userId) {
         Component containerComponent = null;
-
         List<ComponentInstanceProperty> resultOp = null;
         try {
             validateUserExists(userId);
@@ -3002,12 +2944,15 @@ public class ComponentInstanceBusinessLogic extends BaseBusinessLogic {
         return resultOp;
     }
 
-    private List<ComponentInstanceProperty> findCapabilityOfInstance( String componentId, String instanceId, String capabilityType, String capabilityName, String ownerId, Map<String, List<CapabilityDefinition>> instanceCapabilities) {
+    private List<ComponentInstanceProperty> findCapabilityOfInstance(String componentId, String instanceId, String capabilityType,
+                                                                     String capabilityName, String ownerId,
+                                                                     Map<String, List<CapabilityDefinition>> instanceCapabilities) {
         CapabilityDefinition foundCapability;
         if (MapUtils.isNotEmpty(instanceCapabilities)) {
             List<CapabilityDefinition> capabilitiesPerType = instanceCapabilities.get(capabilityType);
             if (capabilitiesPerType != null) {
-                Optional<CapabilityDefinition> capabilityOpt = capabilitiesPerType.stream().filter(c -> c.getName().equals(capabilityName) && c.getOwnerId().equals(ownerId)).findFirst();
+                Optional<CapabilityDefinition> capabilityOpt = capabilitiesPerType.stream()
+                    .filter(c -> c.getName().equals(capabilityName) && c.getOwnerId().equals(ownerId)).findFirst();
                 if (capabilityOpt.isPresent()) {
                     foundCapability = capabilityOpt.get();
                     return foundCapability.getProperties() == null ? new ArrayList<>() : foundCapability.getProperties();
@@ -3017,43 +2962,42 @@ public class ComponentInstanceBusinessLogic extends BaseBusinessLogic {
         return fetchComponentInstanceCapabilityProperties(componentId, instanceId, capabilityType, capabilityName, ownerId);
     }
 
-    private List<ComponentInstanceProperty> fetchComponentInstanceCapabilityProperties(String componentId, String instanceId, String capabilityType, String capabilityName, String ownerId) {
+    private List<ComponentInstanceProperty> fetchComponentInstanceCapabilityProperties(String componentId, String instanceId, String capabilityType,
+                                                                                       String capabilityName, String ownerId) {
         try {
             return toscaOperationFacade.getComponentInstanceCapabilityProperties(componentId, instanceId, capabilityName, capabilityType, ownerId)
-                    .left()
-                    .on(this::componentInstancePropertyListException);
-        } catch(Exception e){
-            log.debug("The exception {} occurred upon the component {} instance {} capability {} properties retrieving. ", componentId, instanceId, capabilityName, e);
+                .left().on(this::componentInstancePropertyListException);
+        } catch (Exception e) {
+            log.debug("The exception {} occurred upon the component {} instance {} capability {} properties retrieving. ", componentId, instanceId,
+                capabilityName, e);
             throw new ByActionStatusComponentException(ActionStatus.GENERAL_ERROR);
         }
     }
 
     public Either<RequirementDefinition, ResponseFormat> updateInstanceRequirement(ComponentTypeEnum componentTypeEnum, String containerComponentId,
                                                                                    String componentInstanceUniqueId,
-            RequirementDefinition requirementDef, String userId) {
-
+                                                                                   RequirementDefinition requirementDef, String userId) {
         Either<RequirementDefinition, ResponseFormat> resultOp = null;
-
         validateUserExists(userId);
         if (componentTypeEnum == null) {
             BeEcompErrorManager.getInstance().logInvalidInputError("updateInstanceRequirement", INVALID_COMPONENT_TYPE, ErrorSeverity.INFO);
             return Either.right(componentsUtils.getResponseFormat(ActionStatus.NOT_ALLOWED));
         }
         Either<Component, StorageOperationStatus> getResourceResult = toscaOperationFacade.getToscaFullElement(containerComponentId);
-
         if (getResourceResult.isRight()) {
             log.debug(FAILED_TO_RETRIEVE_COMPONENT_COMPONENT_ID, containerComponentId);
             return Either.right(componentsUtils.getResponseFormat(ActionStatus.RESTRICTED_OPERATION));
         }
         Component containerComponent = getResourceResult.left().value();
-
         if (!ComponentValidationUtils.canWorkOnComponent(containerComponent, userId)) {
             log.info("Restricted operation for user: {} on component {}", userId, containerComponentId);
             return Either.right(componentsUtils.getResponseFormat(ActionStatus.RESTRICTED_OPERATION));
         }
-        Either<ComponentInstance, StorageOperationStatus> resourceInstanceStatus = getResourceInstanceById(containerComponent, componentInstanceUniqueId);
+        Either<ComponentInstance, StorageOperationStatus> resourceInstanceStatus = getResourceInstanceById(containerComponent,
+            componentInstanceUniqueId);
         if (resourceInstanceStatus.isRight()) {
-            return Either.right(componentsUtils.getResponseFormat(ActionStatus.RESOURCE_INSTANCE_NOT_FOUND_ON_SERVICE, componentInstanceUniqueId, containerComponentId));
+            return Either.right(componentsUtils
+                .getResponseFormat(ActionStatus.RESOURCE_INSTANCE_NOT_FOUND_ON_SERVICE, componentInstanceUniqueId, containerComponentId));
         }
         // lock resource
         StorageOperationStatus lockStatus = graphLockOperation.lockComponent(containerComponentId, componentTypeEnum.getNodeType());
@@ -3061,15 +3005,16 @@ public class ComponentInstanceBusinessLogic extends BaseBusinessLogic {
             log.debug("Failed to lock component {}", containerComponentId);
             return Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(lockStatus)));
         }
-
         try {
-            StorageOperationStatus updateRequirementStatus = toscaOperationFacade.updateComponentInstanceRequirement(containerComponentId, componentInstanceUniqueId, requirementDef);
+            StorageOperationStatus updateRequirementStatus = toscaOperationFacade
+                .updateComponentInstanceRequirement(containerComponentId, componentInstanceUniqueId, requirementDef);
             if (updateRequirementStatus != StorageOperationStatus.OK) {
-                log.debug("Failed to update component instance requirement on instance {} in container {}", componentInstanceUniqueId, containerComponentId);
+                log.debug("Failed to update component instance requirement on instance {} in container {}", componentInstanceUniqueId,
+                    containerComponentId);
                 return Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(updateRequirementStatus)));
             }
-            Either<Component, StorageOperationStatus> updateContainerRes = toscaOperationFacade.updateComponentInstanceMetadataOfTopologyTemplate(containerComponent);
-
+            Either<Component, StorageOperationStatus> updateContainerRes = toscaOperationFacade
+                .updateComponentInstanceMetadataOfTopologyTemplate(containerComponent);
             if (updateContainerRes.isRight()) {
                 ActionStatus actionStatus = componentsUtils.convertFromStorageResponseForResourceInstanceProperty(updateContainerRes.right().value());
                 resultOp = Either.right(componentsUtils.getResponseFormatForResourceInstanceProperty(actionStatus, ""));
@@ -3077,7 +3022,6 @@ public class ComponentInstanceBusinessLogic extends BaseBusinessLogic {
             }
             resultOp = Either.left(requirementDef);
             return resultOp;
-
         } finally {
             if (resultOp == null || resultOp.isRight()) {
                 janusGraphDao.rollback();
@@ -3089,30 +3033,33 @@ public class ComponentInstanceBusinessLogic extends BaseBusinessLogic {
         }
     }
 
-    public Either<List<ComponentInstanceProperty>, ResponseFormat> updateInstanceCapabilityProperties(ComponentTypeEnum componentTypeEnum, String containerComponentId, String componentInstanceUniqueId, String capabilityType, String capabilityName,
-                                                                                                      List<ComponentInstanceProperty> properties, String userId) {
+    public Either<List<ComponentInstanceProperty>, ResponseFormat> updateInstanceCapabilityProperties(ComponentTypeEnum componentTypeEnum,
+                                                                                                      String containerComponentId,
+                                                                                                      String componentInstanceUniqueId,
+                                                                                                      String capabilityType, String capabilityName,
+                                                                                                      List<ComponentInstanceProperty> properties,
+                                                                                                      String userId) {
         Either<List<ComponentInstanceProperty>, ResponseFormat> resultOp = null;
-
         validateUserExists(userId);
         if (componentTypeEnum == null) {
             BeEcompErrorManager.getInstance().logInvalidInputError("updateInstanceCapabilityProperty", INVALID_COMPONENT_TYPE, ErrorSeverity.INFO);
             return Either.right(componentsUtils.getResponseFormat(ActionStatus.NOT_ALLOWED));
         }
         Either<Component, StorageOperationStatus> getResourceResult = toscaOperationFacade.getToscaFullElement(containerComponentId);
-
         if (getResourceResult.isRight()) {
             log.debug(FAILED_TO_RETRIEVE_COMPONENT_COMPONENT_ID, containerComponentId);
             return Either.right(componentsUtils.getResponseFormat(ActionStatus.RESTRICTED_OPERATION));
         }
         Component containerComponent = getResourceResult.left().value();
-
         if (!ComponentValidationUtils.canWorkOnComponent(containerComponent, userId)) {
             log.info("Restricted operation for user: {} on component {}", userId, containerComponentId);
             return Either.right(componentsUtils.getResponseFormat(ActionStatus.RESTRICTED_OPERATION));
         }
-        Either<ComponentInstance, StorageOperationStatus> resourceInstanceStatus = getResourceInstanceById(containerComponent, componentInstanceUniqueId);
+        Either<ComponentInstance, StorageOperationStatus> resourceInstanceStatus = getResourceInstanceById(containerComponent,
+            componentInstanceUniqueId);
         if (resourceInstanceStatus.isRight()) {
-            return Either.right(componentsUtils.getResponseFormat(ActionStatus.RESOURCE_INSTANCE_NOT_FOUND_ON_SERVICE, componentInstanceUniqueId, containerComponentId));
+            return Either.right(componentsUtils
+                .getResponseFormat(ActionStatus.RESOURCE_INSTANCE_NOT_FOUND_ON_SERVICE, componentInstanceUniqueId, containerComponentId));
         }
         ComponentInstance foundResourceInstance = resourceInstanceStatus.left().value();
         // lock resource
@@ -3121,16 +3068,15 @@ public class ComponentInstanceBusinessLogic extends BaseBusinessLogic {
             log.debug("Failed to lock component {}", containerComponentId);
             return Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(lockStatus)));
         }
-
         try {
             for (ComponentInstanceProperty property : properties) {
                 Either<String, ResponseFormat> newPropertyValueEither = validatePropertyObjectValue(property, property.getValue(), false);
-                newPropertyValueEither.bimap(updatedValue ->
-                                updateCapabilityPropertyOnContainerComponent(property,updatedValue, containerComponent, foundResourceInstance, capabilityType, capabilityName),
-                        Either::right);
+                newPropertyValueEither.bimap(
+                    updatedValue -> updateCapabilityPropertyOnContainerComponent(property, updatedValue, containerComponent, foundResourceInstance,
+                        capabilityType, capabilityName), Either::right);
             }
-            Either<Component, StorageOperationStatus> updateContainerRes = toscaOperationFacade.updateComponentInstanceMetadataOfTopologyTemplate(containerComponent);
-
+            Either<Component, StorageOperationStatus> updateContainerRes = toscaOperationFacade
+                .updateComponentInstanceMetadataOfTopologyTemplate(containerComponent);
             if (updateContainerRes.isRight()) {
                 ActionStatus actionStatus = componentsUtils.convertFromStorageResponseForResourceInstanceProperty(updateContainerRes.right().value());
                 resultOp = Either.right(componentsUtils.getResponseFormatForResourceInstanceProperty(actionStatus, ""));
@@ -3138,7 +3084,6 @@ public class ComponentInstanceBusinessLogic extends BaseBusinessLogic {
             }
             resultOp = Either.left(properties);
             return resultOp;
-
         } finally {
             if (resultOp == null || resultOp.isRight()) {
                 janusGraphDao.rollback();
@@ -3151,62 +3096,46 @@ public class ComponentInstanceBusinessLogic extends BaseBusinessLogic {
     }
 
     public Either<Map<String, ComponentInstance>, ResponseFormat> copyComponentInstance(ComponentInstance inputComponentInstance,
-                                                                                        String containerComponentId,
-                                                                                        String componentInstanceId,
+                                                                                        String containerComponentId, String componentInstanceId,
                                                                                         String userId) {
-
         Map<String, ComponentInstance> resultMap = new HashMap<>();
         Either<Component, StorageOperationStatus> getOrigComponent = toscaOperationFacade.getToscaElement(containerComponentId);
         if (getOrigComponent.isRight()) {
             log.error("Failed to get the original component information");
-            return Either.right(componentsUtils.getResponseFormat(
-                    ActionStatus.USER_DEFINED, FAILED_TO_COPY_COMP_INSTANCE_TO_CANVAS));
+            return Either.right(componentsUtils.getResponseFormat(ActionStatus.USER_DEFINED, FAILED_TO_COPY_COMP_INSTANCE_TO_CANVAS));
         }
-
         Component origComponent = getOrigComponent.left().value();
-
         try {
             lockComponent(origComponent, "copyComponentInstance");
-
         } catch (ComponentException e) {
             log.error("destComponentInstance's data is {}", origComponent.toString());
-            return Either.right(componentsUtils.getResponseFormat(
-                    ActionStatus.USER_DEFINED, "Failed to lock component destComponentInstance's data is {}", origComponent.toString()));
+            return Either.right(componentsUtils
+                .getResponseFormat(ActionStatus.USER_DEFINED, "Failed to lock component destComponentInstance's data is {}",
+                    origComponent.toString()));
         }
-
         boolean failed = false;
         ComponentInstance actionResponse = null;
         try {
-
-            actionResponse = createComponentInstance(
-                    "services", containerComponentId, userId, inputComponentInstance, false);
-
+            actionResponse = createComponentInstance("services", containerComponentId, userId, inputComponentInstance, false);
         } catch (ComponentException e) {
             failed = true;
             // on failure of the create instance unlock the resource and rollback the transaction.
             return Either.right(componentsUtils.getResponseFormat(ActionStatus.USER_DEFINED, FAILED_TO_COPY_COMP_INSTANCE_TO_CANVAS));
         } finally {
-
             // on failure of the create instance unlock the resource and rollback the transaction.
             if (null == actionResponse) {
                 log.error(FAILED_TO_COPY_COMP_INSTANCE_TO_CANVAS);
-
                 unlockComponent(failed, origComponent);
             }
         }
-
         Either<String, ResponseFormat> resultOp = null;
-
         try {
             ComponentInstance destComponentInstance = actionResponse;
             log.debug("destComponentInstance's data is {}", destComponentInstance);
-
             resultOp = deepCopyComponentInstance(origComponent, containerComponentId, componentInstanceId, destComponentInstance, userId);
-
             resultMap.put("componentInstance", destComponentInstance);
         } finally {
             // unlock resource
-
             if (resultOp == null || resultOp.isRight()) {
                 unlockComponent(true, origComponent);
                 janusGraphDao.rollback();
@@ -3218,66 +3147,58 @@ public class ComponentInstanceBusinessLogic extends BaseBusinessLogic {
             }
         }
         if (resultOp == null || resultOp.isRight()) {
-            return Either.right(componentsUtils.getResponseFormat(ActionStatus.USER_DEFINED, "Failed to deep copy the component instance to the canvas"));
+            return Either
+                .right(componentsUtils.getResponseFormat(ActionStatus.USER_DEFINED, "Failed to deep copy the component instance to the canvas"));
         } else {
             return Either.left(resultMap);
         }
-
     }
 
-    private Either<String, ResponseFormat> deepCopyComponentInstance(
-            Component sourceComponent, String containerComponentId, String sourceComponentInstanceId,
-            ComponentInstance destComponentInstance, String userId) {
-
+    private Either<String, ResponseFormat> deepCopyComponentInstance(Component sourceComponent, String containerComponentId,
+                                                                     String sourceComponentInstanceId, ComponentInstance destComponentInstance,
+                                                                     String userId) {
         Either<Component, StorageOperationStatus> getDestComponent = toscaOperationFacade.getToscaElement(containerComponentId);
         if (getDestComponent.isRight()) {
             log.error("Failed to get the dest component information");
             return Either.right(componentsUtils.getResponseFormat(ActionStatus.USER_DEFINED, FAILED_TO_COPY_COMP_INSTANCE_TO_CANVAS));
         }
-
         Component destComponent = getDestComponent.left().value();
-
-        Either<String, ResponseFormat> copyComponentInstanceWithPropertiesAndInputs = copyComponentInstanceWithPropertiesAndInputs(
-            sourceComponent, destComponent, sourceComponentInstanceId, destComponentInstance);
+        Either<String, ResponseFormat> copyComponentInstanceWithPropertiesAndInputs = copyComponentInstanceWithPropertiesAndInputs(sourceComponent,
+            destComponent, sourceComponentInstanceId, destComponentInstance);
         if (copyComponentInstanceWithPropertiesAndInputs.isRight()) {
             log.error("Failed to copy component instance with properties and inputs as part of deep copy");
-            return Either.right(componentsUtils.getResponseFormat(
-                    ActionStatus.USER_DEFINED, "Failed to copy the component instance with properties and inputs as part of deep copy"));
+            return Either.right(componentsUtils.getResponseFormat(ActionStatus.USER_DEFINED,
+                "Failed to copy the component instance with properties and inputs as part of deep copy"));
         }
-
-        Either<String, ResponseFormat> copyComponentInstanceWithAttributes = copyComponentInstanceWithAttributes(
-                sourceComponent, destComponent, sourceComponentInstanceId, destComponentInstance, userId);
+        Either<String, ResponseFormat> copyComponentInstanceWithAttributes = copyComponentInstanceWithAttributes(sourceComponent, destComponent,
+            sourceComponentInstanceId, destComponentInstance, userId);
         if (copyComponentInstanceWithAttributes.isRight()) {
             log.error("Failed to copy component instance with attributes as part of deep copy");
-            return Either.right(componentsUtils.getResponseFormat(
-                    ActionStatus.USER_DEFINED, "Failed to copy the component instance with attributes as part of deep copy"));
+            return Either.right(componentsUtils
+                .getResponseFormat(ActionStatus.USER_DEFINED, "Failed to copy the component instance with attributes as part of deep copy"));
         }
         return Either.left(COPY_COMPONENT_INSTANCE_OK);
     }
 
-    private Either<String, ResponseFormat> copyComponentInstanceWithPropertiesAndInputs(
-        Component sourceComponent, Component destComponent, String sourceComponentInstanceId,
-        ComponentInstance destComponentInstance) {
+    private Either<String, ResponseFormat> copyComponentInstanceWithPropertiesAndInputs(Component sourceComponent, Component destComponent,
+                                                                                        String sourceComponentInstanceId,
+                                                                                        ComponentInstance destComponentInstance) {
         log.debug("start to copy ComponentInstance with properties and inputs");
-
         List<ComponentInstanceProperty> sourcePropList = null;
         if (sourceComponent.getComponentInstancesProperties() != null
             && sourceComponent.getComponentInstancesProperties().get(sourceComponentInstanceId) != null) {
             sourcePropList = sourceComponent.getComponentInstancesProperties().get(sourceComponentInstanceId);
             log.debug("sourcePropList");
         }
-
         List<ComponentInstanceProperty> destPropList = null;
         String destComponentInstanceId = destComponentInstance.getUniqueId();
         log.debug("destComponentInstanceId: {}", destComponentInstance.getUniqueId());
         if (destComponent.getComponentInstancesProperties() != null
-                && destComponent.getComponentInstancesProperties().get(destComponentInstanceId) != null) {
+            && destComponent.getComponentInstancesProperties().get(destComponentInstanceId) != null) {
             destPropList = destComponent.getComponentInstancesProperties().get(destComponentInstanceId);
             log.debug("destPropList {}");
         }
-
         List<ComponentInstancePropInput> componentInstancePropInputList = new ArrayList<>();
-
         if (null != destPropList && null != sourcePropList) {
             log.debug("start to set property and attribute");
             for (ComponentInstanceProperty destProp : destPropList) {
@@ -3288,32 +3209,28 @@ public class ComponentInstanceBusinessLogic extends BaseBusinessLogic {
                     }
                     log.debug("now set property");
                     final List<GetInputValueDataDefinition> getInputValues = sourceProp.getGetInputValues();
-                    if (getInputValues == null && !StringUtils.isEmpty(sourceProp.getValue())
-                        && (destProp.getValue() == null || !destProp.getValue().equals(sourceProp.getValue()))) {
+                    if (getInputValues == null && !StringUtils.isEmpty(sourceProp.getValue()) && (destProp.getValue() == null || !destProp.getValue()
+                        .equals(sourceProp.getValue()))) {
                         log.debug("Now starting to copy the property {} in value {}", destPropertyName, sourceProp.getValue());
-
                         destProp.setValue(sourceProp.getValue());
-                        Either<String, ResponseFormat> updatePropertyValueEither = updateComponentInstanceProperty(
-                            destComponent.getUniqueId(), destComponentInstanceId, destProp);
+                        Either<String, ResponseFormat> updatePropertyValueEither = updateComponentInstanceProperty(destComponent.getUniqueId(),
+                            destComponentInstanceId, destProp);
                         if (updatePropertyValueEither.isRight()) {
                             log.error("Failed to copy the property {}", destPropertyName);
-                            return Either.right(componentsUtils.getResponseFormat(
-                                ActionStatus.INVALID_CONTENT_PARAM, "Failed to paste component instance to the canvas, property copy"));
+                            return Either.right(componentsUtils.getResponseFormat(ActionStatus.INVALID_CONTENT_PARAM,
+                                "Failed to paste component instance to the canvas, property copy"));
                         }
                         break;
                     }
-
                     log.debug("Now start to update inputs");
-
                     if (getInputValues != null) {
                         if (getInputValues.isEmpty()) {
                             log.debug("property is return from input, set by man");
                             break;
                         }
                         log.debug("Now starting to copy the {} property", destPropertyName);
-
-                        Either<String, ResponseFormat> getSourceInputDefaultValue = getInputListDefaultValue(
-                            sourceComponent, getInputValues.get(0).getInputId());
+                        Either<String, ResponseFormat> getSourceInputDefaultValue = getInputListDefaultValue(sourceComponent,
+                            getInputValues.get(0).getInputId());
                         if (getSourceInputDefaultValue.isRight()) {
                             return Either.right(getSourceInputDefaultValue.right().value());
                         }
@@ -3325,121 +3242,93 @@ public class ComponentInstanceBusinessLogic extends BaseBusinessLogic {
         return Either.left(COPY_COMPONENT_INSTANCE_OK);
     }
 
-    private Either<String, ResponseFormat> copyComponentInstanceWithAttributes(Component sourceComponent,
-                                                                               Component destComponent,
+    private Either<String, ResponseFormat> copyComponentInstanceWithAttributes(Component sourceComponent, Component destComponent,
                                                                                String sourceComponentInstanceId,
-                                                                               ComponentInstance destComponentInstance,
-                                                                               String userId) {
+                                                                               ComponentInstance destComponentInstance, String userId) {
         String destComponentInstanceId = destComponentInstance.getUniqueId();
-
         log.info("start to copy component instance with attributes");
-
         List<ComponentInstanceAttribute> sourceAttributeList = null;
         if (sourceComponent.getComponentInstancesAttributes() != null
-                && sourceComponent.getComponentInstancesAttributes().get(sourceComponentInstanceId) != null) {
+            && sourceComponent.getComponentInstancesAttributes().get(sourceComponentInstanceId) != null) {
             sourceAttributeList = sourceComponent.getComponentInstancesAttributes().get(sourceComponentInstanceId);
             log.info("sourceAttributes {}");
         }
-
         List<ComponentInstanceAttribute> destAttributeList = null;
         if (destComponent.getComponentInstancesAttributes() != null
-                && destComponent.getComponentInstancesAttributes().get(destComponentInstanceId) != null) {
+            && destComponent.getComponentInstancesAttributes().get(destComponentInstanceId) != null) {
             destAttributeList = destComponent.getComponentInstancesAttributes().get(destComponentInstanceId);
             log.info("destAttributeList {}");
         }
         if (null != sourceAttributeList && null != destAttributeList) {
             log.info("set attribute");
-
             for (ComponentInstanceAttribute sourceAttribute : sourceAttributeList) {
                 String sourceAttributeName = sourceAttribute.getName();
                 for (ComponentInstanceAttribute destAttribute : destAttributeList) {
                     if (sourceAttributeName.equals(destAttribute.getName())) {
                         log.debug("Start to copy the attribute exists {}", sourceAttributeName);
-
                         sourceAttribute.setUniqueId(
-                            UniqueIdBuilder.buildResourceInstanceUniuqeId(
-                                "attribute", destComponentInstanceId.split("\\.")[1], sourceAttributeName));
-
-                        Either<ComponentInstanceAttribute, ResponseFormat> updateAttributeValueEither =
-                            createOrUpdateAttributeValueForCopyPaste(ComponentTypeEnum.SERVICE,
-                                destComponent.getUniqueId(), destComponentInstanceId, sourceAttribute,
-                                userId);
+                            UniqueIdBuilder.buildResourceInstanceUniuqeId("attribute", destComponentInstanceId.split("\\.")[1], sourceAttributeName));
+                        Either<ComponentInstanceAttribute, ResponseFormat> updateAttributeValueEither = createOrUpdateAttributeValueForCopyPaste(
+                            ComponentTypeEnum.SERVICE, destComponent.getUniqueId(), destComponentInstanceId, sourceAttribute, userId);
                         if (updateAttributeValueEither.isRight()) {
                             log.error("Failed to copy the attribute");
-                            return Either.right(componentsUtils
-                                .getResponseFormat(ActionStatus.INVALID_CONTENT_PARAM,
-                                    "Failed to paste component instance to the canvas, attribute copy"));
+                            return Either.right(componentsUtils.getResponseFormat(ActionStatus.INVALID_CONTENT_PARAM,
+                                "Failed to paste component instance to the canvas, attribute copy"));
                         }
                         break;
                     }
                 }
             }
         }
-
         return Either.left(COPY_COMPONENT_INSTANCE_OK);
     }
 
     private Either<ComponentInstanceAttribute, ResponseFormat> createOrUpdateAttributeValueForCopyPaste(ComponentTypeEnum componentTypeEnum,
-                                                                                                       String componentId,
-                                                                                                       String resourceInstanceId,
-                                                                                                       ComponentInstanceAttribute attribute,
-                                                                                                       String userId) {
-
+                                                                                                        String componentId, String resourceInstanceId,
+                                                                                                        ComponentInstanceAttribute attribute,
+                                                                                                        String userId) {
         Either<ComponentInstanceAttribute, ResponseFormat> resultOp = null;
-
         validateUserExists(userId);
-
         if (componentTypeEnum == null) {
-            BeEcompErrorManager.getInstance().logInvalidInputError(
-                    "createOrUpdateAttributeValue", INVALID_COMPONENT_TYPE, ErrorSeverity.INFO);
+            BeEcompErrorManager.getInstance().logInvalidInputError("createOrUpdateAttributeValue", INVALID_COMPONENT_TYPE, ErrorSeverity.INFO);
             resultOp = Either.right(componentsUtils.getResponseFormat(ActionStatus.NOT_ALLOWED));
             return resultOp;
         }
-
         Either<Component, StorageOperationStatus> getResourceResult = toscaOperationFacade.getToscaElement(componentId, JsonParseFlagEnum.ParseAll);
-
         if (getResourceResult.isRight()) {
             log.info("Failed to retrieve component id {}", componentId);
             resultOp = Either.right(componentsUtils.getResponseFormat(ActionStatus.RESTRICTED_OPERATION));
             return resultOp;
         }
-
         Component containerComponent = getResourceResult.left().value();
-
         Either<ComponentInstance, StorageOperationStatus> resourceInstanceStatus = getResourceInstanceById(containerComponent, resourceInstanceId);
-
         if (resourceInstanceStatus.isRight()) {
-            resultOp = Either.right(componentsUtils.getResponseFormat(
-                    ActionStatus.RESOURCE_INSTANCE_NOT_FOUND_ON_SERVICE, resourceInstanceId, componentId));
+            resultOp = Either
+                .right(componentsUtils.getResponseFormat(ActionStatus.RESOURCE_INSTANCE_NOT_FOUND_ON_SERVICE, resourceInstanceId, componentId));
             return resultOp;
         }
-
         ComponentInstance foundResourceInstance = resourceInstanceStatus.left().value();
-
-
         String propertyType = attribute.getType();
         ToscaPropertyType type = ToscaPropertyType.isValidType(propertyType);
         log.info("The type of attribute id{},is {} ", attribute.getUniqueId(), propertyType);
-
         if (type == ToscaPropertyType.LIST || type == ToscaPropertyType.MAP) {
             SchemaDefinition def = attribute.getSchema();
             if (def == null) {
                 log.info("Schema doesn't exists for attribute of type {}", type);
-                return Either.right(componentsUtils.getResponseFormat(
-                        componentsUtils.convertFromStorageResponse(StorageOperationStatus.INVALID_VALUE)));
+                return Either
+                    .right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(StorageOperationStatus.INVALID_VALUE)));
             }
             PropertyDataDefinition propDef = def.getProperty();
             if (propDef == null) {
                 log.info("Attribute in Schema Definition inside attribute of type {} doesn't exist", type);
-                return Either.right(componentsUtils.getResponseFormat(
-                        componentsUtils.convertFromStorageResponse(StorageOperationStatus.INVALID_VALUE)));
+                return Either
+                    .right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(StorageOperationStatus.INVALID_VALUE)));
             }
         }
-
         List<ComponentInstanceAttribute> instanceAttributes = containerComponent.getComponentInstancesAttributes().get(resourceInstanceId);
-        Optional<ComponentInstanceAttribute> instanceAttribute = instanceAttributes.stream().filter(p -> p.getUniqueId().equals(attribute.getUniqueId())).findAny();
+        Optional<ComponentInstanceAttribute> instanceAttribute = instanceAttributes.stream()
+            .filter(p -> p.getUniqueId().equals(attribute.getUniqueId())).findAny();
         StorageOperationStatus status;
-
         if (instanceAttribute.isPresent()) {
             log.info("updateComponentInstanceAttribute");
             status = toscaOperationFacade.updateComponentInstanceAttribute(containerComponent, foundResourceInstance.getUniqueId(), attribute);
@@ -3455,54 +3344,41 @@ public class ComponentInstanceBusinessLogic extends BaseBusinessLogic {
         List<String> path = new ArrayList<>();
         path.add(foundResourceInstance.getUniqueId());
         attribute.setPath(path);
-
         foundResourceInstance.setCustomizationUUID(UUID.randomUUID().toString());
-        Either<Component, StorageOperationStatus> updateContainerRes = toscaOperationFacade.
-                updateComponentInstanceMetadataOfTopologyTemplate(containerComponent);
-
+        Either<Component, StorageOperationStatus> updateContainerRes = toscaOperationFacade
+            .updateComponentInstanceMetadataOfTopologyTemplate(containerComponent);
         if (updateContainerRes.isRight()) {
-            ActionStatus actionStatus = componentsUtils.
-                    convertFromStorageResponseForResourceInstanceProperty(updateContainerRes.right().value());
-            resultOp = Either.right(componentsUtils.
-                    getResponseFormatForResourceInstanceProperty(actionStatus, ""));
+            ActionStatus actionStatus = componentsUtils.convertFromStorageResponseForResourceInstanceProperty(updateContainerRes.right().value());
+            resultOp = Either.right(componentsUtils.getResponseFormatForResourceInstanceProperty(actionStatus, ""));
             return resultOp;
         }
         resultOp = Either.left(attribute);
         return resultOp;
     }
 
-    private Either<String, ResponseFormat> updateComponentInstanceProperty(String containerComponentId,
-                                                                           String componentInstanceId,
+    private Either<String, ResponseFormat> updateComponentInstanceProperty(String containerComponentId, String componentInstanceId,
                                                                            ComponentInstanceProperty property) {
         Either<String, ResponseFormat> resultOp;
         Either<Component, StorageOperationStatus> getComponent = toscaOperationFacade.getToscaElement(containerComponentId);
-
         if (getComponent.isRight()) {
             log.error("Failed to get the component information");
-            return Either.right(componentsUtils.getResponseFormatForResourceInstanceProperty(
-                    ActionStatus.INVALID_CONTENT_PARAM, "Failed to get the component information"));
+            return Either.right(componentsUtils
+                .getResponseFormatForResourceInstanceProperty(ActionStatus.INVALID_CONTENT_PARAM, "Failed to get the component information"));
         }
-
         Component containerComponent = getComponent.left().value();
-
-        StorageOperationStatus status = toscaOperationFacade.updateComponentInstanceProperty(
-                containerComponent, componentInstanceId, property);
+        StorageOperationStatus status = toscaOperationFacade.updateComponentInstanceProperty(containerComponent, componentInstanceId, property);
         if (status != StorageOperationStatus.OK) {
             ActionStatus actionStatus = componentsUtils.convertFromStorageResponseForResourceInstanceProperty(status);
             resultOp = Either.right(componentsUtils.getResponseFormatForResourceInstanceProperty(actionStatus, ""));
             return resultOp;
         }
-
-        Either<Component, StorageOperationStatus> updateContainerRes = toscaOperationFacade.
-                updateComponentInstanceMetadataOfTopologyTemplate(containerComponent);
-
+        Either<Component, StorageOperationStatus> updateContainerRes = toscaOperationFacade
+            .updateComponentInstanceMetadataOfTopologyTemplate(containerComponent);
         if (updateContainerRes.isRight()) {
-            ActionStatus actionStatus = componentsUtils.
-                    convertFromStorageResponseForResourceInstanceProperty(updateContainerRes.right().value());
+            ActionStatus actionStatus = componentsUtils.convertFromStorageResponseForResourceInstanceProperty(updateContainerRes.right().value());
             resultOp = Either.right(componentsUtils.getResponseFormatForResourceInstanceProperty(actionStatus, ""));
             return resultOp;
         }
-
         return Either.left("Update OK");
     }
 
@@ -3518,34 +3394,31 @@ public class ComponentInstanceBusinessLogic extends BaseBusinessLogic {
             }
         }
         log.error("The input's default value with id {} is not found", inputId);
-        return Either.right(componentsUtils.getResponseFormat(
-                ActionStatus.USER_DEFINED, "Failed to paste component instance to the canvas"));
+        return Either.right(componentsUtils.getResponseFormat(ActionStatus.USER_DEFINED, "Failed to paste component instance to the canvas"));
     }
 
     /**
      * Method to delete selected nodes and edges on composition page
+     *
      * @param containerComponentType
      * @param componentId
      * @param componentInstanceIdList
      * @param userId
      * @return
      */
-    public Map<String, List<String>> batchDeleteComponentInstance(String containerComponentType,
-                                                                  String componentId,
-                                                                  List<String> componentInstanceIdList,
-                                                                  String userId) {
-
+    public Map<String, List<String>> batchDeleteComponentInstance(String containerComponentType, String componentId,
+                                                                  List<String> componentInstanceIdList, String userId) {
         List<String> deleteErrorIds = new ArrayList<>();
         Map<String, List<String>> deleteErrorMap = new HashMap<>();
         validateUserExists(userId);
-        org.openecomp.sdc.be.model.Component containerComponent = validateComponentExists(componentId, ComponentTypeEnum.findByParamName(containerComponentType), null);
-
+        org.openecomp.sdc.be.model.Component containerComponent = validateComponentExists(componentId,
+            ComponentTypeEnum.findByParamName(containerComponentType), null);
         boolean failed = false;
         try {
             lockComponent(containerComponent, "batchDeleteComponentInstance");
             for (String eachInstanceId : componentInstanceIdList) {
-                Either<ComponentInstance, ResponseFormat> actionResponse = batchDeleteComponentInstance(
-                    containerComponent, containerComponentType, eachInstanceId);
+                Either<ComponentInstance, ResponseFormat> actionResponse = batchDeleteComponentInstance(containerComponent, containerComponentType,
+                    eachInstanceId);
                 log.debug("batchDeleteResourceInstances actionResponse is {}", actionResponse);
                 if (actionResponse.isRight()) {
                     log.error("Failed to delete ComponentInstance [{}]", eachInstanceId);
@@ -3555,27 +3428,23 @@ public class ComponentInstanceBusinessLogic extends BaseBusinessLogic {
             //sending the ids of the error nodes that were not deleted to UI
             deleteErrorMap.put("deleteFailedIds", deleteErrorIds);
             return deleteErrorMap;
-        }catch (ComponentException e){
+        } catch (ComponentException e) {
             failed = true;
             throw e;
-        }finally {
+        } finally {
             unlockComponent(failed, containerComponent);
         }
     }
 
-    private Either<ComponentInstance, ResponseFormat> batchDeleteComponentInstance(Component containerComponent,
-                                                                                   String containerComponentType,
+    private Either<ComponentInstance, ResponseFormat> batchDeleteComponentInstance(Component containerComponent, String containerComponentType,
                                                                                    String componentInstanceId) {
-
         ComponentInstance resultOp;
         final ComponentTypeEnum containerComponentTypeEnum = ComponentTypeEnum.findByParamName(containerComponentType);
-
         try {
             resultOp = deleteComponentInstance(containerComponent, componentInstanceId, containerComponentTypeEnum);
             log.info("Successfully deleted instance with id {}", componentInstanceId);
             return Either.left(resultOp);
-        }
-        catch (ComponentException e){
+        } catch (ComponentException e) {
             log.error("Failed to deleteComponentInstance with instanceId[{}]", componentInstanceId);
             return Either.right(new ResponseFormat());
         }
@@ -3585,5 +3454,4 @@ public class ComponentInstanceBusinessLogic extends BaseBusinessLogic {
         final User user = userValidations.validateUserExists(userId);
         userValidations.validateUserRole(user, Arrays.asList(Role.DESIGNER, Role.ADMIN));
     }
-
 }
index e32c51f..e73ade1 100644 (file)
@@ -18,7 +18,6 @@
  *  SPDX-License-Identifier: Apache-2.0
  *  ============LICENSE_END=========================================================
  */
-
 package org.openecomp.sdc.be.components.impl;
 
 import fj.data.Either;
@@ -59,163 +58,125 @@ import org.springframework.beans.factory.annotation.Autowired;
 @org.springframework.stereotype.Component("componentInterfaceOperationBusinessLogic")
 public class ComponentInterfaceOperationBusinessLogic extends BaseBusinessLogic {
 
+    private static final Logger LOGGER = LoggerFactory.getLogger(ComponentInterfaceOperationBusinessLogic.class);
     private final ComponentValidations componentValidations;
 
-    private static final Logger LOGGER = LoggerFactory.getLogger(ComponentInterfaceOperationBusinessLogic .class);
-
     @Autowired
-    public ComponentInterfaceOperationBusinessLogic(final IElementOperation elementDao,
-                                                    final IGroupOperation groupOperation,
+    public ComponentInterfaceOperationBusinessLogic(final IElementOperation elementDao, final IGroupOperation groupOperation,
                                                     final IGroupInstanceOperation groupInstanceOperation,
-                                                    final IGroupTypeOperation groupTypeOperation,
-                                                    final InterfaceOperation interfaceOperation,
+                                                    final IGroupTypeOperation groupTypeOperation, final InterfaceOperation interfaceOperation,
                                                     final InterfaceLifecycleOperation interfaceLifecycleTypeOperation,
                                                     final ArtifactsOperations artifactToscaOperation,
                                                     final ComponentValidations componentValidations) {
-        super(elementDao, groupOperation, groupInstanceOperation, groupTypeOperation, interfaceOperation,
-            interfaceLifecycleTypeOperation, artifactToscaOperation);
+        super(elementDao, groupOperation, groupInstanceOperation, groupTypeOperation, interfaceOperation, interfaceLifecycleTypeOperation,
+            artifactToscaOperation);
         this.componentValidations = componentValidations;
     }
 
-    public Optional<ComponentInstance> updateComponentInstanceInterfaceOperation(final String componentId,
-                                                                                 final String componentInstanceId,
+    public Optional<ComponentInstance> updateComponentInstanceInterfaceOperation(final String componentId, final String componentInstanceId,
                                                                                  final InterfaceDefinition interfaceDefinition,
                                                                                  final ComponentTypeEnum componentTypeEnum,
-                                                                                 final Wrapper<ResponseFormat> errorWrapper,
-                                                                                 final boolean shouldLock)
+                                                                                 final Wrapper<ResponseFormat> errorWrapper, final boolean shouldLock)
         throws BusinessLogicException {
-
         final Component component = getComponent(componentId);
-        final Optional<ComponentInstance> componentInstanceOptional = componentValidations
-            .getComponentInstance(component, componentInstanceId);
+        final Optional<ComponentInstance> componentInstanceOptional = componentValidations.getComponentInstance(component, componentInstanceId);
         ResponseFormat responseFormat;
         if (componentInstanceOptional.isEmpty()) {
             responseFormat = componentsUtils.getResponseFormat(ActionStatus.COMPONENT_INSTANCE_NOT_FOUND);
-            LOGGER.debug("Failed to found component instance with id {}, error: {}",
-                componentInstanceId, responseFormat);
+            LOGGER.debug("Failed to found component instance with id {}, error: {}", componentInstanceId, responseFormat);
             errorWrapper.setInnerElement(responseFormat);
             return Optional.empty();
         }
-
-        Map<String, List<ComponentInstanceInterface>> componentInstancesInterfaceMap = component
-            .getComponentInstancesInterfaces();
+        Map<String, List<ComponentInstanceInterface>> componentInstancesInterfaceMap = component.getComponentInstancesInterfaces();
         if (MapUtils.isEmpty(componentInstancesInterfaceMap)) {
             componentInstancesInterfaceMap = new HashMap<>();
             component.setComponentInstancesInterfaces(componentInstancesInterfaceMap);
         }
-        final List<ComponentInstanceInterface> componentInstanceInterfaceList = componentInstancesInterfaceMap
-            .get(componentInstanceId);
-
+        final List<ComponentInstanceInterface> componentInstanceInterfaceList = componentInstancesInterfaceMap.get(componentInstanceId);
         if (CollectionUtils.isEmpty(componentInstanceInterfaceList)) {
             responseFormat = componentsUtils.getResponseFormat(ActionStatus.COMPONENT_INSTANCE_NOT_FOUND);
-            LOGGER.debug("Failed to found component instance with id {}, error: {}",
-                componentInstanceId, responseFormat);
+            LOGGER.debug("Failed to found component instance with id {}, error: {}", componentInstanceId, responseFormat);
             errorWrapper.setInnerElement(responseFormat);
             return Optional.empty();
         }
-
-        final Optional<OperationDataDefinition> optionalOperationDataDefinition = interfaceDefinition
-            .getOperations().values().stream().findFirst();
+        final Optional<OperationDataDefinition> optionalOperationDataDefinition = interfaceDefinition.getOperations().values().stream().findFirst();
         if (optionalOperationDataDefinition.isEmpty()) {
             responseFormat = componentsUtils.getResponseFormat(ActionStatus.INTERFACE_OPERATION_NOT_FOUND);
-            LOGGER.debug("Failed to found interface operation on component instance with id {}, error: {}",
-                componentInstanceId, responseFormat);
+            LOGGER.debug("Failed to found interface operation on component instance with id {}, error: {}", componentInstanceId, responseFormat);
             errorWrapper.setInnerElement(responseFormat);
             return Optional.empty();
         }
         final OperationDataDefinition updatedOperationDataDefinition = optionalOperationDataDefinition.get();
-        final Optional<ComponentInstanceInterface> optionalComponentInstanceInterface = componentInstanceInterfaceList
-            .stream().filter(ci -> ci.getOperations().values().stream().anyMatch(operationDataDefinition ->
-                operationDataDefinition.getUniqueId()
-                    .equalsIgnoreCase(updatedOperationDataDefinition.getUniqueId()))).findFirst();
-
+        final Optional<ComponentInstanceInterface> optionalComponentInstanceInterface = componentInstanceInterfaceList.stream().filter(
+            ci -> ci.getOperations().values().stream().anyMatch(
+                operationDataDefinition -> operationDataDefinition.getUniqueId().equalsIgnoreCase(updatedOperationDataDefinition.getUniqueId())))
+            .findFirst();
         if (optionalComponentInstanceInterface.isEmpty()) {
             responseFormat = componentsUtils.getResponseFormat(ActionStatus.INTERFACE_NOT_FOUND_IN_COMPONENT);
-            LOGGER.debug("Failed to found ComponentInstanceInterface on component instance with id {}, error: {}",
-                componentInstanceId, responseFormat);
+            LOGGER
+                .debug("Failed to found ComponentInstanceInterface on component instance with id {}, error: {}", componentInstanceId, responseFormat);
             errorWrapper.setInnerElement(responseFormat);
             return Optional.empty();
         }
-
         updateOperationDefinitionImplementation(updatedOperationDataDefinition);
-
-        optionalComponentInstanceInterface.get().getOperations()
-            .replace(updatedOperationDataDefinition.getName(), updatedOperationDataDefinition);
-
+        optionalComponentInstanceInterface.get().getOperations().replace(updatedOperationDataDefinition.getName(), updatedOperationDataDefinition);
         boolean wasLocked = false;
         try {
             if (shouldLock) {
                 lockComponent(componentId, component, "Update Interface Operation on Component instance");
                 wasLocked = true;
             }
-
-            final StorageOperationStatus status = toscaOperationFacade
-                .updateComponentInstanceInterfaces(component, componentInstanceId);
-
+            final StorageOperationStatus status = toscaOperationFacade.updateComponentInstanceInterfaces(component, componentInstanceId);
             if (status != StorageOperationStatus.OK) {
                 janusGraphDao.rollback();
-                responseFormat = componentsUtils
-                    .getResponseFormat(ActionStatus.GENERAL_ERROR);
+                responseFormat = componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR);
                 LOGGER.error("Exception occurred when updating Component Instance Interfaces {}", responseFormat);
                 errorWrapper.setInnerElement(responseFormat);
                 return Optional.empty();
             }
-
             final ComponentParametersView componentFilter = new ComponentParametersView();
             componentFilter.disableAll();
             componentFilter.setIgnoreUsers(false);
             componentFilter.setIgnoreComponentInstances(false);
             componentFilter.setIgnoreInterfaces(false);
             componentFilter.setIgnoreComponentInstancesInterfaces(false);
-
             final Either<Component, StorageOperationStatus> operationStatusEither = toscaOperationFacade
                 .updateComponentInstanceMetadataOfTopologyTemplate(component, componentFilter);
-
             if (operationStatusEither.isRight()) {
                 janusGraphDao.rollback();
-                responseFormat = componentsUtils
-                    .getResponseFormat(ActionStatus.GENERAL_ERROR);
+                responseFormat = componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR);
                 LOGGER.error("Exception occurred when updating Component Instance Topology template {}", responseFormat);
                 errorWrapper.setInnerElement(responseFormat);
                 return Optional.empty();
             }
             janusGraphDao.commit();
-
         } catch (final Exception e) {
             janusGraphDao.rollback();
-            LOGGER.error("Exception occurred when updating Interface Operation on Component Instance: {}",
-                e.getMessage(), e);
+            LOGGER.error("Exception occurred when updating Interface Operation on Component Instance: {}", e.getMessage(), e);
             responseFormat = componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR);
             errorWrapper.setInnerElement(responseFormat);
             throw new BusinessLogicException(responseFormat);
-
         } finally {
             if (wasLocked) {
                 unlockComponent(component.getUniqueId(), componentTypeEnum);
             }
         }
-
         return componentInstanceOptional;
-
     }
 
     public User validateUser(final String userId) {
         final User user = userValidations.validateUserExists(userId);
-        userValidations
-            .validateUserRole(user, Arrays.asList(Role.DESIGNER, Role.ADMIN));
+        userValidations.validateUserRole(user, Arrays.asList(Role.DESIGNER, Role.ADMIN));
         return user;
     }
 
-    private void unlockComponent(final String componentUniqueId,
-                                 final ComponentTypeEnum componentType) {
+    private void unlockComponent(final String componentUniqueId, final ComponentTypeEnum componentType) {
         graphLockOperation.unlockComponent(componentUniqueId, componentType.getNodeType());
     }
 
     private void updateOperationDefinitionImplementation(final OperationDataDefinition updatedOperationDataDefinition) {
         final ArtifactDataDefinition artifactInfo = new ArtifactDataDefinition();
-        artifactInfo.setArtifactName(
-            String.format("'%s'", updatedOperationDataDefinition.getImplementation().getArtifactName())
-        );
+        artifactInfo.setArtifactName(String.format("'%s'", updatedOperationDataDefinition.getImplementation().getArtifactName()));
         updatedOperationDataDefinition.setImplementation(artifactInfo);
     }
 }
index 5358cf5..c7fb395 100644 (file)
@@ -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.
@@ -17,7 +17,6 @@
  * limitations under the License.
  * ============LICENSE_END=========================================================
  */
-
 package org.openecomp.sdc.be.components.impl;
 
 import org.openecomp.sdc.be.datatypes.enums.ComponentTypeEnum;
@@ -28,9 +27,8 @@ import org.openecomp.sdc.be.model.operations.api.StorageOperationStatus;
 import org.openecomp.sdc.be.model.operations.impl.GraphLockOperation;
 import org.openecomp.sdc.common.log.wrappers.Logger;
 
-
 @org.springframework.stereotype.Component
-public class ComponentLocker  {
+public class ComponentLocker {
 
     private static final Logger log = Logger.getLogger(ComponentLocker.class.getName());
     private final GraphLockOperation graphLockOperation;
@@ -55,7 +53,7 @@ public class ComponentLocker  {
         log.debug("#doLockComponent - locking component {} of type {}", id, nodeTypeEnum);
         StorageOperationStatus storageOperationStatus = graphLockOperation.lockComponent(id, nodeTypeEnum);
         if (storageOperationStatus != StorageOperationStatus.OK) {
-               log.debug("#doLockComponent - failed to lock component {} with status {}", id, storageOperationStatus);
+            log.debug("#doLockComponent - failed to lock component {} with status {}", id, storageOperationStatus);
             throw new StorageException(storageOperationStatus);
         }
     }
index f547dcf..e5bb817 100644 (file)
@@ -16,7 +16,6 @@
  *  SPDX-License-Identifier: Apache-2.0
  *  ============LICENSE_END=========================================================
  */
-
 package org.openecomp.sdc.be.components.impl;
 
 import static org.openecomp.sdc.common.log.enums.EcompLoggerErrorCode.BUSINESS_PROCESS_ERROR;
@@ -59,32 +58,25 @@ import org.springframework.beans.factory.annotation.Autowired;
 public class ComponentNodeFilterBusinessLogic extends BaseBusinessLogic {
 
     private static final Logger LOGGER = Logger.getLogger(ComponentNodeFilterBusinessLogic.class.getName());
-
     private final NodeFilterOperation nodeFilterOperation;
     private final NodeFilterValidator nodeFilterValidator;
 
     @Autowired
-    public ComponentNodeFilterBusinessLogic(final IElementOperation elementDao,
-                                            final IGroupOperation groupOperation,
-                                            final IGroupInstanceOperation groupInstanceOperation,
-                                            final IGroupTypeOperation groupTypeOperation,
+    public ComponentNodeFilterBusinessLogic(final IElementOperation elementDao, final IGroupOperation groupOperation,
+                                            final IGroupInstanceOperation groupInstanceOperation, final IGroupTypeOperation groupTypeOperation,
                                             final InterfaceOperation interfaceOperation,
                                             final InterfaceLifecycleOperation interfaceLifecycleTypeOperation,
-                                            final ArtifactsOperations artifactToscaOperation,
-                                            final NodeFilterOperation nodeFilterOperation,
+                                            final ArtifactsOperations artifactToscaOperation, final NodeFilterOperation nodeFilterOperation,
                                             final NodeFilterValidator nodeFilterValidator) {
-        super(elementDao, groupOperation, groupInstanceOperation, groupTypeOperation, interfaceOperation,
-            interfaceLifecycleTypeOperation, artifactToscaOperation);
+        super(elementDao, groupOperation, groupInstanceOperation, groupTypeOperation, interfaceOperation, interfaceLifecycleTypeOperation,
+            artifactToscaOperation);
         this.nodeFilterOperation = nodeFilterOperation;
         this.nodeFilterValidator = nodeFilterValidator;
     }
 
-    public Optional<CINodeFilterDataDefinition> createNodeFilterIfNotExist(final String componentId,
-                                                                           final String componentInstanceId,
-                                                                           final boolean shouldLock,
-                                                                           final ComponentTypeEnum componentTypeEnum)
+    public Optional<CINodeFilterDataDefinition> createNodeFilterIfNotExist(final String componentId, final String componentInstanceId,
+                                                                           final boolean shouldLock, final ComponentTypeEnum componentTypeEnum)
         throws BusinessLogicException {
-
         final Component component = getComponent(componentId);
         final Optional<ComponentInstance> componentInstance = getComponentInstance(componentInstanceId, component);
         Optional<CINodeFilterDataDefinition> filterDataDefinition = getCiNodeFilterDataDefinition(componentInstance);
@@ -95,28 +87,24 @@ public class ComponentNodeFilterBusinessLogic extends BaseBusinessLogic {
         boolean wasLocked = false;
         try {
             if (shouldLock) {
-                lockComponent(component.getUniqueId(), component,"Create Node Filter on component");
+                lockComponent(component.getUniqueId(), component, "Create Node Filter on component");
                 wasLocked = true;
             }
             result = nodeFilterOperation.createNodeFilter(componentId, componentInstanceId);
             if (result.isRight()) {
                 janusGraphDao.rollback();
-                LOGGER.error(BUSINESS_PROCESS_ERROR,
-                    "Failed to Create Node filter on component with id {}", componentId);
-                throw new BusinessLogicException(componentsUtils.getResponseFormatByResource(componentsUtils
-                    .convertFromStorageResponse(result.right().value()), component.getSystemName()));
+                LOGGER.error(BUSINESS_PROCESS_ERROR, "Failed to Create Node filter on component with id {}", componentId);
+                throw new BusinessLogicException(componentsUtils
+                    .getResponseFormatByResource(componentsUtils.convertFromStorageResponse(result.right().value()), component.getSystemName()));
             } else {
                 filterDataDefinition = Optional.ofNullable(result.left().value());
             }
             janusGraphDao.commit();
             LOGGER.debug("Node filter successfully created in component {} . ", component.getSystemName());
-
         } catch (final Exception e) {
             janusGraphDao.rollback();
-            LOGGER.error(BUSINESS_PROCESS_ERROR,
-                "Exception occurred during add Component node filter property values: {}", e.getMessage(), e);
+            LOGGER.error(BUSINESS_PROCESS_ERROR, "Exception occurred during add Component node filter property values: {}", e.getMessage(), e);
             throw new BusinessLogicException(componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR));
-
         } finally {
             if (wasLocked) {
                 unlockComponent(component.getUniqueId(), componentTypeEnum);
@@ -125,41 +113,32 @@ public class ComponentNodeFilterBusinessLogic extends BaseBusinessLogic {
         return filterDataDefinition;
     }
 
-    public Optional<String> deleteNodeFilterIfExists(final String componentId,
-                                                     final String componentInstanceId,
-                                                     final boolean shouldLock,
-                                                     final ComponentTypeEnum componentTypeEnum)
-        throws BusinessLogicException {
-
+    public Optional<String> deleteNodeFilterIfExists(final String componentId, final String componentInstanceId, final boolean shouldLock,
+                                                     final ComponentTypeEnum componentTypeEnum) throws BusinessLogicException {
         final Component component = getComponent(componentId);
-        final Optional<CINodeFilterDataDefinition> nodeFilterDataDefinition =
-            getCiNodeFilterDataDefinition(componentInstanceId, component);
+        final Optional<CINodeFilterDataDefinition> nodeFilterDataDefinition = getCiNodeFilterDataDefinition(componentInstanceId, component);
         if (!nodeFilterDataDefinition.isPresent()) {
             return Optional.ofNullable(componentInstanceId);
         }
-
         final Either<String, StorageOperationStatus> result;
         boolean wasLocked = false;
         try {
             if (shouldLock) {
-                lockComponent(component.getUniqueId(), component,"Delete Node Filter from component");
+                lockComponent(component.getUniqueId(), component, "Delete Node Filter from component");
                 wasLocked = true;
             }
             result = nodeFilterOperation.deleteNodeFilter(component, componentInstanceId);
             if (result.isRight()) {
-                LOGGER.error(BUSINESS_PROCESS_ERROR,
-                    "Failed to delete node filter in component {}. Response is {}. ", component.getName(),
+                LOGGER.error(BUSINESS_PROCESS_ERROR, "Failed to delete node filter in component {}. Response is {}. ", component.getName(),
                     result.right().value());
                 janusGraphDao.rollback();
-                throw new BusinessLogicException(componentsUtils.getResponseFormatByResource(componentsUtils
-                    .convertFromStorageResponse(result.right().value()), component.getSystemName()));
+                throw new BusinessLogicException(componentsUtils
+                    .getResponseFormatByResource(componentsUtils.convertFromStorageResponse(result.right().value()), component.getSystemName()));
             }
             janusGraphDao.commit();
             LOGGER.debug("Node filter successfully deleted in component {} . ", component.getSystemName());
-
         } catch (final Exception e) {
-            LOGGER.error(BUSINESS_PROCESS_ERROR,"Exception occurred during delete deleting node filter: {}",
-                e.getMessage(), e);
+            LOGGER.error(BUSINESS_PROCESS_ERROR, "Exception occurred during delete deleting node filter: {}", e.getMessage(), e);
             janusGraphDao.rollback();
             throw new BusinessLogicException(componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR));
         } finally {
@@ -170,50 +149,39 @@ public class ComponentNodeFilterBusinessLogic extends BaseBusinessLogic {
         return Optional.ofNullable(result.left().value());
     }
 
-    public Optional<CINodeFilterDataDefinition> addNodeFilter(final String componentId,
-                                                              final String componentInstanceId,
-                                                              final NodeFilterConstraintAction action,
-                                                              final String propertyName,
-                                                              final String constraint,
-                                                              final boolean shouldLock,
+    public Optional<CINodeFilterDataDefinition> addNodeFilter(final String componentId, final String componentInstanceId,
+                                                              final NodeFilterConstraintAction action, final String propertyName,
+                                                              final String constraint, final boolean shouldLock,
                                                               final ComponentTypeEnum componentTypeEnum,
-                                                              final NodeFilterConstraintType nodeFilterConstraintType,
-                                                              final String capabilityName)
+                                                              final NodeFilterConstraintType nodeFilterConstraintType, final String capabilityName)
         throws BusinessLogicException {
-
         final Component component = getComponent(componentId);
-        CINodeFilterDataDefinition nodeFilterDataDefinition = validateAndReturnNodeFilterDefinition(componentInstanceId,
-            action, constraint, component, nodeFilterConstraintType);
+        CINodeFilterDataDefinition nodeFilterDataDefinition = validateAndReturnNodeFilterDefinition(componentInstanceId, action, constraint,
+            component, nodeFilterConstraintType);
         boolean wasLocked = false;
         try {
             if (shouldLock) {
-                lockComponent(component.getUniqueId(), component,"Add Node Filter on Component");
+                lockComponent(component.getUniqueId(), component, "Add Node Filter on Component");
                 wasLocked = true;
             }
-            final RequirementNodeFilterPropertyDataDefinition requirementNodeFilterPropertyDataDefinition =
-                new RequirementNodeFilterPropertyDataDefinition();
+            final RequirementNodeFilterPropertyDataDefinition requirementNodeFilterPropertyDataDefinition = new RequirementNodeFilterPropertyDataDefinition();
             requirementNodeFilterPropertyDataDefinition.setName(propertyName);
             requirementNodeFilterPropertyDataDefinition.setConstraints(Collections.singletonList(constraint));
-
-            final Either<CINodeFilterDataDefinition, StorageOperationStatus> result = addNewNodeFilter(componentId,
-                componentInstanceId, nodeFilterConstraintType, nodeFilterDataDefinition,
-                requirementNodeFilterPropertyDataDefinition, capabilityName);
+            final Either<CINodeFilterDataDefinition, StorageOperationStatus> result = addNewNodeFilter(componentId, componentInstanceId,
+                nodeFilterConstraintType, nodeFilterDataDefinition, requirementNodeFilterPropertyDataDefinition, capabilityName);
             if (result.isRight()) {
                 janusGraphDao.rollback();
-                throw new BusinessLogicException(componentsUtils.getResponseFormatByResource(componentsUtils
-                    .convertFromStorageResponse(result.right().value()), component.getSystemName()));
+                throw new BusinessLogicException(componentsUtils
+                    .getResponseFormatByResource(componentsUtils.convertFromStorageResponse(result.right().value()), component.getSystemName()));
             } else {
                 nodeFilterDataDefinition = result.left().value();
             }
             janusGraphDao.commit();
             LOGGER.debug("Node filter successfully created in component {} . ", component.getSystemName());
-
         } catch (final Exception e) {
             janusGraphDao.rollback();
-            LOGGER.error(BUSINESS_PROCESS_ERROR,
-                "Exception occurred during add component node filter property values: {}", e.getMessage(), e);
+            LOGGER.error(BUSINESS_PROCESS_ERROR, "Exception occurred during add component node filter property values: {}", e.getMessage(), e);
             throw new BusinessLogicException(componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR));
-
         } finally {
             if (wasLocked) {
                 unlockComponent(component.getUniqueId(), componentTypeEnum);
@@ -222,44 +190,35 @@ public class ComponentNodeFilterBusinessLogic extends BaseBusinessLogic {
         return Optional.ofNullable(nodeFilterDataDefinition);
     }
 
-    public Optional<CINodeFilterDataDefinition> deleteNodeFilter(final String componentId,
-                                                                 final String componentInstanceId,
-                                                                 final NodeFilterConstraintAction action,
-                                                                 final String constraint,
-                                                                 final int position,
-                                                                 final boolean shouldLock,
-                                                                 final ComponentTypeEnum componentTypeEnum,
+    public Optional<CINodeFilterDataDefinition> deleteNodeFilter(final String componentId, final String componentInstanceId,
+                                                                 final NodeFilterConstraintAction action, final String constraint, final int position,
+                                                                 final boolean shouldLock, final ComponentTypeEnum componentTypeEnum,
                                                                  final NodeFilterConstraintType nodeFilterConstraintType)
         throws BusinessLogicException {
-
         final Component component = getComponent(componentId);
-        CINodeFilterDataDefinition nodeFilterDataDefinition =
-            validateAndReturnNodeFilterDefinition(componentInstanceId, action, constraint, component, nodeFilterConstraintType);
+        CINodeFilterDataDefinition nodeFilterDataDefinition = validateAndReturnNodeFilterDefinition(componentInstanceId, action, constraint,
+            component, nodeFilterConstraintType);
         boolean wasLocked = false;
         try {
             if (shouldLock) {
-                lockComponent(component.getUniqueId(), component,"Add Node Filter on Component");
+                lockComponent(component.getUniqueId(), component, "Add Node Filter on Component");
                 wasLocked = true;
             }
             final Either<CINodeFilterDataDefinition, StorageOperationStatus> result = nodeFilterOperation
-                .deleteConstraint(componentId, componentInstanceId, nodeFilterDataDefinition, position,
-                    nodeFilterConstraintType);
+                .deleteConstraint(componentId, componentInstanceId, nodeFilterDataDefinition, position, nodeFilterConstraintType);
             if (result.isRight()) {
                 janusGraphDao.rollback();
-                throw new BusinessLogicException(componentsUtils.getResponseFormatByResource(componentsUtils
-                    .convertFromStorageResponse(result.right().value()), component.getSystemName()));
+                throw new BusinessLogicException(componentsUtils
+                    .getResponseFormatByResource(componentsUtils.convertFromStorageResponse(result.right().value()), component.getSystemName()));
             } else {
                 nodeFilterDataDefinition = result.left().value();
             }
             janusGraphDao.commit();
             LOGGER.debug("Node filter successfully deleted in component {} . ", component.getSystemName());
-
         } catch (final Exception e) {
             janusGraphDao.rollback();
-            LOGGER.error(BUSINESS_PROCESS_ERROR,
-                "Exception occurred during delete component node filter property values: {}", e.getMessage(), e);
+            LOGGER.error(BUSINESS_PROCESS_ERROR, "Exception occurred during delete component node filter property values: {}", e.getMessage(), e);
             throw new BusinessLogicException(componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR));
-
         } finally {
             if (wasLocked) {
                 unlockComponent(component.getUniqueId(), componentTypeEnum);
@@ -268,33 +227,26 @@ public class ComponentNodeFilterBusinessLogic extends BaseBusinessLogic {
         return Optional.ofNullable(nodeFilterDataDefinition);
     }
 
-    private Either<CINodeFilterDataDefinition, StorageOperationStatus> addNewNodeFilter(
-        final String componentId,
-        final String componentInstanceId,
-        final NodeFilterConstraintType nodeFilterConstraintType,
-        final CINodeFilterDataDefinition nodeFilterDataDefinition,
-        final RequirementNodeFilterPropertyDataDefinition requirementNodeFilterPropertyDataDefinition,
-        final String capabilityName) {
-
+    private Either<CINodeFilterDataDefinition, StorageOperationStatus> addNewNodeFilter(final String componentId, final String componentInstanceId,
+                                                                                        final NodeFilterConstraintType nodeFilterConstraintType,
+                                                                                        final CINodeFilterDataDefinition nodeFilterDataDefinition,
+                                                                                        final RequirementNodeFilterPropertyDataDefinition requirementNodeFilterPropertyDataDefinition,
+                                                                                        final String capabilityName) {
         if (NodeFilterConstraintType.PROPERTIES.equals(nodeFilterConstraintType)) {
-            return nodeFilterOperation.addNewProperty(componentId, componentInstanceId, nodeFilterDataDefinition,
-                requirementNodeFilterPropertyDataDefinition);
+            return nodeFilterOperation
+                .addNewProperty(componentId, componentInstanceId, nodeFilterDataDefinition, requirementNodeFilterPropertyDataDefinition);
         }
-        final RequirementNodeFilterCapabilityDataDefinition requirementNodeFilterCapabilityDataDefinition =
-            new RequirementNodeFilterCapabilityDataDefinition();
+        final RequirementNodeFilterCapabilityDataDefinition requirementNodeFilterCapabilityDataDefinition = new RequirementNodeFilterCapabilityDataDefinition();
         requirementNodeFilterCapabilityDataDefinition.setName(capabilityName);
-        final ListDataDefinition<RequirementNodeFilterPropertyDataDefinition>
-            propertyDataDefinitionListDataDefinition = new ListDataDefinition<>();
-        propertyDataDefinitionListDataDefinition.getListToscaDataDefinition().addAll(
-            Collections.singleton(requirementNodeFilterPropertyDataDefinition));
+        final ListDataDefinition<RequirementNodeFilterPropertyDataDefinition> propertyDataDefinitionListDataDefinition = new ListDataDefinition<>();
+        propertyDataDefinitionListDataDefinition.getListToscaDataDefinition()
+            .addAll(Collections.singleton(requirementNodeFilterPropertyDataDefinition));
         requirementNodeFilterCapabilityDataDefinition.setProperties(propertyDataDefinitionListDataDefinition);
-        return nodeFilterOperation.addNewCapabilities(componentId, componentInstanceId, nodeFilterDataDefinition,
-            requirementNodeFilterCapabilityDataDefinition);
+        return nodeFilterOperation
+            .addNewCapabilities(componentId, componentInstanceId, nodeFilterDataDefinition, requirementNodeFilterCapabilityDataDefinition);
     }
 
-
-    private void unlockComponent(final String componentUniqueId,
-                                 final ComponentTypeEnum componentType) {
+    private void unlockComponent(final String componentUniqueId, final ComponentTypeEnum componentType) {
         graphLockOperation.unlockComponent(componentUniqueId, componentType.getNodeType());
     }
 
@@ -304,29 +256,23 @@ public class ComponentNodeFilterBusinessLogic extends BaseBusinessLogic {
         return user;
     }
 
-    private Optional<ComponentInstance> getComponentInstance(final String componentInstanceId,
-                                                             final Component component) {
+    private Optional<ComponentInstance> getComponentInstance(final String componentInstanceId, final Component component) {
         return component.getComponentInstanceById(componentInstanceId);
     }
 
-    private Optional<CINodeFilterDataDefinition> getCiNodeFilterDataDefinition(
-        final Optional<ComponentInstance> componentInstance) {
-
+    private Optional<CINodeFilterDataDefinition> getCiNodeFilterDataDefinition(final Optional<ComponentInstance> componentInstance) {
         if (componentInstance.isPresent()) {
             return Optional.ofNullable(componentInstance.get().getNodeFilter());
         }
         return Optional.empty();
     }
 
-    private Optional<CINodeFilterDataDefinition> getCiNodeFilterDataDefinition(final String componentInstanceId,
-                                                                               final Component component)
+    private Optional<CINodeFilterDataDefinition> getCiNodeFilterDataDefinition(final String componentInstanceId, final Component component)
         throws BusinessLogicException {
-
-        final Either<Boolean, ResponseFormat> response = nodeFilterValidator
-            .validateComponentInstanceExist(component, componentInstanceId);
+        final Either<Boolean, ResponseFormat> response = nodeFilterValidator.validateComponentInstanceExist(component, componentInstanceId);
         if (response.isRight()) {
-            throw new BusinessLogicException(componentsUtils
-                .getResponseFormat(ActionStatus.NODE_FILTER_NOT_FOUND, response.right().value().getFormattedMessage()));
+            throw new BusinessLogicException(
+                componentsUtils.getResponseFormat(ActionStatus.NODE_FILTER_NOT_FOUND, response.right().value().getFormattedMessage()));
         }
         final Optional<ComponentInstance> componentInstance = getComponentInstance(componentInstanceId, component);
         if (componentInstance.isPresent()) {
@@ -336,55 +282,40 @@ public class ComponentNodeFilterBusinessLogic extends BaseBusinessLogic {
     }
 
     private CINodeFilterDataDefinition validateAndReturnNodeFilterDefinition(final String componentInstanceId,
-                                                                             final NodeFilterConstraintAction action,
-                                                                             final String constraint,
+                                                                             final NodeFilterConstraintAction action, final String constraint,
                                                                              final Component component,
                                                                              final NodeFilterConstraintType nodeFilterConstraintType)
         throws BusinessLogicException {
-
         validateNodeFilter(component, componentInstanceId, action, constraint, nodeFilterConstraintType);
-        final Optional<CINodeFilterDataDefinition> cINodeFilterDataDefinition = getCiNodeFilterDataDefinition(
-            componentInstanceId, component);
+        final Optional<CINodeFilterDataDefinition> cINodeFilterDataDefinition = getCiNodeFilterDataDefinition(componentInstanceId, component);
         if (!cINodeFilterDataDefinition.isPresent()) {
             throw new BusinessLogicException(componentsUtils.getResponseFormat(ActionStatus.NODE_FILTER_NOT_FOUND));
         }
         return cINodeFilterDataDefinition.get();
     }
 
-    private void validateNodeFilter(final Component component,
-                                    final String componentInstanceId,
-                                    final NodeFilterConstraintAction action,
-                                    final String constraint,
-                                    final NodeFilterConstraintType nodeFilterConstraintType) throws BusinessLogicException {
+    private void validateNodeFilter(final Component component, final String componentInstanceId, final NodeFilterConstraintAction action,
+                                    final String constraint, final NodeFilterConstraintType nodeFilterConstraintType) throws BusinessLogicException {
         final Either<Boolean, ResponseFormat> response = nodeFilterValidator
             .validateFilter(component, componentInstanceId, Collections.singletonList(constraint), action, nodeFilterConstraintType);
         if (response.isRight()) {
-            throw new BusinessLogicException(componentsUtils
-                .getResponseFormat(ActionStatus.NODE_FILTER_NOT_FOUND, response.right().value().getFormattedMessage()));
+            throw new BusinessLogicException(
+                componentsUtils.getResponseFormat(ActionStatus.NODE_FILTER_NOT_FOUND, response.right().value().getFormattedMessage()));
         }
     }
 
-    public Optional<CINodeFilterDataDefinition> updateNodeFilter(final String componentId,
-                                                                 final String componentInstanceId,
-                                                                 final UIConstraint uiConstraint,
-                                                                 final ComponentTypeEnum componentTypeEnum,
-                                                                 final NodeFilterConstraintType nodeFilterConstraintType,
-                                                                 final int index)
+    public Optional<CINodeFilterDataDefinition> updateNodeFilter(final String componentId, final String componentInstanceId,
+                                                                 final UIConstraint uiConstraint, final ComponentTypeEnum componentTypeEnum,
+                                                                 final NodeFilterConstraintType nodeFilterConstraintType, final int index)
         throws BusinessLogicException {
-
-        final Optional<CINodeFilterDataDefinition> deleteActionResponse = deleteNodeFilter(componentId,
-            componentInstanceId,
-            NodeFilterConstraintAction.DELETE, null, index, true, componentTypeEnum,
-            nodeFilterConstraintType);
-
+        final Optional<CINodeFilterDataDefinition> deleteActionResponse = deleteNodeFilter(componentId, componentInstanceId,
+            NodeFilterConstraintAction.DELETE, null, index, true, componentTypeEnum, nodeFilterConstraintType);
         if (!deleteActionResponse.isPresent()) {
-            throw new BusinessLogicException(componentsUtils
-                .getResponseFormat(ActionStatus.GENERAL_ERROR, "Failed to delete node filter capabilities"));
+            throw new BusinessLogicException(
+                componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR, "Failed to delete node filter capabilities"));
         }
-
-        return addNodeFilter(componentId.toLowerCase(), componentInstanceId, NodeFilterConstraintAction.ADD,
-            uiConstraint.getServicePropertyName(), new ConstraintConvertor().convert(uiConstraint), true,
-            componentTypeEnum, nodeFilterConstraintType,
+        return addNodeFilter(componentId.toLowerCase(), componentInstanceId, NodeFilterConstraintAction.ADD, uiConstraint.getServicePropertyName(),
+            new ConstraintConvertor().convert(uiConstraint), true, componentTypeEnum, nodeFilterConstraintType,
             StringUtils.isEmpty(uiConstraint.getCapabilityName()) ? "" : uiConstraint.getCapabilityName());
     }
 }
index 0f55ddf..c887463 100644 (file)
@@ -16,7 +16,6 @@
  *  SPDX-License-Identifier: Apache-2.0
  *  ============LICENSE_END=========================================================
  */
-
 package org.openecomp.sdc.be.components.impl;
 
 import static org.openecomp.sdc.be.dao.api.ActionStatus.SUBSTITUTION_FILTER_NOT_FOUND;
@@ -55,31 +54,26 @@ import org.springframework.beans.factory.annotation.Autowired;
 public class ComponentSubstitutionFilterBusinessLogic extends BaseBusinessLogic {
 
     private static final Logger LOGGER = Logger.getLogger(ComponentSubstitutionFilterBusinessLogic.class);
-
     private final SubstitutionFilterOperation substitutionFilterOperation;
     private final NodeFilterValidator nodeFilterValidator;
 
     @Autowired
-    public ComponentSubstitutionFilterBusinessLogic(final IElementOperation elementDao,
-                                                    final IGroupOperation groupOperation,
+    public ComponentSubstitutionFilterBusinessLogic(final IElementOperation elementDao, final IGroupOperation groupOperation,
                                                     final IGroupInstanceOperation groupInstanceOperation,
-                                                    final IGroupTypeOperation groupTypeOperation,
-                                                    final InterfaceOperation interfaceOperation,
+                                                    final IGroupTypeOperation groupTypeOperation, final InterfaceOperation interfaceOperation,
                                                     final InterfaceLifecycleOperation interfaceLifecycleTypeOperation,
                                                     final ArtifactsOperations artifactToscaOperation,
                                                     final SubstitutionFilterOperation substitutionFilterOperation,
                                                     final NodeFilterValidator nodeFilterValidator) {
-        super(elementDao, groupOperation, groupInstanceOperation, groupTypeOperation, interfaceOperation,
-            interfaceLifecycleTypeOperation, artifactToscaOperation);
+        super(elementDao, groupOperation, groupInstanceOperation, groupTypeOperation, interfaceOperation, interfaceLifecycleTypeOperation,
+            artifactToscaOperation);
         this.substitutionFilterOperation = substitutionFilterOperation;
         this.nodeFilterValidator = nodeFilterValidator;
     }
 
-    public Optional<SubstitutionFilterDataDefinition> createSubstitutionFilterIfNotExist(final String componentId,
-                                                                                         final boolean shouldLock,
+    public Optional<SubstitutionFilterDataDefinition> createSubstitutionFilterIfNotExist(final String componentId, final boolean shouldLock,
                                                                                          final ComponentTypeEnum componentTypeEnum)
-            throws BusinessLogicException {
-
+        throws BusinessLogicException {
         final Component component = getComponent(componentId);
         Optional<SubstitutionFilterDataDefinition> substitutionFilterDataDefinition = Optional.ofNullable(component.getSubstitutionFilter());
         if (substitutionFilterDataDefinition.isPresent()) {
@@ -92,13 +86,12 @@ public class ComponentSubstitutionFilterBusinessLogic extends BaseBusinessLogic
                 wasLocked = true;
             }
             final Either<SubstitutionFilterDataDefinition, StorageOperationStatus> result = substitutionFilterOperation
-                    .createSubstitutionFilter(componentId);
+                .createSubstitutionFilter(componentId);
             if (result.isRight()) {
                 janusGraphDao.rollback();
-                LOGGER.error(BUSINESS_PROCESS_ERROR,
-                        "Failed to Create Substitution filter on component with id {}", componentId);
-                throw new BusinessLogicException(componentsUtils.getResponseFormatByResource(componentsUtils
-                        .convertFromStorageResponse(result.right().value()), component.getSystemName()));
+                LOGGER.error(BUSINESS_PROCESS_ERROR, "Failed to Create Substitution filter on component with id {}", componentId);
+                throw new BusinessLogicException(componentsUtils
+                    .getResponseFormatByResource(componentsUtils.convertFromStorageResponse(result.right().value()), component.getSystemName()));
             }
             substitutionFilterDataDefinition = Optional.ofNullable(result.left().value());
             component.setSubstitutionFilter(substitutionFilterDataDefinition.get());
@@ -106,87 +99,69 @@ public class ComponentSubstitutionFilterBusinessLogic extends BaseBusinessLogic
             LOGGER.debug("Substitution filter successfully created in component {} . ", component.getSystemName());
         } catch (final Exception e) {
             janusGraphDao.rollback();
-            LOGGER.error(BUSINESS_PROCESS_ERROR,
-                    "Exception occurred during add Component Substitution filter property values: {}", e.getMessage(), e);
+            LOGGER
+                .error(BUSINESS_PROCESS_ERROR, "Exception occurred during add Component Substitution filter property values: {}", e.getMessage(), e);
             throw new BusinessLogicException(componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR));
-
         } finally {
             if (wasLocked) {
                 unlockComponent(component.getUniqueId(), componentTypeEnum);
             }
         }
-
         return substitutionFilterDataDefinition;
     }
 
-    public Optional<SubstitutionFilterDataDefinition> addSubstitutionFilter(final String componentId,
-                                                                            final String propertyName,
-                                                                            final String constraint,
-                                                                            final boolean shouldLock,
-                                                                            final ComponentTypeEnum componentTypeEnum)
-        throws BusinessLogicException {
-
+    public Optional<SubstitutionFilterDataDefinition> addSubstitutionFilter(final String componentId, final String propertyName,
+                                                                            final String constraint, final boolean shouldLock,
+                                                                            final ComponentTypeEnum componentTypeEnum) throws BusinessLogicException {
         final Component component = getComponent(componentId);
-
         final Either<Boolean, ResponseFormat> response = nodeFilterValidator
-                .validateComponentFilter(component, Collections.singletonList(constraint), NodeFilterConstraintAction.ADD);
+            .validateComponentFilter(component, Collections.singletonList(constraint), NodeFilterConstraintAction.ADD);
         if (response.isRight()) {
-            throw new BusinessLogicException(componentsUtils
-                    .getResponseFormat(ActionStatus.SUBSTITUTION_FILTER_NOT_FOUND, response.right().value().getFormattedMessage()));
+            throw new BusinessLogicException(
+                componentsUtils.getResponseFormat(ActionStatus.SUBSTITUTION_FILTER_NOT_FOUND, response.right().value().getFormattedMessage()));
         }
-
         boolean wasLocked = false;
         try {
             if (shouldLock) {
                 lockComponent(component.getUniqueId(), component, "Add Substitution Filter on Component");
                 wasLocked = true;
             }
-            final RequirementSubstitutionFilterPropertyDataDefinition newProperty =
-                new RequirementSubstitutionFilterPropertyDataDefinition();
+            final RequirementSubstitutionFilterPropertyDataDefinition newProperty = new RequirementSubstitutionFilterPropertyDataDefinition();
             newProperty.setName(propertyName);
             newProperty.setConstraints(Collections.singletonList(constraint));
-            final Either<SubstitutionFilterDataDefinition, StorageOperationStatus> resultEither =
-                substitutionFilterOperation
-                    .addPropertyFilter(componentId, component.getSubstitutionFilter(), newProperty);
-
+            final Either<SubstitutionFilterDataDefinition, StorageOperationStatus> resultEither = substitutionFilterOperation
+                .addPropertyFilter(componentId, component.getSubstitutionFilter(), newProperty);
             if (resultEither.isRight()) {
                 janusGraphDao.rollback();
-                throw new BusinessLogicException(componentsUtils.getResponseFormatByResource(componentsUtils
-                    .convertFromStorageResponse(resultEither.right().value()), component.getSystemName()));
+                throw new BusinessLogicException(componentsUtils
+                    .getResponseFormatByResource(componentsUtils.convertFromStorageResponse(resultEither.right().value()),
+                        component.getSystemName()));
             }
-
             janusGraphDao.commit();
             LOGGER.debug("Substitution filter successfully created in component {} . ", component.getSystemName());
             return Optional.ofNullable(resultEither.left().value());
         } catch (final Exception e) {
             janusGraphDao.rollback();
-            LOGGER.error(BUSINESS_PROCESS_ERROR,
-                "Exception occurred during add component substitution filter property values: {}", e.getMessage(), e);
+            LOGGER
+                .error(BUSINESS_PROCESS_ERROR, "Exception occurred during add component substitution filter property values: {}", e.getMessage(), e);
             throw new BusinessLogicException(componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR));
-
         } finally {
             if (wasLocked) {
                 unlockComponent(component.getUniqueId(), componentTypeEnum);
             }
         }
-
     }
 
-    public Optional<SubstitutionFilterDataDefinition> updateSubstitutionFilter(final String componentId,
-                                                                               final List<String> constraints,
-                                                                               final boolean shouldLock,
-                                                                               final ComponentTypeEnum componentTypeEnum)
+    public Optional<SubstitutionFilterDataDefinition> updateSubstitutionFilter(final String componentId, final List<String> constraints,
+                                                                               final boolean shouldLock, final ComponentTypeEnum componentTypeEnum)
         throws BusinessLogicException {
-
         final Component component = getComponent(componentId);
-
         final Either<Boolean, ResponseFormat> response = nodeFilterValidator
-                .validateComponentFilter(component, constraints, NodeFilterConstraintAction.UPDATE);
+            .validateComponentFilter(component, constraints, NodeFilterConstraintAction.UPDATE);
         if (response.isRight()) {
-            throw new BusinessLogicException(componentsUtils
-                    .getResponseFormat(ActionStatus.SUBSTITUTION_FILTER_NOT_FOUND, response.right().value().getFormattedMessage()));
+            throw new BusinessLogicException(
+                componentsUtils.getResponseFormat(ActionStatus.SUBSTITUTION_FILTER_NOT_FOUND, response.right().value().getFormattedMessage()));
         }
-
         SubstitutionFilterDataDefinition substitutionFilterDataDefinition = component.getSubstitutionFilter();
         if (substitutionFilterDataDefinition == null) {
             throw new BusinessLogicException(componentsUtils.getResponseFormat(SUBSTITUTION_FILTER_NOT_FOUND));
@@ -198,26 +173,23 @@ public class ComponentSubstitutionFilterBusinessLogic extends BaseBusinessLogic
                 wasLocked = true;
             }
             final List<RequirementSubstitutionFilterPropertyDataDefinition> properties = constraints.stream()
-                    .map(this::getRequirementSubstitutionFilterPropertyDataDefinition).collect(Collectors.toList());
+                .map(this::getRequirementSubstitutionFilterPropertyDataDefinition).collect(Collectors.toList());
             final Either<SubstitutionFilterDataDefinition, StorageOperationStatus> result = substitutionFilterOperation
-                    .updateProperties(componentId, substitutionFilterDataDefinition, properties);
-
+                .updateProperties(componentId, substitutionFilterDataDefinition, properties);
             if (result.isRight()) {
                 janusGraphDao.rollback();
-                throw new BusinessLogicException(componentsUtils.getResponseFormatByResource(componentsUtils
-                    .convertFromStorageResponse(result.right().value()), component.getSystemName()));
+                throw new BusinessLogicException(componentsUtils
+                    .getResponseFormatByResource(componentsUtils.convertFromStorageResponse(result.right().value()), component.getSystemName()));
             } else {
                 substitutionFilterDataDefinition = result.left().value();
             }
             janusGraphDao.commit();
             LOGGER.debug("Substitution filter successfully updated in component {} . ", component.getSystemName());
-
         } catch (final Exception e) {
             janusGraphDao.rollback();
             LOGGER.error(BUSINESS_PROCESS_ERROR, this.getClass().getName(),
                 "Exception occurred during update component substitution filter property values: {}", e);
             throw new BusinessLogicException(componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR));
-
         } finally {
             if (wasLocked) {
                 unlockComponent(component.getUniqueId(), componentTypeEnum);
@@ -226,39 +198,33 @@ public class ComponentSubstitutionFilterBusinessLogic extends BaseBusinessLogic
         return Optional.ofNullable(substitutionFilterDataDefinition);
     }
 
-    public Optional<SubstitutionFilterDataDefinition> deleteSubstitutionFilter(final String componentId,
-                                                                               final int position,
-                                                                               final boolean shouldLock,
+    public Optional<SubstitutionFilterDataDefinition> deleteSubstitutionFilter(final String componentId, final int position, final boolean shouldLock,
                                                                                final ComponentTypeEnum componentTypeEnum)
         throws BusinessLogicException {
-
         final Component component = getComponent(componentId);
         SubstitutionFilterDataDefinition substitutionFilterDataDefinition = component.getSubstitutionFilter();
         boolean wasLocked = false;
         try {
             if (shouldLock) {
-                lockComponent(component.getUniqueId(), component,"Delete substitution Filter on Component");
+                lockComponent(component.getUniqueId(), component, "Delete substitution Filter on Component");
                 wasLocked = true;
             }
             final Either<SubstitutionFilterDataDefinition, StorageOperationStatus> result = substitutionFilterOperation
                 .deleteConstraint(componentId, substitutionFilterDataDefinition, position);
             if (result.isRight()) {
                 janusGraphDao.rollback();
-                throw new BusinessLogicException(componentsUtils.getResponseFormatByResource(componentsUtils
-                    .convertFromStorageResponse(result.right().value()), component.getSystemName()));
+                throw new BusinessLogicException(componentsUtils
+                    .getResponseFormatByResource(componentsUtils.convertFromStorageResponse(result.right().value()), component.getSystemName()));
             } else {
                 substitutionFilterDataDefinition = result.left().value();
             }
             janusGraphDao.commit();
             LOGGER.debug("Substitution filter successfully deleted in component {} . ", component.getSystemName());
-
         } catch (final Exception e) {
             janusGraphDao.rollback();
-            LOGGER.error(BUSINESS_PROCESS_ERROR,
-                "Exception occurred during delete component substitution filter property values: {}",
-                e.getMessage(), e);
+            LOGGER.error(BUSINESS_PROCESS_ERROR, "Exception occurred during delete component substitution filter property values: {}", e.getMessage(),
+                e);
             throw new BusinessLogicException(componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR));
-
         } finally {
             if (wasLocked) {
                 unlockComponent(component.getUniqueId(), componentTypeEnum);
@@ -267,8 +233,7 @@ public class ComponentSubstitutionFilterBusinessLogic extends BaseBusinessLogic
         return Optional.ofNullable(substitutionFilterDataDefinition);
     }
 
-    private void unlockComponent(final String componentUniqueId,
-                                 final ComponentTypeEnum componentType) {
+    private void unlockComponent(final String componentUniqueId, final ComponentTypeEnum componentType) {
         graphLockOperation.unlockComponent(componentUniqueId, componentType.getNodeType());
     }
 
@@ -278,11 +243,8 @@ public class ComponentSubstitutionFilterBusinessLogic extends BaseBusinessLogic
         return user;
     }
 
-    private RequirementSubstitutionFilterPropertyDataDefinition getRequirementSubstitutionFilterPropertyDataDefinition(
-        final String constraint) {
-
-        final RequirementSubstitutionFilterPropertyDataDefinition requirementSubstitutionFilterPropertyDataDefinition =
-            new RequirementSubstitutionFilterPropertyDataDefinition();
+    private RequirementSubstitutionFilterPropertyDataDefinition getRequirementSubstitutionFilterPropertyDataDefinition(final String constraint) {
+        final RequirementSubstitutionFilterPropertyDataDefinition requirementSubstitutionFilterPropertyDataDefinition = new RequirementSubstitutionFilterPropertyDataDefinition();
         requirementSubstitutionFilterPropertyDataDefinition.setConstraints(Arrays.asList(constraint));
         return requirementSubstitutionFilterPropertyDataDefinition;
     }
index 20e796e..645eb96 100644 (file)
@@ -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.
  * Modifications copyright (c) 2019 Nokia
  * ================================================================================
  */
-
 package org.openecomp.sdc.be.components.impl;
 
+import java.security.SecureRandom;
+import java.util.ArrayList;
+import java.util.Collection;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+import java.util.Map.Entry;
+import java.util.Optional;
+import java.util.Set;
+import java.util.stream.Collectors;
 import org.apache.commons.lang3.StringUtils;
 import org.apache.commons.lang3.tuple.ImmutablePair;
 import org.openecomp.sdc.be.datatypes.enums.ComponentTypeEnum;
@@ -34,26 +43,14 @@ import org.openecomp.sdc.common.log.wrappers.Logger;
 import org.springframework.beans.factory.annotation.Autowired;
 import org.springframework.stereotype.Component;
 
-import java.security.SecureRandom;
-import java.util.ArrayList;
-import java.util.Collection;
-import java.util.HashMap;
-import java.util.List;
-import java.util.Map;
-import java.util.Map.Entry;
-import java.util.Optional;
-import java.util.Set;
-import java.util.stream.Collectors;
-
 /**
  * This class holds the logic of arranging resource instance on the canvas for imported VF
- * 
- * @author mshitrit
  *
+ * @author mshitrit
  */
 @Component("compositionBusinessLogic")
 public class CompositionBusinessLogic {
-    private final ComponentInstanceBusinessLogic componentInstanceBusinessLogic;
+
     private static final Logger log = Logger.getLogger(CompositionBusinessLogic.class.getName());
     private static final int VFC_CANVAS_ELEMENT_SIZE = 50;
     private static final int CP_CANVAS_ELEMENT_SIZE = 21;
@@ -61,48 +58,48 @@ public class CompositionBusinessLogic {
     private static final int CANVAS_HEIGHT = 700;
     private static final int SPACE_BETWEEN_ELEMENTS = VFC_CANVAS_ELEMENT_SIZE * 4;
     private static final double CP_RADIUS_FACTOR = 0.4;
+    private final ComponentInstanceBusinessLogic componentInstanceBusinessLogic;
 
     @Autowired
     public CompositionBusinessLogic(ComponentInstanceBusinessLogic componentInstanceBusinessLogic) {
         this.componentInstanceBusinessLogic = componentInstanceBusinessLogic;
     }
 
-    enum RelativePosition {
-        LEFT, RIGHT, UP, DOWN
-    };
-
     protected void setPositionsForComponentInstances(Resource resource, String userId) {
-        boolean isNotAllPositionsCalculated = resource.getComponentInstances() == null
-                || resource.getComponentInstances().stream().anyMatch(p -> (p.getPosX() == null || p.getPosX().isEmpty()) || (p.getPosY() == null || p.getPosY().isEmpty()));
-        if (isNotAllPositionsCalculated &&  resource.getComponentInstances() != null) {
+        boolean isNotAllPositionsCalculated = resource.getComponentInstances() == null || resource.getComponentInstances().stream()
+            .anyMatch(p -> (p.getPosX() == null || p.getPosX().isEmpty()) || (p.getPosY() == null || p.getPosY().isEmpty()));
+        if (isNotAllPositionsCalculated && resource.getComponentInstances() != null) {
             // Arrange Icons In Spiral Pattern
-            Map<ImmutablePair<Double, Double>, ComponentInstance> componentInstanceLocations = buildSpiralPatternPositioningForComponentInstances(resource);
+            Map<ImmutablePair<Double, Double>, ComponentInstance> componentInstanceLocations = buildSpiralPatternPositioningForComponentInstances(
+                resource);
             // Set Relative Locations According to Canvas Size
             componentInstanceLocations.entrySet().forEach(this::setRelativePosition);
             // Update in DB
-            componentInstanceBusinessLogic.updateComponentInstance(ComponentTypeEnum.RESOURCE_PARAM_NAME,resource, resource.getUniqueId(),
-                    userId, resource.getComponentInstances(), false);
+            componentInstanceBusinessLogic.updateComponentInstance(ComponentTypeEnum.RESOURCE_PARAM_NAME, resource, resource.getUniqueId(), userId,
+                resource.getComponentInstances(), false);
         }
     }
-       
+
+    ;
+
     protected void setPositionsForComponentInstances(Service service, String userId) {
-        boolean isNotAllPositionsCalculated = service.getComponentInstances() == null
-                                                      || service.getComponentInstances().stream().anyMatch(p -> (p.getPosX() == null || p.getPosX().isEmpty()) || (p.getPosY() == null || p.getPosY().isEmpty()));
-        if (isNotAllPositionsCalculated &&  service.getComponentInstances() != null) {
+        boolean isNotAllPositionsCalculated = service.getComponentInstances() == null || service.getComponentInstances().stream()
+            .anyMatch(p -> (p.getPosX() == null || p.getPosX().isEmpty()) || (p.getPosY() == null || p.getPosY().isEmpty()));
+        if (isNotAllPositionsCalculated && service.getComponentInstances() != null) {
             // Arrange Icons In Spiral Pattern
-            Map<ImmutablePair<Double, Double>, ComponentInstance> componentInstanceLocations = buildSpiralPatternPositioningForComponentInstances(service);
+            Map<ImmutablePair<Double, Double>, ComponentInstance> componentInstanceLocations = buildSpiralPatternPositioningForComponentInstances(
+                service);
             // Set Relative Locations According to Canvas Size
             componentInstanceLocations.entrySet().forEach(this::setRelativePosition);
             // Update in DB
-            componentInstanceBusinessLogic.updateComponentInstance(ComponentTypeEnum.SERVICE_PARAM_NAME, service, service.getUniqueId(),
-                    userId, service.getComponentInstances(), false);
+            componentInstanceBusinessLogic.updateComponentInstance(ComponentTypeEnum.SERVICE_PARAM_NAME, service, service.getUniqueId(), userId,
+                service.getComponentInstances(), false);
         }
     }
 
     private void setRelativePosition(Entry<ImmutablePair<Double, Double>, ComponentInstance> entry) {
         int xCenter = CANVAS_WIDTH / 2;
         int yCenter = CANVAS_HEIGHT / 2;
-
         ImmutablePair<Double, Double> matrixPosition = entry.getKey();
         ComponentInstance componentInstance = entry.getValue();
         componentInstance.setPosX(calculateCompositionPosition(xCenter, matrixPosition.getLeft(), componentInstance));
@@ -113,67 +110,59 @@ public class CompositionBusinessLogic {
         final double topLeftCanvasPosition = center + relativePosition * CompositionBusinessLogic.SPACE_BETWEEN_ELEMENTS;
         double offsetedCanvasPosition;
         switch (componentInstance.getOriginType()) {
-        case CP:
-            offsetedCanvasPosition = topLeftCanvasPosition - CompositionBusinessLogic.CP_CANVAS_ELEMENT_SIZE / 2.0;
-            break;
-        case VL:
-            offsetedCanvasPosition = topLeftCanvasPosition - CompositionBusinessLogic.CP_CANVAS_ELEMENT_SIZE / 2.0;
-            break;
-        case VF:
-            offsetedCanvasPosition = topLeftCanvasPosition - CompositionBusinessLogic.VFC_CANVAS_ELEMENT_SIZE / 2.0;
-            break;
-        case VFC:
-            offsetedCanvasPosition = topLeftCanvasPosition - CompositionBusinessLogic.VFC_CANVAS_ELEMENT_SIZE / 2.0;
-            break;
-        case VFCMT:
-            offsetedCanvasPosition = topLeftCanvasPosition - CompositionBusinessLogic.VFC_CANVAS_ELEMENT_SIZE / 2.0;
-            break;
-        default:
-            offsetedCanvasPosition = topLeftCanvasPosition - CompositionBusinessLogic.VFC_CANVAS_ELEMENT_SIZE / 2.0;
-            break;
+            case CP:
+                offsetedCanvasPosition = topLeftCanvasPosition - CompositionBusinessLogic.CP_CANVAS_ELEMENT_SIZE / 2.0;
+                break;
+            case VL:
+                offsetedCanvasPosition = topLeftCanvasPosition - CompositionBusinessLogic.CP_CANVAS_ELEMENT_SIZE / 2.0;
+                break;
+            case VF:
+                offsetedCanvasPosition = topLeftCanvasPosition - CompositionBusinessLogic.VFC_CANVAS_ELEMENT_SIZE / 2.0;
+                break;
+            case VFC:
+                offsetedCanvasPosition = topLeftCanvasPosition - CompositionBusinessLogic.VFC_CANVAS_ELEMENT_SIZE / 2.0;
+                break;
+            case VFCMT:
+                offsetedCanvasPosition = topLeftCanvasPosition - CompositionBusinessLogic.VFC_CANVAS_ELEMENT_SIZE / 2.0;
+                break;
+            default:
+                offsetedCanvasPosition = topLeftCanvasPosition - CompositionBusinessLogic.VFC_CANVAS_ELEMENT_SIZE / 2.0;
+                break;
         }
         return String.valueOf(offsetedCanvasPosition);
     }
 
     protected Map<ImmutablePair<Double, Double>, ComponentInstance> buildSpiralPatternPositioningForComponentInstances(
-            org.openecomp.sdc.be.model.Component component) {
-
+        org.openecomp.sdc.be.model.Component component) {
         Map<ImmutablePair<Double, Double>, ComponentInstance> componentInstanceLocations = new HashMap<>();
-
         List<ComponentInstance> componentInstances = new ArrayList<>();
-        if (component instanceof Resource){
+        if (component instanceof Resource) {
             Resource resource = (Resource) component;
             List<ComponentInstance> componentInstanceList = resource.getComponentInstances();
             componentInstances.addAll(componentInstanceList);
-        }else if (component instanceof Service){
+        } else if (component instanceof Service) {
             Service service = (Service) component;
             List<ComponentInstance> componentInstanceList = service.getComponentInstances();
             componentInstances.addAll(componentInstanceList);
         }
-
         Map<ComponentInstance, List<ComponentInstance>> connectededCps = getCpsConnectedToVFC(componentInstances, component);
         // Remove all cp that are connected from the list
         componentInstances.removeAll(connectededCps.values().stream().flatMap(Collection::stream).collect(Collectors.toList()));
-
         buildSpiralPatternForMajorComponents(componentInstanceLocations, componentInstances);
         buildCirclePatternForCps(componentInstanceLocations, connectededCps);
-
         return componentInstanceLocations;
     }
 
-    protected void buildCirclePatternForCps(Map<ImmutablePair<Double, Double>, ComponentInstance> componentInstLocations, Map<ComponentInstance, List<ComponentInstance>> connectedCps) {
-
+    protected void buildCirclePatternForCps(Map<ImmutablePair<Double, Double>, ComponentInstance> componentInstLocations,
+                                            Map<ComponentInstance, List<ComponentInstance>> connectedCps) {
         for (Entry<ComponentInstance, List<ComponentInstance>> vfcCpList : connectedCps.entrySet()) {
-            componentInstLocations.entrySet().stream()
-                .filter(p -> p.getValue().getUniqueId().equals(vfcCpList.getKey().getUniqueId()))
-                .findAny()
-                .ifPresent(vfcOfTheCps ->
-                    buildCirclePatternForOneGroupOfCps(vfcOfTheCps.getKey(), vfcCpList.getValue(),
-                        componentInstLocations));
+            componentInstLocations.entrySet().stream().filter(p -> p.getValue().getUniqueId().equals(vfcCpList.getKey().getUniqueId())).findAny()
+                .ifPresent(vfcOfTheCps -> buildCirclePatternForOneGroupOfCps(vfcOfTheCps.getKey(), vfcCpList.getValue(), componentInstLocations));
         }
     }
 
-    private void buildCirclePatternForOneGroupOfCps(ImmutablePair<Double, Double> vfcLocation, List<ComponentInstance> cpsGroup, Map<ImmutablePair<Double, Double>, ComponentInstance> componentInstLocations) {
+    private void buildCirclePatternForOneGroupOfCps(ImmutablePair<Double, Double> vfcLocation, List<ComponentInstance> cpsGroup,
+                                                    Map<ImmutablePair<Double, Double>, ComponentInstance> componentInstLocations) {
         final int numberOfCps = cpsGroup.size();
         double angleBetweenCps = (!cpsGroup.isEmpty()) ? Math.toRadians(360) / numberOfCps : 0;
         double currentAngle = 0;
@@ -185,10 +174,10 @@ public class CompositionBusinessLogic {
             componentInstLocations.put(new ImmutablePair<>(cpXposition, cpYposition), currCp);
             currentAngle += angleBetweenCps;
         }
-
     }
 
-    private void buildSpiralPatternForMajorComponents(Map<ImmutablePair<Double, Double>, ComponentInstance> componentInstanceLocations, List<ComponentInstance> componentInstances) {
+    private void buildSpiralPatternForMajorComponents(Map<ImmutablePair<Double, Double>, ComponentInstance> componentInstanceLocations,
+                                                      List<ComponentInstance> componentInstances) {
         int elementsCounter = 0;
         ImmutablePair<Double, Double> currPlacement;
         ImmutablePair<Double, Double> prevPlacement = null;
@@ -203,30 +192,29 @@ public class CompositionBusinessLogic {
             } else {
                 relationToPrevElement = getRelativePositionForCurrentElement(componentInstanceLocations, relationToPrevElement, prevPlacement);
                 currPlacement = getRelativeElementLocation(prevPlacement, relationToPrevElement);
-
             }
-
             componentInstanceLocations.put(currPlacement, curr);
             prevPlacement = currPlacement;
         }
     }
 
-    protected Map<ComponentInstance, List<ComponentInstance>> getCpsConnectedToVFC(List<ComponentInstance> allComponentInstances, org.openecomp.sdc.be.model.Component component) {
+    protected Map<ComponentInstance, List<ComponentInstance>> getCpsConnectedToVFC(List<ComponentInstance> allComponentInstances,
+                                                                                   org.openecomp.sdc.be.model.Component component) {
         Map<ComponentInstance, List<ComponentInstance>> vfcWithItsCps = new HashMap<>();
         List<RequirementCapabilityRelDef> allRelations = new ArrayList<>();
-        if (component instanceof Resource){
+        if (component instanceof Resource) {
             Resource vf = (Resource) component;
             allRelations = vf.getComponentInstancesRelations();
-        }else if (component instanceof Service){
+        } else if (component instanceof Service) {
             Service sv = (Service) component;
             allRelations = sv.getComponentInstancesRelations();
         }
-
         for (ComponentInstance curr : allComponentInstances) {
             // Filters Only CPs
             if (curr.getOriginType() == OriginTypeEnum.CP) {
                 // List Of elements the CP is connected to
-                List<RequirementCapabilityRelDef> connectedToList = allRelations.stream().filter(p -> p.getFromNode().equals(curr.getUniqueId()) || p.getToNode().equals(curr.getUniqueId())).collect(Collectors.toList());
+                List<RequirementCapabilityRelDef> connectedToList = allRelations.stream()
+                    .filter(p -> p.getFromNode().equals(curr.getUniqueId()) || p.getToNode().equals(curr.getUniqueId())).collect(Collectors.toList());
                 // Adds Only CPs Which are connected to VFC
                 filterCpConnectedToVFC(allComponentInstances, vfcWithItsCps, curr, connectedToList);
             }
@@ -234,18 +222,19 @@ public class CompositionBusinessLogic {
         return vfcWithItsCps;
     }
 
-    private void filterCpConnectedToVFC(List<ComponentInstance> allComponentInstances, Map<ComponentInstance, List<ComponentInstance>> vfcWithItsCps, ComponentInstance currCP, List<RequirementCapabilityRelDef> connectedToTheCPList) {
+    private void filterCpConnectedToVFC(List<ComponentInstance> allComponentInstances, Map<ComponentInstance, List<ComponentInstance>> vfcWithItsCps,
+                                        ComponentInstance currCP, List<RequirementCapabilityRelDef> connectedToTheCPList) {
         if (!connectedToTheCPList.isEmpty()) {
             // Set Of Ids Of components Instances which are connected certain CP
-            Set<String> mateIds = connectedToTheCPList.stream().map(cpRelation -> cpRelation.getFromNode().equals(currCP.getUniqueId()) ? cpRelation.getToNode() : cpRelation.getFromNode()).collect(Collectors.toSet());
-
+            Set<String> mateIds = connectedToTheCPList.stream()
+                .map(cpRelation -> cpRelation.getFromNode().equals(currCP.getUniqueId()) ? cpRelation.getToNode() : cpRelation.getFromNode())
+                .collect(Collectors.toSet());
             // Vfc Component instance Connected to the CP
             Optional<ComponentInstance> optionalVfcConnectedToCP = allComponentInstances.stream().
-            // All instances connected to CP
+                // All instances connected to CP
                     filter(p -> mateIds.contains(p.getUniqueId())).
-                    // Filter in only VFC connected to the CP
+                // Filter in only VFC connected to the CP
                     filter(p -> p.getOriginType() == OriginTypeEnum.VFC).findAny();
-
             if (optionalVfcConnectedToCP.isPresent()) {
                 final ComponentInstance vfcWithCps = optionalVfcConnectedToCP.get();
                 if (vfcWithItsCps.containsKey(vfcWithCps)) {
@@ -259,37 +248,39 @@ public class CompositionBusinessLogic {
         }
     }
 
-    private RelativePosition getRelativePositionForCurrentElement(Map<ImmutablePair<Double, Double>, ComponentInstance> componentInstanceLocations, RelativePosition relationToPrevElement, ImmutablePair<Double, Double> prevPlacement) {
+    private RelativePosition getRelativePositionForCurrentElement(Map<ImmutablePair<Double, Double>, ComponentInstance> componentInstanceLocations,
+                                                                  RelativePosition relationToPrevElement,
+                                                                  ImmutablePair<Double, Double> prevPlacement) {
         switch (relationToPrevElement) {
-        case LEFT: {
-            boolean isOccupied = isAdjacentElementOccupied(prevPlacement, RelativePosition.UP, componentInstanceLocations);
-            relationToPrevElement = isOccupied ? RelativePosition.LEFT : RelativePosition.UP;
-            break;
-        }
-        case RIGHT: {
-            boolean isOccupied = isAdjacentElementOccupied(prevPlacement, RelativePosition.DOWN, componentInstanceLocations);
-            relationToPrevElement = isOccupied ? RelativePosition.RIGHT : RelativePosition.DOWN;
-            break;
-        }
-        case UP: {
-            boolean isOccupied = isAdjacentElementOccupied(prevPlacement, RelativePosition.RIGHT, componentInstanceLocations);
-            relationToPrevElement = isOccupied ? RelativePosition.UP : RelativePosition.RIGHT;
-            break;
-        }
-        case DOWN: {
-            boolean isOccupied = isAdjacentElementOccupied(prevPlacement, RelativePosition.LEFT, componentInstanceLocations);
-            relationToPrevElement = isOccupied ? RelativePosition.DOWN : RelativePosition.LEFT;
-            break;
-        }
-        default: {
-            throw new UnsupportedOperationException();
-        }
+            case LEFT: {
+                boolean isOccupied = isAdjacentElementOccupied(prevPlacement, RelativePosition.UP, componentInstanceLocations);
+                relationToPrevElement = isOccupied ? RelativePosition.LEFT : RelativePosition.UP;
+                break;
+            }
+            case RIGHT: {
+                boolean isOccupied = isAdjacentElementOccupied(prevPlacement, RelativePosition.DOWN, componentInstanceLocations);
+                relationToPrevElement = isOccupied ? RelativePosition.RIGHT : RelativePosition.DOWN;
+                break;
+            }
+            case UP: {
+                boolean isOccupied = isAdjacentElementOccupied(prevPlacement, RelativePosition.RIGHT, componentInstanceLocations);
+                relationToPrevElement = isOccupied ? RelativePosition.UP : RelativePosition.RIGHT;
+                break;
+            }
+            case DOWN: {
+                boolean isOccupied = isAdjacentElementOccupied(prevPlacement, RelativePosition.LEFT, componentInstanceLocations);
+                relationToPrevElement = isOccupied ? RelativePosition.DOWN : RelativePosition.LEFT;
+                break;
+            }
+            default: {
+                throw new UnsupportedOperationException();
+            }
         }
         return relationToPrevElement;
     }
 
-    private boolean isAdjacentElementOccupied(ImmutablePair<Double, Double> currElement, RelativePosition adjacentElementRelationToCurrElement, Map<ImmutablePair<Double, Double>, ComponentInstance> allElements) {
-
+    private boolean isAdjacentElementOccupied(ImmutablePair<Double, Double> currElement, RelativePosition adjacentElementRelationToCurrElement,
+                                              Map<ImmutablePair<Double, Double>, ComponentInstance> allElements) {
         ImmutablePair<Double, Double> adjacentElementPosition = getRelativeElementLocation(currElement, adjacentElementRelationToCurrElement);
         return allElements.containsKey(adjacentElementPosition);
     }
@@ -297,42 +288,42 @@ public class CompositionBusinessLogic {
     private ImmutablePair<Double, Double> getRelativeElementLocation(ImmutablePair<Double, Double> currElement, RelativePosition relativeLocation) {
         ImmutablePair<Double, Double> relativeElementPosition;
         switch (relativeLocation) {
-
-        case LEFT: {
-            relativeElementPosition = new ImmutablePair<>(currElement.getLeft() - 1, currElement.getRight());
-            break;
-        }
-        case RIGHT: {
-            relativeElementPosition = new ImmutablePair<>(currElement.getLeft() + 1, currElement.getRight());
-            break;
-        }
-        case UP: {
-            relativeElementPosition = new ImmutablePair<>(currElement.getLeft(), currElement.getRight() + 1);
-            break;
-        }
-        case DOWN: {
-            relativeElementPosition = new ImmutablePair<>(currElement.getLeft(), currElement.getRight() - 1);
-            break;
-        }
-        default: {
-            throw new UnsupportedOperationException();
-        }
+            case LEFT: {
+                relativeElementPosition = new ImmutablePair<>(currElement.getLeft() - 1, currElement.getRight());
+                break;
+            }
+            case RIGHT: {
+                relativeElementPosition = new ImmutablePair<>(currElement.getLeft() + 1, currElement.getRight());
+                break;
+            }
+            case UP: {
+                relativeElementPosition = new ImmutablePair<>(currElement.getLeft(), currElement.getRight() + 1);
+                break;
+            }
+            case DOWN: {
+                relativeElementPosition = new ImmutablePair<>(currElement.getLeft(), currElement.getRight() - 1);
+                break;
+            }
+            default: {
+                throw new UnsupportedOperationException();
+            }
         }
         return relativeElementPosition;
     }
+
     protected void validateAndSetDefaultCoordinates(ComponentInstance resourceInstance) {
-        int xCenter =  CANVAS_WIDTH / 2;
+        int xCenter = CANVAS_WIDTH / 2;
         int yCenter = CANVAS_HEIGHT / 2;
         double leftLimit = -10D;
         double rightLimit = -1D;
         double generatedDouble = leftLimit + new SecureRandom().nextDouble() * (rightLimit - leftLimit);
-
-        if (StringUtils.isEmpty(resourceInstance.getPosX())|| StringUtils.isEmpty(resourceInstance.getPosY())){
+        if (StringUtils.isEmpty(resourceInstance.getPosX()) || StringUtils.isEmpty(resourceInstance.getPosY())) {
             resourceInstance.setPosX(calculateCompositionPosition(xCenter, generatedDouble, resourceInstance));
             resourceInstance.setPosY(calculateCompositionPosition(yCenter, generatedDouble, resourceInstance));
-            log.debug("Missing Failed PosX/PosY values. new values generated automatically. PosX = {} and PosY = {}", resourceInstance.getPosX(), resourceInstance.getPosY());
+            log.debug("Missing Failed PosX/PosY values. new values generated automatically. PosX = {} and PosY = {}", resourceInstance.getPosX(),
+                resourceInstance.getPosY());
         }
     }
 
-
+    enum RelativePosition {LEFT, RIGHT, UP, DOWN}
 }
index 8b4c1c3..4db24c1 100644 (file)
  * limitations under the License.
  * ============LICENSE_END=========================================================
  */
-
 package org.openecomp.sdc.be.components.impl;
 
 import fj.data.Either;
+import java.util.Date;
 import org.openecomp.sdc.be.components.impl.exceptions.ByActionStatusComponentException;
 import org.openecomp.sdc.be.config.BeEcompErrorManager;
 import org.openecomp.sdc.be.dao.api.ActionStatus;
@@ -45,8 +45,6 @@ import org.openecomp.sdc.exception.ResponseFormat;
 import org.springframework.beans.factory.annotation.Autowired;
 import org.springframework.stereotype.Component;
 
-import java.util.Date;
-
 @Component("ConsumerBusinessLogic")
 public class ConsumerBusinessLogic extends BaseBusinessLogic {
 
@@ -54,35 +52,26 @@ public class ConsumerBusinessLogic extends BaseBusinessLogic {
     private static final String CONSUMER_SALT = "Consumer salt";
     private static final String CONSUMER_PW = "Consumer password";
     private static final String AUDIT_BEFORE_SENDING_RESPONSE = "audit before sending response";
-
+    private static final Logger log = Logger.getLogger(ConsumerBusinessLogic.class.getName());
     @javax.annotation.Resource
     private ConsumerOperation consumerOperation;
 
-    private static final Logger log = Logger.getLogger(ConsumerBusinessLogic.class.getName());
-
     @Autowired
-    public ConsumerBusinessLogic(IElementOperation elementDao,
-                                 IGroupOperation groupOperation,
-                                 IGroupInstanceOperation groupInstanceOperation,
-                                 IGroupTypeOperation groupTypeOperation,
-                                 InterfaceOperation interfaceOperation,
-                                 InterfaceLifecycleOperation interfaceLifecycleTypeOperation,
-                                 ArtifactsOperations artifactToscaOperation) {
-        super(elementDao, groupOperation, groupInstanceOperation, groupTypeOperation,
-            interfaceOperation, interfaceLifecycleTypeOperation, artifactToscaOperation);
+    public ConsumerBusinessLogic(IElementOperation elementDao, IGroupOperation groupOperation, IGroupInstanceOperation groupInstanceOperation,
+                                 IGroupTypeOperation groupTypeOperation, InterfaceOperation interfaceOperation,
+                                 InterfaceLifecycleOperation interfaceLifecycleTypeOperation, ArtifactsOperations artifactToscaOperation) {
+        super(elementDao, groupOperation, groupInstanceOperation, groupTypeOperation, interfaceOperation, interfaceLifecycleTypeOperation,
+            artifactToscaOperation);
     }
 
     public Either<ConsumerDefinition, ResponseFormat> createConsumer(User user, ConsumerDefinition consumer) {
-
         Either<User, ResponseFormat> userValidation = validateUser(user, consumer, AuditingActionEnum.ADD_ECOMP_USER_CREDENTIALS);
-
         if (userValidation.isRight()) {
             return Either.right(userValidation.right().value());
         }
         checkFieldsForOverrideAttempt(consumer);
         user = userValidation.left().value();
         consumer.setLastModfierAtuid(user.getUserId());
-
         Either<ConsumerDefinition, ResponseFormat> consumerValidationResponse = validateConsumer(consumer);
         if (consumerValidationResponse.isRight()) {
             ResponseFormat responseFormat = consumerValidationResponse.right().value();
@@ -95,7 +84,6 @@ public class ConsumerBusinessLogic extends BaseBusinessLogic {
             BeEcompErrorManager.getInstance().logBeFailedLockObjectError("createConsumer", NodeTypeEnum.ConsumerCredentials.getName(), consumerName);
             log.debug("Failed to lock consumer: {} error - {}", consumerName, lockResult);
             ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR);
-
             componentsUtils.auditConsumerCredentialsEvent(AuditingActionEnum.ADD_ECOMP_USER_CREDENTIALS, consumer, responseFormat, user);
             return Either.right(responseFormat);
         }
@@ -104,15 +92,13 @@ public class ConsumerBusinessLogic extends BaseBusinessLogic {
             if (getResponse.isLeft() && getResponse.left().value() != null) {
                 return updateConsumer(consumer);
             }
-
             Date date = new Date();
             consumer.setConsumerDetailsLastupdatedtime(date.getTime());
             consumer.setConsumerLastAuthenticationTime(Long.valueOf(0));
-
             Either<ConsumerData, StorageOperationStatus> createResponse = consumerOperation.createCredentials(new ConsumerData(consumer));
-
             if (createResponse.isRight()) {
-                ResponseFormat responseFormat = componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponseForConsumer(createResponse.right().value()));
+                ResponseFormat responseFormat = componentsUtils
+                    .getResponseFormat(componentsUtils.convertFromStorageResponseForConsumer(createResponse.right().value()));
                 componentsUtils.auditConsumerCredentialsEvent(AuditingActionEnum.ADD_ECOMP_USER_CREDENTIALS, consumer, responseFormat, user);
                 return Either.right(responseFormat);
             }
@@ -127,7 +113,6 @@ public class ConsumerBusinessLogic extends BaseBusinessLogic {
     }
 
     private Either<User, ResponseFormat> validateUser(User user, ConsumerDefinition consumer, AuditingActionEnum auditAction) {
-
         if (user.getUserId() == null || user.getUserId().trim().isEmpty()) {
             log.debug("createEcompUser method - user is missing. userId= {}", user.getUserId());
             ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.MISSING_INFORMATION);
@@ -139,14 +124,13 @@ public class ConsumerBusinessLogic extends BaseBusinessLogic {
         User userFromDB;
         try {
             userFromDB = userAdmin.getUser(user.getUserId(), false);
-        }catch (ByActionStatusComponentException e){
+        } catch (ByActionStatusComponentException e) {
             log.debug("createEcompUser method - user is not listed. userId= {}", user.getUserId());
             ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.RESTRICTED_ACCESS);
             log.debug(AUDIT_BEFORE_SENDING_RESPONSE);
             componentsUtils.auditConsumerCredentialsEvent(auditAction, consumer, responseFormat, user);
             return Either.right(responseFormat);
         }
-
         user = userFromDB;
         // validate user role
         log.debug("validate user role");
@@ -175,7 +159,6 @@ public class ConsumerBusinessLogic extends BaseBusinessLogic {
             return Either.right(validateEcompUserSalt.right().value());
         }
         return Either.left(consumer);
-
     }
 
     private Either<ConsumerDefinition, ResponseFormat> validateConsumerName(ConsumerDefinition consumer) {
@@ -190,13 +173,13 @@ public class ConsumerBusinessLogic extends BaseBusinessLogic {
         }
         if (!ValidationUtils.validateLength(name, ValidationUtils.CONSUMER_NAME_MAX_LENGTH)) {
             log.debug("Consumer name exceeds limit.");
-            return Either.right(componentsUtils.getResponseFormat(ActionStatus.EXCEEDS_LIMIT, CONSUMER_NAME, String.valueOf(ValidationUtils.CONSUMER_NAME_MAX_LENGTH)));
+            return Either.right(componentsUtils
+                .getResponseFormat(ActionStatus.EXCEEDS_LIMIT, CONSUMER_NAME, String.valueOf(ValidationUtils.CONSUMER_NAME_MAX_LENGTH)));
         }
         if (!ValidationUtils.isUTF8Str(name)) {
             log.debug("Consumer name includes non UTF 8 characters.");
             return Either.right(componentsUtils.getResponseFormat(ActionStatus.INVALID_CONTENT_PARAM, CONSUMER_NAME));
         }
-
         return Either.left(consumer);
     }
 
@@ -215,7 +198,6 @@ public class ConsumerBusinessLogic extends BaseBusinessLogic {
             log.debug("Consumer password is invalid.");
             return Either.right(componentsUtils.getResponseFormat(ActionStatus.INVALID_CONTENT_PARAM, CONSUMER_PW));
         }
-
         return Either.left(consumer);
     }
 
@@ -233,7 +215,6 @@ public class ConsumerBusinessLogic extends BaseBusinessLogic {
             log.debug("Consumer salt is invalid.");
             return Either.right(componentsUtils.getResponseFormat(ActionStatus.INVALID_CONTENT_PARAM, CONSUMER_SALT));
         }
-
         return Either.left(consumer);
     }
 
@@ -299,7 +280,8 @@ public class ConsumerBusinessLogic extends BaseBusinessLogic {
     public Either<ConsumerDefinition, ResponseFormat> updateConsumer(ConsumerDefinition consumer) {
         Either<ConsumerData, StorageOperationStatus> updateResult = consumerOperation.updateCredentials(new ConsumerData(consumer));
         if (updateResult.isRight()) {
-            ResponseFormat responseFormat = componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponseForConsumer(updateResult.right().value()));
+            ResponseFormat responseFormat = componentsUtils
+                .getResponseFormat(componentsUtils.convertFromStorageResponseForConsumer(updateResult.right().value()));
             return Either.right(responseFormat);
         }
         consumer = new ConsumerDefinition(updateResult.left().value().getConsumerDataDefinition());
@@ -317,5 +299,4 @@ public class ConsumerBusinessLogic extends BaseBusinessLogic {
             log.info("Consumer Last Modifier USER_ID cannot be defined by user. This field will be overridden by the application");
         }
     }
-
 }
index 1757fcd..fad72cc 100644 (file)
  * limitations under the License.
  * ============LICENSE_END=========================================================
  */
-
 package org.openecomp.sdc.be.components.impl;
 
 import fj.data.Either;
-import org.apache.commons.lang3.tuple.ImmutablePair;
-import org.openecomp.sdc.be.config.BeEcompErrorManager;
-import org.openecomp.sdc.be.config.BeEcompErrorManager.ErrorSeverity;
-import org.openecomp.sdc.be.dao.api.ActionStatus;
-import org.openecomp.sdc.be.impl.ComponentsUtils;
-import org.openecomp.sdc.be.tosca.CsarUtils;
-import org.openecomp.sdc.common.log.wrappers.Logger;
-import org.openecomp.sdc.common.util.GeneralUtility;
-import org.openecomp.sdc.exception.ResponseFormat;
-
 import java.io.ByteArrayInputStream;
 import java.io.IOException;
 import java.io.StringReader;
@@ -43,11 +32,19 @@ import java.util.Properties;
 import java.util.regex.Matcher;
 import java.util.regex.Pattern;
 import java.util.stream.Collectors;
+import org.apache.commons.lang3.tuple.ImmutablePair;
+import org.openecomp.sdc.be.config.BeEcompErrorManager;
+import org.openecomp.sdc.be.config.BeEcompErrorManager.ErrorSeverity;
+import org.openecomp.sdc.be.dao.api.ActionStatus;
+import org.openecomp.sdc.be.impl.ComponentsUtils;
+import org.openecomp.sdc.be.tosca.CsarUtils;
+import org.openecomp.sdc.common.log.wrappers.Logger;
+import org.openecomp.sdc.common.util.GeneralUtility;
+import org.openecomp.sdc.exception.ResponseFormat;
 
 public class CsarValidationUtils {
 
     private static final Logger log = Logger.getLogger(CsarValidationUtils.class.getName());
-
     private static final String TOSCA_META_FILE_VERSION = "TOSCA-Meta-File-Version";
     private static final String CSAR_VERSION = "CSAR-Version";
     private static final String CREATED_BY = "Created-By";
@@ -56,11 +53,10 @@ public class CsarValidationUtils {
     private static final String TOSCA_FILE = "TOSCA.meta";
     private static final String DEL_PATTERN = "([/\\\\]+)";
     private static final String TOSCA_METADATA_PATH_PATTERN = TOSCA_METADATA +
-            // Artifact Group (i.e Deployment/Informational)
-            DEL_PATTERN + TOSCA_FILE;
-
+        // Artifact Group (i.e Deployment/Informational)
+        DEL_PATTERN + TOSCA_FILE;
     private static final String TOSCA_META_ENTRY_DEFINITIONS = "Entry-Definitions";
-    private static final String[] TOSCA_METADATA_FIELDS = { TOSCA_META_FILE_VERSION, CSAR_VERSION, CREATED_BY, TOSCA_META_ENTRY_DEFINITIONS };
+    private static final String[] TOSCA_METADATA_FIELDS = {TOSCA_META_FILE_VERSION, CSAR_VERSION, CREATED_BY, TOSCA_META_ENTRY_DEFINITIONS};
     private static final String ARTIFACTS_METADATA_FILE = "HEAT.meta";
     private static final String TOSCA_CSAR_EXTENSION = ".csar";
     private static final String TOSCA_METADATA_TOSCA_META_FILE_IS_NOT_IN_EXPECTED_KEY_VALUE_FORM_IN_CSAR_CSAR_ID = "TOSCA-Metadata/TOSCA.meta file is not in expected key-value form in csar, csar ID {}";
@@ -74,6 +70,7 @@ public class CsarValidationUtils {
 
     /**
      * Validates Csar
+     *
      * @param csar
      * @param csarUUID
      * @param componentsUtils
@@ -84,9 +81,7 @@ public class CsarValidationUtils {
         if (validateStatus.isRight()) {
             return Either.right(validateStatus.right().value());
         }
-
         removeNonUniqueArtifactsFromCsar(csar);
-
         log.trace("TOSCA-Metadata/TOSCA.meta file found, CSAR id {}", csarUUID);
         validateStatus = validateTOSCAMetadataFile(csar, csarUUID, componentsUtils);
         if (validateStatus.isRight()) {
@@ -96,26 +91,25 @@ public class CsarValidationUtils {
     }
 
     private static void removeNonUniqueArtifactsFromCsar(Map<String, byte[]> csar) {
-
         List<String> nonUniqueArtifactsToRemove = new ArrayList<>();
         String[] paths = csar.keySet().toArray(new String[csar.keySet().size()]);
         int numberOfArtifacts = paths.length;
-        for(int i = 0; i < numberOfArtifacts; ++i ){
+        for (int i = 0; i < numberOfArtifacts; ++i) {
             collectNonUniqueArtifact(paths, i, numberOfArtifacts, nonUniqueArtifactsToRemove);
         }
         nonUniqueArtifactsToRemove.stream().forEach(csar::remove);
     }
 
-    private static void collectNonUniqueArtifact( String[] paths, int currInd, int numberOfArtifacts, List<String> nonUniqueArtifactsToRemove) {
-
+    private static void collectNonUniqueArtifact(String[] paths, int currInd, int numberOfArtifacts, List<String> nonUniqueArtifactsToRemove) {
         String[] parsedPath = paths[currInd].split("/");
         String[] otherParsedPath;
         int artifactNameInd = parsedPath.length - 1;
-        for(int j = currInd + 1; j < numberOfArtifacts; ++j ){
+        for (int j = currInd + 1; j < numberOfArtifacts; ++j) {
             otherParsedPath = paths[j].split("/");
-            if(parsedPath.length == otherParsedPath.length && parsedPath.length > 3 && isEqualArtifactNames(parsedPath, otherParsedPath)){
-                log.error("Can't upload two artifact with the same name {}. The artifact with path {} will be handled, and the artifact with path {} will be ignored. ",
-                        parsedPath[artifactNameInd], paths[currInd], paths[j]);
+            if (parsedPath.length == otherParsedPath.length && parsedPath.length > 3 && isEqualArtifactNames(parsedPath, otherParsedPath)) {
+                log.error(
+                    "Can't upload two artifact with the same name {}. The artifact with path {} will be handled, and the artifact with path {} will be ignored. ",
+                    parsedPath[artifactNameInd], paths[currInd], paths[j]);
                 nonUniqueArtifactsToRemove.add(paths[j]);
             }
         }
@@ -130,158 +124,175 @@ public class CsarValidationUtils {
         String otherGroupType = otherParsedPath[artifactGroupTypeInd];
         String otherArtifactName = otherParsedPath[artifactNameInd];
         String vfcToscaName = parsedPath.length == 5 ? parsedPath[1] : null;
-
-        if(artifactName.equalsIgnoreCase(otherArtifactName) && groupType.equalsIgnoreCase(otherGroupType)){
+        if (artifactName.equalsIgnoreCase(otherArtifactName) && groupType.equalsIgnoreCase(otherGroupType)) {
             isEqualArtifactNames = vfcToscaName == null || vfcToscaName.equalsIgnoreCase(otherParsedPath[1]);
         }
         return isEqualArtifactNames;
     }
 
-    public static Either<ImmutablePair<String, String>, ResponseFormat> getToscaYaml(Map<String, byte[]> csar, String csarUUID, ComponentsUtils componentsUtils) {
+    public static Either<ImmutablePair<String, String>, ResponseFormat> getToscaYaml(Map<String, byte[]> csar, String csarUUID,
+                                                                                     ComponentsUtils componentsUtils) {
         Either<Boolean, ResponseFormat> validateStatus = validateIsTOSCAMetadataExist(csar, csarUUID, componentsUtils);
         if (validateStatus.isRight()) {
             return Either.right(validateStatus.right().value());
         }
         Pattern pattern = Pattern.compile(TOSCA_METADATA_PATH_PATTERN);
         Optional<String> keyOp = csar.keySet().stream().filter(k -> pattern.matcher(k).matches()).findAny();
-        if(!keyOp.isPresent()){
+        if (!keyOp.isPresent()) {
             log.debug(TOSCA_METADATA_TOSCA_META_FILE_IS_NOT_IN_EXPECTED_KEY_VALUE_FORM_IN_CSAR_CSAR_ID, csarUUID);
-            BeEcompErrorManager.getInstance().logInternalDataError(TOSCA_METADATA_TOSCA_META_FILE_NOT_IN_EXPECTED_KEY_VALUE_FORM_IN_CSAR_WITH_ID + csarUUID, CSAR_INTERNALS_ARE_INVALID, ErrorSeverity.ERROR);
+            BeEcompErrorManager.getInstance()
+                .logInternalDataError(TOSCA_METADATA_TOSCA_META_FILE_NOT_IN_EXPECTED_KEY_VALUE_FORM_IN_CSAR_WITH_ID + csarUUID,
+                    CSAR_INTERNALS_ARE_INVALID, ErrorSeverity.ERROR);
             return Either.right(componentsUtils.getResponseFormat(ActionStatus.CSAR_INVALID_FORMAT, csarUUID));
         }
         byte[] toscaMetaBytes = csar.get(keyOp.get());
         Properties props = new Properties();
         try {
             String propStr = new String(toscaMetaBytes);
-            props.load(new StringReader(propStr.replace("\\","\\\\")));
+            props.load(new StringReader(propStr.replace("\\", "\\\\")));
         } catch (IOException e) {
             log.debug(TOSCA_METADATA_TOSCA_META_FILE_IS_NOT_IN_EXPECTED_KEY_VALUE_FORM_IN_CSAR_CSAR_ID, csarUUID, e);
-            BeEcompErrorManager.getInstance().logInternalDataError(TOSCA_METADATA_TOSCA_META_FILE_NOT_IN_EXPECTED_KEY_VALUE_FORM_IN_CSAR_WITH_ID + csarUUID, CSAR_INTERNALS_ARE_INVALID, ErrorSeverity.ERROR);
+            BeEcompErrorManager.getInstance()
+                .logInternalDataError(TOSCA_METADATA_TOSCA_META_FILE_NOT_IN_EXPECTED_KEY_VALUE_FORM_IN_CSAR_WITH_ID + csarUUID,
+                    CSAR_INTERNALS_ARE_INVALID, ErrorSeverity.ERROR);
             return Either.right(componentsUtils.getResponseFormat(ActionStatus.CSAR_INVALID_FORMAT, csarUUID));
         }
-
         String yamlFileName = props.getProperty(TOSCA_META_ENTRY_DEFINITIONS);
         String[] ops = yamlFileName.split(DEL_PATTERN);
         List<String> list = Arrays.asList(ops);
         String result = list.stream().map(x -> x).collect(Collectors.joining(DEL_PATTERN));
         keyOp = csar.keySet().stream().filter(k -> Pattern.compile(result).matcher(k).matches()).findAny();
-        if(!keyOp.isPresent()){
+        if (!keyOp.isPresent()) {
             log.debug(ENTRY_DEFINITIONS_ENTRY_NOT_FOUND_IN_TOSCA_METADATA_TOSCA_META_FILE_CSAR_ID, csarUUID);
-            BeEcompErrorManager.getInstance().logInternalDataError(ENTRY_DEFINITIONS_ENTRY_NOT_FOUND_IN_TOSCA_METADATA_TOSCA_META_FILE_CSAR_ID + csarUUID, CSAR_INTERNALS_ARE_INVALID, ErrorSeverity.ERROR);
+            BeEcompErrorManager.getInstance()
+                .logInternalDataError(ENTRY_DEFINITIONS_ENTRY_NOT_FOUND_IN_TOSCA_METADATA_TOSCA_META_FILE_CSAR_ID + csarUUID,
+                    CSAR_INTERNALS_ARE_INVALID, ErrorSeverity.ERROR);
             return Either.right(componentsUtils.getResponseFormat(ActionStatus.YAML_NOT_FOUND_IN_CSAR, csarUUID, yamlFileName));
         }
-
         log.trace("Found Entry-Definitions property in TOSCA-Metadata/TOSCA.meta, Entry-Definitions: {}, CSAR id: {}", yamlFileName, csarUUID);
         byte[] yamlFileBytes = csar.get(yamlFileName);
         if (yamlFileBytes == null) {
             log.debug("Entry-Definitions {} file not found in csar, csar ID {}", yamlFileName, csarUUID);
-            BeEcompErrorManager.getInstance().logInternalDataError(ENTRY_DEFINITIONS + yamlFileName + FILE_NOT_FOUND_IN_CSAR_WITH_ID + csarUUID, CSAR_STRUCTURE_IS_INVALID, ErrorSeverity.ERROR);
+            BeEcompErrorManager.getInstance()
+                .logInternalDataError(ENTRY_DEFINITIONS + yamlFileName + FILE_NOT_FOUND_IN_CSAR_WITH_ID + csarUUID, CSAR_STRUCTURE_IS_INVALID,
+                    ErrorSeverity.ERROR);
             return Either.right(componentsUtils.getResponseFormat(ActionStatus.YAML_NOT_FOUND_IN_CSAR, csarUUID, yamlFileName));
         }
-
         String yamlFileContents = new String(yamlFileBytes);
-
         return Either.left(new ImmutablePair<>(yamlFileName, yamlFileContents));
     }
 
-    public static Either<ImmutablePair<String, String>, ResponseFormat> getArtifactsMeta(Map<String, byte[]> csar, String csarUUID, ComponentsUtils componentsUtils) {
-
-        if( !csar.containsKey(CsarUtils.ARTIFACTS_PATH + ARTIFACTS_METADATA_FILE) ) {
+    public static Either<ImmutablePair<String, String>, ResponseFormat> getArtifactsMeta(Map<String, byte[]> csar, String csarUUID,
+                                                                                         ComponentsUtils componentsUtils) {
+        if (!csar.containsKey(CsarUtils.ARTIFACTS_PATH + ARTIFACTS_METADATA_FILE)) {
             log.debug(ENTRY_DEFINITIONS_ENTRY_NOT_FOUND_IN_TOSCA_METADATA_TOSCA_META_FILE_CSAR_ID, csarUUID);
-            BeEcompErrorManager.getInstance().logInternalDataError(ENTRY_DEFINITIONS_ENTRY_NOT_FOUND_IN_TOSCA_METADATA_TOSCA_META_FILE_CSAR_ID + csarUUID, CSAR_INTERNALS_ARE_INVALID, ErrorSeverity.ERROR);
+            BeEcompErrorManager.getInstance()
+                .logInternalDataError(ENTRY_DEFINITIONS_ENTRY_NOT_FOUND_IN_TOSCA_METADATA_TOSCA_META_FILE_CSAR_ID + csarUUID,
+                    CSAR_INTERNALS_ARE_INVALID, ErrorSeverity.ERROR);
             return Either.right(componentsUtils.getResponseFormat(ActionStatus.YAML_NOT_FOUND_IN_CSAR, csarUUID, ARTIFACTS_METADATA_FILE));
         }
-
-        log.trace("Found Entry-Definitions property in TOSCA-Metadata/TOSCA.meta, Entry-Definitions: {}, CSAR id: {}", ARTIFACTS_METADATA_FILE, csarUUID);
+        log.trace("Found Entry-Definitions property in TOSCA-Metadata/TOSCA.meta, Entry-Definitions: {}, CSAR id: {}", ARTIFACTS_METADATA_FILE,
+            csarUUID);
         byte[] artifactsMetaBytes = csar.get(CsarUtils.ARTIFACTS_PATH + ARTIFACTS_METADATA_FILE);
         if (artifactsMetaBytes == null) {
             log.debug("Entry-Definitions {}{} file not found in csar, csar ID {}", CsarUtils.ARTIFACTS_PATH, ARTIFACTS_METADATA_FILE, csarUUID);
-            BeEcompErrorManager.getInstance().logInternalDataError(ENTRY_DEFINITIONS + CsarUtils.ARTIFACTS_PATH + ARTIFACTS_METADATA_FILE + FILE_NOT_FOUND_IN_CSAR_WITH_ID + csarUUID, CSAR_STRUCTURE_IS_INVALID, ErrorSeverity.ERROR);
-            return Either.right(componentsUtils.getResponseFormat(ActionStatus.YAML_NOT_FOUND_IN_CSAR, csarUUID, CsarUtils.ARTIFACTS_PATH + ARTIFACTS_METADATA_FILE));
+            BeEcompErrorManager.getInstance().logInternalDataError(
+                ENTRY_DEFINITIONS + CsarUtils.ARTIFACTS_PATH + ARTIFACTS_METADATA_FILE + FILE_NOT_FOUND_IN_CSAR_WITH_ID + csarUUID,
+                CSAR_STRUCTURE_IS_INVALID, ErrorSeverity.ERROR);
+            return Either.right(
+                componentsUtils.getResponseFormat(ActionStatus.YAML_NOT_FOUND_IN_CSAR, csarUUID, CsarUtils.ARTIFACTS_PATH + ARTIFACTS_METADATA_FILE));
         }
-
         String artifactsFileContents = new String(artifactsMetaBytes);
-
         return Either.left(new ImmutablePair<>(CsarUtils.ARTIFACTS_PATH + ARTIFACTS_METADATA_FILE, artifactsFileContents));
     }
 
-    public static Either<ImmutablePair<String, byte[]>, ResponseFormat> getArtifactContent(String csarUUID, Map<String, byte[]> csar, String artifactPath, String artifactName, ComponentsUtils componentsUtils) {
+    public static Either<ImmutablePair<String, byte[]>, ResponseFormat> getArtifactContent(String csarUUID, Map<String, byte[]> csar,
+                                                                                           String artifactPath, String artifactName,
+                                                                                           ComponentsUtils componentsUtils) {
         if (!csar.containsKey(artifactPath)) {
             log.debug("Entry-Definitions entry not found in Artifacts/HEAT.meta file, csar ID {}", csarUUID);
-            BeEcompErrorManager.getInstance().logInternalDataError(ENTRY_DEFINITIONS_ENTRY_NOT_FOUND_IN_TOSCA_METADATA_TOSCA_META_FILE_CSAR_ID + csarUUID, CSAR_INTERNALS_ARE_INVALID, ErrorSeverity.ERROR);
-            return Either.right(componentsUtils.getResponseFormat(ActionStatus.ARTIFACT_NOT_FOUND_IN_CSAR, CsarUtils.ARTIFACTS_PATH + artifactName, csarUUID));
+            BeEcompErrorManager.getInstance()
+                .logInternalDataError(ENTRY_DEFINITIONS_ENTRY_NOT_FOUND_IN_TOSCA_METADATA_TOSCA_META_FILE_CSAR_ID + csarUUID,
+                    CSAR_INTERNALS_ARE_INVALID, ErrorSeverity.ERROR);
+            return Either
+                .right(componentsUtils.getResponseFormat(ActionStatus.ARTIFACT_NOT_FOUND_IN_CSAR, CsarUtils.ARTIFACTS_PATH + artifactName, csarUUID));
         }
-
         log.trace("Found Entry-Definitions property in Artifacts/HEAT.meta, Entry-Definitions: {}, CSAR id: {}", artifactPath, csarUUID);
         byte[] artifactFileBytes = csar.get(artifactPath);
         if (artifactFileBytes == null) {
             log.debug("Entry-Definitions {}{} file not found in csar, csar ID {}", CsarUtils.ARTIFACTS_PATH, artifactName, csarUUID);
-            BeEcompErrorManager.getInstance().logInternalDataError(ENTRY_DEFINITIONS + artifactPath + FILE_NOT_FOUND_IN_CSAR_WITH_ID + csarUUID, CSAR_STRUCTURE_IS_INVALID, ErrorSeverity.ERROR);
+            BeEcompErrorManager.getInstance()
+                .logInternalDataError(ENTRY_DEFINITIONS + artifactPath + FILE_NOT_FOUND_IN_CSAR_WITH_ID + csarUUID, CSAR_STRUCTURE_IS_INVALID,
+                    ErrorSeverity.ERROR);
             return Either.right(componentsUtils.getResponseFormat(ActionStatus.ARTIFACT_NOT_FOUND_IN_CSAR, artifactPath, csarUUID));
         }
-
         return Either.left(new ImmutablePair<>(artifactName, artifactFileBytes));
     }
 
-    private static Either<Boolean, ResponseFormat> validateTOSCAMetadataFile(Map<String, byte[]> csar, String csarUUID, ComponentsUtils componentsUtils) {
-
+    private static Either<Boolean, ResponseFormat> validateTOSCAMetadataFile(Map<String, byte[]> csar, String csarUUID,
+                                                                             ComponentsUtils componentsUtils) {
         Pattern pattern = Pattern.compile(TOSCA_METADATA_PATH_PATTERN);
         Optional<String> keyOp = csar.keySet().stream().filter(k -> pattern.matcher(k).matches()).findAny();
-        if(!keyOp.isPresent()){
+        if (!keyOp.isPresent()) {
             log.debug(TOSCA_METADATA_TOSCA_META_FILE_IS_NOT_IN_EXPECTED_KEY_VALUE_FORM_IN_CSAR_CSAR_ID, csarUUID);
-            BeEcompErrorManager.getInstance().logInternalDataError(TOSCA_METADATA_TOSCA_META_FILE_NOT_IN_EXPECTED_KEY_VALUE_FORM_IN_CSAR_WITH_ID + csarUUID, CSAR_INTERNALS_ARE_INVALID, ErrorSeverity.ERROR);
+            BeEcompErrorManager.getInstance()
+                .logInternalDataError(TOSCA_METADATA_TOSCA_META_FILE_NOT_IN_EXPECTED_KEY_VALUE_FORM_IN_CSAR_WITH_ID + csarUUID,
+                    CSAR_INTERNALS_ARE_INVALID, ErrorSeverity.ERROR);
             return Either.right(componentsUtils.getResponseFormat(ActionStatus.CSAR_INVALID_FORMAT, csarUUID));
         }
-
         byte[] toscaMetaBytes = csar.get(keyOp.get());
         String toscaMetadata = new String(toscaMetaBytes);
         String[] splited = toscaMetadata.split(NEW_LINE_DELM);
         if (splited == null || splited.length < TOSCA_METADATA_FIELDS.length) {
             log.debug(TOSCA_METADATA_TOSCA_META_FILE_IS_NOT_IN_EXPECTED_KEY_VALUE_FORM_IN_CSAR_CSAR_ID, csarUUID);
-            BeEcompErrorManager.getInstance().logInternalDataError(TOSCA_METADATA_TOSCA_META_FILE_NOT_IN_EXPECTED_KEY_VALUE_FORM_IN_CSAR_WITH_ID + csarUUID, CSAR_INTERNALS_ARE_INVALID, ErrorSeverity.ERROR);
+            BeEcompErrorManager.getInstance()
+                .logInternalDataError(TOSCA_METADATA_TOSCA_META_FILE_NOT_IN_EXPECTED_KEY_VALUE_FORM_IN_CSAR_WITH_ID + csarUUID,
+                    CSAR_INTERNALS_ARE_INVALID, ErrorSeverity.ERROR);
             return Either.right(componentsUtils.getResponseFormat(ActionStatus.CSAR_INVALID_FORMAT, csarUUID));
         }
-
         Either<Boolean, ResponseFormat> blockStatus = validateBlock(csarUUID, splited, componentsUtils);
         if (blockStatus.isRight()) {
             return Either.right(blockStatus.right().value());
         }
-
         return Either.left(true);
-
     }
 
     private static Either<Boolean, ResponseFormat> validateBlock(String csarUUID, String[] splited, ComponentsUtils componentsUtils) {
         int index = 0;
         for (String toscaField : TOSCA_METADATA_FIELDS) {
-
             Properties props = new Properties();
-
             try {
                 props.load(new ByteArrayInputStream(splited[index].getBytes()));
             } catch (IOException e) {
                 log.debug(TOSCA_METADATA_TOSCA_META_FILE_IS_NOT_IN_EXPECTED_KEY_VALUE_FORM_IN_CSAR_CSAR_ID, csarUUID, e);
-                BeEcompErrorManager.getInstance().logInternalDataError(TOSCA_METADATA_TOSCA_META_FILE_NOT_IN_EXPECTED_KEY_VALUE_FORM_IN_CSAR_WITH_ID + csarUUID, CSAR_INTERNALS_ARE_INVALID, ErrorSeverity.ERROR);
+                BeEcompErrorManager.getInstance()
+                    .logInternalDataError(TOSCA_METADATA_TOSCA_META_FILE_NOT_IN_EXPECTED_KEY_VALUE_FORM_IN_CSAR_WITH_ID + csarUUID,
+                        CSAR_INTERNALS_ARE_INVALID, ErrorSeverity.ERROR);
                 return Either.right(componentsUtils.getResponseFormat(ActionStatus.CSAR_INVALID_FORMAT, csarUUID));
             }
             if (!props.containsKey(toscaField)) {
                 log.debug("TOSCA.meta file format is invalid: No new line after block_0 as expected in csar, csar ID {}", csarUUID);
-                BeEcompErrorManager.getInstance().logInternalDataError(TOSCA_METADATA_TOSCA_META_FILE_NOT_IN_EXPECTED_KEY_VALUE_FORM_IN_CSAR_WITH_ID + csarUUID, CSAR_INTERNALS_ARE_INVALID, ErrorSeverity.ERROR);
+                BeEcompErrorManager.getInstance()
+                    .logInternalDataError(TOSCA_METADATA_TOSCA_META_FILE_NOT_IN_EXPECTED_KEY_VALUE_FORM_IN_CSAR_WITH_ID + csarUUID,
+                        CSAR_INTERNALS_ARE_INVALID, ErrorSeverity.ERROR);
                 return Either.right(componentsUtils.getResponseFormat(ActionStatus.CSAR_INVALID_FORMAT, csarUUID));
             }
             String value = props.getProperty(toscaField);
             if (value == null || value.isEmpty()) {
                 log.debug(TOSCA_METADATA_TOSCA_META_FILE_IS_NOT_IN_EXPECTED_KEY_VALUE_FORM_IN_CSAR_CSAR_ID, csarUUID);
-                BeEcompErrorManager.getInstance().logInternalDataError(TOSCA_METADATA_TOSCA_META_FILE_NOT_IN_EXPECTED_KEY_VALUE_FORM_IN_CSAR_WITH_ID + csarUUID, CSAR_INTERNALS_ARE_INVALID, ErrorSeverity.ERROR);
+                BeEcompErrorManager.getInstance()
+                    .logInternalDataError(TOSCA_METADATA_TOSCA_META_FILE_NOT_IN_EXPECTED_KEY_VALUE_FORM_IN_CSAR_WITH_ID + csarUUID,
+                        CSAR_INTERNALS_ARE_INVALID, ErrorSeverity.ERROR);
                 return Either.right(componentsUtils.getResponseFormat(ActionStatus.CSAR_INVALID_FORMAT, csarUUID));
             }
-
             // TOSCA-Meta-File-Version & CSAR-Version : digit.digit - format
+
             // validation
             if ((toscaField.equals(TOSCA_META_FILE_VERSION) || toscaField.equals(CSAR_VERSION)) && !validateTOSCAMetaProperty(value)) {
                 log.debug("TOSCA-Metadata/TOSCA.meta file contains {} in wrong format (digit.digit), csar ID {}", toscaField, csarUUID);
                 BeEcompErrorManager.getInstance()
-                        .logInternalDataError(TOSCA_METADATA_TOSCA_META_FILE_NOT_IN_EXPECTED_KEY_VALUE_FORM_IN_CSAR_WITH_ID + csarUUID, CSAR_INTERNALS_ARE_INVALID, ErrorSeverity.ERROR);
+                    .logInternalDataError(TOSCA_METADATA_TOSCA_META_FILE_NOT_IN_EXPECTED_KEY_VALUE_FORM_IN_CSAR_WITH_ID + csarUUID,
+                        CSAR_INTERNALS_ARE_INVALID, ErrorSeverity.ERROR);
                 return Either.right(componentsUtils.getResponseFormat(ActionStatus.CSAR_INVALID_FORMAT, csarUUID));
             }
             index++;
@@ -294,48 +305,45 @@ public class CsarValidationUtils {
         return floatMatcher.matches();
     }
 
-    private static Either<Boolean, ResponseFormat> validateIsTOSCAMetadataExist(Map<String, byte[]> csar, String csarUUID, ComponentsUtils componentsUtils) {
+    private static Either<Boolean, ResponseFormat> validateIsTOSCAMetadataExist(Map<String, byte[]> csar, String csarUUID,
+                                                                                ComponentsUtils componentsUtils) {
         if (csar == null || csar.isEmpty()) {
             log.debug("Error when fetching csar with ID {}", csarUUID);
             BeEcompErrorManager.getInstance().logBeDaoSystemError("Creating resource from CSAR: fetching CSAR with id " + csarUUID + " failed");
             ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.CSAR_INVALID, csarUUID);
             return Either.right(responseFormat);
         }
-
         Pattern pattern = Pattern.compile(TOSCA_METADATA_PATH_PATTERN);
         Optional<String> keyOp = csar.keySet().stream().filter(k -> pattern.matcher(k).matches()).findAny();
-        if(!keyOp.isPresent()){
-
+        if (!keyOp.isPresent()) {
             log.debug("TOSCA-Metadata/TOSCA.meta file not found in csar, csar ID {}", csarUUID);
-            BeEcompErrorManager.getInstance().logInternalDataError("TOSCA-Metadata/TOSCA.meta file not found in CSAR with id " + csarUUID, CSAR_STRUCTURE_IS_INVALID, ErrorSeverity.ERROR);
+            BeEcompErrorManager.getInstance()
+                .logInternalDataError("TOSCA-Metadata/TOSCA.meta file not found in CSAR with id " + csarUUID, CSAR_STRUCTURE_IS_INVALID,
+                    ErrorSeverity.ERROR);
             return Either.right(componentsUtils.getResponseFormat(ActionStatus.CSAR_INVALID, csarUUID));
         }
         byte[] toscaMetaBytes = csar.get(keyOp.get());
-
         if (toscaMetaBytes == null || toscaMetaBytes.length == 0) {
             log.debug("TOSCA-Metadata/TOSCA.meta file not found in csar, csar ID {}", csarUUID);
-            BeEcompErrorManager.getInstance().logInternalDataError("TOSCA-Metadata/TOSCA.meta file not found in CSAR with id " + csarUUID, CSAR_STRUCTURE_IS_INVALID, ErrorSeverity.ERROR);
+            BeEcompErrorManager.getInstance()
+                .logInternalDataError("TOSCA-Metadata/TOSCA.meta file not found in CSAR with id " + csarUUID, CSAR_STRUCTURE_IS_INVALID,
+                    ErrorSeverity.ERROR);
             return Either.right(componentsUtils.getResponseFormat(ActionStatus.CSAR_INVALID, csarUUID));
         }
-
         return Either.left(Boolean.TRUE);
     }
 
     public static Either<String, ResponseFormat> getToscaYamlChecksum(Map<String, byte[]> csar, String csarUUID, ComponentsUtils componentsUtils) {
-
         Either<ImmutablePair<String, String>, ResponseFormat> toscaYamlRes = getToscaYaml(csar, csarUUID, componentsUtils);
         if (toscaYamlRes.isRight() || toscaYamlRes.left().value() == null || toscaYamlRes.left().value().getRight() == null) {
             log.debug("Faild to create toscaYamlChecksum for csar, csar ID {}", csarUUID);
             return Either.right(toscaYamlRes.right().value());
         }
-
         String newCheckSum = GeneralUtility.calculateMD5Base64EncodedByByteArray(toscaYamlRes.left().value().getRight().getBytes());
         return Either.left(newCheckSum);
-
     }
 
     public static boolean isCsarPayloadName(String payloadName) {
         return payloadName != null && payloadName.toLowerCase().endsWith(TOSCA_CSAR_EXTENSION);
     }
-
 }
index 5af7cf6..4012228 100644 (file)
  * limitations under the License.
  * ============LICENSE_END=========================================================
  */
-
 package org.openecomp.sdc.be.components.impl;
 
 import fj.data.Either;
+import java.util.ArrayList;
+import java.util.List;
+import java.util.Optional;
 import org.openecomp.sdc.be.model.Component;
 import org.openecomp.sdc.be.model.ComponentParametersView;
 import org.openecomp.sdc.be.model.DataTypeDefinition;
@@ -35,23 +37,15 @@ import org.openecomp.sdc.be.model.operations.impl.InterfaceLifecycleOperation;
 import org.springframework.beans.factory.annotation.Autowired;
 import org.springframework.util.CollectionUtils;
 
-import java.util.ArrayList;
-import java.util.List;
-import java.util.Optional;
-
 @org.springframework.stereotype.Component("dataTypeBusinessLogic")
 public class DataTypeBusinessLogic extends BaseBusinessLogic {
 
     @Autowired
-    public DataTypeBusinessLogic(IElementOperation elementDao,
-        IGroupOperation groupOperation,
-        IGroupInstanceOperation groupInstanceOperation,
-        IGroupTypeOperation groupTypeOperation,
-        InterfaceOperation interfaceOperation,
-        InterfaceLifecycleOperation interfaceLifecycleTypeOperation,
-        ArtifactsOperations artifactToscaOperation) {
-        super(elementDao, groupOperation, groupInstanceOperation, groupTypeOperation,
-            interfaceOperation, interfaceLifecycleTypeOperation, artifactToscaOperation);
+    public DataTypeBusinessLogic(IElementOperation elementDao, IGroupOperation groupOperation, IGroupInstanceOperation groupInstanceOperation,
+                                 IGroupTypeOperation groupTypeOperation, InterfaceOperation interfaceOperation,
+                                 InterfaceLifecycleOperation interfaceLifecycleTypeOperation, ArtifactsOperations artifactToscaOperation) {
+        super(elementDao, groupOperation, groupInstanceOperation, groupTypeOperation, interfaceOperation, interfaceLifecycleTypeOperation,
+            artifactToscaOperation);
     }
 
     /**
@@ -64,22 +58,19 @@ public class DataTypeBusinessLogic extends BaseBusinessLogic {
         ComponentParametersView filter = new ComponentParametersView();
         filter.disableAll();
         filter.setIgnoreDataType(false);
-
         // Get Component object
-        Either<? extends Component, StorageOperationStatus> componentResult =
-                toscaOperationFacade.getToscaElement(componentId, filter);
+        Either<? extends Component, StorageOperationStatus> componentResult = toscaOperationFacade.getToscaElement(componentId, filter);
         if (componentResult.isRight()) {
             return Either.right(componentResult.right().value());
         }
         Component component = componentResult.left().value();
-
         List<DataTypeDefinition> dataTypesToReturn = component.getDataTypes();
         if (dataTypesToReturn == null) {
             // this means there is no DATA_TYPES graph vertex.
+
             // in this case, returns empty list.
             dataTypesToReturn = new ArrayList<>();
         }
-
         return Either.left(dataTypesToReturn);
     }
 
@@ -114,23 +105,19 @@ public class DataTypeBusinessLogic extends BaseBusinessLogic {
         ComponentParametersView filter = new ComponentParametersView();
         filter.disableAll();
         filter.setIgnoreDataType(false);
-
         // Get Component object
-        Either<? extends Component, StorageOperationStatus> componentResult =
-                toscaOperationFacade.getToscaElement(componentId, filter);
+        Either<? extends Component, StorageOperationStatus> componentResult = toscaOperationFacade.getToscaElement(componentId, filter);
         if (componentResult.isRight()) {
             // not exists
             return Either.right(componentResult.right().value());
         }
-
         return deletePrivateDataType(componentResult.left().value(), dataTypeName);
     }
 
     /**
      * Delete a data type from the Component.
      *
-     * @param component    Component object which has data types.
-     *                     needs to be fetched with componentParametersView.setIgnoreDataType(false)
+     * @param component    Component object which has data types. needs to be fetched with componentParametersView.setIgnoreDataType(false)
      * @param dataTypeName Data type name to be deleted
      * @return deleted data type
      */
@@ -140,18 +127,15 @@ public class DataTypeBusinessLogic extends BaseBusinessLogic {
         if (CollectionUtils.isEmpty(dataTypes)) {
             return Either.right(StorageOperationStatus.NOT_FOUND);
         }
-        Optional<DataTypeDefinition> dataTypeResult =
-                dataTypes.stream().filter(e -> e.getName().equals(dataTypeName)).findFirst();
+        Optional<DataTypeDefinition> dataTypeResult = dataTypes.stream().filter(e -> e.getName().equals(dataTypeName)).findFirst();
         if (!dataTypeResult.isPresent()) {
             return Either.right(StorageOperationStatus.NOT_FOUND);
         }
-
         // delete it
         StorageOperationStatus deleteResult = toscaOperationFacade.deleteDataTypeOfComponent(component, dataTypeName);
         if (deleteResult != StorageOperationStatus.OK) {
             return Either.right(deleteResult);
         }
-
         // return deleted data type if ok
         return Either.left(dataTypeResult.get());
     }
index 2e8344f..4c7f072 100644 (file)
@@ -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.
  * limitations under the License.
  * ============LICENSE_END=========================================================
  */
-
 package org.openecomp.sdc.be.components.impl;
 
 import fj.data.Either;
+import java.util.ArrayList;
+import java.util.HashSet;
+import java.util.List;
+import java.util.Map;
+import java.util.Set;
+import java.util.stream.Collectors;
+import javax.annotation.Resource;
 import org.apache.commons.lang3.tuple.ImmutablePair;
 import org.openecomp.sdc.be.components.impl.CommonImportManager.ElementTypeEnum;
 import org.openecomp.sdc.be.dao.api.ActionStatus;
@@ -36,14 +42,6 @@ import org.openecomp.sdc.common.log.wrappers.Logger;
 import org.openecomp.sdc.exception.ResponseFormat;
 import org.springframework.stereotype.Component;
 
-import javax.annotation.Resource;
-import java.util.ArrayList;
-import java.util.HashSet;
-import java.util.List;
-import java.util.Map;
-import java.util.Set;
-import java.util.stream.Collectors;
-
 @Component("dataTypeImportManager")
 public class DataTypeImportManager {
 
@@ -56,91 +54,90 @@ public class DataTypeImportManager {
     private CommonImportManager commonImportManager;
 
     public Either<List<ImmutablePair<DataTypeDefinition, Boolean>>, ResponseFormat> createDataTypes(String dataTypeYml) {
-        return commonImportManager.createElementTypes(dataTypeYml, this::createDataTypesFromYml, this::createDataTypesByDao, ElementTypeEnum.DATA_TYPE);
+        return commonImportManager
+            .createElementTypes(dataTypeYml, this::createDataTypesFromYml, this::createDataTypesByDao, ElementTypeEnum.DATA_TYPE);
     }
 
     private Either<List<DataTypeDefinition>, ActionStatus> createDataTypesFromYml(String dataTypesYml) {
         return commonImportManager.createElementTypesFromYml(dataTypesYml, this::createDataType);
     }
 
-    private Either<List<ImmutablePair<DataTypeDefinition, Boolean>>, ResponseFormat> createDataTypesByDao(List<DataTypeDefinition> dataTypesToCreate) {
-
-        return commonImportManager.createElementTypesByDao(dataTypesToCreate, this::validateDataType, dataType -> new ImmutablePair<>(ElementTypeEnum.DATA_TYPE, dataType.getName()),
-                dataTypeName -> propertyOperation.getDataTypeByNameWithoutDerived(dataTypeName), dataType -> propertyOperation.addDataType(dataType), (newDataType, oldDataType) -> propertyOperation.updateDataType(newDataType, oldDataType));
+    private Either<List<ImmutablePair<DataTypeDefinition, Boolean>>, ResponseFormat> createDataTypesByDao(
+        List<DataTypeDefinition> dataTypesToCreate) {
+        return commonImportManager.createElementTypesByDao(dataTypesToCreate, this::validateDataType,
+            dataType -> new ImmutablePair<>(ElementTypeEnum.DATA_TYPE, dataType.getName()),
+            dataTypeName -> propertyOperation.getDataTypeByNameWithoutDerived(dataTypeName), dataType -> propertyOperation.addDataType(dataType),
+            (newDataType, oldDataType) -> propertyOperation.updateDataType(newDataType, oldDataType));
     }
 
     private Either<ActionStatus, ResponseFormat> validateDataType(DataTypeDefinition dataType) {
-
         String dataTypeName = dataType.getName();
         List<PropertyDefinition> properties = dataType.getProperties();
         if (properties == null) {
             // At least one parameter should be defined either in the properties
+
             // section or at one of the parents
             String derivedDataType = dataType.getDerivedFromName();
             // If there are no properties, then we can create a data type if it
+
             // is an abstract one or it derives from non abstract data type
             if (derivedDataType == null || derivedDataType.isEmpty()) {
                 if (!isAbstract(dataType.getName()) && !ToscaPropertyType.isScalarType(dataTypeName)) {
                     log.debug("Data type {} must have properties unless it derives from non abstract data type", dataType.getName());
-                    ResponseFormat responseFormat = componentsUtils.getResponseFormatByDataType(ActionStatus.DATA_TYPE_NOR_PROPERTIES_NEITHER_DERIVED_FROM, dataType, null);
+                    ResponseFormat responseFormat = componentsUtils
+                        .getResponseFormatByDataType(ActionStatus.DATA_TYPE_NOR_PROPERTIES_NEITHER_DERIVED_FROM, dataType, null);
                     return Either.right(responseFormat);
                 }
             } else {
                 if (!ToscaPropertyType.isScalarType(dataTypeName) && isAbstract(derivedDataType)) {
                     log.warn("Creating data type {} which derived from abstract data type with no properties", dataType.getName());
                 }
-            } 
+            }
         } else {
             // properties tag cannot be empty
             if (properties.isEmpty()) {
-                ResponseFormat responseFormat = componentsUtils.getResponseFormatByDataType(ActionStatus.DATA_TYPE_PROPERTIES_CANNOT_BE_EMPTY, dataType, null);
-
+                ResponseFormat responseFormat = componentsUtils
+                    .getResponseFormatByDataType(ActionStatus.DATA_TYPE_PROPERTIES_CANNOT_BE_EMPTY, dataType, null);
                 return Either.right(responseFormat);
             }
-
             // check no duplicates
             Set<String> collect = properties.stream().map(PropertyDataDefinition::getName).collect(Collectors.toSet());
             if (collect != null && properties.size() != collect.size()) {
-                ResponseFormat responseFormat = componentsUtils.getResponseFormatByDataType(ActionStatus.DATA_TYPE_DUPLICATE_PROPERTY, dataType, null);
-
+                ResponseFormat responseFormat = componentsUtils
+                    .getResponseFormatByDataType(ActionStatus.DATA_TYPE_DUPLICATE_PROPERTY, dataType, null);
                 return Either.right(responseFormat);
             }
-
-            List<String> propertiesWithSameTypeAsDataType = properties.stream().filter(p -> p.getType().equals(dataType.getName())).map(PropertyDataDefinition::getName).collect(Collectors.toList());
+            List<String> propertiesWithSameTypeAsDataType = properties.stream().filter(p -> p.getType().equals(dataType.getName()))
+                .map(PropertyDataDefinition::getName).collect(Collectors.toList());
             if (propertiesWithSameTypeAsDataType != null && !propertiesWithSameTypeAsDataType.isEmpty()) {
                 log.debug("The data type {} contains properties with the type {}", dataType.getName(), dataType.getName());
-                ResponseFormat responseFormat = componentsUtils.getResponseFormatByDataType(ActionStatus.DATA_TYPE_PROEPRTY_CANNOT_HAVE_SAME_TYPE_OF_DATA_TYPE, dataType, propertiesWithSameTypeAsDataType);
-
+                ResponseFormat responseFormat = componentsUtils
+                    .getResponseFormatByDataType(ActionStatus.DATA_TYPE_PROEPRTY_CANNOT_HAVE_SAME_TYPE_OF_DATA_TYPE, dataType,
+                        propertiesWithSameTypeAsDataType);
                 return Either.right(responseFormat);
             }
         }
-
         String derivedDataType = dataType.getDerivedFromName();
         if (derivedDataType != null) {
             Either<DataTypeDefinition, StorageOperationStatus> derivedDataTypeByName = propertyOperation.getDataTypeByName(derivedDataType, true);
             if (derivedDataTypeByName.isRight()) {
                 StorageOperationStatus status = derivedDataTypeByName.right().value();
                 if (status == StorageOperationStatus.NOT_FOUND) {
-                    ResponseFormat responseFormat = componentsUtils.getResponseFormatByDataType(ActionStatus.DATA_TYPE_DERIVED_IS_MISSING, dataType, null);
-
+                    ResponseFormat responseFormat = componentsUtils
+                        .getResponseFormatByDataType(ActionStatus.DATA_TYPE_DERIVED_IS_MISSING, dataType, null);
                     return Either.right(responseFormat);
                 } else {
                     ResponseFormat responseFormat = componentsUtils.getResponseFormatByDataType(ActionStatus.GENERAL_ERROR, dataType, null);
-
                     return Either.right(responseFormat);
-
                 }
             } else {
-
                 DataTypeDefinition derivedDataTypeDef = derivedDataTypeByName.left().value();
-                if (properties != null && !properties.isEmpty() && derivedDataTypeDef!=null) {
-
+                if (properties != null && !properties.isEmpty() && derivedDataTypeDef != null) {
                     if (isScalarType(derivedDataTypeDef)) {
-                        ResponseFormat responseFormat = componentsUtils.getResponseFormatByDataType(ActionStatus.DATA_TYPE_CANNOT_HAVE_PROPERTIES, dataType, null);
-
+                        ResponseFormat responseFormat = componentsUtils
+                            .getResponseFormatByDataType(ActionStatus.DATA_TYPE_CANNOT_HAVE_PROPERTIES, dataType, null);
                         return Either.right(responseFormat);
                     }
-
                     Set<String> allParentsProps = new HashSet<>();
                     do {
                         List<PropertyDefinition> currentParentsProps = derivedDataTypeDef.getProperties();
@@ -151,18 +148,18 @@ public class DataTypeImportManager {
                         }
                         derivedDataTypeDef = derivedDataTypeDef.getDerivedFrom();
                     } while (derivedDataTypeDef != null);
-
                     // Check that no property is already defined in one of the
+
                     // ancestors
-                    Set<String> alreadyExistPropsCollection = properties.stream().filter(p -> allParentsProps.contains(p.getName())).map(PropertyDataDefinition::getName).collect(Collectors.toSet());
+                    Set<String> alreadyExistPropsCollection = properties.stream().filter(p -> allParentsProps.contains(p.getName()))
+                        .map(PropertyDataDefinition::getName).collect(Collectors.toSet());
                     if (alreadyExistPropsCollection != null && !alreadyExistPropsCollection.isEmpty()) {
                         List<String> duplicateProps = new ArrayList<>();
                         duplicateProps.addAll(alreadyExistPropsCollection);
-                        ResponseFormat responseFormat = componentsUtils.getResponseFormatByDataType(ActionStatus.DATA_TYPE_PROPERTY_ALREADY_DEFINED_IN_ANCESTOR, dataType, duplicateProps);
-
+                        ResponseFormat responseFormat = componentsUtils
+                            .getResponseFormatByDataType(ActionStatus.DATA_TYPE_PROPERTY_ALREADY_DEFINED_IN_ANCESTOR, dataType, duplicateProps);
                         return Either.right(responseFormat);
                     }
-
                 }
             }
         }
@@ -170,37 +167,27 @@ public class DataTypeImportManager {
     }
 
     private boolean isAbstract(String dataTypeName) {
-
         ToscaPropertyType isPrimitiveToscaType = ToscaPropertyType.isValidType(dataTypeName);
-
         return isPrimitiveToscaType != null && isPrimitiveToscaType.isAbstract();
-
     }
 
     private boolean isScalarType(DataTypeDefinition dataTypeDef) {
-
         boolean isScalar = false;
         DataTypeDefinition dataType = dataTypeDef;
-
         while (dataType != null) {
-
             String name = dataType.getName();
             if (ToscaPropertyType.isScalarType(name)) {
                 isScalar = true;
                 break;
             }
-
             dataType = dataType.getDerivedFrom();
         }
-
         return isScalar;
     }
 
     private DataTypeDefinition createDataType(String dataTypeName, Map<String, Object> toscaJson) {
         DataTypeDefinition dataType = new DataTypeDefinition();
-
         dataType.setName(dataTypeName);
-
         if (toscaJson != null) {
             // Description
             commonImportManager.setField(toscaJson, TypeUtils.ToscaTagNamesEnum.DESCRIPTION.getElementName(), dataType::setDescription);
@@ -211,5 +198,4 @@ public class DataTypeImportManager {
         }
         return dataType;
     }
-
 }
index cc831d4..be61e7b 100644 (file)
@@ -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.
  * limitations under the License.
  * ============LICENSE_END=========================================================
  */
-
 package org.openecomp.sdc.be.components.impl;
 
 import fj.data.Either;
+import java.util.Map;
 import org.openecomp.sdc.be.config.BeEcompErrorManager;
 import org.openecomp.sdc.be.dao.api.ActionStatus;
 import org.openecomp.sdc.be.dao.janusgraph.JanusGraphOperationStatus;
@@ -30,8 +30,6 @@ import org.openecomp.sdc.be.model.cache.ApplicationDataTypeCache;
 import org.openecomp.sdc.exception.ResponseFormat;
 import org.springframework.stereotype.Component;
 
-import java.util.Map;
-
 @Component
 public class DataTypesService {
 
@@ -46,14 +44,15 @@ public class DataTypesService {
         if (allDataTypes.isRight()) {
             JanusGraphOperationStatus operationStatus = allDataTypes.right().value();
             if (operationStatus == JanusGraphOperationStatus.NOT_FOUND) {
-                BeEcompErrorManager.getInstance().logInternalDataError("FetchDataTypes", "Data types are not loaded", BeEcompErrorManager.ErrorSeverity.ERROR);
+                BeEcompErrorManager.getInstance()
+                    .logInternalDataError("FetchDataTypes", "Data types are not loaded", BeEcompErrorManager.ErrorSeverity.ERROR);
                 return Either.right(componentsUtils.getResponseFormat(ActionStatus.DATA_TYPE_CANNOT_BE_EMPTY));
             } else {
-                BeEcompErrorManager.getInstance().logInternalFlowError("FetchDataTypes", "Failed to fetch data types", BeEcompErrorManager.ErrorSeverity.ERROR);
+                BeEcompErrorManager.getInstance()
+                    .logInternalFlowError("FetchDataTypes", "Failed to fetch data types", BeEcompErrorManager.ErrorSeverity.ERROR);
                 return Either.right(componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR));
             }
         }
         return Either.left(allDataTypes.left().value());
     }
-
 }
index 66cab35..f3334e6 100644 (file)
  * limitations under the License.
  * ============LICENSE_END=========================================================
  */
-
 package org.openecomp.sdc.be.components.impl;
 
 import fj.data.Either;
+import java.util.ArrayList;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
 import java.util.Optional;
+import java.util.Set;
 import org.apache.http.HttpStatus;
 import org.openecomp.sdc.be.dao.api.ActionStatus;
 import org.openecomp.sdc.be.dao.cassandra.AuditCassandraDao;
@@ -45,44 +49,28 @@ import org.openecomp.sdc.exception.ResponseFormat;
 import org.springframework.beans.factory.annotation.Autowired;
 import org.springframework.stereotype.Component;
 
-import java.util.ArrayList;
-import java.util.HashMap;
-import java.util.List;
-import java.util.Map;
-import java.util.Set;
-
 @Component("distributionMonitoringBusinessLogic")
 public class DistributionMonitoringBusinessLogic extends BaseBusinessLogic {
-    private static final String DEPLOYED = "Deployed";
 
+    private static final String DEPLOYED = "Deployed";
     private static final String ERROR = "Error";
-
     private static final String DISTRIBUTED = "Distributed";
-
     private static final String IN_PROGRESS = "In Progress";
-
     private static final Logger log = Logger.getLogger(ArtifactsBusinessLogic.class.getName());
-
     private final AuditCassandraDao cassandraDao;
 
     @Autowired
-    public DistributionMonitoringBusinessLogic(IElementOperation elementDao,
-        IGroupOperation groupOperation,
-        IGroupInstanceOperation groupInstanceOperation,
-        IGroupTypeOperation groupTypeOperation,
-        InterfaceOperation interfaceOperation,
-        InterfaceLifecycleOperation interfaceLifecycleTypeOperation,
-        AuditCassandraDao cassandraDao,
-        ArtifactsOperations artifactToscaOperation) {
-        super(elementDao, groupOperation, groupInstanceOperation, groupTypeOperation,
-            interfaceOperation, interfaceLifecycleTypeOperation, artifactToscaOperation);
+    public DistributionMonitoringBusinessLogic(IElementOperation elementDao, IGroupOperation groupOperation,
+                                               IGroupInstanceOperation groupInstanceOperation, IGroupTypeOperation groupTypeOperation,
+                                               InterfaceOperation interfaceOperation, InterfaceLifecycleOperation interfaceLifecycleTypeOperation,
+                                               AuditCassandraDao cassandraDao, ArtifactsOperations artifactToscaOperation) {
+        super(elementDao, groupOperation, groupInstanceOperation, groupTypeOperation, interfaceOperation, interfaceLifecycleTypeOperation,
+            artifactToscaOperation);
         this.cassandraDao = cassandraDao;
     }
 
     public Either<DistributionStatusListResponse, ResponseFormat> getListOfDistributionStatus(String did, String userId) {
-
         validateUserExists(userId);
-
         log.trace("getListOfDistributionStatus for did {}", did);
         Either<List<DistributionStatusEvent>, ActionStatus> distributionStatus = cassandraDao.getListOfDistributionStatuses(did);
         if (distributionStatus.isRight()) {
@@ -96,7 +84,6 @@ public class DistributionMonitoringBusinessLogic extends BaseBusinessLogic {
                 distribStatusInfoList.add(new DistributionStatusInfo(distributionStatusEvent));
             }
         }
-
         DistributionStatusListResponse distributionStatusListResponse = new DistributionStatusListResponse();
         distributionStatusListResponse.setDistributionStatusList(distribStatusInfoList);
         log.trace("list statuses for did {} is {} ", did, distribStatusInfoList);
@@ -105,7 +92,6 @@ public class DistributionMonitoringBusinessLogic extends BaseBusinessLogic {
 
     public Either<DistributionStatusOfServiceListResponce, ResponseFormat> getListOfDistributionServiceStatus(String serviceUuid, String userId) {
         validateUserExists(userId);
-
         log.trace("getListOfDistributionServiceStatus for serviceUUID {}", serviceUuid);
         Either<List<? extends AuditingGenericEvent>, ActionStatus> status = cassandraDao.getServiceDistributionStatusesList(serviceUuid);
         if (status.isRight()) {
@@ -134,15 +120,12 @@ public class DistributionMonitoringBusinessLogic extends BaseBusinessLogic {
             AuditingGenericEvent resAuditingGenericEvent = null;
             for (AuditingGenericEvent auditingGenericEvent : auditingGenericEventList) {
                 auditingGenericEvent.fillFields();
-
                 String action = (String) auditingGenericEvent.getFields().get(AuditingFieldsKey.AUDIT_ACTION.getDisplayName());
                 Object modifierUserId = auditingGenericEvent.getFields().get(AuditingFieldsKey.AUDIT_MODIFIER_UID.getDisplayName());
                 if (modifierUserId != null) {
                     distributionStatusOfServiceInfo.setUserId((String) modifierUserId);
                 }
-
                 if (action.equals(AuditingActionEnum.DISTRIBUTION_DEPLOY.getName())) {
-
                     isResult = true;
                     resAuditingGenericEvent = auditingGenericEvent;
                     break;
@@ -151,38 +134,34 @@ public class DistributionMonitoringBusinessLogic extends BaseBusinessLogic {
                 } else if (action.equals(AuditingActionEnum.DISTRIBUTION_NOTIFY.getName())) {
                     dNotifyStatus = getStatusFromAuditEvent(auditingGenericEvent);
                 }
-
                 resAuditingGenericEvent = auditingGenericEvent;
             }
-
             if (resAuditingGenericEvent != null) {
                 Map<String, Object> fields = resAuditingGenericEvent.getFields();
-
                 if (fields != null) {
-                    Optional.ofNullable(
-                        fields.get(AuditingFieldsKey.AUDIT_TIMESTAMP.getDisplayName()))
+                    Optional.ofNullable(fields.get(AuditingFieldsKey.AUDIT_TIMESTAMP.getDisplayName()))
                         .ifPresent(timestamp -> distributionStatusOfServiceInfo.setTimestamp((String) timestamp));
                 }
             }
-
             if (!isResult) {
                 if (dReguestStatus.equals(String.valueOf(HttpStatus.SC_OK))) {
                     if (dNotifyStatus.isEmpty()) {
                         distributionStatusOfServiceInfo.setDeployementStatus(IN_PROGRESS);
-
                     } else {
-                        if (dNotifyStatus.equals(String.valueOf(HttpStatus.SC_OK)))
+                        if (dNotifyStatus.equals(String.valueOf(HttpStatus.SC_OK))) {
                             distributionStatusOfServiceInfo.setDeployementStatus(DISTRIBUTED);
-                        else
+                        } else {
                             distributionStatusOfServiceInfo.setDeployementStatus(ERROR);
+                        }
                     }
-                } else
+                } else {
                     distributionStatusOfServiceInfo.setDeployementStatus(ERROR);
-            } else
+                }
+            } else {
                 distributionStatusOfServiceInfo.setDeployementStatus(DEPLOYED);
+            }
             reslist.add(distributionStatusOfServiceInfo);
         }
-
         return reslist;
     }
 
@@ -196,25 +175,21 @@ public class DistributionMonitoringBusinessLogic extends BaseBusinessLogic {
     }
 
     private Map<String, List<AuditingGenericEvent>> createServiceDidMap(List<? extends AuditingGenericEvent> distribStatusInfoList) {
-
         Map<String, List<AuditingGenericEvent>> serviceDidMap = new HashMap<>();
         for (AuditingGenericEvent auditingGenericEvent : distribStatusInfoList) {
             List<AuditingGenericEvent> auditingGenericEventList = null;
             String did = "";
             auditingGenericEvent.fillFields();
-
             Object didValue = auditingGenericEvent.getFields().get(AuditingFieldsKey.AUDIT_DISTRIBUTION_ID.getDisplayName());
             if (didValue != null) {
                 did = (String) didValue;
             }
-
             if (!did.isEmpty()) {
                 if (serviceDidMap.containsKey(did)) {
                     auditingGenericEventList = serviceDidMap.get(did);
                 }
                 if (auditingGenericEventList == null) {
                     auditingGenericEventList = new ArrayList<>();
-
                 }
                 auditingGenericEventList.add(auditingGenericEvent);
                 serviceDidMap.put(did, auditingGenericEventList);
@@ -222,5 +197,4 @@ public class DistributionMonitoringBusinessLogic extends BaseBusinessLogic {
         }
         return serviceDidMap;
     }
-
 }
index 631daef..499a612 100644 (file)
  * Modifications copyright (c) 2019 Nokia
  * ================================================================================
  */
-
 package org.openecomp.sdc.be.components.impl;
 
+import static org.apache.commons.lang.BooleanUtils.isTrue;
+import static org.openecomp.sdc.be.components.impl.ImportUtils.Constants.DEFAULT_ICON;
+
 import fj.data.Either;
+import java.nio.charset.StandardCharsets;
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.EnumMap;
+import java.util.HashMap;
+import java.util.HashSet;
+import java.util.LinkedList;
+import java.util.List;
+import java.util.Map;
+import java.util.Objects;
+import java.util.Optional;
+import java.util.Set;
+import java.util.function.Predicate;
+import java.util.stream.Collectors;
 import org.apache.commons.lang3.tuple.ImmutablePair;
 import org.apache.http.NameValuePair;
 import org.apache.http.client.utils.URLEncodedUtils;
@@ -89,24 +105,6 @@ import org.openecomp.sdc.common.util.ValidationUtils;
 import org.openecomp.sdc.exception.ResponseFormat;
 import org.springframework.beans.factory.annotation.Autowired;
 
-import java.nio.charset.StandardCharsets;
-import java.util.ArrayList;
-import java.util.Arrays;
-import java.util.EnumMap;
-import java.util.HashMap;
-import java.util.HashSet;
-import java.util.LinkedList;
-import java.util.List;
-import java.util.Map;
-import java.util.Objects;
-import java.util.Optional;
-import java.util.Set;
-import java.util.function.Predicate;
-import java.util.stream.Collectors;
-
-import static org.apache.commons.lang.BooleanUtils.isTrue;
-import static org.openecomp.sdc.be.components.impl.ImportUtils.Constants.DEFAULT_ICON;
-
 @org.springframework.stereotype.Component("elementsBusinessLogic")
 public class ElementBusinessLogic extends BaseBusinessLogic {
 
@@ -116,27 +114,21 @@ public class ElementBusinessLogic extends BaseBusinessLogic {
     private static final String VALIDATION_OF_USER_FAILED_USER_ID = "Validation of user failed, userId {}";
     private static final String COMPONENT_TYPE_IS_INVALID = "Component type {} is invalid";
     private static final String VALIDATION_OF_USER_ROLE_FAILED_USER_ID = "Validation of user role failed, userId {}";
-
     private final IElementOperation elementOperation;
     private final UserBusinessLogic userAdminManager;
 
     @Autowired
-    public ElementBusinessLogic(IElementOperation elementDao,
-        IGroupOperation groupOperation,
-        IGroupInstanceOperation groupInstanceOperation,
-        IGroupTypeOperation groupTypeOperation,
-        GroupBusinessLogic groupBusinessLogic,
-        InterfaceOperation interfaceOperation,
-        InterfaceLifecycleOperation interfaceLifecycleTypeOperation,
-        ArtifactsOperations artifactToscaOperation, IElementOperation elementOperation,
-        UserBusinessLogic userAdminManager) {
-        super(elementDao, groupOperation, groupInstanceOperation, groupTypeOperation,
-            interfaceOperation, interfaceLifecycleTypeOperation, artifactToscaOperation);
+    public ElementBusinessLogic(IElementOperation elementDao, IGroupOperation groupOperation, IGroupInstanceOperation groupInstanceOperation,
+                                IGroupTypeOperation groupTypeOperation, GroupBusinessLogic groupBusinessLogic, InterfaceOperation interfaceOperation,
+                                InterfaceLifecycleOperation interfaceLifecycleTypeOperation, ArtifactsOperations artifactToscaOperation,
+                                IElementOperation elementOperation, UserBusinessLogic userAdminManager) {
+        super(elementDao, groupOperation, groupInstanceOperation, groupTypeOperation, interfaceOperation, interfaceLifecycleTypeOperation,
+            artifactToscaOperation);
         this.elementOperation = elementOperation;
         this.userAdminManager = userAdminManager;
     }
+
     /**
-     *
      * @param user
      * @return
      */
@@ -147,35 +139,29 @@ public class ElementBusinessLogic extends BaseBusinessLogic {
         String role = user.getRole();
         String userId = user.getUserId();
         Role currentRole = Role.valueOf(role);
-
         switch (currentRole) {
-        case DESIGNER:
-            response = handleDesigner(userId);
-            break;
-
-        case PRODUCT_STRATEGIST:
-            response = handleProductStrategist();
-            break;
-
-        case PRODUCT_MANAGER:
-            response = handleProductManager(userId);
-            break;
-
-        case ADMIN:
-            response = handleAdmin();
-            break;
-
-        default:
-            response = Either.right(componentsUtils.getResponseFormat(ActionStatus.RESTRICTED_OPERATION));
-            break;
+            case DESIGNER:
+                response = handleDesigner(userId);
+                break;
+            case PRODUCT_STRATEGIST:
+                response = handleProductStrategist();
+                break;
+            case PRODUCT_MANAGER:
+                response = handleProductManager(userId);
+                break;
+            case ADMIN:
+                response = handleAdmin();
+                break;
+            default:
+                response = Either.right(componentsUtils.getResponseFormat(ActionStatus.RESTRICTED_OPERATION));
+                break;
         }
         // converting the Set to List so the rest of the code will handle it normally (Was changed because the same element with the same uuid was returned twice)
         return convertedToListResponse(response);
-
     }
 
-    private Either<Map<String, List<? extends Component>>, ResponseFormat> convertedToListResponse(Either<Map<String, Set<? extends Component>>, ResponseFormat> setResponse) {
-
+    private Either<Map<String, List<? extends Component>>, ResponseFormat> convertedToListResponse(
+        Either<Map<String, Set<? extends Component>>, ResponseFormat> setResponse) {
         Map<String, List<? extends Component>> arrayResponse = new HashMap<>();
         if (setResponse.isLeft()) {
             for (Map.Entry<String, Set<? extends Component>> entry : setResponse.left().value().entrySet()) {
@@ -228,13 +214,15 @@ public class ElementBusinessLogic extends BaseBusinessLogic {
         return response;
     }
 
-    private Either<Map<String, Set<? extends Component>>, ResponseFormat> getFollowedResourcesAndServices(String userId, Set<LifecycleStateEnum> lifecycleStates, Set<LifecycleStateEnum> lastStateStates) {
-
+    private Either<Map<String, Set<? extends Component>>, ResponseFormat> getFollowedResourcesAndServices(String userId,
+                                                                                                          Set<LifecycleStateEnum> lifecycleStates,
+                                                                                                          Set<LifecycleStateEnum> lastStateStates) {
         try {
-            Either<Set<Resource>, StorageOperationStatus> resources = toscaOperationFacade.getFollowed(userId, lifecycleStates, lastStateStates, ComponentTypeEnum.RESOURCE);
-
+            Either<Set<Resource>, StorageOperationStatus> resources = toscaOperationFacade
+                .getFollowed(userId, lifecycleStates, lastStateStates, ComponentTypeEnum.RESOURCE);
             if (resources.isLeft()) {
-                Either<Set<Service>, StorageOperationStatus> services = toscaOperationFacade.getFollowed(userId, lifecycleStates, lastStateStates, ComponentTypeEnum.SERVICE);
+                Either<Set<Service>, StorageOperationStatus> services = toscaOperationFacade
+                    .getFollowed(userId, lifecycleStates, lastStateStates, ComponentTypeEnum.SERVICE);
                 if (services.isLeft()) {
                     Map<String, Set<? extends Component>> result = new HashMap<>();
                     result.put(SERVICES, services.left().value());
@@ -251,8 +239,10 @@ public class ElementBusinessLogic extends BaseBusinessLogic {
         }
     }
 
-    private Either<Map<String, Set<? extends Component>>, ResponseFormat> getFollowedProducts(String userId, Set<LifecycleStateEnum> lifecycleStates, Set<LifecycleStateEnum> lastStateStates) {
-        Either<Set<Product>, StorageOperationStatus> products = toscaOperationFacade.getFollowed(userId, lifecycleStates, lastStateStates, ComponentTypeEnum.PRODUCT);
+    private Either<Map<String, Set<? extends Component>>, ResponseFormat> getFollowedProducts(String userId, Set<LifecycleStateEnum> lifecycleStates,
+                                                                                              Set<LifecycleStateEnum> lastStateStates) {
+        Either<Set<Product>, StorageOperationStatus> products = toscaOperationFacade
+            .getFollowed(userId, lifecycleStates, lastStateStates, ComponentTypeEnum.PRODUCT);
         if (products.isLeft()) {
             Map<String, Set<? extends Component>> result = new HashMap<>();
             result.put("products", products.left().value());
@@ -274,12 +264,10 @@ public class ElementBusinessLogic extends BaseBusinessLogic {
     }
 
     public Either<CategoryDefinition, ResponseFormat> createCategory(CategoryDefinition category, String componentTypeParamName, String userId) {
-
         AuditingActionEnum auditingAction = AuditingActionEnum.ADD_CATEGORY;
         ComponentTypeEnum componentTypeEnum = ComponentTypeEnum.findByParamName(componentTypeParamName);
         String componentType = componentTypeEnum == null ? componentTypeParamName : componentTypeEnum.getValue();
         CategoryTypeEnum categoryType = CategoryTypeEnum.CATEGORY;
-
         User user = validateUserExists(userId);
         if (category == null) {
             log.debug("Category json is invalid");
@@ -287,7 +275,6 @@ public class ElementBusinessLogic extends BaseBusinessLogic {
             handleCategoryAuditing(responseFormat, user, null, auditingAction, componentType);
             return Either.right(responseFormat);
         }
-
         String categoryName = category.getName();
         // For auditing of failures we need the original non-normalized name
         String origCategoryName = categoryName;
@@ -297,7 +284,6 @@ public class ElementBusinessLogic extends BaseBusinessLogic {
             handleCategoryAuditing(responseFormat, user, origCategoryName, auditingAction, componentType);
             return Either.right(responseFormat);
         }
-
         Either<Boolean, ResponseFormat> validateUserRole = validateUserRole(user, componentTypeEnum);
         if (validateUserRole.isRight()) {
             log.debug(VALIDATION_OF_USER_ROLE_FAILED_USER_ID, userId);
@@ -305,35 +291,30 @@ public class ElementBusinessLogic extends BaseBusinessLogic {
             handleCategoryAuditing(responseFormat, user, origCategoryName, auditingAction, componentType);
             return Either.right(responseFormat);
         }
-
         if (!ValidationUtils.validateCategoryDisplayNameFormat(categoryName)) {
             log.debug("Category display name format is invalid, name {}, componentType {}", categoryName, componentType);
-            ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.COMPONENT_ELEMENT_INVALID_NAME_FORMAT, componentType, categoryType.getValue());
+            ResponseFormat responseFormat = componentsUtils
+                .getResponseFormat(ActionStatus.COMPONENT_ELEMENT_INVALID_NAME_FORMAT, componentType, categoryType.getValue());
             handleCategoryAuditing(responseFormat, user, origCategoryName, auditingAction, componentType);
             return Either.right(responseFormat);
         }
-
         categoryName = ValidationUtils.normalizeCategoryName4Display(categoryName);
-
         if (!ValidationUtils.validateCategoryDisplayNameLength(categoryName)) {
-            log.debug("Category display name length is invalid, should be from 4 to 25 chars, name {}, componentType {}", categoryName, componentType);
-            ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.COMPONENT_ELEMENT_INVALID_NAME_LENGTH, componentType, categoryType.getValue());
+            log.debug("Category display name length is invalid, should be from 4 to 25 chars, name {}, componentType {}", categoryName,
+                componentType);
+            ResponseFormat responseFormat = componentsUtils
+                .getResponseFormat(ActionStatus.COMPONENT_ELEMENT_INVALID_NAME_LENGTH, componentType, categoryType.getValue());
             handleCategoryAuditing(responseFormat, user, origCategoryName, auditingAction, componentType);
             return Either.right(responseFormat);
         }
-
         category.setName(categoryName);
-
         String normalizedName = ValidationUtils.normalizeCategoryName4Uniqueness(categoryName);
         category.setNormalizedName(normalizedName);
-
-        if (ValidationUtils.validateCategoryIconNotEmpty(category.getIcons())){
+        if (ValidationUtils.validateCategoryIconNotEmpty(category.getIcons())) {
             log.debug("createCategory: setting category icon to default icon since service category was created without an icon ");
             category.setIcons(Arrays.asList(DEFAULT_ICON));
         }
-
         NodeTypeEnum nodeType = NodeTypeConvertUtils.getCategoryNodeTypeByComponentParam(componentTypeEnum, categoryType);
-
         Either<Boolean, ActionStatus> categoryUniqueEither = elementOperation.isCategoryUniqueForType(nodeType, normalizedName);
         if (categoryUniqueEither.isRight()) {
             log.debug("Failed to check category uniqueness, name {}, componentType {}", categoryName, componentType);
@@ -341,19 +322,19 @@ public class ElementBusinessLogic extends BaseBusinessLogic {
             handleCategoryAuditing(responseFormat, user, origCategoryName, auditingAction, componentType);
             return Either.right(responseFormat);
         }
-
         Boolean isCategoryUnique = categoryUniqueEither.left().value();
         if (!isCategoryUnique) {
             log.debug("Category is not unique, name {}, componentType {}", categoryName, componentType);
-            ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.COMPONENT_CATEGORY_ALREADY_EXISTS, componentType, categoryName);
+            ResponseFormat responseFormat = componentsUtils
+                .getResponseFormat(ActionStatus.COMPONENT_CATEGORY_ALREADY_EXISTS, componentType, categoryName);
             handleCategoryAuditing(responseFormat, user, origCategoryName, auditingAction, componentType);
             return Either.right(responseFormat);
         }
-
         Either<CategoryDefinition, ActionStatus> createCategoryByType = elementOperation.createCategory(category, nodeType);
         if (createCategoryByType.isRight()) {
             log.debug("Failed to create category, name {}, componentType {}", categoryName, componentType);
-            ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.COMPONENT_CATEGORY_ALREADY_EXISTS, componentType, categoryName);
+            ResponseFormat responseFormat = componentsUtils
+                .getResponseFormat(ActionStatus.COMPONENT_CATEGORY_ALREADY_EXISTS, componentType, categoryName);
             handleCategoryAuditing(responseFormat, user, origCategoryName, auditingAction, componentType);
             return Either.right(componentsUtils.getResponseFormat(createCategoryByType.right().value()));
         }
@@ -364,37 +345,33 @@ public class ElementBusinessLogic extends BaseBusinessLogic {
         return Either.left(category);
     }
 
-    public Either<SubCategoryDefinition, ResponseFormat> createSubCategory(SubCategoryDefinition subCategory, String componentTypeParamName, String parentCategoryId, String userId) {
-
+    public Either<SubCategoryDefinition, ResponseFormat> createSubCategory(SubCategoryDefinition subCategory, String componentTypeParamName,
+                                                                           String parentCategoryId, String userId) {
         AuditingActionEnum auditingAction = AuditingActionEnum.ADD_SUB_CATEGORY;
         ComponentTypeEnum componentTypeEnum = ComponentTypeEnum.findByParamName(componentTypeParamName);
         String componentType = componentTypeEnum == null ? componentTypeParamName : componentTypeEnum.getValue();
         CategoryTypeEnum categoryType = CategoryTypeEnum.SUBCATEGORY;
         // For auditing
         String parentCategoryName = parentCategoryId;
-
         if (subCategory == null) {
             log.debug("Sub-category json is invalid");
             ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.INVALID_CONTENT);
             handleCategoryAuditing(responseFormat, null, parentCategoryName, null, auditingAction, componentType);
             return Either.right(responseFormat);
         }
-
         String subCategoryName = subCategory.getName();
         // For auditing of failures we need the original non-normalized name
         String origSubCategoryName = subCategoryName;
         User user;
-        try{
-            user =  validateUserExists(userId);
-        } catch(ByActionStatusComponentException e){
+        try {
+            user = validateUserExists(userId);
+        } catch (ByActionStatusComponentException e) {
             ResponseFormat responseFormat = componentsUtils.getResponseFormat(e.getActionStatus(), e.getParams());
-            handleComponentException(userId, auditingAction, componentType, parentCategoryName, origSubCategoryName,
-                responseFormat);
+            handleComponentException(userId, auditingAction, componentType, parentCategoryName, origSubCategoryName, responseFormat);
             throw e;
-        } catch(ByResponseFormatComponentException e){
+        } catch (ByResponseFormatComponentException e) {
             ResponseFormat responseFormat = e.getResponseFormat();
-            handleComponentException(userId, auditingAction, componentType, parentCategoryName, origSubCategoryName,
-                responseFormat);
+            handleComponentException(userId, auditingAction, componentType, parentCategoryName, origSubCategoryName, responseFormat);
             throw e;
         }
         if (componentTypeEnum == null) {
@@ -403,7 +380,6 @@ public class ElementBusinessLogic extends BaseBusinessLogic {
             handleCategoryAuditing(responseFormat, user, parentCategoryName, origSubCategoryName, auditingAction, componentType);
             return Either.right(responseFormat);
         }
-
         Either<Boolean, ResponseFormat> validateComponentType = validateComponentTypeForCategory(componentTypeEnum, categoryType);
         if (validateComponentType.isRight()) {
             log.debug("Validation of component type for sub-category failed");
@@ -411,7 +387,6 @@ public class ElementBusinessLogic extends BaseBusinessLogic {
             handleCategoryAuditing(responseFormat, user, parentCategoryName, origSubCategoryName, auditingAction, componentType);
             return Either.right(responseFormat);
         }
-
         Either<Boolean, ResponseFormat> validateUserRole = validateUserRole(user, componentTypeEnum);
         if (validateUserRole.isRight()) {
             log.debug(VALIDATION_OF_USER_ROLE_FAILED_USER_ID, userId);
@@ -419,65 +394,69 @@ public class ElementBusinessLogic extends BaseBusinessLogic {
             handleCategoryAuditing(responseFormat, user, parentCategoryName, origSubCategoryName, auditingAction, componentType);
             return Either.right(responseFormat);
         }
-
         NodeTypeEnum parentNodeType = NodeTypeConvertUtils.getCategoryNodeTypeByComponentParam(componentTypeEnum, CategoryTypeEnum.CATEGORY);
         NodeTypeEnum childNodeType = NodeTypeConvertUtils.getCategoryNodeTypeByComponentParam(componentTypeEnum, CategoryTypeEnum.SUBCATEGORY);
-
         CategoryDefinition categoryDefinition;
-        Either<CategoryDefinition, ResponseFormat> validateCategoryExists = validateCategoryExists(parentNodeType, parentCategoryId, componentTypeEnum);
+        Either<CategoryDefinition, ResponseFormat> validateCategoryExists = validateCategoryExists(parentNodeType, parentCategoryId,
+            componentTypeEnum);
         if (validateCategoryExists.isRight()) {
             log.debug("Validation of parent category exists failed, parent categoryId {}", parentCategoryId);
             ResponseFormat responseFormat = validateCategoryExists.right().value();
             handleCategoryAuditing(responseFormat, user, parentCategoryName, origSubCategoryName, auditingAction, componentType);
             return Either.right(responseFormat);
         }
-
         categoryDefinition = validateCategoryExists.left().value();
         parentCategoryName = categoryDefinition.getName();
-
         if (!ValidationUtils.validateCategoryDisplayNameFormat(subCategoryName)) {
             log.debug("Sub-category display name format is invalid, name {}, componentType {}", subCategoryName, componentType);
-            ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.COMPONENT_ELEMENT_INVALID_NAME_FORMAT, componentType, categoryType.getValue());
+            ResponseFormat responseFormat = componentsUtils
+                .getResponseFormat(ActionStatus.COMPONENT_ELEMENT_INVALID_NAME_FORMAT, componentType, categoryType.getValue());
             handleCategoryAuditing(responseFormat, user, parentCategoryName, origSubCategoryName, auditingAction, componentType);
             return Either.right(responseFormat);
         }
-
         subCategoryName = ValidationUtils.normalizeCategoryName4Display(subCategoryName);
-
         if (!ValidationUtils.validateCategoryDisplayNameLength(subCategoryName)) {
-            log.debug("Sub-category display name length is invalid, should be from 4 to 25 chars, name {}, componentType {}", subCategoryName, componentType);
-            ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.COMPONENT_ELEMENT_INVALID_NAME_LENGTH, componentType, categoryType.getValue());
+            log.debug("Sub-category display name length is invalid, should be from 4 to 25 chars, name {}, componentType {}", subCategoryName,
+                componentType);
+            ResponseFormat responseFormat = componentsUtils
+                .getResponseFormat(ActionStatus.COMPONENT_ELEMENT_INVALID_NAME_LENGTH, componentType, categoryType.getValue());
             handleCategoryAuditing(responseFormat, user, parentCategoryName, origSubCategoryName, auditingAction, componentType);
             return Either.right(responseFormat);
         }
-
         String normalizedName = ValidationUtils.normalizeCategoryName4Uniqueness(subCategoryName);
         subCategory.setNormalizedName(normalizedName);
-
         // Uniqueness under this category
-        Either<Boolean, ActionStatus> subCategoryUniqueForCategory = elementOperation.isSubCategoryUniqueForCategory(childNodeType, normalizedName, parentCategoryId);
+        Either<Boolean, ActionStatus> subCategoryUniqueForCategory = elementOperation
+            .isSubCategoryUniqueForCategory(childNodeType, normalizedName, parentCategoryId);
         if (subCategoryUniqueForCategory.isRight()) {
-            log.debug("Failed to check sub-category uniqueness, parent name {}, subcategory norm name {}, componentType {}", parentCategoryName, normalizedName, componentType);
+            log.debug("Failed to check sub-category uniqueness, parent name {}, subcategory norm name {}, componentType {}", parentCategoryName,
+                normalizedName, componentType);
             ResponseFormat responseFormat = componentsUtils.getResponseFormat(subCategoryUniqueForCategory.right().value());
             handleCategoryAuditing(responseFormat, user, parentCategoryName, origSubCategoryName, auditingAction, componentType);
             return Either.right(responseFormat);
         }
-
         Boolean isSubUnique = subCategoryUniqueForCategory.left().value();
         if (!isSubUnique) {
-            log.debug("Sub-category is not unique for category, parent name {}, subcategory norm name {}, componentType {}", parentCategoryName, normalizedName, componentType);
-            ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.COMPONENT_SUB_CATEGORY_EXISTS_FOR_CATEGORY, componentType, subCategoryName, parentCategoryName);
+            log.debug("Sub-category is not unique for category, parent name {}, subcategory norm name {}, componentType {}", parentCategoryName,
+                normalizedName, componentType);
+            ResponseFormat responseFormat = componentsUtils
+                .getResponseFormat(ActionStatus.COMPONENT_SUB_CATEGORY_EXISTS_FOR_CATEGORY, componentType, subCategoryName, parentCategoryName);
             handleCategoryAuditing(responseFormat, user, parentCategoryName, origSubCategoryName, auditingAction, componentType);
             return Either.right(responseFormat);
         }
-
         // Setting name of subcategory to fit the similar subcategory name
+
         // ignoring cases.
+
         // For example if Network-->kUKU exists for service category Network,
+
         // and user is trying to create Router-->Kuku for service category
+
         // Router,
+
         // his subcategory name will be Router-->kUKU.
-        Either<SubCategoryDefinition, ActionStatus> subCategoryUniqueForType = elementOperation.getSubCategoryUniqueForType(childNodeType, normalizedName);
+        Either<SubCategoryDefinition, ActionStatus> subCategoryUniqueForType = elementOperation
+            .getSubCategoryUniqueForType(childNodeType, normalizedName);
         if (subCategoryUniqueForType.isRight()) {
             log.debug("Failed validation of whether similar sub-category exists, normalizedName {} componentType {}", normalizedName, componentType);
             ResponseFormat responseFormat = componentsUtils.getResponseFormat(subCategoryUniqueForType.right().value());
@@ -488,18 +467,16 @@ public class ElementBusinessLogic extends BaseBusinessLogic {
         if (subCategoryDefinition != null) {
             subCategoryName = subCategoryDefinition.getName();
         }
-
         subCategory.setName(subCategoryName);
         ///////////////////////////////////////////// Validations end
-
-        Either<SubCategoryDefinition, ActionStatus> createSubCategory = elementOperation.createSubCategory(parentCategoryId, subCategory, childNodeType);
+        Either<SubCategoryDefinition, ActionStatus> createSubCategory = elementOperation
+            .createSubCategory(parentCategoryId, subCategory, childNodeType);
         if (createSubCategory.isRight()) {
             log.debug("Failed to create sub-category, name {}, componentType {}", subCategoryName, componentType);
             ResponseFormat responseFormat = componentsUtils.getResponseFormat(subCategoryUniqueForType.right().value());
             handleCategoryAuditing(responseFormat, user, parentCategoryName, origSubCategoryName, auditingAction, componentType);
             return Either.right(responseFormat);
         }
-
         SubCategoryDefinition subCategoryCreated = createSubCategory.left().value();
         log.debug("Created sub-category for component {}, name {}, uniqueId {}", componentType, subCategoryName, subCategoryCreated.getUniqueId());
         ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.CREATED);
@@ -507,25 +484,23 @@ public class ElementBusinessLogic extends BaseBusinessLogic {
         return Either.left(subCategoryCreated);
     }
 
-    private void handleComponentException(String userId, AuditingActionEnum auditingAction, String componentType,
-        String parentCategoryName, String origSubCategoryName, ResponseFormat responseFormat) {
+    private void handleComponentException(String userId, AuditingActionEnum auditingAction, String componentType, String parentCategoryName,
+                                          String origSubCategoryName, ResponseFormat responseFormat) {
         User user;
         log.debug(VALIDATION_OF_USER_FAILED_USER_ID, userId);
         user = new User();
         user.setUserId(userId);
-        handleCategoryAuditing(responseFormat, user, parentCategoryName, origSubCategoryName, auditingAction,
-            componentType);
+        handleCategoryAuditing(responseFormat, user, parentCategoryName, origSubCategoryName, auditingAction, componentType);
     }
 
-    private void handleComponentException(GroupingDefinition grouping, String userId, AuditingActionEnum auditingAction,
-        String componentType, String parentCategoryName, String parentSubCategoryName, ResponseFormat responseFormat) {
+    private void handleComponentException(GroupingDefinition grouping, String userId, AuditingActionEnum auditingAction, String componentType,
+                                          String parentCategoryName, String parentSubCategoryName, ResponseFormat responseFormat) {
         User user;
         log.debug(VALIDATION_OF_USER_FAILED_USER_ID, userId);
         user = new User();
         user.setUserId(userId);
         String groupingNameForAudit = grouping == null ? null : grouping.getName();
-        handleCategoryAuditing(responseFormat, user, parentCategoryName, parentSubCategoryName, groupingNameForAudit,
-            auditingAction, componentType);
+        handleCategoryAuditing(responseFormat, user, parentCategoryName, parentSubCategoryName, groupingNameForAudit, auditingAction, componentType);
     }
 
     private void handleComponentException(String componentType, String userId, ResponseFormat responseFormat) {
@@ -536,8 +511,8 @@ public class ElementBusinessLogic extends BaseBusinessLogic {
         componentsUtils.auditGetCategoryHierarchy(user, componentType, responseFormat);
     }
 
-    public Either<GroupingDefinition, ResponseFormat> createGrouping(GroupingDefinition grouping, String componentTypeParamName, String grandParentCategoryId, String parentSubCategoryId, String userId) {
-
+    public Either<GroupingDefinition, ResponseFormat> createGrouping(GroupingDefinition grouping, String componentTypeParamName,
+                                                                     String grandParentCategoryId, String parentSubCategoryId, String userId) {
         AuditingActionEnum auditingAction = AuditingActionEnum.ADD_GROUPING;
         ComponentTypeEnum componentTypeEnum = ComponentTypeEnum.findByParamName(componentTypeParamName);
         String componentType = componentTypeEnum == null ? componentTypeParamName : componentTypeEnum.getValue();
@@ -545,41 +520,33 @@ public class ElementBusinessLogic extends BaseBusinessLogic {
         // For auditing
         String parentCategoryName = grandParentCategoryId;
         String parentSubCategoryName = parentSubCategoryId;
-
         User user;
-        try{
+        try {
             user = validateUserExists(userId);
-        } catch(ByResponseFormatComponentException e){
+        } catch (ByResponseFormatComponentException e) {
             ResponseFormat responseFormat = e.getResponseFormat();
-            handleComponentException(grouping, userId, auditingAction, componentType, parentCategoryName,
-                parentSubCategoryName,
-                responseFormat);
+            handleComponentException(grouping, userId, auditingAction, componentType, parentCategoryName, parentSubCategoryName, responseFormat);
             throw e;
-        } catch(ByActionStatusComponentException e){
+        } catch (ByActionStatusComponentException e) {
             ResponseFormat responseFormat = componentsUtils.getResponseFormat(e.getActionStatus(), e.getParams());
-            handleComponentException(grouping, userId, auditingAction, componentType, parentCategoryName,
-                parentSubCategoryName, responseFormat);
+            handleComponentException(grouping, userId, auditingAction, componentType, parentCategoryName, parentSubCategoryName, responseFormat);
             throw e;
         }
-
         if (grouping == null) {
             log.debug("Grouping json is invalid");
             ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.INVALID_CONTENT);
             handleCategoryAuditing(responseFormat, user, parentCategoryName, parentSubCategoryName, null, auditingAction, componentType);
             return Either.right(responseFormat);
         }
-
         String groupingName = grouping.getName();
         // For auditing of failures we need the original non-normalized name
         String origGroupingName = groupingName;
-
         if (componentTypeEnum == null) {
             log.debug(COMPONENT_TYPE_IS_INVALID, componentTypeParamName);
             ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.INVALID_CONTENT);
             handleCategoryAuditing(responseFormat, user, parentCategoryName, parentSubCategoryName, origGroupingName, auditingAction, componentType);
             return Either.right(responseFormat);
         }
-
         Either<Boolean, ResponseFormat> validateComponentType = validateComponentTypeForCategory(componentTypeEnum, categoryType);
         if (validateComponentType.isRight()) {
             log.debug("Validation of component type for grouping failed");
@@ -587,7 +554,6 @@ public class ElementBusinessLogic extends BaseBusinessLogic {
             handleCategoryAuditing(responseFormat, user, parentCategoryName, parentSubCategoryName, origGroupingName, auditingAction, componentType);
             return Either.right(responseFormat);
         }
-
         Either<Boolean, ResponseFormat> validateUserRole = validateUserRole(user, componentTypeEnum);
         if (validateUserRole.isRight()) {
             log.debug(VALIDATION_OF_USER_ROLE_FAILED_USER_ID, userId);
@@ -595,78 +561,80 @@ public class ElementBusinessLogic extends BaseBusinessLogic {
             handleCategoryAuditing(responseFormat, user, parentCategoryName, parentSubCategoryName, origGroupingName, auditingAction, componentType);
             return Either.right(responseFormat);
         }
-
         NodeTypeEnum grandParentNodeType = NodeTypeConvertUtils.getCategoryNodeTypeByComponentParam(componentTypeEnum, CategoryTypeEnum.CATEGORY);
         NodeTypeEnum parentNodeType = NodeTypeConvertUtils.getCategoryNodeTypeByComponentParam(componentTypeEnum, CategoryTypeEnum.SUBCATEGORY);
         NodeTypeEnum childNodeType = NodeTypeConvertUtils.getCategoryNodeTypeByComponentParam(componentTypeEnum, CategoryTypeEnum.GROUPING);
-
         // Validate category
         CategoryDefinition categoryDefinition;
-        Either<CategoryDefinition, ResponseFormat> validateCategoryExists = validateCategoryExists(grandParentNodeType, grandParentCategoryId, componentTypeEnum);
+        Either<CategoryDefinition, ResponseFormat> validateCategoryExists = validateCategoryExists(grandParentNodeType, grandParentCategoryId,
+            componentTypeEnum);
         if (validateCategoryExists.isRight()) {
             log.debug("Validation of parent category exists failed, parent categoryId {}", grandParentCategoryId);
             ResponseFormat responseFormat = validateCategoryExists.right().value();
             handleCategoryAuditing(responseFormat, user, parentCategoryName, parentSubCategoryName, origGroupingName, auditingAction, componentType);
             return Either.right(responseFormat);
         }
-
         categoryDefinition = validateCategoryExists.left().value();
         parentCategoryName = categoryDefinition.getName();
-
         // Validate subcategory
         SubCategoryDefinition subCategoryDefinition;
-        Either<SubCategoryDefinition, ResponseFormat> validateSubCategoryExists = validateSubCategoryExists(parentNodeType, parentSubCategoryId, componentTypeEnum);
+        Either<SubCategoryDefinition, ResponseFormat> validateSubCategoryExists = validateSubCategoryExists(parentNodeType, parentSubCategoryId,
+            componentTypeEnum);
         if (validateSubCategoryExists.isRight()) {
             log.debug("Validation of parent sub-category exists failed, parent sub-category id {}", parentSubCategoryId);
             ResponseFormat responseFormat = validateSubCategoryExists.right().value();
             handleCategoryAuditing(responseFormat, user, parentCategoryName, parentSubCategoryName, origGroupingName, auditingAction, componentType);
             return Either.right(responseFormat);
         }
-
         subCategoryDefinition = validateSubCategoryExists.left().value();
         parentSubCategoryName = subCategoryDefinition.getName();
-
         if (!ValidationUtils.validateCategoryDisplayNameFormat(groupingName)) {
             log.debug("Sub-category display name format is invalid, name {}, componentType {}", groupingName, componentType);
-            ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.COMPONENT_ELEMENT_INVALID_NAME_FORMAT, componentType, categoryType.getValue());
+            ResponseFormat responseFormat = componentsUtils
+                .getResponseFormat(ActionStatus.COMPONENT_ELEMENT_INVALID_NAME_FORMAT, componentType, categoryType.getValue());
             handleCategoryAuditing(responseFormat, user, parentCategoryName, parentSubCategoryName, origGroupingName, auditingAction, componentType);
             return Either.right(responseFormat);
         }
-
         groupingName = ValidationUtils.normalizeCategoryName4Display(groupingName);
-
         if (!ValidationUtils.validateCategoryDisplayNameLength(groupingName)) {
-            log.debug("Grouping display name length is invalid, should be from 4 to 25 chars, name {}, componentType {}", groupingName, componentType);
-            ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.COMPONENT_ELEMENT_INVALID_NAME_LENGTH, componentType, categoryType.getValue());
+            log.debug("Grouping display name length is invalid, should be from 4 to 25 chars, name {}, componentType {}", groupingName,
+                componentType);
+            ResponseFormat responseFormat = componentsUtils
+                .getResponseFormat(ActionStatus.COMPONENT_ELEMENT_INVALID_NAME_LENGTH, componentType, categoryType.getValue());
             handleCategoryAuditing(responseFormat, user, parentCategoryName, parentSubCategoryName, origGroupingName, auditingAction, componentType);
             return Either.right(responseFormat);
         }
-
         String normalizedName = ValidationUtils.normalizeCategoryName4Uniqueness(groupingName);
         grouping.setNormalizedName(normalizedName);
-
         // Uniqueness under this category
-        Either<Boolean, ActionStatus> groupingUniqueForSubCategory = elementOperation.isGroupingUniqueForSubCategory(childNodeType, normalizedName, parentSubCategoryId);
+        Either<Boolean, ActionStatus> groupingUniqueForSubCategory = elementOperation
+            .isGroupingUniqueForSubCategory(childNodeType, normalizedName, parentSubCategoryId);
         if (groupingUniqueForSubCategory.isRight()) {
-            log.debug("Failed to check grouping uniqueness, parent name {}, grouping norm name {}, componentType {}", parentSubCategoryName, normalizedName, componentType);
+            log.debug("Failed to check grouping uniqueness, parent name {}, grouping norm name {}, componentType {}", parentSubCategoryName,
+                normalizedName, componentType);
             ResponseFormat responseFormat = componentsUtils.getResponseFormat(groupingUniqueForSubCategory.right().value());
             handleCategoryAuditing(responseFormat, user, parentCategoryName, parentSubCategoryName, origGroupingName, auditingAction, componentType);
             return Either.right(responseFormat);
         }
-
         Boolean isGroupingUnique = groupingUniqueForSubCategory.left().value();
         if (!isGroupingUnique) {
-            log.debug("Grouping is not unique for sub-category, parent name {}, grouping norm name {}, componentType {}", parentSubCategoryName, normalizedName, componentType);
-            ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.COMPONENT_GROUPING_EXISTS_FOR_SUB_CATEGORY, componentType, groupingName, parentSubCategoryName);
+            log.debug("Grouping is not unique for sub-category, parent name {}, grouping norm name {}, componentType {}", parentSubCategoryName,
+                normalizedName, componentType);
+            ResponseFormat responseFormat = componentsUtils
+                .getResponseFormat(ActionStatus.COMPONENT_GROUPING_EXISTS_FOR_SUB_CATEGORY, componentType, groupingName, parentSubCategoryName);
             handleCategoryAuditing(responseFormat, user, parentCategoryName, parentSubCategoryName, origGroupingName, auditingAction, componentType);
             return Either.right(responseFormat);
         }
-
         // Setting name of grouping to fit the similar grouping name ignoring
+
         // cases.
+
         // For example if Network-->kUKU exists for service sub-category
+
         // Network, and user is trying to create grouping Router-->Kuku for
+
         // service sub-category Router,
+
         // his grouping name will be Router-->kUKU.
         Either<GroupingDefinition, ActionStatus> groupingUniqueForType = elementOperation.getGroupingUniqueForType(childNodeType, normalizedName);
         if (groupingUniqueForType.isRight()) {
@@ -679,10 +647,8 @@ public class ElementBusinessLogic extends BaseBusinessLogic {
         if (groupingDefinition != null) {
             groupingName = groupingDefinition.getName();
         }
-
         grouping.setName(groupingName);
         ///////////////////////////////////////////// Validations end
-
         Either<GroupingDefinition, ActionStatus> createGrouping = elementOperation.createGrouping(parentSubCategoryId, grouping, childNodeType);
         if (createGrouping.isRight()) {
             log.debug("Failed to create grouping, name {}, componentType {}", groupingName, componentType);
@@ -690,16 +656,14 @@ public class ElementBusinessLogic extends BaseBusinessLogic {
             handleCategoryAuditing(responseFormat, user, parentCategoryName, parentSubCategoryName, origGroupingName, auditingAction, componentType);
             return Either.right(responseFormat);
         }
-
         GroupingDefinition groupingCreated = createGrouping.left().value();
         log.debug("Created grouping for component {}, name {}, uniqueId {}", componentType, groupingName, groupingCreated.getUniqueId());
         ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.CREATED);
-        handleCategoryAuditing(responseFormat, user, parentCategoryName, parentSubCategoryName, groupingCreated.getName(), auditingAction, componentType);
+        handleCategoryAuditing(responseFormat, user, parentCategoryName, parentSubCategoryName, groupingCreated.getName(), auditingAction,
+            componentType);
         return Either.left(groupingCreated);
     }
 
-
-
     public Either<List<CategoryDefinition>, ResponseFormat> getAllCategories(String componentType, String userId) {
         ResponseFormat responseFormat;
         User user = new User();
@@ -711,11 +675,11 @@ public class ElementBusinessLogic extends BaseBusinessLogic {
         }
         try {
             user = validateUserExists(userId);
-        } catch (ByActionStatusComponentException e){
+        } catch (ByActionStatusComponentException e) {
             responseFormat = componentsUtils.getResponseFormat(e.getActionStatus(), e.getParams());
             handleComponentException(componentType, userId, responseFormat);
             throw e;
-        } catch (ByResponseFormatComponentException e){
+        } catch (ByResponseFormatComponentException e) {
             responseFormat = e.getResponseFormat();
             handleComponentException(componentType, userId, responseFormat);
             throw e;
@@ -727,7 +691,6 @@ public class ElementBusinessLogic extends BaseBusinessLogic {
             componentsUtils.auditGetCategoryHierarchy(user, componentType, responseFormat);
             return Either.right(responseFormat);
         }
-
         NodeTypeEnum nodeTypeEnum = NodeTypeConvertUtils.getCategoryNodeTypeByComponentParam(componentTypeEnum, CategoryTypeEnum.CATEGORY);
         Either<List<CategoryDefinition>, ActionStatus> getAllCategoriesByType = elementOperation.getAllCategories(nodeTypeEnum, false);
         if (getAllCategoriesByType.isRight()) {
@@ -741,25 +704,22 @@ public class ElementBusinessLogic extends BaseBusinessLogic {
         return Either.left(categories);
     }
 
-
-
     public Either<UiCategories, ResponseFormat> getAllCategories(String userId) {
         ResponseFormat responseFormat;
         UiCategories categories = new UiCategories();
-
         User user = validateUserExists(userId);
-
         // GET resource categories
-        Either<List<CategoryDefinition>, ActionStatus> getResourceCategoriesByType = elementOperation.getAllCategories(NodeTypeEnum.ResourceNewCategory, false);
+        Either<List<CategoryDefinition>, ActionStatus> getResourceCategoriesByType = elementOperation
+            .getAllCategories(NodeTypeEnum.ResourceNewCategory, false);
         if (getResourceCategoriesByType.isRight()) {
             responseFormat = componentsUtils.getResponseFormat(getResourceCategoriesByType.right().value());
             componentsUtils.auditGetCategoryHierarchy(user, ComponentTypeEnum.RESOURCE.getValue(), responseFormat);
             return Either.right(responseFormat);
         }
         categories.setResourceCategories(getResourceCategoriesByType.left().value());
-
         // GET service categories
-        Either<List<CategoryDefinition>, ActionStatus> getServiceCategoriesByType = elementOperation.getAllCategories(NodeTypeEnum.ServiceNewCategory, false);
+        Either<List<CategoryDefinition>, ActionStatus> getServiceCategoriesByType = elementOperation
+            .getAllCategories(NodeTypeEnum.ServiceNewCategory, false);
         if (getServiceCategoriesByType.isRight()) {
             responseFormat = componentsUtils.getResponseFormat(getServiceCategoriesByType.right().value());
             componentsUtils.auditGetCategoryHierarchy(user, ComponentTypeEnum.SERVICE.getValue(), responseFormat);
@@ -771,17 +731,13 @@ public class ElementBusinessLogic extends BaseBusinessLogic {
     }
 
     public Either<CategoryDefinition, ResponseFormat> deleteCategory(String categoryId, String componentTypeParamName, String userId) {
-
         validateUserExists(userId);
-
         ComponentTypeEnum componentTypeEnum = ComponentTypeEnum.findByParamName(componentTypeParamName);
         if (componentTypeEnum == null) {
             log.debug("Cannot create category for component type {}", componentTypeParamName);
             return Either.right(componentsUtils.getResponseFormat(ActionStatus.INVALID_CONTENT));
         }
-
         NodeTypeEnum nodeTypeEnum = NodeTypeConvertUtils.getCategoryNodeTypeByComponentParam(componentTypeEnum, CategoryTypeEnum.CATEGORY);
-
         Either<CategoryDefinition, ActionStatus> deleteCategoryByType = elementOperation.deleteCategory(nodeTypeEnum, categoryId);
         if (deleteCategoryByType.isRight()) {
             // auditing, logging here...
@@ -793,17 +749,13 @@ public class ElementBusinessLogic extends BaseBusinessLogic {
     }
 
     public Either<SubCategoryDefinition, ResponseFormat> deleteSubCategory(String parentSubCategoryId, String componentTypeParamName, String userId) {
-
         validateUserExists(userId);
-
         ComponentTypeEnum componentTypeEnum = ComponentTypeEnum.findByParamName(componentTypeParamName);
         if (componentTypeEnum == null) {
             log.debug("Cannot delete sub-category for component type {}", componentTypeParamName);
             return Either.right(componentsUtils.getResponseFormat(ActionStatus.INVALID_CONTENT));
         }
-
         NodeTypeEnum nodeTypeEnum = NodeTypeConvertUtils.getCategoryNodeTypeByComponentParam(componentTypeEnum, CategoryTypeEnum.SUBCATEGORY);
-
         Either<SubCategoryDefinition, ActionStatus> deleteSubCategoryByType = elementOperation.deleteSubCategory(nodeTypeEnum, parentSubCategoryId);
         if (deleteSubCategoryByType.isRight()) {
             // auditing, logging here...
@@ -815,17 +767,13 @@ public class ElementBusinessLogic extends BaseBusinessLogic {
     }
 
     public Either<GroupingDefinition, ResponseFormat> deleteGrouping(String groupingId, String componentTypeParamName, String userId) {
-
         validateUserExists(userId);
-
         ComponentTypeEnum componentTypeEnum = ComponentTypeEnum.findByParamName(componentTypeParamName);
         if (componentTypeEnum == null) {
             log.debug("Cannot delete grouping for component type {}", componentTypeParamName);
             return Either.right(componentsUtils.getResponseFormat(ActionStatus.INVALID_CONTENT));
         }
-
         NodeTypeEnum nodeTypeEnum = NodeTypeConvertUtils.getCategoryNodeTypeByComponentParam(componentTypeEnum, CategoryTypeEnum.GROUPING);
-
         Either<GroupingDefinition, ActionStatus> deleteGroupingByType = elementOperation.deleteGrouping(nodeTypeEnum, groupingId);
         if (deleteGroupingByType.isRight()) {
             // auditing, logging here...
@@ -838,26 +786,31 @@ public class ElementBusinessLogic extends BaseBusinessLogic {
 
     private Either<Boolean, ResponseFormat> validateUserRole(User user, ComponentTypeEnum componentTypeEnum) {
         String role = user.getRole();
-        boolean validAdminAction = role.equals(Role.ADMIN.name()) && (componentTypeEnum == ComponentTypeEnum.SERVICE || componentTypeEnum == ComponentTypeEnum.RESOURCE);
+        boolean validAdminAction =
+            role.equals(Role.ADMIN.name()) && (componentTypeEnum == ComponentTypeEnum.SERVICE || componentTypeEnum == ComponentTypeEnum.RESOURCE);
         boolean validProductAction = role.equals(Role.PRODUCT_STRATEGIST.name()) && (componentTypeEnum == ComponentTypeEnum.PRODUCT);
-
         if (!(validAdminAction || validProductAction)) {
             ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.RESTRICTED_OPERATION);
-            log.debug("User not permitted to perform operation on category, userId = {}, role = {}, componentType = {}", user.getUserId(), role, componentTypeEnum);
+            log.debug("User not permitted to perform operation on category, userId = {}, role = {}, componentType = {}", user.getUserId(), role,
+                componentTypeEnum);
             return Either.right(responseFormat);
         }
         return Either.left(true);
     }
 
     private Either<Boolean, ResponseFormat> validateComponentTypeForCategory(ComponentTypeEnum componentType, CategoryTypeEnum categoryType) {
-        boolean validResourceAction = componentType == ComponentTypeEnum.RESOURCE && (categoryType == CategoryTypeEnum.CATEGORY || categoryType == CategoryTypeEnum.SUBCATEGORY);
+        boolean validResourceAction = componentType == ComponentTypeEnum.RESOURCE && (categoryType == CategoryTypeEnum.CATEGORY
+            || categoryType == CategoryTypeEnum.SUBCATEGORY);
         boolean validServiceAction = componentType == ComponentTypeEnum.SERVICE && categoryType == CategoryTypeEnum.CATEGORY;
         boolean validProductAction = componentType == ComponentTypeEnum.PRODUCT; // can
-                                                                                 // be
-                                                                                 // any
-                                                                                 // category
-                                                                                 // type
 
+        // be
+
+        // any
+
+        // category
+
+        // type
         if (!(validResourceAction || validServiceAction || validProductAction)) {
             ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.INVALID_CONTENT);
             log.debug("It's not allowed to create category type {} for component type {}", categoryType, componentType);
@@ -866,14 +819,16 @@ public class ElementBusinessLogic extends BaseBusinessLogic {
         return Either.left(true);
     }
 
-    private Either<CategoryDefinition, ResponseFormat> validateCategoryExists(NodeTypeEnum nodeType, String categoryId, ComponentTypeEnum componentType) {
+    private Either<CategoryDefinition, ResponseFormat> validateCategoryExists(NodeTypeEnum nodeType, String categoryId,
+                                                                              ComponentTypeEnum componentType) {
         Either<CategoryDefinition, ActionStatus> categoryByTypeAndId = elementOperation.getCategory(nodeType, categoryId);
         if (categoryByTypeAndId.isRight()) {
             log.debug("Failed to fetch parent category, parent categoryId {}", categoryId);
             ActionStatus actionStatus = categoryByTypeAndId.right().value();
             ResponseFormat responseFormat;
             if (actionStatus == ActionStatus.COMPONENT_CATEGORY_NOT_FOUND) {
-                responseFormat = componentsUtils.getResponseFormat(actionStatus, componentType.getValue().toLowerCase(), CategoryTypeEnum.CATEGORY.getValue(), "");
+                responseFormat = componentsUtils
+                    .getResponseFormat(actionStatus, componentType.getValue().toLowerCase(), CategoryTypeEnum.CATEGORY.getValue(), "");
             } else {
                 responseFormat = componentsUtils.getResponseFormat(actionStatus);
             }
@@ -882,14 +837,16 @@ public class ElementBusinessLogic extends BaseBusinessLogic {
         return Either.left(categoryByTypeAndId.left().value());
     }
 
-    private Either<SubCategoryDefinition, ResponseFormat> validateSubCategoryExists(NodeTypeEnum nodeType, String subCategoryId, ComponentTypeEnum componentType) {
+    private Either<SubCategoryDefinition, ResponseFormat> validateSubCategoryExists(NodeTypeEnum nodeType, String subCategoryId,
+                                                                                    ComponentTypeEnum componentType) {
         Either<SubCategoryDefinition, ActionStatus> subCategoryByTypeAndId = elementOperation.getSubCategory(nodeType, subCategoryId);
         if (subCategoryByTypeAndId.isRight()) {
             log.debug("Failed to fetch parent category, parent categoryId {}", subCategoryId);
             ActionStatus actionStatus = subCategoryByTypeAndId.right().value();
             ResponseFormat responseFormat;
             if (actionStatus == ActionStatus.COMPONENT_CATEGORY_NOT_FOUND) {
-                responseFormat = componentsUtils.getResponseFormat(actionStatus, componentType.getValue().toLowerCase(), CategoryTypeEnum.SUBCATEGORY.getValue(), "");
+                responseFormat = componentsUtils
+                    .getResponseFormat(actionStatus, componentType.getValue().toLowerCase(), CategoryTypeEnum.SUBCATEGORY.getValue(), "");
             } else {
                 responseFormat = componentsUtils.getResponseFormat(actionStatus);
             }
@@ -898,22 +855,24 @@ public class ElementBusinessLogic extends BaseBusinessLogic {
         return Either.left(subCategoryByTypeAndId.left().value());
     }
 
-    private void handleCategoryAuditing(ResponseFormat responseFormat, User user, String category, AuditingActionEnum auditingAction, String componentType) {
+    private void handleCategoryAuditing(ResponseFormat responseFormat, User user, String category, AuditingActionEnum auditingAction,
+                                        String componentType) {
         componentsUtils.auditCategory(responseFormat, user, category, null, null, auditingAction, componentType);
     }
 
-    private void handleCategoryAuditing(ResponseFormat responseFormat, User user, String category, String subCategory, AuditingActionEnum auditingAction, String componentType) {
+    private void handleCategoryAuditing(ResponseFormat responseFormat, User user, String category, String subCategory,
+                                        AuditingActionEnum auditingAction, String componentType) {
         componentsUtils.auditCategory(responseFormat, user, category, subCategory, null, auditingAction, componentType);
     }
 
-    private void handleCategoryAuditing(ResponseFormat responseFormat, User user, String category, String subCategory, String grouping, AuditingActionEnum auditingAction, String componentType) {
+    private void handleCategoryAuditing(ResponseFormat responseFormat, User user, String category, String subCategory, String grouping,
+                                        AuditingActionEnum auditingAction, String componentType) {
         componentsUtils.auditCategory(responseFormat, user, category, subCategory, grouping, auditingAction, componentType);
     }
 
     /*
      * New categories flow - end
      */
-
     public Either<List<Tag>, ActionStatus> getAllTags(String userId) {
         ActionStatus status = validateUserExistsActionStatus(userId);
         if (ActionStatus.OK != status) {
@@ -942,19 +901,18 @@ public class ElementBusinessLogic extends BaseBusinessLogic {
         return elementOperation.getDefaultHeatTimeout();
     }
 
-       public Either<Map<String, List<CatalogComponent>>, ResponseFormat> getCatalogComponents(String userId, List<OriginTypeEnum> excludeTypes) {
+    public Either<Map<String, List<CatalogComponent>>, ResponseFormat> getCatalogComponents(String userId, List<OriginTypeEnum> excludeTypes) {
         try {
             return toscaOperationFacade.getCatalogOrArchiveComponents(true, excludeTypes)
-                    .bimap(this::groupByComponentType,
-                            err -> componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(err)));
+                .bimap(this::groupByComponentType, err -> componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(err)));
         } finally {
             janusGraphDao.commit();
         }
     }
 
     private Map<String, List<CatalogComponent>> groupByComponentType(List<CatalogComponent> components) {
-        Map<String, List<CatalogComponent>> map = components.stream().collect(Collectors.groupingBy(cmpt -> cmptTypeToString(cmpt.getComponentType())));
-
+        Map<String, List<CatalogComponent>> map = components.stream()
+            .collect(Collectors.groupingBy(cmpt -> cmptTypeToString(cmpt.getComponentType())));
         // fixed response for UI!!! UI need to receive always map!
         if (map == null) {
             map = new HashMap<>();
@@ -966,26 +924,26 @@ public class ElementBusinessLogic extends BaseBusinessLogic {
 
     private String cmptTypeToString(ComponentTypeEnum componentTypeEnum) {
         switch (componentTypeEnum) {
-        case RESOURCE:
-            return RESOURCES;
-        case SERVICE:
-            return SERVICES;
-        default:
-            throw new IllegalStateException("resources or services only");
+            case RESOURCE:
+                return RESOURCES;
+            case SERVICE:
+                return SERVICES;
+            default:
+                throw new IllegalStateException("resources or services only");
         }
     }
 
-    public Either<List<? extends Component>, ResponseFormat> getFilteredCatalogComponents(String assetType, Map<FilterKeyEnum, String> filters, String query) {
+    public Either<List<? extends Component>, ResponseFormat> getFilteredCatalogComponents(String assetType, Map<FilterKeyEnum, String> filters,
+                                                                                          String query) {
         ComponentTypeEnum assetTypeEnum = AssetTypeEnum.convertToComponentTypeEnum(assetType);
-
         if (query != null) {
             Optional<NameValuePair> invalidFilter = findInvalidFilter(query, assetTypeEnum);
             if (invalidFilter.isPresent()) {
                 log.debug("getFilteredAssetList: invalid filter key");
-                return Either.right(componentsUtils.getResponseFormat(ActionStatus.INVALID_FILTER_KEY, invalidFilter.get().getName(), FilterKeyEnum.getValidFiltersByAssetType(assetTypeEnum).toString()));
+                return Either.right(componentsUtils.getResponseFormat(ActionStatus.INVALID_FILTER_KEY, invalidFilter.get().getName(),
+                    FilterKeyEnum.getValidFiltersByAssetType(assetTypeEnum).toString()));
             }
         }
-
         if (filters == null || filters.isEmpty()) {
             Either<List<Component>, StorageOperationStatus> componentsList = toscaOperationFacade.getCatalogComponents(assetTypeEnum, null, false);
             if (componentsList.isRight()) {
@@ -993,38 +951,35 @@ public class ElementBusinessLogic extends BaseBusinessLogic {
             }
             return Either.left(componentsList.left().value());
         }
-
         Either<List<Component>, StorageOperationStatus> result = getFilteredComponents(filters, assetTypeEnum, false);
-
         // category hierarchy mismatch or category/subCategory/distributionStatus not found
         if (result.isRight()) {
             List<String> params = getErrorResponseParams(filters, assetTypeEnum);
-            return Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(result.right().value()), params.get(0), params.get(1), params.get(2)));
+            return Either.right(componentsUtils
+                .getResponseFormat(componentsUtils.convertFromStorageResponse(result.right().value()), params.get(0), params.get(1), params.get(2)));
         }
         if (result.left().value().isEmpty()) {// no assets found for requested
-                                              // criteria
+
+            // criteria
             return Either.right(componentsUtils.getResponseFormat(ActionStatus.NO_ASSETS_FOUND, assetType, query));
         }
         return Either.left(result.left().value());
     }
 
-    private Either<List<Component>, StorageOperationStatus> getFilteredComponents(Map<FilterKeyEnum, String> filters, ComponentTypeEnum assetType, boolean inTransaction) {
+    private Either<List<Component>, StorageOperationStatus> getFilteredComponents(Map<FilterKeyEnum, String> filters, ComponentTypeEnum assetType,
+                                                                                  boolean inTransaction) {
         Either<List<Component>, StorageOperationStatus> assetResult = Either.left(new LinkedList<>());
         if (assetType == ComponentTypeEnum.RESOURCE) {
-
             assetResult = getFilteredResources(filters, inTransaction);
-
         } else if (assetType == ComponentTypeEnum.SERVICE) {
-
             assetResult = getFilteredServices(filters, inTransaction);
         }
         return assetResult;
     }
 
-    private <T extends Component> Either<List<T>, StorageOperationStatus> getFilteredServices(Map<FilterKeyEnum, String> filters, boolean inTransaction) {
-
+    private <T extends Component> Either<List<T>, StorageOperationStatus> getFilteredServices(Map<FilterKeyEnum, String> filters,
+                                                                                              boolean inTransaction) {
         Either<List<T>, StorageOperationStatus> components = null;
-
         String categoryName = filters.get(FilterKeyEnum.CATEGORY);
         String distributionStatus = filters.get(FilterKeyEnum.DISTRIBUTION_STATUS);
         DistributionStatusEnum distEnum = DistributionStatusEnum.findState(distributionStatus);
@@ -1032,7 +987,6 @@ public class ElementBusinessLogic extends BaseBusinessLogic {
             filters.remove(FilterKeyEnum.CATEGORY);
             return Either.right(StorageOperationStatus.CATEGORY_NOT_FOUND);
         }
-
         if (categoryName != null) { // primary filter
             components = fetchByCategoryOrSubCategoryName(categoryName, NodeTypeEnum.ServiceNewCategory, NodeTypeEnum.Service, inTransaction, null);
             if (components.isLeft() && distEnum != null) {// secondary filter
@@ -1042,52 +996,44 @@ public class ElementBusinessLogic extends BaseBusinessLogic {
             filters.remove(FilterKeyEnum.DISTRIBUTION_STATUS);
             return components;
         }
-
         Set<DistributionStatusEnum> distStatusSet = new HashSet<>();
         distStatusSet.add(distEnum);
         Either<List<Service>, StorageOperationStatus> servicesWithDistStatus = toscaOperationFacade.getServicesWithDistStatus(distStatusSet, null);
         if (servicesWithDistStatus.isRight()) { // not found == empty list
             return Either.left(new ArrayList<>());
         }
-
         return Either.left((List<T>) servicesWithDistStatus.left().value());
     }
 
     public Either<List<? extends Component>, ResponseFormat> getCatalogComponentsByUuidAndAssetType(String assetType, String uuid) {
-
         if (assetType == null || uuid == null) {
             log.debug("getCatalogComponentsByUuidAndAssetType: One of the function parameteres is null");
             return Either.right(componentsUtils.getResponseFormat(ActionStatus.INVALID_CONTENT));
         }
-
         ComponentTypeEnum assetTypeEnum = AssetTypeEnum.convertToComponentTypeEnum(assetType);
-
         if (assetTypeEnum == null) {
             log.debug("getCatalogComponentsByUuidAndAssetType: Corresponding ComponentTypeEnum not found");
             return Either.right(componentsUtils.getResponseFormat(ActionStatus.INVALID_CONTENT));
         }
-
         Map<GraphPropertyEnum, Object> additionalPropertiesToMatch = new EnumMap<>(GraphPropertyEnum.class);
-
         switch (assetTypeEnum) {
-        case RESOURCE:
-            additionalPropertiesToMatch.put(GraphPropertyEnum.COMPONENT_TYPE, ComponentTypeEnum.RESOURCE.name());
-            break;
-        case SERVICE:
-            additionalPropertiesToMatch.put(GraphPropertyEnum.COMPONENT_TYPE, ComponentTypeEnum.SERVICE.name());
-            break;
-        default:
-            log.debug("getCatalogComponentsByUuidAndAssetType: Corresponding ComponentTypeEnum not allowed for this API");
-            return Either.right(componentsUtils.getResponseFormat(ActionStatus.INVALID_CONTENT));
-        }
-
-        Either<List<Component>, StorageOperationStatus> componentsListByUuid = toscaOperationFacade.getComponentListByUuid(uuid, additionalPropertiesToMatch);
+            case RESOURCE:
+                additionalPropertiesToMatch.put(GraphPropertyEnum.COMPONENT_TYPE, ComponentTypeEnum.RESOURCE.name());
+                break;
+            case SERVICE:
+                additionalPropertiesToMatch.put(GraphPropertyEnum.COMPONENT_TYPE, ComponentTypeEnum.SERVICE.name());
+                break;
+            default:
+                log.debug("getCatalogComponentsByUuidAndAssetType: Corresponding ComponentTypeEnum not allowed for this API");
+                return Either.right(componentsUtils.getResponseFormat(ActionStatus.INVALID_CONTENT));
+        }
+        Either<List<Component>, StorageOperationStatus> componentsListByUuid = toscaOperationFacade
+            .getComponentListByUuid(uuid, additionalPropertiesToMatch);
         if (componentsListByUuid.isRight()) {
             log.debug("getCatalogComponentsByUuidAndAssetType: " + assetTypeEnum.getValue() + " fetching failed");
             ActionStatus actionStatus = componentsUtils.convertFromStorageResponse(componentsListByUuid.right().value(), assetTypeEnum);
             return Either.right(componentsUtils.getResponseFormat(actionStatus, uuid));
         }
-
         log.debug("getCatalogComponentsByUuidAndAssetType: " + assetTypeEnum.getValue() + assetTypeEnum.getValue() + "fetching successful");
         return Either.left(componentsListByUuid.left().value());
     }
@@ -1135,13 +1081,11 @@ public class ElementBusinessLogic extends BaseBusinessLogic {
     }
 
     public Either<List<Component>, StorageOperationStatus> getFilteredResources(Map<FilterKeyEnum, String> filters, boolean inTransaction) {
-
         String subCategoryName = filters.get(FilterKeyEnum.SUB_CATEGORY);
         String categoryName = filters.get(FilterKeyEnum.CATEGORY);
         ResourceTypeEnum resourceType = ResourceTypeEnum.getType(filters.get(FilterKeyEnum.RESOURCE_TYPE));
         Either<List<ImmutablePair<SubCategoryData, GraphEdge>>, StorageOperationStatus> subcategories = null;
         Optional<ImmutablePair<SubCategoryData, GraphEdge>> subCategoryData;
-
         if (categoryName != null) {
             subcategories = getAllSubCategories(categoryName);
             if (subcategories.isRight()) {
@@ -1155,10 +1099,11 @@ public class ElementBusinessLogic extends BaseBusinessLogic {
                 if (!subCategoryData.isPresent()) {
                     return Either.right(StorageOperationStatus.MATCH_NOT_FOUND);
                 }
-                return fetchByCategoryOrSubCategoryUid(subCategoryData.get().getLeft().getUniqueId(), NodeTypeEnum.Resource, inTransaction, resourceType);
+                return fetchByCategoryOrSubCategoryUid(subCategoryData.get().getLeft().getUniqueId(), NodeTypeEnum.Resource, inTransaction,
+                    resourceType);
             }
-
-            return fetchByCategoryOrSubCategoryName(subCategoryName, NodeTypeEnum.ResourceSubcategory, NodeTypeEnum.Resource, inTransaction, resourceType);
+            return fetchByCategoryOrSubCategoryName(subCategoryName, NodeTypeEnum.ResourceSubcategory, NodeTypeEnum.Resource, inTransaction,
+                resourceType);
         }
         if (subcategories != null) {
             return fetchByMainCategory(subcategories.left().value(), inTransaction, resourceType);
@@ -1167,12 +1112,12 @@ public class ElementBusinessLogic extends BaseBusinessLogic {
     }
 
     private Either<List<ImmutablePair<SubCategoryData, GraphEdge>>, StorageOperationStatus> getAllSubCategories(String categoryName) {
-        Either<CategoryData, StorageOperationStatus> categoryResult = elementOperation.getNewCategoryData(categoryName, NodeTypeEnum.ResourceNewCategory, CategoryData.class);
+        Either<CategoryData, StorageOperationStatus> categoryResult = elementOperation
+            .getNewCategoryData(categoryName, NodeTypeEnum.ResourceNewCategory, CategoryData.class);
         if (categoryResult.isRight()) {
             return Either.right(categoryResult.right().value());
         }
         CategoryData categoryData = categoryResult.left().value();
-
         Either<List<ImmutablePair<SubCategoryData, GraphEdge>>, JanusGraphOperationStatus> childrenNodes = janusGraphGenericDao
             .getChildrenNodes(UniqueIdBuilder.getKeyByNodeType(NodeTypeEnum.ResourceNewCategory), (String) categoryData.getUniqueId(),
                 GraphEdgeLabels.SUB_CATEGORY, NodeTypeEnum.ResourceSubcategory, SubCategoryData.class);
@@ -1182,12 +1127,17 @@ public class ElementBusinessLogic extends BaseBusinessLogic {
         return Either.left(childrenNodes.left().value());
     }
 
-    private Optional<ImmutablePair<SubCategoryData, GraphEdge>> validateCategoryHierarcy(List<ImmutablePair<SubCategoryData, GraphEdge>> childNodes, String subCategoryName) {
-        Predicate<ImmutablePair<SubCategoryData, GraphEdge>> matchName = p -> p.getLeft().getSubCategoryDataDefinition().getName().equals(subCategoryName);
+    private Optional<ImmutablePair<SubCategoryData, GraphEdge>> validateCategoryHierarcy(List<ImmutablePair<SubCategoryData, GraphEdge>> childNodes,
+                                                                                         String subCategoryName) {
+        Predicate<ImmutablePair<SubCategoryData, GraphEdge>> matchName = p -> p.getLeft().getSubCategoryDataDefinition().getName()
+            .equals(subCategoryName);
         return childNodes.stream().filter(matchName).findAny();
     }
 
-    protected <T extends Component> Either<List<T>, StorageOperationStatus> fetchByCategoryOrSubCategoryUid(String categoryUid, NodeTypeEnum categoryType, boolean inTransaction, ResourceTypeEnum resourceType) {
+    protected <T extends Component> Either<List<T>, StorageOperationStatus> fetchByCategoryOrSubCategoryUid(String categoryUid,
+                                                                                                            NodeTypeEnum categoryType,
+                                                                                                            boolean inTransaction,
+                                                                                                            ResourceTypeEnum resourceType) {
         try {
             return collectComponents(categoryType, categoryUid, resourceType);
         } finally {
@@ -1197,7 +1147,11 @@ public class ElementBusinessLogic extends BaseBusinessLogic {
         }
     }
 
-    protected <T extends Component> Either<List<T>, StorageOperationStatus> fetchByCategoryOrSubCategoryName(String categoryName, NodeTypeEnum categoryType, NodeTypeEnum neededType, boolean inTransaction, ResourceTypeEnum resourceType) {
+    protected <T extends Component> Either<List<T>, StorageOperationStatus> fetchByCategoryOrSubCategoryName(String categoryName,
+                                                                                                             NodeTypeEnum categoryType,
+                                                                                                             NodeTypeEnum neededType,
+                                                                                                             boolean inTransaction,
+                                                                                                             ResourceTypeEnum resourceType) {
         List<T> components = new ArrayList<>();
         try {
             Class categoryClazz = categoryType == NodeTypeEnum.ServiceNewCategory ? CategoryData.class : SubCategoryData.class;
@@ -1211,11 +1165,11 @@ public class ElementBusinessLogic extends BaseBusinessLogic {
                 Either<List<T>, StorageOperationStatus> result = collectComponents(neededType, category.getUniqueId(), resourceType);
                 if (result.isRight() && result.right().value() != StorageOperationStatus.NOT_FOUND) {
                     return result;
-                } else if (result.isLeft()){
+                } else if (result.isLeft()) {
                     components.addAll(result.left().value());
                 }
             }
-            if (components.isEmpty()){
+            if (components.isEmpty()) {
                 return Either.right(StorageOperationStatus.NOT_FOUND);
             }
             return Either.left(components);
@@ -1226,36 +1180,35 @@ public class ElementBusinessLogic extends BaseBusinessLogic {
         }
     }
 
-
-    private <T extends Component> Either<List<T>, StorageOperationStatus> collectComponents(NodeTypeEnum neededType, String categoryUid, ResourceTypeEnum resourceType) {
+    private <T extends Component> Either<List<T>, StorageOperationStatus> collectComponents(NodeTypeEnum neededType, String categoryUid,
+                                                                                            ResourceTypeEnum resourceType) {
         List<T> components = new ArrayList<>();
         Either<GraphVertex, JanusGraphOperationStatus> categoryVertexById = janusGraphDao.getVertexById(categoryUid, JsonParseFlagEnum.NoParse);
-        if (categoryVertexById.isRight()){
+        if (categoryVertexById.isRight()) {
             JanusGraphOperationStatus status = categoryVertexById.right().value();
             log.debug("#collectComponents Failed to get category vertex with uid {}, status is {}.", categoryUid, status);
             return Either.right(DaoStatusConverter.convertJanusGraphStatusToStorageStatus(status));
         }
         GraphVertex categoryVertex = categoryVertexById.left().value();
-        Either<List<GraphVertex>, JanusGraphOperationStatus> componentsVertices = janusGraphDao.getParentVertices(categoryVertex, EdgeLabelEnum.CATEGORY, JsonParseFlagEnum.ParseMetadata);
-        if (componentsVertices.isRight()){
+        Either<List<GraphVertex>, JanusGraphOperationStatus> componentsVertices = janusGraphDao
+            .getParentVertices(categoryVertex, EdgeLabelEnum.CATEGORY, JsonParseFlagEnum.ParseMetadata);
+        if (componentsVertices.isRight()) {
             JanusGraphOperationStatus status = componentsVertices.right().value();
             log.debug("#collectComponents Failed to get components vertices of category {}, status is {}.", categoryVertex, status);
             return Either.right(DaoStatusConverter.convertJanusGraphStatusToStorageStatus(status));
         }
-        List<ComponentMetadataDataDefinition> componentsMetadataDataDefinition = componentsVertices.left().value()
-                .stream()
-                .filter(Objects::nonNull)
-                .filter(componentsVertex -> Objects.nonNull(componentsVertex.getType()))
-                .map(ModelConverter::convertToComponentMetadataDataDefinition)
-                .collect(Collectors.toList());
+        List<ComponentMetadataDataDefinition> componentsMetadataDataDefinition = componentsVertices.left().value().stream().filter(Objects::nonNull)
+            .filter(componentsVertex -> Objects.nonNull(componentsVertex.getType())).map(ModelConverter::convertToComponentMetadataDataDefinition)
+            .collect(Collectors.toList());
         for (ComponentMetadataDataDefinition component : componentsMetadataDataDefinition) {
             boolean isHighest = isTrue(component.isHighestVersion());
             boolean isMatchingResourceType = isMatchingByResourceType(neededType, resourceType, component);
             boolean isDeleted = isTrue(component.isDeleted());
             boolean isArchived = isTrue(component.isArchived());
             if (isHighest && isMatchingResourceType && !isDeleted && !isArchived) {
-                Either<T, StorageOperationStatus> result = toscaOperationFacade.getToscaElement(component.getUniqueId(), JsonParseFlagEnum.ParseMetadata);
-                 if (result.isRight()) {
+                Either<T, StorageOperationStatus> result = toscaOperationFacade
+                    .getToscaElement(component.getUniqueId(), JsonParseFlagEnum.ParseMetadata);
+                if (result.isRight()) {
                     return Either.right(result.right().value());
                 }
                 components.add(result.left().value());
@@ -1264,8 +1217,8 @@ public class ElementBusinessLogic extends BaseBusinessLogic {
         return Either.left(components);
     }
 
-    private boolean isMatchingByResourceType(NodeTypeEnum componentType, ResourceTypeEnum resourceType, ComponentMetadataDataDefinition componentData) {
-
+    private boolean isMatchingByResourceType(NodeTypeEnum componentType, ResourceTypeEnum resourceType,
+                                             ComponentMetadataDataDefinition componentData) {
         boolean isMatching;
         if (componentType == NodeTypeEnum.Resource) {
             if (resourceType == null) {
@@ -1279,12 +1232,12 @@ public class ElementBusinessLogic extends BaseBusinessLogic {
         return isMatching;
     }
 
-    private <T extends Component> Either<List<T>, StorageOperationStatus> fetchByMainCategory(List<ImmutablePair<SubCategoryData, GraphEdge>> subcategories, boolean inTransaction, ResourceTypeEnum resourceType) {
+    private <T extends Component> Either<List<T>, StorageOperationStatus> fetchByMainCategory(
+        List<ImmutablePair<SubCategoryData, GraphEdge>> subcategories, boolean inTransaction, ResourceTypeEnum resourceType) {
         List<T> components = new ArrayList<>();
-
         for (ImmutablePair<SubCategoryData, GraphEdge> subCategory : subcategories) {
-            Either<List<T>, StorageOperationStatus> fetched = fetchByCategoryOrSubCategoryUid(subCategory.getLeft().getUniqueId(), NodeTypeEnum.Resource,
-                    inTransaction, resourceType);
+            Either<List<T>, StorageOperationStatus> fetched = fetchByCategoryOrSubCategoryUid(subCategory.getLeft().getUniqueId(),
+                NodeTypeEnum.Resource, inTransaction, resourceType);
             if (fetched.isRight()) {
                 continue;
             }
@@ -1299,8 +1252,10 @@ public class ElementBusinessLogic extends BaseBusinessLogic {
         Wrapper<StorageOperationStatus> statusWrapper = new Wrapper<>();
         Either<List<Component>, StorageOperationStatus> result;
         try {
-            ComponentParametersView fetchUsersAndCategoriesFilter = new ComponentParametersView(Arrays.asList(ComponentFieldsEnum.USERS.getValue(), ComponentFieldsEnum.CATEGORIES.getValue()));
-            Either<List<Component>, StorageOperationStatus> getResources = toscaOperationFacade.fetchMetaDataByResourceType(resourceType, fetchUsersAndCategoriesFilter);
+            ComponentParametersView fetchUsersAndCategoriesFilter = new ComponentParametersView(
+                Arrays.asList(ComponentFieldsEnum.USERS.getValue(), ComponentFieldsEnum.CATEGORIES.getValue()));
+            Either<List<Component>, StorageOperationStatus> getResources = toscaOperationFacade
+                .fetchMetaDataByResourceType(resourceType, fetchUsersAndCategoriesFilter);
             if (getResources.isRight()) {
                 status = getResources.right().value();
                 if (status != StorageOperationStatus.NOT_FOUND) {
@@ -1324,15 +1279,11 @@ public class ElementBusinessLogic extends BaseBusinessLogic {
         }
     }
 
-
     public CatalogUpdateTimestamp getCatalogUpdateTime(String userId) {
-
-        try{
+        try {
             return toscaOperationFacade.getCatalogTimes();
-
         } finally {
             janusGraphDao.commit();
         }
-
     }
 }
index 2c824c8..acd19e4 100644 (file)
@@ -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.
  * limitations under the License.
  * ============LICENSE_END=========================================================
  */
-
 package org.openecomp.sdc.be.components.impl;
 
 import fj.data.Either;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
 import org.openecomp.sdc.be.components.impl.exceptions.ByActionStatusComponentException;
 import org.openecomp.sdc.be.components.impl.lock.LockingTransactional;
 import org.openecomp.sdc.be.components.validation.AccessValidations;
@@ -34,10 +36,6 @@ import org.openecomp.sdc.be.model.jsonjanusgraph.operations.ToscaOperationFacade
 import org.openecomp.sdc.be.model.operations.api.StorageOperationStatus;
 import org.openecomp.sdc.common.log.wrappers.Logger;
 
-import java.util.HashMap;
-import java.util.List;
-import java.util.Map;
-
 /**
  * Created by yavivi on 04/02/2018.
  */
@@ -45,20 +43,21 @@ import java.util.Map;
 public class ExternalRefsBusinessLogic {
 
     private static final Logger log = Logger.getLogger(ExternalRefsBusinessLogic.class);
-
     private final ExternalReferencesOperation externalReferencesOperation;
     private final ToscaOperationFacade toscaOperationFacade;
     private final AccessValidations accessValidations;
     private final ComponentLocker componentLocker;
 
-    public ExternalRefsBusinessLogic(ExternalReferencesOperation externalReferencesOperation, ToscaOperationFacade toscaOperationFacade, AccessValidations accessValidations, ComponentLocker componentLocker) {
+    public ExternalRefsBusinessLogic(ExternalReferencesOperation externalReferencesOperation, ToscaOperationFacade toscaOperationFacade,
+                                     AccessValidations accessValidations, ComponentLocker componentLocker) {
         this.externalReferencesOperation = externalReferencesOperation;
         this.toscaOperationFacade = toscaOperationFacade;
         this.accessValidations = accessValidations;
         this.componentLocker = componentLocker;
     }
 
-    public Either<List<String>, ActionStatus> getExternalReferences(String assetUuid, String version, String componentInstanceName, String objectType){
+    public Either<List<String>, ActionStatus> getExternalReferences(String assetUuid, String version, String componentInstanceName,
+                                                                    String objectType) {
         Either<Component, StorageOperationStatus> componentsResult = toscaOperationFacade.getComponentByUuidAndVersion(assetUuid, version);
         if (componentsResult == null || componentsResult.isRight()) {
             return Either.right(ActionStatus.RESOURCE_NOT_FOUND);
@@ -67,16 +66,15 @@ public class ExternalRefsBusinessLogic {
         return this.externalReferencesOperation.getExternalReferences(component.getUniqueId(), componentInstanceName, objectType);
     }
 
-    public Either<Map<String, List<String>>, ActionStatus> getExternalReferences(String assetUuid, String version, String objectType){
+    public Either<Map<String, List<String>>, ActionStatus> getExternalReferences(String assetUuid, String version, String objectType) {
         Either<Component, StorageOperationStatus> componentsResult = toscaOperationFacade.getComponentByUuidAndVersion(assetUuid, version);
         if (componentsResult == null || componentsResult.isRight()) {
             return Either.right(ActionStatus.RESOURCE_NOT_FOUND);
         }
-
         Component component = componentsResult.left().value();
-
-        Either<Map<String, List<String>>, ActionStatus> externalReferencesResult = this.externalReferencesOperation.getExternalReferences(component.getUniqueId(), objectType);
-        if (externalReferencesResult.isRight()){
+        Either<Map<String, List<String>>, ActionStatus> externalReferencesResult = this.externalReferencesOperation
+            .getExternalReferences(component.getUniqueId(), objectType);
+        if (externalReferencesResult.isRight()) {
             return Either.right(externalReferencesResult.right().value());
         } else {
             return Either.left(externalReferencesResult.left().value());
@@ -84,36 +82,38 @@ public class ExternalRefsBusinessLogic {
     }
 
     @LockingTransactional
-    public Either<String, ActionStatus> addExternalReference(String componentId, ComponentTypeEnum componentType, String userId, String componentInstanceName, String objectType, ExternalRefDTO ref) {
+    public Either<String, ActionStatus> addExternalReference(String componentId, ComponentTypeEnum componentType, String userId,
+                                                             String componentInstanceName, String objectType, ExternalRefDTO ref) {
         return this.doAction(componentId, componentType, userId, "POST", componentId, componentInstanceName, objectType, ref.getReferenceUUID(), "");
     }
 
     @LockingTransactional
-    public Either<String, ActionStatus> deleteExternalReference(String componentId, ComponentTypeEnum componentType, String userId, String componentInstanceName, String objectType, String reference) {
+    public Either<String, ActionStatus> deleteExternalReference(String componentId, ComponentTypeEnum componentType, String userId,
+                                                                String componentInstanceName, String objectType, String reference) {
         return this.doAction(componentId, componentType, userId, "DELETE", componentId, componentInstanceName, objectType, reference, "");
     }
 
     @LockingTransactional
-    public Either<String, ActionStatus> updateExternalReference(String componentId, ComponentTypeEnum componentType, String userId, String componentInstanceName, String objectType, String oldRefValue, String newRefValue) {
+    public Either<String, ActionStatus> updateExternalReference(String componentId, ComponentTypeEnum componentType, String userId,
+                                                                String componentInstanceName, String objectType, String oldRefValue,
+                                                                String newRefValue) {
         return this.doAction(componentId, componentType, userId, "PUT", componentId, componentInstanceName, objectType, oldRefValue, newRefValue);
     }
 
-    public String fetchComponentUniqueIdByUuid(String uuid, ComponentTypeEnum componentType){
-        Either<Component, StorageOperationStatus> latestServiceByUuid = toscaOperationFacade.getLatestComponentByUuid(uuid, createPropsToMatch(componentType));
-        if (latestServiceByUuid == null || latestServiceByUuid.isRight()){
+    public String fetchComponentUniqueIdByUuid(String uuid, ComponentTypeEnum componentType) {
+        Either<Component, StorageOperationStatus> latestServiceByUuid = toscaOperationFacade
+            .getLatestComponentByUuid(uuid, createPropsToMatch(componentType));
+        if (latestServiceByUuid == null || latestServiceByUuid.isRight()) {
             throw new ByActionStatusComponentException(ActionStatus.RESOURCE_NOT_FOUND, uuid);
         }
-
         //Get Component Unique ID
         Component component = latestServiceByUuid.left().value();
         return component.getUniqueId();
     }
 
-
-    public Either<String, ActionStatus> doAction(String componentId, ComponentTypeEnum componentType, String userId, String action, String uuid, String componentInstanceName, String objectType, String ref1, String ref2){
-
+    public Either<String, ActionStatus> doAction(String componentId, ComponentTypeEnum componentType, String userId, String action, String uuid,
+                                                 String componentInstanceName, String objectType, String ref1, String ref2) {
         accessValidations.validateUserCanWorkOnComponent(componentId, componentType, userId, action + " EXTERNAL REF");
-
         switch (action) {
             case "POST":
                 return this.externalReferencesOperation.addExternalReferenceWithCommit(componentId, componentInstanceName, objectType, ref1);
@@ -124,7 +124,6 @@ public class ExternalRefsBusinessLogic {
             default:
                 return Either.right(ActionStatus.GENERAL_ERROR);
         }
-
     }
 
     private Map<GraphPropertyEnum, Object> createPropsToMatch(ComponentTypeEnum componentType) {
@@ -132,5 +131,4 @@ public class ExternalRefsBusinessLogic {
         propertiesToMatch.put(GraphPropertyEnum.COMPONENT_TYPE, componentType.name());
         return propertiesToMatch;
     }
-
 }
index 4f092c6..1f9aad5 100644 (file)
@@ -17,7 +17,6 @@
  * limitations under the License.
  * ============LICENSE_END=========================================================
  */
-
 package org.openecomp.sdc.be.components.impl;
 
 import com.google.gson.Gson;
@@ -27,6 +26,8 @@ import com.google.gson.JsonElement;
 import com.google.gson.JsonObject;
 import com.google.gson.JsonSerializationContext;
 import com.google.gson.JsonSerializer;
+import java.io.IOException;
+import java.lang.reflect.Type;
 import org.onap.sdc.gab.GABService;
 import org.onap.sdc.gab.GABServiceImpl;
 import org.onap.sdc.gab.model.GABQuery;
@@ -41,24 +42,18 @@ import org.openecomp.sdc.be.model.operations.api.IGroupTypeOperation;
 import org.openecomp.sdc.be.model.operations.impl.InterfaceLifecycleOperation;
 import org.springframework.beans.factory.annotation.Autowired;
 
-import java.io.IOException;
-import java.lang.reflect.Type;
-
 @org.springframework.stereotype.Component
 public class GenericArtifactBrowserBusinessLogic extends BaseBusinessLogic {
 
     private GABService gabService;
 
     @Autowired
-    public GenericArtifactBrowserBusinessLogic(IElementOperation elementDao,
-        IGroupOperation groupOperation,
-        IGroupInstanceOperation groupInstanceOperation,
-        IGroupTypeOperation groupTypeOperation,
-        InterfaceOperation interfaceOperation,
-        InterfaceLifecycleOperation interfaceLifecycleTypeOperation,
-        ArtifactsOperations artifactToscaOperation) {
-        super(elementDao, groupOperation, groupInstanceOperation, groupTypeOperation,
-            interfaceOperation, interfaceLifecycleTypeOperation, artifactToscaOperation);
+    public GenericArtifactBrowserBusinessLogic(IElementOperation elementDao, IGroupOperation groupOperation,
+                                               IGroupInstanceOperation groupInstanceOperation, IGroupTypeOperation groupTypeOperation,
+                                               InterfaceOperation interfaceOperation, InterfaceLifecycleOperation interfaceLifecycleTypeOperation,
+                                               ArtifactsOperations artifactToscaOperation) {
+        super(elementDao, groupOperation, groupInstanceOperation, groupTypeOperation, interfaceOperation, interfaceLifecycleTypeOperation,
+            artifactToscaOperation);
         gabService = new GABServiceImpl();
     }
 
@@ -67,17 +62,15 @@ public class GenericArtifactBrowserBusinessLogic extends BaseBusinessLogic {
         return createGsonForGABResult().toJson(gabResults);
     }
 
-    private Gson createGsonForGABResult(){
-        return new GsonBuilder().setPrettyPrinting()
-            .registerTypeAdapter(GABResult.class, new GABResultSerializer())
-            .registerTypeAdapter(GABResults.class, new GABResultsSerializer())
-            .create();
+    private Gson createGsonForGABResult() {
+        return new GsonBuilder().setPrettyPrinting().registerTypeAdapter(GABResult.class, new GABResultSerializer())
+            .registerTypeAdapter(GABResults.class, new GABResultsSerializer()).create();
     }
 
     private class GABResultsSerializer implements JsonSerializer<GABResults> {
+
         @Override
-        public JsonElement serialize(GABResults gabResults, Type type,
-            JsonSerializationContext jsonSerializationContext) {
+        public JsonElement serialize(GABResults gabResults, Type type, JsonSerializationContext jsonSerializationContext) {
             JsonObject result = new JsonObject();
             JsonArray jsonArray = new JsonArray();
             gabResults.getRows().stream().map(jsonSerializationContext::serialize).forEach(jsonArray::add);
@@ -87,6 +80,7 @@ public class GenericArtifactBrowserBusinessLogic extends BaseBusinessLogic {
     }
 
     private class GABResultSerializer implements JsonSerializer<GABResult> {
+
         @Override
         public JsonElement serialize(GABResult gabResult, Type type, JsonSerializationContext jsonSerializationContext) {
             JsonObject result = new JsonObject();
@@ -94,5 +88,4 @@ public class GenericArtifactBrowserBusinessLogic extends BaseBusinessLogic {
             return result;
         }
     }
-
 }
index fe9d448..fee80c6 100644 (file)
  * Modifications copyright (c) 2019 Nokia
  * ================================================================================
  */
-
 package org.openecomp.sdc.be.components.impl;
 
+import static java.util.stream.Collectors.toList;
+import static org.openecomp.sdc.be.model.jsonjanusgraph.utils.ModelConverter.extractCapabilitiesFromGroups;
+import static org.openecomp.sdc.be.model.jsonjanusgraph.utils.ModelConverter.extractCapabilityPropertiesFromGroups;
+
 import fj.data.Either;
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.Collection;
+import java.util.Collections;
+import java.util.EnumMap;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+import java.util.Map.Entry;
+import java.util.Optional;
+import java.util.Set;
+import java.util.regex.Pattern;
+import java.util.stream.Collectors;
 import org.apache.commons.collections.CollectionUtils;
 import org.apache.commons.collections.MapUtils;
 import org.apache.commons.io.FilenameUtils;
@@ -89,68 +105,47 @@ import org.openecomp.sdc.common.util.ValidationUtils;
 import org.openecomp.sdc.exception.ResponseFormat;
 import org.springframework.beans.factory.annotation.Autowired;
 
-import java.util.ArrayList;
-import java.util.Arrays;
-import java.util.Collection;
-import java.util.Collections;
-import java.util.EnumMap;
-import java.util.HashMap;
-import java.util.List;
-import java.util.Map;
-import java.util.Map.Entry;
-import java.util.Optional;
-import java.util.Set;
-import java.util.regex.Pattern;
-import java.util.stream.Collectors;
-
-import static java.util.stream.Collectors.toList;
-import static org.openecomp.sdc.be.model.jsonjanusgraph.utils.ModelConverter.extractCapabilitiesFromGroups;
-import static org.openecomp.sdc.be.model.jsonjanusgraph.utils.ModelConverter.extractCapabilityPropertiesFromGroups;
-
 @org.springframework.stereotype.Component("groupBusinessLogic")
 public class GroupBusinessLogic extends BaseBusinessLogic {
 
     public static final String GROUP_DELIMITER_REGEX = "\\.\\.";
-
     public static final String INITIAL_VERSION = "0.0";
-
     private static final String ADDING_GROUP = "AddingGroup";
-
     private static final String CREATE_GROUP = "CreateGroup";
-
     private static final String UPDATE_GROUP = "UpdateGroup";
-
     private static final String GET_GROUP = "GetGroup";
-
     private static final String DELETE_GROUP = "DeleteGroup";
-
     private static final Logger log = Logger.getLogger(GroupBusinessLogic.class);
-
     private static final LoggerSupportability loggerSupportability = LoggerSupportability.getLogger(GroupBusinessLogic.class.getName());
-
     private final AccessValidations accessValidations;
     private final PolicyTargetsUpdateHandler policyTargetsUpdateHandler;
-
     @javax.annotation.Resource
     private final GroupsOperation groupsOperation;
 
-
     @Autowired
-    public GroupBusinessLogic(IElementOperation elementDao,
-        IGroupOperation groupOperation,
-        IGroupInstanceOperation groupInstanceOperation,
-        IGroupTypeOperation groupTypeOperation,
-        InterfaceOperation interfaceOperation,
-        InterfaceLifecycleOperation interfaceLifecycleTypeOperation, AccessValidations accessValidations,
-        GroupsOperation groupsOperation, PolicyTargetsUpdateHandler policyTargetsUpdateHandler,
-        ArtifactsOperations artifactToscaOperation) {
-        super(elementDao, groupOperation, groupInstanceOperation, groupTypeOperation,
-            interfaceOperation, interfaceLifecycleTypeOperation, artifactToscaOperation);
+    public GroupBusinessLogic(IElementOperation elementDao, IGroupOperation groupOperation, IGroupInstanceOperation groupInstanceOperation,
+                              IGroupTypeOperation groupTypeOperation, InterfaceOperation interfaceOperation,
+                              InterfaceLifecycleOperation interfaceLifecycleTypeOperation, AccessValidations accessValidations,
+                              GroupsOperation groupsOperation, PolicyTargetsUpdateHandler policyTargetsUpdateHandler,
+                              ArtifactsOperations artifactToscaOperation) {
+        super(elementDao, groupOperation, groupInstanceOperation, groupTypeOperation, interfaceOperation, interfaceLifecycleTypeOperation,
+            artifactToscaOperation);
         this.accessValidations = accessValidations;
         this.groupsOperation = groupsOperation;
         this.policyTargetsUpdateHandler = policyTargetsUpdateHandler;
     }
 
+    private static boolean groupExistsInComponent(String groupDefinitionName, Component component) {
+        boolean found = false;
+        List<GroupDefinition> groups = component.getGroups();
+        if (CollectionUtils.isNotEmpty(groups)) {
+            found = groups.stream()
+                .filter(p -> (p.getName().equalsIgnoreCase(groupDefinitionName)) || p.getInvariantName().equalsIgnoreCase(groupDefinitionName))
+                .findFirst().orElse(null) != null;
+        }
+        return found;
+    }
+
     private String getComponentTypeForResponse(org.openecomp.sdc.be.model.Component component) {
         String componentTypeForResponse = "SERVICE";
         if (component instanceof Resource) {
@@ -167,26 +162,23 @@ public class GroupBusinessLogic extends BaseBusinessLogic {
      * @return
      */
     private Either<Boolean, ResponseFormat> verifyArtifactsBelongsToComponent(Component component, List<String> artifacts, String context) {
-
         if (CollectionUtils.isEmpty(artifacts)) {
             return Either.left(true);
         }
-
         Map<String, ArtifactDefinition> deploymentArtifacts = component.getDeploymentArtifacts();
         if (MapUtils.isEmpty(deploymentArtifacts)) {
-            BeEcompErrorManager.getInstance().logInvalidInputError(context, "No deployment artifact found under component " + component.getNormalizedName(), ErrorSeverity.INFO);
+            BeEcompErrorManager.getInstance()
+                .logInvalidInputError(context, "No deployment artifact found under component " + component.getNormalizedName(), ErrorSeverity.INFO);
             return Either.right(componentsUtils.getResponseFormat(ActionStatus.INVALID_CONTENT));
         }
-
         List<String> currentArtifacts = deploymentArtifacts.values().stream().map(ArtifactDefinition::getUniqueId).collect(toList());
         log.debug("The deployment artifacts of component {} are {}", component.getNormalizedName(), deploymentArtifacts);
         if (!currentArtifacts.containsAll(artifacts)) {
-            BeEcompErrorManager.getInstance().logInvalidInputError(context, "Not all artifacts belongs to component " + component.getNormalizedName(), ErrorSeverity.INFO);
+            BeEcompErrorManager.getInstance()
+                .logInvalidInputError(context, "Not all artifacts belongs to component " + component.getNormalizedName(), ErrorSeverity.INFO);
             return Either.right(componentsUtils.getResponseFormat(ActionStatus.INVALID_CONTENT));
         }
-
         return Either.left(true);
-
     }
 
     /**
@@ -197,43 +189,38 @@ public class GroupBusinessLogic extends BaseBusinessLogic {
      * @param memberToscaTypes
      * @return
      */
-    private Either<Boolean, ResponseFormat> verifyComponentInstancesAreValidMembers(Component component, String groupName, Map<String, String> groupMembers, List<String> memberToscaTypes) {
-
+    private Either<Boolean, ResponseFormat> verifyComponentInstancesAreValidMembers(Component component, String groupName,
+                                                                                    Map<String, String> groupMembers, List<String> memberToscaTypes) {
         if (MapUtils.isEmpty(groupMembers)) {
             return Either.left(true);
         }
-
         if (CollectionUtils.isEmpty(memberToscaTypes)) {
             return Either.left(true);
         }
-
         List<ComponentInstance> componentInstances = component.getComponentInstances();
         if (CollectionUtils.isNotEmpty(componentInstances)) {
-            Map<String, ComponentInstance> compInstUidToCompInstMap = componentInstances.stream().collect(Collectors.toMap(ComponentInstance::getUniqueId, p -> p));
-
+            Map<String, ComponentInstance> compInstUidToCompInstMap = componentInstances.stream()
+                .collect(Collectors.toMap(ComponentInstance::getUniqueId, p -> p));
             Set<String> allCompInstances = compInstUidToCompInstMap.keySet();
-
             for (Entry<String, String> groupMember : groupMembers.entrySet()) {
                 String compName = groupMember.getKey();
                 String compUid = groupMember.getValue();
-
                 if (!allCompInstances.contains(compUid)) {
                     /*
                      * %1 - member name %2 - group name %3 - VF name %4 - component type [VF ]
                      */
                     String componentTypeForResponse = getComponentTypeForResponse(component);
-
-                    BeEcompErrorManager.getInstance().logInvalidInputError(CREATE_GROUP, "Not all group members exists under the component", ErrorSeverity.INFO);
-                    return Either.right(componentsUtils.getResponseFormat(ActionStatus.GROUP_INVALID_COMPONENT_INSTANCE, compName, groupName, component.getNormalizedName(), componentTypeForResponse));
+                    BeEcompErrorManager.getInstance()
+                        .logInvalidInputError(CREATE_GROUP, "Not all group members exists under the component", ErrorSeverity.INFO);
+                    return Either.right(componentsUtils
+                        .getResponseFormat(ActionStatus.GROUP_INVALID_COMPONENT_INSTANCE, compName, groupName, component.getNormalizedName(),
+                            componentTypeForResponse));
                 }
             }
         }
-
         return Either.left(true);
     }
 
-
-
     /**
      * Update GroupDefinition metadata
      *
@@ -244,8 +231,9 @@ public class GroupBusinessLogic extends BaseBusinessLogic {
      * @param inTransaction
      * @return
      */
-    public Either<GroupDefinition, ResponseFormat> validateAndUpdateGroupMetadata(String componentId, User user, ComponentTypeEnum componentType, GroupDefinition updatedGroup, boolean inTransaction , boolean shouldLock) {
-
+    public Either<GroupDefinition, ResponseFormat> validateAndUpdateGroupMetadata(String componentId, User user, ComponentTypeEnum componentType,
+                                                                                  GroupDefinition updatedGroup, boolean inTransaction,
+                                                                                  boolean shouldLock) {
         Either<GroupDefinition, ResponseFormat> result = null;
         boolean failed = false;
         try {
@@ -257,35 +245,40 @@ public class GroupBusinessLogic extends BaseBusinessLogic {
             validateCanWorkOnComponent(component, user.getUserId());
             List<GroupDefinition> currentGroups = component.getGroups();
             if (CollectionUtils.isEmpty(currentGroups)) {
-                log.error("Failed to update the metadata of group {} on component {}. The status is {}. ", updatedGroup.getName(), component.getName(), ActionStatus.GROUP_IS_MISSING);
-                result = Either.right(componentsUtils.getResponseFormat(ActionStatus.GROUP_IS_MISSING, updatedGroup.getName(), component.getName(), component.getComponentType().getValue()));
+                log.error("Failed to update the metadata of group {} on component {}. The status is {}. ", updatedGroup.getName(),
+                    component.getName(), ActionStatus.GROUP_IS_MISSING);
+                result = Either.right(componentsUtils.getResponseFormat(ActionStatus.GROUP_IS_MISSING, updatedGroup.getName(), component.getName(),
+                    component.getComponentType().getValue()));
                 return result;
             }
             // Validate groups exists in the component
-            Optional<GroupDefinition> currentGroupOpt = currentGroups.stream().filter(g -> g.getUniqueId().equals(updatedGroup.getUniqueId())).findAny();
+            Optional<GroupDefinition> currentGroupOpt = currentGroups.stream().filter(g -> g.getUniqueId().equals(updatedGroup.getUniqueId()))
+                .findAny();
             if (!currentGroupOpt.isPresent()) {
-                log.error("Failed to update the metadata of group {} on component {}. The status is {}. ", updatedGroup.getName(), component.getName(), ActionStatus.GROUP_IS_MISSING);
-                result = Either.right(componentsUtils.getResponseFormat(ActionStatus.GROUP_IS_MISSING, updatedGroup.getName(), component.getName(), component.getComponentType().getValue()));
+                log.error("Failed to update the metadata of group {} on component {}. The status is {}. ", updatedGroup.getName(),
+                    component.getName(), ActionStatus.GROUP_IS_MISSING);
+                result = Either.right(componentsUtils.getResponseFormat(ActionStatus.GROUP_IS_MISSING, updatedGroup.getName(), component.getName(),
+                    component.getComponentType().getValue()));
                 return result;
             }
             GroupDefinition currentGroup = currentGroupOpt.get();
-            if ( shouldLock ){
+            if (shouldLock) {
                 lockComponent(componentId, component, "Update GroupDefinition Metadata");
             }
             // Validate group type is vfModule
             if (currentGroup.getType().equals(Constants.GROUP_TOSCA_HEAT)) {
-                log.error("Failed to update the metadata of group {}. Group type is {} and cannot be updated", currentGroup.getName(), currentGroup.getType());
+                log.error("Failed to update the metadata of group {}. Group type is {} and cannot be updated", currentGroup.getName(),
+                    currentGroup.getType());
                 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.GROUP_TYPE_IS_INVALID, updatedGroup.getType());
                 result = Either.right(responseFormat);
                 return result;
             }
             result = updateGroupMetadata(component, currentGroup, updatedGroup);
             return result;
-
-        }catch (ComponentException e){
+        } catch (ComponentException e) {
             failed = true;
             throw e;
-        }finally {
+        } finally {
             if (!failed) {
                 janusGraphDao.commit();
             } else {
@@ -297,10 +290,10 @@ public class GroupBusinessLogic extends BaseBusinessLogic {
         }
     }
 
-    private Either<GroupDefinition, ResponseFormat> updateGroupMetadata(Component component, GroupDefinition currentGroup, GroupDefinition updatedGroup) {
+    private Either<GroupDefinition, ResponseFormat> updateGroupMetadata(Component component, GroupDefinition currentGroup,
+                                                                        GroupDefinition updatedGroup) {
         String currentGroupName = currentGroup.getName();
         Either<GroupDefinition, ResponseFormat> result = validateAndUpdateGroupMetadata(currentGroup, updatedGroup);
-
         if (result.isRight()) {
             log.debug("Failed to validate a metadata of the group {} on component {}. ", updatedGroup.getName(), component.getName());
         }
@@ -338,14 +331,12 @@ public class GroupBusinessLogic extends BaseBusinessLogic {
             ResponseFormat errorResponse = response.right().value();
             return Either.right(errorResponse);
         }
-
         // Do not allow to update GroupDefinition version directly.
         String versionUpdated = groupUpdate.getVersion();
         String versionCurrent = currentGroup.getVersion();
         if (versionUpdated != null && !versionCurrent.equals(versionUpdated)) {
             log.info("update Group: recived request to update version to {} the field is not updatable ignoring.", versionUpdated);
         }
-
         return Either.left(currentGroup);
     }
 
@@ -360,7 +351,7 @@ public class GroupBusinessLogic extends BaseBusinessLogic {
         String nameUpdated = groupUpdate.getName();
         String nameCurrent = currentGroup.getName();
         if (!nameCurrent.equals(nameUpdated)) {
-            Either<Boolean, ResponseFormat> validatNameResponse = validateGroupName(currentGroup.getName(), groupUpdate.getName() ,true);
+            Either<Boolean, ResponseFormat> validatNameResponse = validateGroupName(currentGroup.getName(), groupUpdate.getName()true);
             if (validatNameResponse.isRight()) {
                 ResponseFormat errorRespons = validatNameResponse.right().value();
                 return Either.right(errorRespons);
@@ -371,44 +362,41 @@ public class GroupBusinessLogic extends BaseBusinessLogic {
     }
 
     /**
-     * Validate that group name to update is valid (same as current group name except for middle part). For example: Current group name: MyResource..MyDesc..Module-1 Group to update: MyResource..MyDesc2..Module-1 Verify that only the second part
-     * MyDesc was changed.
+     * Validate that group name to update is valid (same as current group name except for middle part). For example: Current group name:
+     * MyResource..MyDesc..Module-1 Group to update: MyResource..MyDesc2..Module-1 Verify that only the second part MyDesc was changed.
      *
      * @param currentGroupName
      * @param groupUpdateName
      * @return
      */
-    private Either<Boolean, ResponseFormat> validateGroupName(String currentGroupName, String groupUpdateName , boolean isforceNameModification) {
+    private Either<Boolean, ResponseFormat> validateGroupName(String currentGroupName, String groupUpdateName, boolean isforceNameModification) {
         try {
             // Check if the group name is in old format.
             if (Pattern.compile(Constants.MODULE_OLD_NAME_PATTERN).matcher(groupUpdateName).matches()) {
                 log.error("Group name {} is in old format", groupUpdateName);
                 return Either.right(componentsUtils.getResponseFormat(ActionStatus.INVALID_VF_MODULE_NAME, groupUpdateName));
             }
-
             // Check that name pats 1 and 3 did not changed (only the second
+
             // part can be changed)
+
             // But verify before that the current group format is the new one
             if (!Pattern.compile(Constants.MODULE_OLD_NAME_PATTERN).matcher(currentGroupName).matches()) {
                 String[] split1 = currentGroupName.split(GROUP_DELIMITER_REGEX);
                 String currentResourceName = split1[0];
                 String currentCounter = split1[2];
-
                 String[] split2 = groupUpdateName.split(GROUP_DELIMITER_REGEX);
                 String groupUpdateResourceName = split2[0];
                 String groupUpdateCounter = split2[2];
-                if (!isforceNameModification){            //if not forced ,allow name prefix&suffix validation [no changes]
+                if (!isforceNameModification) {            //if not forced ,allow name prefix&suffix validation [no changes]
                     if (!currentResourceName.equals(groupUpdateResourceName)) {
                         return Either.right(componentsUtils.getResponseFormat(ActionStatus.INVALID_VF_MODULE_NAME_MODIFICATION, currentResourceName));
                     }
-
                     if (!currentCounter.equals(groupUpdateCounter)) {
                         return Either.right(componentsUtils.getResponseFormat(ActionStatus.INVALID_VF_MODULE_NAME_MODIFICATION, currentCounter));
                     }
                 }
-
             }
-
             return Either.left(true);
         } catch (Exception e) {
             log.error("Error valiadting group name", e);
@@ -416,7 +404,6 @@ public class GroupBusinessLogic extends BaseBusinessLogic {
         }
     }
 
-
     /**
      * associate artifacts to a given group
      *
@@ -426,59 +413,54 @@ public class GroupBusinessLogic extends BaseBusinessLogic {
      * @param inTransaction
      * @return
      */
-    public Either<GroupDefinitionInfo, ResponseFormat> getGroupWithArtifactsById(ComponentTypeEnum componentType, String componentId, String groupId, String userId, boolean inTransaction) {
-
+    public Either<GroupDefinitionInfo, ResponseFormat> getGroupWithArtifactsById(ComponentTypeEnum componentType, String componentId, String groupId,
+                                                                                 String userId, boolean inTransaction) {
         Either<GroupDefinitionInfo, ResponseFormat> result = null;
-
         // Validate user exist
         validateUserExists(userId);
         // Validate component exist
         org.openecomp.sdc.be.model.Component component = null;
-
         try {
             ComponentParametersView componentParametersView = new ComponentParametersView();
             componentParametersView.disableAll();
             componentParametersView.setIgnoreGroups(false);
             componentParametersView.setIgnoreArtifacts(false);
             componentParametersView.setIgnoreUsers(false);
-
             component = validateComponentExists(componentId, componentType, componentParametersView);
-
             Either<GroupDefinition, StorageOperationStatus> groupEither = findGroupOnComponent(component, groupId);
-
             if (groupEither.isRight()) {
                 log.debug("Failed to find group {} under component {}", groupId, component.getUniqueId());
-                BeEcompErrorManager.getInstance().logInvalidInputError(GET_GROUP, "group  " + groupId + " not found under component " + component.getUniqueId(), ErrorSeverity.INFO);
+                BeEcompErrorManager.getInstance()
+                    .logInvalidInputError(GET_GROUP, "group  " + groupId + " not found under component " + component.getUniqueId(),
+                        ErrorSeverity.INFO);
                 String componentTypeForResponse = getComponentTypeForResponse(component);
-                result = Either.right(componentsUtils.getResponseFormat(ActionStatus.GROUP_IS_MISSING, groupId, component.getSystemName(), componentTypeForResponse));
+                result = Either.right(
+                    componentsUtils.getResponseFormat(ActionStatus.GROUP_IS_MISSING, groupId, component.getSystemName(), componentTypeForResponse));
                 return result;
             }
             GroupDefinition group = groupEither.left().value();
-
             List<GroupProperty> props = group.convertToGroupProperties();
             Boolean isBase = isBaseProp(component, props);
-
             List<ArtifactDefinitionInfo> artifacts = new ArrayList<>();
             List<ArtifactDefinition> artifactsFromComponent = new ArrayList<>();
             List<String> artifactsIds = group.getArtifacts();
-
             Map<String, ArtifactDefinition> deploymentArtifacts = null;
             if (MapUtils.isNotEmpty(component.getDeploymentArtifacts())) {
-                deploymentArtifacts = component.getDeploymentArtifacts().values().stream().collect(Collectors.toMap(ArtifactDataDefinition::getUniqueId, a -> a));
+                deploymentArtifacts = component.getDeploymentArtifacts().values().stream()
+                    .collect(Collectors.toMap(ArtifactDataDefinition::getUniqueId, a -> a));
             }
-
             if (artifactsIds != null && !artifactsIds.isEmpty()) {
                 for (String id : artifactsIds) {
                     if (deploymentArtifacts == null || !deploymentArtifacts.containsKey(id)) {
                         log.debug("Failed to get artifact {} . Status is {} ", id, StorageOperationStatus.NOT_FOUND);
-                        ResponseFormat responseFormat = componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(StorageOperationStatus.NOT_FOUND));
+                        ResponseFormat responseFormat = componentsUtils
+                            .getResponseFormat(componentsUtils.convertFromStorageResponse(StorageOperationStatus.NOT_FOUND));
                         result = Either.right(responseFormat);
                         return result;
                     }
                     artifactsFromComponent.add(deploymentArtifacts.get(id));
                 }
                 addArtifactsToList(artifacts, artifactsFromComponent);
-
             }
             GroupDefinitionInfo resultInfo = new GroupDefinitionInfo(group);
             resultInfo.setIsBase(isBase);
@@ -486,17 +468,14 @@ public class GroupBusinessLogic extends BaseBusinessLogic {
                 resultInfo.setArtifacts(artifacts);
             }
             result = Either.left(resultInfo);
-
             return result;
-
         } finally {
             closeTransaction(inTransaction, result);
         }
-
     }
 
     private void addArtifactsToList(List<ArtifactDefinitionInfo> artifacts, List<ArtifactDefinition> artifactsFromComponent) {
-        artifactsFromComponent.forEach(a-> artifacts.add(new ArtifactDefinitionInfo(a)));
+        artifactsFromComponent.forEach(a -> artifacts.add(new ArtifactDefinitionInfo(a)));
     }
 
     private Boolean isBaseProp(Component component, List<GroupProperty> props) {
@@ -506,16 +485,15 @@ public class GroupBusinessLogic extends BaseBusinessLogic {
             if (isBasePropOp.isPresent()) {
                 GroupProperty propIsBase = isBasePropOp.get();
                 isBase = Boolean.parseBoolean(propIsBase.getValue());
-
             } else {
-                BeEcompErrorManager.getInstance().logInvalidInputError(GET_GROUP, "failed to find prop isBase " + component.getNormalizedName(), ErrorSeverity.INFO);
+                BeEcompErrorManager.getInstance()
+                    .logInvalidInputError(GET_GROUP, "failed to find prop isBase " + component.getNormalizedName(), ErrorSeverity.INFO);
             }
         }
         return isBase;
     }
 
     private Either<GroupDefinition, StorageOperationStatus> findGroupOnComponent(Component component, String groupId) {
-
         Either<GroupDefinition, StorageOperationStatus> result = null;
         if (CollectionUtils.isNotEmpty(component.getGroups())) {
             Optional<GroupDefinition> foundGroup = component.getGroups().stream().filter(g -> g.getUniqueId().equals(groupId)).findFirst();
@@ -529,11 +507,13 @@ public class GroupBusinessLogic extends BaseBusinessLogic {
         return result;
     }
 
-    public Either<Boolean, ResponseFormat> validateGenerateVfModuleGroupNames(List<ArtifactTemplateInfo> allGroups, String resourceSystemName, int startGroupCounter) {
+    public Either<Boolean, ResponseFormat> validateGenerateVfModuleGroupNames(List<ArtifactTemplateInfo> allGroups, String resourceSystemName,
+                                                                              int startGroupCounter) {
         Either<Boolean, ResponseFormat> validateGenerateGroupNamesRes = Either.left(true);
         Collections.sort(allGroups, ArtifactTemplateInfo::compareByGroupName);
         for (ArtifactTemplateInfo group : allGroups) {
-            Either<String, ResponseFormat> validateGenerateGroupNameRes = validateGenerateVfModuleGroupName(resourceSystemName, group.getDescription(), startGroupCounter++);
+            Either<String, ResponseFormat> validateGenerateGroupNameRes = validateGenerateVfModuleGroupName(resourceSystemName,
+                group.getDescription(), startGroupCounter++);
             if (validateGenerateGroupNameRes.isRight()) {
                 validateGenerateGroupNamesRes = Either.right(validateGenerateGroupNameRes.right().value());
                 break;
@@ -555,7 +535,8 @@ public class GroupBusinessLogic extends BaseBusinessLogic {
         Either<String, ResponseFormat> validateGenerateGroupNameRes;
         if (resourceSystemName != null && description != null && Pattern.compile(Constants.MODULE_DESC_PATTERN).matcher(description).matches()) {
             final String fileName = description.replaceAll(GROUP_DELIMITER_REGEX, "\\.");
-            validateGenerateGroupNameRes = Either.left(String.format(Constants.MODULE_NAME_FORMAT, resourceSystemName, FilenameUtils.removeExtension(fileName), groupCounter));
+            validateGenerateGroupNameRes = Either
+                .left(String.format(Constants.MODULE_NAME_FORMAT, resourceSystemName, FilenameUtils.removeExtension(fileName), groupCounter));
         } else {
             validateGenerateGroupNameRes = Either.right(componentsUtils.getResponseFormat(ActionStatus.INVALID_VF_MODULE_NAME));
         }
@@ -563,7 +544,6 @@ public class GroupBusinessLogic extends BaseBusinessLogic {
     }
 
     Either<Map<String, GroupDefinition>, ResponseFormat> validateUpdateVfGroupNames(Map<String, GroupDefinition> groups, String resourceSystemName) {
-
         Map<String, GroupDefinition> updatedNamesGroups = new HashMap<>();
         Either<Map<String, GroupDefinition>, ResponseFormat> result = Either.left(updatedNamesGroups);
         for (Entry<String, GroupDefinition> groupEntry : groups.entrySet()) {
@@ -573,8 +553,8 @@ public class GroupBusinessLogic extends BaseBusinessLogic {
             int counter;
             String description;
             Either<String, ResponseFormat> newGroupNameRes;
-            if (groupType.equals(Constants.DEFAULT_GROUP_VF_MODULE) && !Pattern.compile(Constants.MODULE_NEW_NAME_PATTERN).matcher(groupName).matches()) {
-
+            if (groupType.equals(Constants.DEFAULT_GROUP_VF_MODULE) && !Pattern.compile(Constants.MODULE_NEW_NAME_PATTERN).matcher(groupName)
+                .matches()) {
                 if (Pattern.compile(Constants.MODULE_OLD_NAME_PATTERN).matcher(groupEntry.getKey()).matches()) {
                     counter = Integer.parseInt(groupEntry.getKey().split(Constants.MODULE_NAME_DELIMITER)[1]);
                     description = curGroup.getDescription();
@@ -585,7 +565,8 @@ public class GroupBusinessLogic extends BaseBusinessLogic {
                 newGroupNameRes = validateGenerateVfModuleGroupName(resourceSystemName, description, counter);
                 if (newGroupNameRes.isRight()) {
                     log.debug("Failed to generate new vf module group name. Status is {} ", newGroupNameRes.right().value());
-                    loggerSupportability.log(LogLevel.INFO,LoggerSupportabilityActions.CREATE_RESOURCE_FROM_YAML.getName(),StatusCode.ERROR.name(),"Failed to generate new vf module group name. Status is: "+newGroupNameRes.right().value());
+                    loggerSupportability.log(LogLevel.INFO, LoggerSupportabilityActions.CREATE_RESOURCE_FROM_YAML.getName(), StatusCode.ERROR.name(),
+                        "Failed to generate new vf module group name. Status is: " + newGroupNameRes.right().value());
                     result = Either.right(newGroupNameRes.right().value());
                     break;
                 }
@@ -608,8 +589,10 @@ public class GroupBusinessLogic extends BaseBusinessLogic {
     public int getNextVfModuleNameCounter(Collection<GroupDefinition> groups) {
         int counter = 0;
         if (groups != null && !groups.isEmpty()) {
-            List<Integer> counters = groups.stream().filter(group -> Pattern.compile(Constants.MODULE_NEW_NAME_PATTERN).matcher(group.getName()).matches() || Pattern.compile(Constants.MODULE_OLD_NAME_PATTERN).matcher(group.getName()).matches())
-                    .map(group -> Integer.parseInt(group.getName().split(Constants.MODULE_NAME_DELIMITER)[1])).collect(toList());
+            List<Integer> counters = groups.stream().filter(
+                group -> Pattern.compile(Constants.MODULE_NEW_NAME_PATTERN).matcher(group.getName()).matches() || Pattern
+                    .compile(Constants.MODULE_OLD_NAME_PATTERN).matcher(group.getName()).matches())
+                .map(group -> Integer.parseInt(group.getName().split(Constants.MODULE_NAME_DELIMITER)[1])).collect(toList());
             counter = (counters == null || counters.isEmpty()) ? 0 : counters.stream().max(Integer::compare).get() + 1;
         }
         return counter;
@@ -617,14 +600,14 @@ public class GroupBusinessLogic extends BaseBusinessLogic {
 
     public Either<List<GroupDefinition>, ResponseFormat> validateUpdateVfGroupNamesOnGraph(List<GroupDefinition> groups, Component component) {
         List<GroupDefinition> updatedGroups = new ArrayList<>();
-
         for (GroupDefinition group : groups) {
             String groupType = group.getType();
             String oldGroupName = group.getName();
             String newGroupName;
             Either<String, ResponseFormat> newGroupNameRes;
             int counter;
-            if (groupType.equals(Constants.DEFAULT_GROUP_VF_MODULE) && Pattern.compile(Constants.MODULE_OLD_NAME_PATTERN).matcher(oldGroupName).matches()) {
+            if (groupType.equals(Constants.DEFAULT_GROUP_VF_MODULE) && Pattern.compile(Constants.MODULE_OLD_NAME_PATTERN).matcher(oldGroupName)
+                .matches()) {
                 counter = Integer.parseInt(group.getName().split(Constants.MODULE_NAME_DELIMITER)[1]);
                 newGroupNameRes = validateGenerateVfModuleGroupName(component.getSystemName(), group.getDescription(), counter);
                 if (newGroupNameRes.isRight()) {
@@ -633,54 +616,45 @@ public class GroupBusinessLogic extends BaseBusinessLogic {
                 }
                 newGroupName = newGroupNameRes.left().value();
                 group.setName(newGroupName);
-
             }
             updatedGroups.add(group);
-
         }
-
         return Either.left(updatedGroups);
     }
 
-
-    public Either<GroupDefinitionInfo, ResponseFormat> getGroupInstWithArtifactsById(ComponentTypeEnum componentType, String componentId, String componentInstanceId, String groupInstId, String userId, boolean inTransaction) {
+    public Either<GroupDefinitionInfo, ResponseFormat> getGroupInstWithArtifactsById(ComponentTypeEnum componentType, String componentId,
+                                                                                     String componentInstanceId, String groupInstId, String userId,
+                                                                                     boolean inTransaction) {
         Either<GroupDefinitionInfo, ResponseFormat> result = null;
-
         // Validate user exist
         validateUserExists(userId);
         // Validate component exist
         org.openecomp.sdc.be.model.Component component;
-
         try {
             ComponentParametersView componentParametersView = new ComponentParametersView();
             componentParametersView.disableAll();
             componentParametersView.setIgnoreUsers(false);
             componentParametersView.setIgnoreComponentInstances(false);
             componentParametersView.setIgnoreArtifacts(false);
-
             component = validateComponentExists(componentId, componentType, componentParametersView);
-            Either<ImmutablePair<ComponentInstance, GroupInstance>, StorageOperationStatus> findComponentInstanceAndGroupInstanceRes = findComponentInstanceAndGroupInstanceOnComponent(component, componentInstanceId, groupInstId);
-
+            Either<ImmutablePair<ComponentInstance, GroupInstance>, StorageOperationStatus> findComponentInstanceAndGroupInstanceRes = findComponentInstanceAndGroupInstanceOnComponent(
+                component, componentInstanceId, groupInstId);
             if (findComponentInstanceAndGroupInstanceRes.isRight()) {
                 log.debug("Failed to get group {} . Status is {} ", groupInstId, findComponentInstanceAndGroupInstanceRes.right().value());
-                ResponseFormat responseFormat = componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(findComponentInstanceAndGroupInstanceRes.right().value()));
+                ResponseFormat responseFormat = componentsUtils
+                    .getResponseFormat(componentsUtils.convertFromStorageResponse(findComponentInstanceAndGroupInstanceRes.right().value()));
                 result = Either.right(responseFormat);
                 return result;
             }
-
             GroupInstance group = findComponentInstanceAndGroupInstanceRes.left().value().getRight();
-
             Boolean isBase = isBaseProperty(component, group);
-
             List<ArtifactDefinitionInfo> artifacts = new ArrayList<>();
             List<String> artifactsIds = group.getArtifacts();
             if (artifactsIds != null && !artifactsIds.isEmpty()) {
-
                 List<ComponentInstance> instances = component.getComponentInstances();
                 if (instances != null) {
-                    instances.stream().filter(i -> i.getUniqueId().equals(componentInstanceId))
-                            .findFirst()
-                            .ifPresent(f->getFirstComponentInstance(group, artifacts, artifactsIds, f));
+                    instances.stream().filter(i -> i.getUniqueId().equals(componentInstanceId)).findFirst()
+                        .ifPresent(f -> getFirstComponentInstance(group, artifacts, artifactsIds, f));
                 }
             }
             GroupDefinitionInfo resultInfo = new GroupDefinitionInfo(group);
@@ -689,31 +663,23 @@ public class GroupBusinessLogic extends BaseBusinessLogic {
                 resultInfo.setArtifacts(artifacts);
             }
             result = Either.left(resultInfo);
-
             return result;
-
         } finally {
             closeTransaction(inTransaction, result);
         }
     }
 
-    private void getFirstComponentInstance(GroupInstance group, List<ArtifactDefinitionInfo> artifacts, List<String> artifactsIds, ComponentInstance ci) {
+    private void getFirstComponentInstance(GroupInstance group, List<ArtifactDefinitionInfo> artifacts, List<String> artifactsIds,
+                                           ComponentInstance ci) {
         Map<String, ArtifactDefinition> deploymentArtifacts = ci.getDeploymentArtifacts();
-        artifactsIds.forEach(id -> deploymentArtifacts.values().stream()
-                .filter(a -> a.getUniqueId().equals(id))
-                .findFirst()
-                .ifPresent(g -> artifacts.add(new ArtifactDefinitionInfo(g))));
-
+        artifactsIds.forEach(id -> deploymentArtifacts.values().stream().filter(a -> a.getUniqueId().equals(id)).findFirst()
+            .ifPresent(g -> artifacts.add(new ArtifactDefinitionInfo(g))));
         List<String> instArtifactsIds = group.getGroupInstanceArtifacts();
-        instArtifactsIds.forEach(id -> deploymentArtifacts.values()
-                .stream()
-                .filter(a -> a.getUniqueId().equals(id))
-                .findFirst()
-                .ifPresent(g -> artifacts.add(new ArtifactDefinitionInfo(g))));
-   }
+        instArtifactsIds.forEach(id -> deploymentArtifacts.values().stream().filter(a -> a.getUniqueId().equals(id)).findFirst()
+            .ifPresent(g -> artifacts.add(new ArtifactDefinitionInfo(g))));
+    }
 
     private Boolean isBaseProperty(Component component, GroupInstance group) {
-
         Boolean isBase = null;
         List<? extends GroupProperty> props = group.convertToGroupInstancesProperties();
         if (props != null && !props.isEmpty()) {
@@ -721,9 +687,9 @@ public class GroupBusinessLogic extends BaseBusinessLogic {
             if (isBasePropOp.isPresent()) {
                 GroupProperty propIsBase = isBasePropOp.get();
                 isBase = Boolean.parseBoolean(propIsBase.getValue());
-
             } else {
-                BeEcompErrorManager.getInstance().logInvalidInputError(GET_GROUP, "failed to find prop isBase " + component.getNormalizedName(), ErrorSeverity.INFO);
+                BeEcompErrorManager.getInstance()
+                    .logInvalidInputError(GET_GROUP, "failed to find prop isBase " + component.getNormalizedName(), ErrorSeverity.INFO);
             }
         }
         return isBase;
@@ -733,20 +699,21 @@ public class GroupBusinessLogic extends BaseBusinessLogic {
         if (!inTransaction) {
             if (result == null || result.isRight()) {
                 log.debug("Going to execute rollback on create group.");
-                    janusGraphDao.rollback();
+                janusGraphDao.rollback();
             } else {
                 log.debug("Going to execute commit on create group.");
-                    janusGraphDao.commit();
+                janusGraphDao.commit();
             }
         }
     }
 
-    private Either<ImmutablePair<ComponentInstance, GroupInstance>, StorageOperationStatus> findComponentInstanceAndGroupInstanceOnComponent(Component component, String componentInstanceId, String groupInstId) {
-
+    private Either<ImmutablePair<ComponentInstance, GroupInstance>, StorageOperationStatus> findComponentInstanceAndGroupInstanceOnComponent(
+        Component component, String componentInstanceId, String groupInstId) {
         Either<ImmutablePair<ComponentInstance, GroupInstance>, StorageOperationStatus> result = null;
         if (CollectionUtils.isNotEmpty(component.getComponentInstances())) {
             Optional<GroupInstance> foundGroup;
-            Optional<ComponentInstance> foundComponent = component.getComponentInstances().stream().filter(ci -> ci.getUniqueId().equals(componentInstanceId)).findFirst();
+            Optional<ComponentInstance> foundComponent = component.getComponentInstances().stream()
+                .filter(ci -> ci.getUniqueId().equals(componentInstanceId)).findFirst();
             if (foundComponent.isPresent() && CollectionUtils.isNotEmpty(foundComponent.get().getGroupInstances())) {
                 foundGroup = foundComponent.get().getGroupInstances().stream().filter(gi -> gi.getUniqueId().equals(groupInstId)).findFirst();
                 if (foundGroup.isPresent()) {
@@ -760,39 +727,44 @@ public class GroupBusinessLogic extends BaseBusinessLogic {
         return result;
     }
 
-    private Boolean validateMinMaxAndInitialCountPropertyLogic(Map<PropertyNames, String> newValues, Map<PropertyNames, String> currValues, Map<PropertyNames, String> parentValues) {
-
+    private Boolean validateMinMaxAndInitialCountPropertyLogic(Map<PropertyNames, String> newValues, Map<PropertyNames, String> currValues,
+                                                               Map<PropertyNames, String> parentValues) {
         for (Entry<PropertyNames, String> entry : newValues.entrySet()) {
             PropertyNames currPropertyName = entry.getKey();
             if (currPropertyName == PropertyNames.MIN_INSTANCES) {
                 String minValue = parentValues.get(PropertyNames.MIN_INSTANCES);
                 String maxValue = getMaxValue(newValues, currValues);
-                validateValueInRange(new ImmutablePair<>(currPropertyName, entry.getValue()), new ImmutablePair<>(PropertyNames.MIN_INSTANCES, minValue),
-                        new ImmutablePair<>(PropertyNames.MAX_INSTANCES, maxValue));
+                validateValueInRange(new ImmutablePair<>(currPropertyName, entry.getValue()),
+                    new ImmutablePair<>(PropertyNames.MIN_INSTANCES, minValue), new ImmutablePair<>(PropertyNames.MAX_INSTANCES, maxValue));
             } else if (currPropertyName == PropertyNames.INITIAL_COUNT) {
-                String minValue = newValues.containsKey(PropertyNames.MIN_INSTANCES) ? newValues.get(PropertyNames.MIN_INSTANCES) : currValues.get(PropertyNames.MIN_INSTANCES);
-                String maxValue = newValues.containsKey(PropertyNames.MAX_INSTANCES) ? newValues.get(PropertyNames.MAX_INSTANCES) : currValues.get(PropertyNames.MAX_INSTANCES);
-                validateValueInRange(new ImmutablePair<>(currPropertyName, entry.getValue()), new ImmutablePair<>(PropertyNames.MIN_INSTANCES, minValue),
-                        new ImmutablePair<>(PropertyNames.MAX_INSTANCES, maxValue));
+                String minValue = newValues.containsKey(PropertyNames.MIN_INSTANCES) ? newValues.get(PropertyNames.MIN_INSTANCES)
+                    : currValues.get(PropertyNames.MIN_INSTANCES);
+                String maxValue = newValues.containsKey(PropertyNames.MAX_INSTANCES) ? newValues.get(PropertyNames.MAX_INSTANCES)
+                    : currValues.get(PropertyNames.MAX_INSTANCES);
+                validateValueInRange(new ImmutablePair<>(currPropertyName, entry.getValue()),
+                    new ImmutablePair<>(PropertyNames.MIN_INSTANCES, minValue), new ImmutablePair<>(PropertyNames.MAX_INSTANCES, maxValue));
             } else if (currPropertyName == PropertyNames.MAX_INSTANCES) {
                 String minValue = getMinValue(newValues, currValues);
                 String maxValue = parentValues.get(PropertyNames.MAX_INSTANCES);
-                validateValueInRange(new ImmutablePair<>(currPropertyName, entry.getValue()), new ImmutablePair<>(PropertyNames.MIN_INSTANCES, minValue),
-                        new ImmutablePair<>(PropertyNames.MAX_INSTANCES, maxValue));
+                validateValueInRange(new ImmutablePair<>(currPropertyName, entry.getValue()),
+                    new ImmutablePair<>(PropertyNames.MIN_INSTANCES, minValue), new ImmutablePair<>(PropertyNames.MAX_INSTANCES, maxValue));
             }
         }
         return true;
     }
 
     private String getMaxValue(Map<PropertyNames, String> newValues, Map<PropertyNames, String> currValues) {
-        return newValues.containsKey(PropertyNames.INITIAL_COUNT) ? newValues.get(PropertyNames.MAX_INSTANCES) : currValues.get(PropertyNames.INITIAL_COUNT);
+        return newValues.containsKey(PropertyNames.INITIAL_COUNT) ? newValues.get(PropertyNames.MAX_INSTANCES)
+            : currValues.get(PropertyNames.INITIAL_COUNT);
     }
 
     private String getMinValue(Map<PropertyNames, String> newValues, Map<PropertyNames, String> currValues) {
-        return newValues.containsKey(PropertyNames.INITIAL_COUNT) ? newValues.get(PropertyNames.MIN_INSTANCES) : currValues.get(PropertyNames.INITIAL_COUNT);
+        return newValues.containsKey(PropertyNames.INITIAL_COUNT) ? newValues.get(PropertyNames.MIN_INSTANCES)
+            : currValues.get(PropertyNames.INITIAL_COUNT);
     }
 
-    private Boolean validateValueInRange(ImmutablePair<PropertyNames, String> newValue, ImmutablePair<PropertyNames, String> min, ImmutablePair<PropertyNames, String> max) {
+    private Boolean validateValueInRange(ImmutablePair<PropertyNames, String> newValue, ImmutablePair<PropertyNames, String> min,
+                                         ImmutablePair<PropertyNames, String> max) {
         final String warnMessage = "Failed to validate {} as property value of {}. It must be not higher than {}, and not lower than {}.";
         int newValueInt = parseIntValue(newValue.getValue(), newValue.getKey());
         int minInt = parseIntValue(min.getValue(), min.getKey());
@@ -801,8 +773,8 @@ public class GroupBusinessLogic extends BaseBusinessLogic {
             throw new ByActionStatusComponentException(ActionStatus.INVALID_PROPERTY);
         } else if (newValueInt < minInt || newValueInt > maxInt) {
             log.debug(warnMessage, newValue.getValue(), newValue.getKey().getPropertyName(), min.getValue(), max.getValue());
-            throw new ByActionStatusComponentException(ActionStatus.INVALID_GROUP_MIN_MAX_INSTANCES_PROPERTY_VALUE, newValue.getKey().getPropertyName(),
-                    maxInt == Integer.MAX_VALUE ? Constants.UNBOUNDED : max.getValue(), min.getValue());
+            throw new ByActionStatusComponentException(ActionStatus.INVALID_GROUP_MIN_MAX_INSTANCES_PROPERTY_VALUE,
+                newValue.getKey().getPropertyName(), maxInt == Integer.MAX_VALUE ? Constants.UNBOUNDED : max.getValue(), min.getValue());
         }
         return true;
     }
@@ -826,17 +798,20 @@ public class GroupBusinessLogic extends BaseBusinessLogic {
      * @param newProperties
      * @return
      */
-    public Either<GroupInstance, ResponseFormat> validateAndUpdateGroupInstancePropertyValues(String componentId, String instanceId, GroupInstance oldGroupInstance, List<GroupInstanceProperty> newProperties) {
-
+    public Either<GroupInstance, ResponseFormat> validateAndUpdateGroupInstancePropertyValues(String componentId, String instanceId,
+                                                                                              GroupInstance oldGroupInstance,
+                                                                                              List<GroupInstanceProperty> newProperties) {
         Either<GroupInstance, ResponseFormat> actionResult = null;
         Either<GroupInstance, StorageOperationStatus> updateGroupInstanceResult = null;
         List<GroupInstanceProperty> validateRes = validateReduceGroupInstancePropertiesBeforeUpdate(oldGroupInstance, newProperties);
         if (actionResult == null) {
             List<GroupInstanceProperty> validatedReducedNewProperties = validateRes;
-            updateGroupInstanceResult = groupsOperation.updateGroupInstancePropertyValuesOnGraph(componentId, instanceId, oldGroupInstance, validatedReducedNewProperties);
+            updateGroupInstanceResult = groupsOperation
+                .updateGroupInstancePropertyValuesOnGraph(componentId, instanceId, oldGroupInstance, validatedReducedNewProperties);
             if (updateGroupInstanceResult.isRight()) {
                 log.debug("Failed to update group instance {} property values. ", oldGroupInstance.getName());
-                actionResult = Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(updateGroupInstanceResult.right().value())));
+                actionResult = Either
+                    .right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(updateGroupInstanceResult.right().value())));
             }
         }
         if (actionResult == null) {
@@ -845,11 +820,12 @@ public class GroupBusinessLogic extends BaseBusinessLogic {
         return actionResult;
     }
 
-    private List<GroupInstanceProperty> validateReduceGroupInstancePropertiesBeforeUpdate(GroupInstance oldGroupInstance, List<GroupInstanceProperty> newProperties) {
-
+    private List<GroupInstanceProperty> validateReduceGroupInstancePropertiesBeforeUpdate(GroupInstance oldGroupInstance,
+                                                                                          List<GroupInstanceProperty> newProperties) {
         Boolean validationRes = null;
         List<GroupInstanceProperty> actionResult = null;
-        Map<String, GroupInstanceProperty> existingProperties = oldGroupInstance.convertToGroupInstancesProperties().stream().collect(Collectors.toMap(PropertyDataDefinition::getName, p -> p));
+        Map<String, GroupInstanceProperty> existingProperties = oldGroupInstance.convertToGroupInstancesProperties().stream()
+            .collect(Collectors.toMap(PropertyDataDefinition::getName, p -> p));
         Map<PropertyNames, String> newPropertyValues = new EnumMap<>(PropertyNames.class);
         List<GroupInstanceProperty> reducedProperties = new ArrayList<>();
         String currPropertyName;
@@ -874,7 +850,9 @@ public class GroupBusinessLogic extends BaseBusinessLogic {
         return actionResult;
     }
 
-    private void fillValuesAndParentValuesFromExistingProperties(Map<String, GroupInstanceProperty> existingProperties, Map<PropertyNames, String> propertyValues, Map<PropertyNames, String> parentPropertyValues) {
+    private void fillValuesAndParentValuesFromExistingProperties(Map<String, GroupInstanceProperty> existingProperties,
+                                                                 Map<PropertyNames, String> propertyValues,
+                                                                 Map<PropertyNames, String> parentPropertyValues) {
         PropertyNames[] allPropertyNames = PropertyNames.values();
         for (PropertyNames name : allPropertyNames) {
             if (isUpdatable(name)) {
@@ -884,8 +862,8 @@ public class GroupBusinessLogic extends BaseBusinessLogic {
         }
     }
 
-    private Boolean handleAndAddProperty(List<GroupInstanceProperty> reducedProperties, Map<PropertyNames, String> newPropertyValues, GroupInstanceProperty currNewProperty, GroupInstanceProperty currExistingProperty) {
-
+    private Boolean handleAndAddProperty(List<GroupInstanceProperty> reducedProperties, Map<PropertyNames, String> newPropertyValues,
+                                         GroupInstanceProperty currNewProperty, GroupInstanceProperty currExistingProperty) {
         Boolean validationRes = null;
         String currPropertyName = currNewProperty.getName();
         PropertyNames propertyName = PropertyNames.findName(currPropertyName);
@@ -908,11 +886,14 @@ public class GroupBusinessLogic extends BaseBusinessLogic {
     }
 
     private boolean isUpdatable(PropertyNames updatablePropertyName) {
-        return updatablePropertyName != null && updatablePropertyName.getUpdateBehavior().getLevelNumber() >= GroupInstancePropertyValueUpdateBehavior.UPDATABLE_ON_SERVICE_LEVEL.getLevelNumber();
+        return updatablePropertyName != null
+            && updatablePropertyName.getUpdateBehavior().getLevelNumber() >= GroupInstancePropertyValueUpdateBehavior.UPDATABLE_ON_SERVICE_LEVEL
+            .getLevelNumber();
     }
 
-    private void addPropertyUpdatedValues(List<GroupInstanceProperty> reducedProperties, PropertyNames propertyName, Map<PropertyNames, String> newPropertyValues, GroupInstanceProperty newProperty, GroupInstanceProperty existingProperty) {
-
+    private void addPropertyUpdatedValues(List<GroupInstanceProperty> reducedProperties, PropertyNames propertyName,
+                                          Map<PropertyNames, String> newPropertyValues, GroupInstanceProperty newProperty,
+                                          GroupInstanceProperty existingProperty) {
         String newValue = newProperty.getValue();
         if (!newValue.equals(String.valueOf(existingProperty.getValue()))) {
             newProperty.setValueUniqueUid(existingProperty.getValueUniqueUid());
@@ -932,7 +913,6 @@ public class GroupBusinessLogic extends BaseBusinessLogic {
     }
 
     private int convertIfUnboundMax(String value) {
-
         int result;
         if (!NumberUtils.isNumber(value)) {
             result = Integer.MAX_VALUE;
@@ -943,9 +923,7 @@ public class GroupBusinessLogic extends BaseBusinessLogic {
     }
 
     private Boolean validateAndUpdatePropertyValue(GroupInstanceProperty newProperty, GroupInstanceProperty existingProperty) {
-
         String parentValue = existingProperty.getParentValue();
-
         newProperty.setParentValue(parentValue);
         if (StringUtils.isEmpty(newProperty.getValue())) {
             newProperty.setValue(parentValue);
@@ -955,34 +933,30 @@ public class GroupBusinessLogic extends BaseBusinessLogic {
         }
         StorageOperationStatus status = groupOperation.validateAndUpdatePropertyValue(newProperty);
         if (status != StorageOperationStatus.OK) {
-            log.debug("Failed to validate property value {} of property with name {}. Status is {}. ", newProperty.getValue(), newProperty.getName(), status);
+            log.debug("Failed to validate property value {} of property with name {}. Status is {}. ", newProperty.getValue(), newProperty.getName(),
+                status);
             throw new ByActionStatusComponentException(componentsUtils.convertFromStorageResponse(status));
         }
         return true;
     }
 
     private void validateImmutableProperty(GroupProperty oldProperty, GroupProperty newProperty) {
-        if (oldProperty.getValue() == null && newProperty.getValue() != null || oldProperty.getValue() != null && !oldProperty.getValue().equals(newProperty.getValue())) {
-            log.warn("The value of property with the name {} cannot be updated on service level. Going to ignore new property value {}. ", oldProperty.getName(), newProperty.getValue());
+        if (oldProperty.getValue() == null && newProperty.getValue() != null || oldProperty.getValue() != null && !oldProperty.getValue()
+            .equals(newProperty.getValue())) {
+            log.warn("The value of property with the name {} cannot be updated on service level. Going to ignore new property value {}. ",
+                oldProperty.getName(), newProperty.getValue());
         }
     }
 
     @LockingTransactional
-    public GroupDefinition createGroup(String componentId, ComponentTypeEnum componentTypeEnum, String groupType,
-                                       String userId) {
-
+    public GroupDefinition createGroup(String componentId, ComponentTypeEnum componentTypeEnum, String groupType, String userId) {
         Component component = accessValidations.validateUserCanWorkOnComponent(componentId, componentTypeEnum, userId, CREATE_GROUP);
-
         validateGroupTypePerComponent(groupType, component);
-
-        GroupTypeDefinition groupTypeDefinition = groupTypeOperation.getLatestGroupTypeByType(groupType, false)
-                .left()
-                .on(se -> onGroupTypeNotFound(component));
-
+        GroupTypeDefinition groupTypeDefinition = groupTypeOperation.getLatestGroupTypeByType(groupType, false).left()
+            .on(se -> onGroupTypeNotFound(component));
         boolean hasExistingGroups = CollectionUtils.isNotEmpty(component.getGroups());
         GroupDefinition groupDefinition = new GroupDefinition();
         groupDefinition.setType(groupType);
-
         //find next valid counter
         int nextCounter = 0;
         if (hasExistingGroups) {
@@ -993,26 +967,17 @@ public class GroupBusinessLogic extends BaseBusinessLogic {
         groupDefinition.setDescription(groupTypeDefinition.getDescription());
         groupDefinition.setInvariantName(name);
         groupDefinition.setCreatedFrom(CreatedFrom.UI);
-
         //Add default type properties
         List<PropertyDefinition> groupTypeProperties = groupTypeDefinition.getProperties();
-        List<GroupProperty> properties = groupTypeProperties.stream()
-                .map(GroupProperty::new)
-                .collect(toList());
+        List<GroupProperty> properties = groupTypeProperties.stream().map(GroupProperty::new).collect(toList());
         groupDefinition.convertFromGroupProperties(properties);
-
         groupDefinition.convertCapabilityDefinitions(groupTypeDefinition.getCapabilities());
-
         List<GroupDefinition> gdList;
         if (toscaOperationFacade.canAddGroups(componentId)) {
-            gdList = addGroups(component, Arrays.asList(groupDefinition), false)
-                    .left()
-                    .on(this::onFailedGroupDBOperation);
+            gdList = addGroups(component, Arrays.asList(groupDefinition), false).left().on(this::onFailedGroupDBOperation);
         } else {
             //createGroups also creates an edge and vertex to store group data
-            gdList = createGroups(component, Arrays.asList(groupDefinition), false)
-                    .left()
-                    .on(this::onFailedGroupDBOperation);
+            gdList = createGroups(component, Arrays.asList(groupDefinition), false).left().on(this::onFailedGroupDBOperation);
         }
         return gdList.get(0);
     }
@@ -1020,51 +985,35 @@ public class GroupBusinessLogic extends BaseBusinessLogic {
     private void validateGroupTypePerComponent(String groupType, Component component) {
         String specificType = component.getComponentMetadataDefinition().getMetadataDataDefinition().getActualComponentType();
         if (!component.isTopologyTemplate()) {
-            throw new ByActionStatusComponentException(ActionStatus.GROUP_TYPE_ILLEGAL_PER_COMPONENT, groupType,
-                    specificType);
+            throw new ByActionStatusComponentException(ActionStatus.GROUP_TYPE_ILLEGAL_PER_COMPONENT, groupType, specificType);
         }
         Map<String, Set<String>> excludedGroupTypesMap = ConfigurationManager.getConfigurationManager().getConfiguration()
-                .getExcludedGroupTypesMapping();
-
+            .getExcludedGroupTypesMapping();
         if (MapUtils.isNotEmpty(excludedGroupTypesMap) && StringUtils.isNotEmpty(specificType)) {
             Set<String> excludedGroupTypesPerComponent = excludedGroupTypesMap.get(specificType);
-            if (excludedGroupTypesPerComponent!=null && excludedGroupTypesPerComponent.contains(groupType)) {
+            if (excludedGroupTypesPerComponent != null && excludedGroupTypesPerComponent.contains(groupType)) {
                 throw new ByActionStatusComponentException(ActionStatus.GROUP_TYPE_ILLEGAL_PER_COMPONENT, groupType, specificType);
             }
         }
     }
 
     private int getNewGroupCounter(Component component) {
-        List<String> existingNames = component.getGroups()
-                .stream()
-                .map(GroupDataDefinition::getInvariantName)
-                .collect(toList());
-        List<String> existingIds = component.getGroups()
-                .stream()
-                .map(GroupDataDefinition::getUniqueId)
-                .collect(toList());
+        List<String> existingNames = component.getGroups().stream().map(GroupDataDefinition::getInvariantName).collect(toList());
+        List<String> existingIds = component.getGroups().stream().map(GroupDataDefinition::getUniqueId).collect(toList());
         existingIds.addAll(existingNames);
-
         return Utils.getNextCounter(existingIds);
     }
 
     @LockingTransactional
-    public GroupDefinition updateGroup(String componentId, ComponentTypeEnum componentTypeEnum, String groupId,
-                                       String userId, GroupDefinition updatedGroup) {
+    public GroupDefinition updateGroup(String componentId, ComponentTypeEnum componentTypeEnum, String groupId, String userId,
+                                       GroupDefinition updatedGroup) {
         Component component = accessValidations.validateUserCanWorkOnComponent(componentId, componentTypeEnum, userId, UPDATE_GROUP);
-
-        GroupDefinition existingGroup = findGroupOnComponent(component, groupId)
-                .left()
-                .on(se -> onGroupNotFoundInComponentError(component, groupId));
-
+        GroupDefinition existingGroup = findGroupOnComponent(component, groupId).left().on(se -> onGroupNotFoundInComponentError(component, groupId));
         String existingGroupName = existingGroup.getName();
         String updatedGroupName = updatedGroup.getName();
         assertNewNameIsValidAndUnique(existingGroupName, updatedGroupName, component);
         existingGroup.setName(updatedGroupName);
-
-        return updateGroup(component, existingGroup, existingGroupName)
-                .left()
-                .on(this::onFailedUpdateGroupDBOperation);
+        return updateGroup(component, existingGroup, existingGroupName).left().on(this::onFailedUpdateGroupDBOperation);
     }
 
     private void assertNewNameIsValidAndUnique(String currentGroupName, String updatedGroupName, Component component) {
@@ -1080,18 +1029,11 @@ public class GroupBusinessLogic extends BaseBusinessLogic {
     }
 
     @LockingTransactional
-    public GroupDefinition deleteGroup(String componentId, ComponentTypeEnum componentTypeEnum, String groupId,
-                                       String userId) {
+    public GroupDefinition deleteGroup(String componentId, ComponentTypeEnum componentTypeEnum, String groupId, String userId) {
         Component component = accessValidations.validateUserCanWorkOnComponent(componentId, componentTypeEnum, userId, DELETE_GROUP);
-
-        GroupDefinition groupDefinition = findGroupOnComponent(component, groupId)
-                .left()
-                .on(se -> onGroupNotFoundInComponentError(component, groupId));
-
-        List<GroupDefinition> gdList = deleteGroups(component, java.util.Arrays.asList(groupDefinition))
-                .left()
-                .on(this::onFailedGroupDBOperation);
-
+        GroupDefinition groupDefinition = findGroupOnComponent(component, groupId).left()
+            .on(se -> onGroupNotFoundInComponentError(component, groupId));
+        List<GroupDefinition> gdList = deleteGroups(component, java.util.Arrays.asList(groupDefinition)).left().on(this::onFailedGroupDBOperation);
         updatePolicyTargetReferencingDeletedGroup(groupId, component);
         return gdList.get(0);
     }
@@ -1107,17 +1049,18 @@ public class GroupBusinessLogic extends BaseBusinessLogic {
     }
 
     private GroupDefinition onGroupNotFoundInComponentError(Component component, String groupId) {
-        throw new ByActionStatusComponentException(ActionStatus.GROUP_IS_MISSING, groupId,
-                component.getSystemName(), getComponentTypeForResponse(component));
+        throw new ByActionStatusComponentException(ActionStatus.GROUP_IS_MISSING, groupId, component.getSystemName(),
+            getComponentTypeForResponse(component));
     }
 
     private GroupTypeDefinition onGroupTypeNotFound(Component component) {
         throw new ByActionStatusComponentException(ActionStatus.GROUP_TYPE_IS_INVALID, component.getSystemName(),
-                component.getComponentType().toString());
+            component.getComponentType().toString());
     }
 
     private void updatePolicyTargetReferencingDeletedGroup(String groupId, Component component) {
-        log.debug("#updatePolicyTargetReferencingDeletedGroup - removing all component {} policy targets referencing group {}", component.getUniqueId(), groupId);
+        log.debug("#updatePolicyTargetReferencingDeletedGroup - removing all component {} policy targets referencing group {}",
+            component.getUniqueId(), groupId);
         ActionStatus actionStatus = policyTargetsUpdateHandler.removePoliciesTargets(component, groupId, PolicyTargetType.GROUPS);
         if (ActionStatus.OK != actionStatus) {
             janusGraphDao.rollback();
@@ -1125,20 +1068,19 @@ public class GroupBusinessLogic extends BaseBusinessLogic {
         }
     }
 
-
-    public Either<List<GroupDefinition>, ResponseFormat> createGroups(Component component, final List<GroupDefinition> groupDefinitions, boolean fromCsar) {
-
+    public Either<List<GroupDefinition>, ResponseFormat> createGroups(Component component, final List<GroupDefinition> groupDefinitions,
+                                                                      boolean fromCsar) {
         Map<String, GroupDataDefinition> groups = new HashMap<>();
         Either<List<GroupDefinition>, ResponseFormat> result = null;
         Either<List<GroupDefinition>, StorageOperationStatus> createGroupsResult = null;
         Either<Map<String, DataTypeDefinition>, JanusGraphOperationStatus> allDataTypes = dataTypeCache.getAll();
         if (allDataTypes.isRight()) {
             JanusGraphOperationStatus status = allDataTypes.right().value();
-            BeEcompErrorManager.getInstance().logInternalFlowError("AddPropertyToGroup", "Failed to add property to group. Status is " + status, ErrorSeverity.ERROR);
-            return Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(DaoStatusConverter.convertJanusGraphStatusToStorageStatus(status))));
-
+            BeEcompErrorManager.getInstance()
+                .logInternalFlowError("AddPropertyToGroup", "Failed to add property to group. Status is " + status, ErrorSeverity.ERROR);
+            return Either.right(componentsUtils
+                .getResponseFormat(componentsUtils.convertFromStorageResponse(DaoStatusConverter.convertJanusGraphStatusToStorageStatus(status))));
         }
-
         // handle groups and convert to tosca data
         if (groupDefinitions != null && !groupDefinitions.isEmpty()) {
             for (GroupDefinition groupDefinition : groupDefinitions) {
@@ -1149,13 +1091,13 @@ public class GroupBusinessLogic extends BaseBusinessLogic {
                 }
                 GroupDefinition handledGroup = handleGroupRes.left().value();
                 groups.put(handledGroup.getInvariantName(), new GroupDataDefinition(handledGroup));
-
             }
         }
         if (result == null) {
             createGroupsResult = groupsOperation.createGroups(component, groups);
             if (createGroupsResult.isRight()) {
-                result = Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(createGroupsResult.right().value())));
+                result = Either
+                    .right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(createGroupsResult.right().value())));
             }
         }
         if (result == null) {
@@ -1168,26 +1110,27 @@ public class GroupBusinessLogic extends BaseBusinessLogic {
         return result;
     }
 
-    private void updateCalculatedCapabilitiesWithPropertiesOnComponent(Component component, final List<GroupDefinition> groupDefinitions, boolean fromCsar) {
+    private void updateCalculatedCapabilitiesWithPropertiesOnComponent(Component component, final List<GroupDefinition> groupDefinitions,
+                                                                       boolean fromCsar) {
         groupDefinitions.forEach(GroupDefinition::updateEmptyCapabilitiesOwnerFields);
-        StorageOperationStatus status = groupsOperation.updateCalculatedCapabilitiesWithProperties(component.getUniqueId(),
-                extractCapabilitiesFromGroups(groupDefinitions), extractCapabilityPropertiesFromGroups(groupDefinitions, fromCsar));
-        if(status != StorageOperationStatus.OK){
-            log.error("#updateCalculatedCapabilitiesWithPropertiesOnComponent - failed to update the groups' calculated capabilities with the properties on the component {}. ", component.getUniqueId());
+        StorageOperationStatus status = groupsOperation
+            .updateCalculatedCapabilitiesWithProperties(component.getUniqueId(), extractCapabilitiesFromGroups(groupDefinitions),
+                extractCapabilityPropertiesFromGroups(groupDefinitions, fromCsar));
+        if (status != StorageOperationStatus.OK) {
+            log.error(
+                "#updateCalculatedCapabilitiesWithPropertiesOnComponent - failed to update the groups' calculated capabilities with the properties on the component {}. ",
+                component.getUniqueId());
             rollbackWithException(componentsUtils.convertFromStorageResponse(status));
         }
     }
 
-    private void addCalculatedCapabilitiesWithPropertiesToComponent(Component component,
-        final List<GroupDefinition> groupDefinitions, boolean fromCsar) {
-        final List<GroupDefinition> nonNullGroupDefinitions =
-            (groupDefinitions == null) ? Collections.emptyList() : groupDefinitions;
-
+    private void addCalculatedCapabilitiesWithPropertiesToComponent(Component component, final List<GroupDefinition> groupDefinitions,
+                                                                    boolean fromCsar) {
+        final List<GroupDefinition> nonNullGroupDefinitions = (groupDefinitions == null) ? Collections.emptyList() : groupDefinitions;
         nonNullGroupDefinitions.forEach(GroupDefinition::updateEmptyCapabilitiesOwnerFields);
-        StorageOperationStatus status = groupsOperation.addCalculatedCapabilitiesWithProperties(
-            component.getUniqueId(),
-            extractCapabilitiesFromGroups(nonNullGroupDefinitions),
-            extractCapabilityPropertiesFromGroups(nonNullGroupDefinitions, fromCsar));
+        StorageOperationStatus status = groupsOperation
+            .addCalculatedCapabilitiesWithProperties(component.getUniqueId(), extractCapabilitiesFromGroups(nonNullGroupDefinitions),
+                extractCapabilityPropertiesFromGroups(nonNullGroupDefinitions, fromCsar));
         if (status != StorageOperationStatus.OK) {
             log.error(
                 "#addCalculatedCapabilitiesWithPropertiesToComponent - failed to add the groups' calculated capabilities with the properties to the component {}. ",
@@ -1198,26 +1141,27 @@ public class GroupBusinessLogic extends BaseBusinessLogic {
 
     private void deleteCalculatedCapabilitiesWithPropertiesFromComponent(Component component, final List<GroupDefinition> groupDefinitions) {
         StorageOperationStatus status = groupsOperation.deleteCalculatedCapabilitiesWithProperties(component.getUniqueId(), groupDefinitions);
-        if(status != StorageOperationStatus.OK){
-            log.error("#deleteCalculatedCapabilitiesWithPropertiesFromComponent - failed to remove the groups' calculated capabilities with the properties from the component {}. ", component.getUniqueId());
+        if (status != StorageOperationStatus.OK) {
+            log.error(
+                "#deleteCalculatedCapabilitiesWithPropertiesFromComponent - failed to remove the groups' calculated capabilities with the properties from the component {}. ",
+                component.getUniqueId());
             rollbackWithException(componentsUtils.convertFromStorageResponse(status));
         }
     }
 
-    public Either<List<GroupDefinition>, ResponseFormat> addGroups(Component component, final List<GroupDefinition> groupDefinitions, boolean fromCsar) {
-
+    public Either<List<GroupDefinition>, ResponseFormat> addGroups(Component component, final List<GroupDefinition> groupDefinitions,
+                                                                   boolean fromCsar) {
         Either<List<GroupDefinition>, ResponseFormat> result = null;
         Either<List<GroupDefinition>, StorageOperationStatus> createGroupsResult = null;
         List<GroupDataDefinition> groups = new ArrayList<>();
-
         Either<Map<String, DataTypeDefinition>, JanusGraphOperationStatus> allDataTypes = dataTypeCache.getAll();
         if (allDataTypes.isRight()) {
             JanusGraphOperationStatus status = allDataTypes.right().value();
-            BeEcompErrorManager.getInstance().logInternalFlowError("AddPropertyToGroup", "Failed to add property to group. Status is " + status, ErrorSeverity.ERROR);
-            return Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(DaoStatusConverter.convertJanusGraphStatusToStorageStatus(status))));
-
+            BeEcompErrorManager.getInstance()
+                .logInternalFlowError("AddPropertyToGroup", "Failed to add property to group. Status is " + status, ErrorSeverity.ERROR);
+            return Either.right(componentsUtils
+                .getResponseFormat(componentsUtils.convertFromStorageResponse(DaoStatusConverter.convertJanusGraphStatusToStorageStatus(status))));
         }
-
         // handle groups and convert to tosca data
         if (groupDefinitions != null && !groupDefinitions.isEmpty()) {
             for (GroupDefinition groupDefinition : groupDefinitions) {
@@ -1233,7 +1177,8 @@ public class GroupBusinessLogic extends BaseBusinessLogic {
         if (result == null) {
             createGroupsResult = groupsOperation.addGroups(component, groups);
             if (createGroupsResult.isRight()) {
-                result = Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(createGroupsResult.right().value())));
+                result = Either
+                    .right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(createGroupsResult.right().value())));
             }
             component.addGroups(createGroupsResult.left().value());
         }
@@ -1247,16 +1192,14 @@ public class GroupBusinessLogic extends BaseBusinessLogic {
     }
 
     public Either<List<GroupDefinition>, ResponseFormat> deleteGroups(Component component, List<GroupDefinition> groupDefinitions) {
-
         Either<List<GroupDefinition>, StorageOperationStatus> deleteGroupsResult;
-
         deleteGroupsResult = groupsOperation.deleteGroups(component, groupDefinitions.stream().map(GroupDataDefinition::new).collect(toList()));
         if (deleteGroupsResult.isRight()) {
             return Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(deleteGroupsResult.right().value())));
         } else {
             deleteCalculatedCapabilitiesWithPropertiesFromComponent(component, groupDefinitions);
         }
-        if (component.getGroups()!=null) {
+        if (component.getGroups() != null) {
             component.getGroups().removeAll(deleteGroupsResult.left().value());
         }
         return Either.left(deleteGroupsResult.left().value());
@@ -1264,15 +1207,14 @@ public class GroupBusinessLogic extends BaseBusinessLogic {
 
     /**
      * Update specific group version
-     * @param fromCsar TODO
      *
+     * @param fromCsar TODO
      */
     public Either<List<GroupDefinition>, ResponseFormat> updateGroups(Component component, List<GroupDefinition> groupDefinitions, boolean fromCsar) {
-
         Either<List<GroupDefinition>, ResponseFormat> result = null;
         Either<List<GroupDefinition>, StorageOperationStatus> createGroupsResult;
-
-        createGroupsResult = groupsOperation.updateGroups(component, groupDefinitions.stream().map(GroupDataDefinition::new).collect(toList()), PromoteVersionEnum.MINOR);
+        createGroupsResult = groupsOperation
+            .updateGroups(component, groupDefinitions.stream().map(GroupDataDefinition::new).collect(toList()), PromoteVersionEnum.MINOR);
         if (createGroupsResult.isRight()) {
             result = Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(createGroupsResult.right().value())));
         }
@@ -1285,15 +1227,17 @@ public class GroupBusinessLogic extends BaseBusinessLogic {
         return result;
     }
 
-    private Either<GroupDefinition, ResponseFormat> handleGroup(Component component, GroupDefinition groupDefinition, Map<String, DataTypeDefinition> allDAtaTypes) {
-
+    private Either<GroupDefinition, ResponseFormat> handleGroup(Component component, GroupDefinition groupDefinition,
+                                                                Map<String, DataTypeDefinition> allDAtaTypes) {
         log.trace("Going to create group {}", groupDefinition);
-        loggerSupportability.log(LoggerSupportabilityActions.CREATE_GROUP_POLICY,component.getComponentMetadataForSupportLog(),StatusCode.STARTED,"Start to create group: {}",groupDefinition.getName()+ " for component " + component.getName());
+        loggerSupportability.log(LoggerSupportabilityActions.CREATE_GROUP_POLICY, component.getComponentMetadataForSupportLog(), StatusCode.STARTED,
+            "Start to create group: {}", groupDefinition.getName() + " for component " + component.getName());
         // 3. verify group not already exist
         String groupDefinitionName = groupDefinition.getName();
         if (groupExistsInComponent(groupDefinitionName, component)) {
             String componentTypeForResponse = getComponentTypeForResponse(component);
-            return Either.right(componentsUtils.getResponseFormat(ActionStatus.GROUP_ALREADY_EXIST, groupDefinitionName, component.getNormalizedName(), componentTypeForResponse));
+            return Either.right(componentsUtils
+                .getResponseFormat(ActionStatus.GROUP_ALREADY_EXIST, groupDefinitionName, component.getNormalizedName(), componentTypeForResponse));
         }
         // 4. verify type of group exist
         String groupType = groupDefinition.getType();
@@ -1304,56 +1248,60 @@ public class GroupBusinessLogic extends BaseBusinessLogic {
         if (getGroupType.isRight()) {
             StorageOperationStatus status = getGroupType.right().value();
             if (status == StorageOperationStatus.NOT_FOUND) {
-                loggerSupportability.log(LoggerSupportabilityActions.CREATE_GROUP_POLICY,component.getComponentMetadataForSupportLog(), StatusCode.ERROR,"group {} cannot be found",groupDefinition.getName());
-                BeEcompErrorManager.getInstance().logInvalidInputError(CREATE_GROUP, "group type " + groupType + " cannot be found", ErrorSeverity.INFO);
+                loggerSupportability
+                    .log(LoggerSupportabilityActions.CREATE_GROUP_POLICY, component.getComponentMetadataForSupportLog(), StatusCode.ERROR,
+                        "group {} cannot be found", groupDefinition.getName());
+                BeEcompErrorManager.getInstance()
+                    .logInvalidInputError(CREATE_GROUP, "group type " + groupType + " cannot be found", ErrorSeverity.INFO);
                 return Either.right(componentsUtils.getResponseFormat(ActionStatus.GROUP_TYPE_IS_INVALID, groupType));
             } else {
                 return Either.right(componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR));
             }
         }
         // 6. verify the component instances type are allowed according to
+
         // the member types in the group type
         GroupTypeDefinition groupTypeDefinition = getGroupType.left().value();
-
-        Either<Boolean, ResponseFormat> areValidMembers = verifyComponentInstancesAreValidMembers(component, groupDefinitionName, groupDefinition.getMembers(), groupTypeDefinition.getMembers());
-
+        Either<Boolean, ResponseFormat> areValidMembers = verifyComponentInstancesAreValidMembers(component, groupDefinitionName,
+            groupDefinition.getMembers(), groupTypeDefinition.getMembers());
         if (areValidMembers.isRight()) {
             ResponseFormat responseFormat = areValidMembers.right().value();
             return Either.right(responseFormat);
         }
         // 7. verify the artifacts belongs to the component
-        Either<Boolean, ResponseFormat> areValidArtifacts = verifyArtifactsBelongsToComponent(component, groupDefinition.getArtifacts(), CREATE_GROUP);
+        Either<Boolean, ResponseFormat> areValidArtifacts = verifyArtifactsBelongsToComponent(component, groupDefinition.getArtifacts(),
+            CREATE_GROUP);
         if (areValidArtifacts.isRight()) {
             ResponseFormat responseFormat = areValidArtifacts.right().value();
             return Either.right(responseFormat);
         }
         List<PropertyDefinition> groupTypeProperties = groupTypeDefinition.getProperties();
-
         List<GroupProperty> properties = groupDefinition.convertToGroupProperties();
         List<GroupProperty> updatedGroupTypeProperties = new ArrayList<>();
         if (CollectionUtils.isNotEmpty(properties)) {
             if (CollectionUtils.isEmpty(groupTypeProperties)) {
                 BeEcompErrorManager.getInstance().logInvalidInputError(ADDING_GROUP, "group type does not have properties", ErrorSeverity.INFO);
-                loggerSupportability.log(LoggerSupportabilityActions.CREATE_GROUP_POLICY,component.getComponentMetadataForSupportLog(), StatusCode.ERROR,"group {} does not have properties ",groupDefinition.getName());
-                return Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(DaoStatusConverter.convertJanusGraphStatusToStorageStatus(JanusGraphOperationStatus.MATCH_NOT_FOUND))));
+                loggerSupportability
+                    .log(LoggerSupportabilityActions.CREATE_GROUP_POLICY, component.getComponentMetadataForSupportLog(), StatusCode.ERROR,
+                        "group {} does not have properties ", groupDefinition.getName());
+                return Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(
+                    DaoStatusConverter.convertJanusGraphStatusToStorageStatus(JanusGraphOperationStatus.MATCH_NOT_FOUND))));
             }
-
-            Map<String, PropertyDefinition> groupTypePropertiesMap = groupTypeProperties.stream().collect(Collectors.toMap(PropertyDefinition::getName, p -> p));
-
+            Map<String, PropertyDefinition> groupTypePropertiesMap = groupTypeProperties.stream()
+                .collect(Collectors.toMap(PropertyDefinition::getName, p -> p));
             Either<GroupProperty, JanusGraphOperationStatus> addPropertyResult;
             int i = 1;
             for (GroupProperty prop : properties) {
                 addPropertyResult = handleProperty(prop, groupTypePropertiesMap.get(prop.getName()), i, allDAtaTypes, groupType);
                 if (addPropertyResult.isRight()) {
                     BeEcompErrorManager.getInstance().logInvalidInputError(ADDING_GROUP, "failed to validate property", ErrorSeverity.INFO);
-                    return Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(DaoStatusConverter.convertJanusGraphStatusToStorageStatus(addPropertyResult.right().value()))));
+                    return Either.right(componentsUtils.getResponseFormat(componentsUtils
+                        .convertFromStorageResponse(DaoStatusConverter.convertJanusGraphStatusToStorageStatus(addPropertyResult.right().value()))));
                 }
                 updatedGroupTypeProperties.add(addPropertyResult.left().value());
-
                 i++;
             }
         }
-
         if (groupDefinition.getUniqueId() == null) {
             String uid = UniqueIdBuilder.buildGroupingUid(component.getUniqueId(), groupDefinitionName);
             groupDefinition.setUniqueId(uid);
@@ -1363,42 +1311,27 @@ public class GroupBusinessLogic extends BaseBusinessLogic {
         groupDefinition.setGroupUUID(UniqueIdBuilder.generateUUID());
         groupDefinition.setVersion(INITIAL_VERSION);
         groupDefinition.setTypeUid(groupTypeDefinition.getUniqueId());
-        loggerSupportability.log(LoggerSupportabilityActions.CREATE_GROUP_POLICY,component.getComponentMetadataForSupportLog(), StatusCode.COMPLETE,"group {} has been created ",groupDefinition.getName());
+        loggerSupportability.log(LoggerSupportabilityActions.CREATE_GROUP_POLICY, component.getComponentMetadataForSupportLog(), StatusCode.COMPLETE,
+            "group {} has been created ", groupDefinition.getName());
         return Either.left(groupDefinition);
     }
 
-    private static boolean groupExistsInComponent(String groupDefinitionName, Component component) {
-        boolean found = false;
-        List<GroupDefinition> groups = component.getGroups();
-        if (CollectionUtils.isNotEmpty(groups)) {
-            found = groups.stream().filter(p -> (p.getName().equalsIgnoreCase(groupDefinitionName))
-                    || p.getInvariantName().equalsIgnoreCase(groupDefinitionName))
-                    .findFirst().orElse(null) != null;
-        }
-        return found;
-    }
-
-    private Either<GroupProperty, JanusGraphOperationStatus> handleProperty(GroupProperty groupProperty, PropertyDefinition prop, Integer index, Map<String, DataTypeDefinition> allDataTypes, String groupType) {
-
+    private Either<GroupProperty, JanusGraphOperationStatus> handleProperty(GroupProperty groupProperty, PropertyDefinition prop, Integer index,
+                                                                            Map<String, DataTypeDefinition> allDataTypes, String groupType) {
         if (prop == null) {
             return Either.right(JanusGraphOperationStatus.ILLEGAL_ARGUMENT);
         }
-
         String propertyType = prop.getType();
         String value = groupProperty.getValue();
-
         Either<String, JanusGraphOperationStatus> checkInnerType = propertyOperation.checkInnerType(prop);
         if (checkInnerType.isRight()) {
             JanusGraphOperationStatus status = checkInnerType.right().value();
             return Either.right(status);
         }
-
         String innerType = checkInnerType.left().value();
-
         log.debug("Before validateAndUpdatePropertyValue");
         Either<Object, Boolean> isValid = propertyOperation.validateAndUpdatePropertyValue(propertyType, value, innerType, allDataTypes);
         log.debug("After validateAndUpdatePropertyValue. isValid = {}", isValid);
-
         String newValue = value;
         if (isValid.isRight()) {
             Boolean res = isValid.right().value();
@@ -1411,10 +1344,8 @@ public class GroupBusinessLogic extends BaseBusinessLogic {
                 newValue = object.toString();
             }
         }
-
-        String uniqueId = shouldReconstructUniqueId(groupType) ? UniqueIdBuilder.buildGroupPropertyValueUid(prop.getUniqueId(), index)
-                : prop.getUniqueId();
-
+        String uniqueId =
+            shouldReconstructUniqueId(groupType) ? UniqueIdBuilder.buildGroupPropertyValueUid(prop.getUniqueId(), index) : prop.getUniqueId();
         groupProperty.setUniqueId(uniqueId);
         groupProperty.setValue(newValue);
         groupProperty.setType(prop.getType());
@@ -1423,16 +1354,13 @@ public class GroupBusinessLogic extends BaseBusinessLogic {
         groupProperty.setSchema(prop.getSchema());
         groupProperty.setPassword(prop.isPassword());
         groupProperty.setParentUniqueId(prop.getUniqueId());
-
         log.debug("Before adding property value to graph {}", groupProperty);
-
         return Either.left(groupProperty);
     }
-
     // For old groups we want to leave indexing of property
+
     // For new groups we just need the types
     private boolean shouldReconstructUniqueId(String groupType) {
         return Constants.GROUP_TOSCA_HEAT.equals(groupType) || Constants.DEFAULT_GROUP_VF_MODULE.equals(groupType);
     }
-
 }
index eb576a4..46b6f79 100644 (file)
  */
 package org.openecomp.sdc.be.components.impl;
 
+import static org.openecomp.sdc.be.components.impl.BaseBusinessLogic.enumHasValueFilter;
+
+import java.util.ArrayList;
+import java.util.EnumMap;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+import java.util.stream.Collectors;
 import org.apache.commons.collections.CollectionUtils;
 import org.apache.commons.collections.MapUtils;
 import org.apache.commons.lang.StringUtils;
@@ -46,15 +54,6 @@ import org.openecomp.sdc.be.model.operations.impl.GroupOperation;
 import org.openecomp.sdc.common.util.ValidationUtils;
 import org.springframework.transaction.annotation.Transactional;
 
-import java.util.ArrayList;
-import java.util.EnumMap;
-import java.util.HashMap;
-import java.util.List;
-import java.util.Map;
-import java.util.stream.Collectors;
-
-import static org.openecomp.sdc.be.components.impl.BaseBusinessLogic.enumHasValueFilter;
-
 @org.springframework.stereotype.Component
 public class GroupBusinessLogicNew {
 
@@ -63,7 +62,8 @@ public class GroupBusinessLogicNew {
     private final GroupsOperation groupsOperation;
     private final GroupOperation groupOperation;
 
-    public GroupBusinessLogicNew(AccessValidations accessValidations, ComponentValidations componentValidations, GroupsOperation groupsOperation, GroupOperation groupOperation) {
+    public GroupBusinessLogicNew(AccessValidations accessValidations, ComponentValidations componentValidations, GroupsOperation groupsOperation,
+                                 GroupOperation groupOperation) {
         this.accessValidations = accessValidations;
         this.componentValidations = componentValidations;
         this.groupsOperation = groupsOperation;
@@ -71,7 +71,8 @@ public class GroupBusinessLogicNew {
     }
 
     @LockingTransactional
-    public List<String> updateMembers(String componentId, ComponentTypeEnum componentType, String userId, String groupUniqueId, List<String> members) {
+    public List<String> updateMembers(String componentId, ComponentTypeEnum componentType, String userId, String groupUniqueId,
+                                      List<String> members) {
         Component component = accessValidations.validateUserCanWorkOnComponent(componentId, componentType, userId, "UPDATE GROUP MEMBERS");
         GroupDefinition groupDefinition = getGroup(component, groupUniqueId);
         groupDefinition.setMembers(buildMembersMap(component, members));
@@ -80,13 +81,13 @@ public class GroupBusinessLogicNew {
     }
 
     @LockingTransactional
-    public List<GroupProperty> updateProperties(String componentId, ComponentTypeEnum componentType, String userId, String groupUniqueId, List<GroupProperty> newProperties) {
+    public List<GroupProperty> updateProperties(String componentId, ComponentTypeEnum componentType, String userId, String groupUniqueId,
+                                                List<GroupProperty> newProperties) {
         Component component = accessValidations.validateUserCanWorkOnComponent(componentId, componentType, userId, "UPDATE GROUP PROPERTIES");
         GroupDefinition currentGroup = getGroup(component, groupUniqueId);
         validateUpdatedPropertiesAndSetEmptyValues(currentGroup, newProperties);
-        return groupsOperation.updateGroupPropertiesOnComponent(componentId, currentGroup, newProperties, PromoteVersionEnum.MINOR)
-                .left()
-                .on(this::onUpdatePropertyError);
+        return groupsOperation.updateGroupPropertiesOnComponent(componentId, currentGroup, newProperties, PromoteVersionEnum.MINOR).left()
+            .on(this::onUpdatePropertyError);
     }
 
     @Transactional
@@ -110,31 +111,26 @@ public class GroupBusinessLogicNew {
     }
 
     private ComponentInstance getComponentInstance(Component component, String memberUniqueId) {
-        return componentValidations.getComponentInstance(component, memberUniqueId)
-                .orElseThrow(() -> new ByActionStatusComponentException(ActionStatus.COMPONENT_INSTANCE_NOT_FOUND_ON_CONTAINER,
-                        memberUniqueId, "",
-                        component.getActualComponentType(), component.getSystemName()));
+        return componentValidations.getComponentInstance(component, memberUniqueId).orElseThrow(
+            () -> new ByActionStatusComponentException(ActionStatus.COMPONENT_INSTANCE_NOT_FOUND_ON_CONTAINER, memberUniqueId, "",
+                component.getActualComponentType(), component.getSystemName()));
     }
 
     private GroupDefinition getGroup(Component component, String groupUniqueId) {
-        return component.getGroupById(groupUniqueId)
-                .orElseThrow(() -> new ByActionStatusComponentException(ActionStatus.GROUP_IS_MISSING,
-                        component.getSystemName(), component.getActualComponentType()));
+        return component.getGroupById(groupUniqueId).orElseThrow(
+            () -> new ByActionStatusComponentException(ActionStatus.GROUP_IS_MISSING, component.getSystemName(), component.getActualComponentType()));
     }
 
     private void validateUpdatedPropertiesAndSetEmptyValues(GroupDefinition originalGroup, List<GroupProperty> groupPropertiesToUpdate) {
-
         if (CollectionUtils.isEmpty(groupPropertiesToUpdate)) {
             throw new ByActionStatusComponentException(ActionStatus.PROPERTY_NOT_FOUND, StringUtils.EMPTY);
         }
         if (CollectionUtils.isEmpty(originalGroup.getProperties())) {
-            throw new ByActionStatusComponentException(ActionStatus.PROPERTY_NOT_FOUND, groupPropertiesToUpdate.get(NumberUtils.INTEGER_ZERO).getName());
+            throw new ByActionStatusComponentException(ActionStatus.PROPERTY_NOT_FOUND,
+                groupPropertiesToUpdate.get(NumberUtils.INTEGER_ZERO).getName());
         }
-        Map<String, GroupProperty> originalProperties = originalGroup.convertToGroupProperties()
-                .stream()
-                .collect(Collectors.toMap(PropertyDataDefinition::getName, p -> p));
-
-
+        Map<String, GroupProperty> originalProperties = originalGroup.convertToGroupProperties().stream()
+            .collect(Collectors.toMap(PropertyDataDefinition::getName, p -> p));
         for (GroupProperty gp : groupPropertiesToUpdate) {
             String updatedPropertyName = gp.getName();
             if (!originalProperties.containsKey(updatedPropertyName)) {
@@ -151,12 +147,10 @@ public class GroupBusinessLogicNew {
                 throw new StorageException(sos, updatedPropertyName);
             }
         }
-
         validatePropertyBusinessLogic(groupPropertiesToUpdate, originalGroup);
     }
 
     private void validatePropertyBusinessLogic(List<GroupProperty> groupPropertiesToUpdate, GroupDefinition originalGroup) {
-
         Map<PropertyDefinition.PropertyNames, String> enumValueMap = new EnumMap<>(PropertyDefinition.PropertyNames.class);
         for (GroupProperty gp : groupPropertiesToUpdate) {
             // Filter out non special properties which does not have Enum
@@ -168,20 +162,19 @@ public class GroupBusinessLogicNew {
         if (MapUtils.isEmpty(enumValueMap)) {
             return;
         }
-
         validateVFInstancesLogic(enumValueMap, prepareMapWithOriginalProperties(originalGroup));
-
-        if (enumValueMap.containsKey(PropertyDefinition.PropertyNames.VF_MODULE_DESCRIPTION) || enumValueMap.containsKey(PropertyDefinition.PropertyNames.VF_MODULE_LABEL)) {
-            groupPropertiesToUpdate.stream()
-                    .filter(e -> enumHasValueFilter(e.getName(), PropertyDefinition.PropertyNames::findName, PropertyDefinition.PropertyNames.VF_MODULE_DESCRIPTION, PropertyDefinition.PropertyNames.VF_MODULE_LABEL))
-                    .forEach(this::validateFreeText);
+        if (enumValueMap.containsKey(PropertyDefinition.PropertyNames.VF_MODULE_DESCRIPTION) || enumValueMap
+            .containsKey(PropertyDefinition.PropertyNames.VF_MODULE_LABEL)) {
+            groupPropertiesToUpdate.stream().filter(e -> enumHasValueFilter(e.getName(), PropertyDefinition.PropertyNames::findName,
+                PropertyDefinition.PropertyNames.VF_MODULE_DESCRIPTION, PropertyDefinition.PropertyNames.VF_MODULE_LABEL))
+                .forEach(this::validateFreeText);
         }
     }
 
     private Map<PropertyDefinition.PropertyNames, String> prepareMapWithOriginalProperties(GroupDefinition originalGroup) {
         Map<PropertyDefinition.PropertyNames, String> oldValueMap = new EnumMap<>(PropertyDefinition.PropertyNames.class);
-        PropertyDefinition.PropertyNames[] propertiesToCheck = new PropertyDefinition.PropertyNames[] { PropertyDefinition.PropertyNames.INITIAL_COUNT, PropertyDefinition.PropertyNames.MAX_INSTANCES, PropertyDefinition.PropertyNames.MIN_INSTANCES };
-
+        PropertyDefinition.PropertyNames[] propertiesToCheck = new PropertyDefinition.PropertyNames[]{PropertyDefinition.PropertyNames.INITIAL_COUNT,
+            PropertyDefinition.PropertyNames.MAX_INSTANCES, PropertyDefinition.PropertyNames.MIN_INSTANCES};
         for (GroupProperty gp : originalGroup.convertToGroupProperties()) {
             if (enumHasValueFilter(gp.getName(), PropertyDefinition.PropertyNames::findName, propertiesToCheck)) {
                 oldValueMap.put(PropertyDefinition.PropertyNames.findName(gp.getName()), gp.getValue());
@@ -193,35 +186,39 @@ public class GroupBusinessLogicNew {
         return oldValueMap;
     }
 
-    private void validateVFInstancesLogic(Map<PropertyDefinition.PropertyNames, String> newValues, Map<PropertyDefinition.PropertyNames, String> parentValues) {
-        if (!newValues.containsKey(PropertyDefinition.PropertyNames.INITIAL_COUNT)
-                && !newValues.containsKey(PropertyDefinition.PropertyNames.MAX_INSTANCES)
-                && !newValues.containsKey(PropertyDefinition.PropertyNames.MIN_INSTANCES)) {
+    private void validateVFInstancesLogic(Map<PropertyDefinition.PropertyNames, String> newValues,
+                                          Map<PropertyDefinition.PropertyNames, String> parentValues) {
+        if (!newValues.containsKey(PropertyDefinition.PropertyNames.INITIAL_COUNT) && !newValues
+            .containsKey(PropertyDefinition.PropertyNames.MAX_INSTANCES) && !newValues.containsKey(PropertyDefinition.PropertyNames.MIN_INSTANCES)) {
             return;
         }
         int latestMaxInstances = getLatestIntProperty(newValues, parentValues, PropertyDefinition.PropertyNames.MAX_INSTANCES);
         int latestInitialCount = getLatestIntProperty(newValues, parentValues, PropertyDefinition.PropertyNames.INITIAL_COUNT);
         int latestMinInstances = getLatestIntProperty(newValues, parentValues, PropertyDefinition.PropertyNames.MIN_INSTANCES);
-
-        if (isPropertyChanged(newValues, parentValues, PropertyDefinition.PropertyNames.INITIAL_COUNT)
-                && (latestInitialCount > latestMaxInstances || latestInitialCount < latestMinInstances)) {
-            throw new ByActionStatusComponentException(ActionStatus.INVALID_GROUP_INITIAL_COUNT_PROPERTY_VALUE, PropertyDefinition.PropertyNames.INITIAL_COUNT.getPropertyName(), String.valueOf(latestMinInstances), String.valueOf(latestMaxInstances));
+        if (isPropertyChanged(newValues, parentValues, PropertyDefinition.PropertyNames.INITIAL_COUNT) && (latestInitialCount > latestMaxInstances
+            || latestInitialCount < latestMinInstances)) {
+            throw new ByActionStatusComponentException(ActionStatus.INVALID_GROUP_INITIAL_COUNT_PROPERTY_VALUE,
+                PropertyDefinition.PropertyNames.INITIAL_COUNT.getPropertyName(), String.valueOf(latestMinInstances),
+                String.valueOf(latestMaxInstances));
         }
-        if (isPropertyChanged(newValues, parentValues, PropertyDefinition.PropertyNames.MAX_INSTANCES) &&
-                latestMaxInstances < latestInitialCount) {
-            throw new ByActionStatusComponentException(ActionStatus.INVALID_GROUP_PROPERTY_VALUE_LOWER_HIGHER, PropertyDefinition.PropertyNames.MAX_INSTANCES.getPropertyName(), "higher", String.valueOf(latestInitialCount));
+        if (isPropertyChanged(newValues, parentValues, PropertyDefinition.PropertyNames.MAX_INSTANCES) && latestMaxInstances < latestInitialCount) {
+            throw new ByActionStatusComponentException(ActionStatus.INVALID_GROUP_PROPERTY_VALUE_LOWER_HIGHER,
+                PropertyDefinition.PropertyNames.MAX_INSTANCES.getPropertyName(), "higher", String.valueOf(latestInitialCount));
         }
-        if (isPropertyChanged(newValues, parentValues, PropertyDefinition.PropertyNames.MIN_INSTANCES) &&
-                latestMinInstances > latestInitialCount) {
-            throw new ByActionStatusComponentException(ActionStatus.INVALID_GROUP_PROPERTY_VALUE_LOWER_HIGHER, PropertyDefinition.PropertyNames.MIN_INSTANCES.getPropertyName(), "lower", String.valueOf(latestInitialCount));
+        if (isPropertyChanged(newValues, parentValues, PropertyDefinition.PropertyNames.MIN_INSTANCES) && latestMinInstances > latestInitialCount) {
+            throw new ByActionStatusComponentException(ActionStatus.INVALID_GROUP_PROPERTY_VALUE_LOWER_HIGHER,
+                PropertyDefinition.PropertyNames.MIN_INSTANCES.getPropertyName(), "lower", String.valueOf(latestInitialCount));
         }
     }
 
-    private boolean isPropertyChanged(Map<PropertyDefinition.PropertyNames, String> newValues, Map<PropertyDefinition.PropertyNames, String> parentValues, final PropertyDefinition.PropertyNames minInstances) {
+    private boolean isPropertyChanged(Map<PropertyDefinition.PropertyNames, String> newValues,
+                                      Map<PropertyDefinition.PropertyNames, String> parentValues,
+                                      final PropertyDefinition.PropertyNames minInstances) {
         return newValues.containsKey(minInstances) && !newValues.get(minInstances).equals(parentValues.get(minInstances));
     }
 
-    private int getLatestIntProperty(Map<PropertyDefinition.PropertyNames, String> newValues, Map<PropertyDefinition.PropertyNames, String> parentValues, PropertyDefinition.PropertyNames propertyKey) {
+    private int getLatestIntProperty(Map<PropertyDefinition.PropertyNames, String> newValues,
+                                     Map<PropertyDefinition.PropertyNames, String> parentValues, PropertyDefinition.PropertyNames propertyKey) {
         String value;
         if (newValues.containsKey(propertyKey)) {
             value = newValues.get(propertyKey);
@@ -240,22 +237,19 @@ public class GroupBusinessLogicNew {
         groupProperty2Duplicate.setValue(null);
         groupProperty2Duplicate.setSchema(null);
         groupProperty2Duplicate.setParentUniqueId(null);
-        return StringUtils.equals(groupProperty1Duplicate.getValueUniqueUid(), groupProperty2Duplicate.getValueUniqueUid())
-                && groupProperty1Duplicate.equals(groupProperty2Duplicate);
+        return StringUtils.equals(groupProperty1Duplicate.getValueUniqueUid(), groupProperty2Duplicate.getValueUniqueUid()) && groupProperty1Duplicate
+            .equals(groupProperty2Duplicate);
     }
 
     private void validateFreeText(GroupProperty groupPropertyToUpdate) {
         final String groupTypeValue = groupPropertyToUpdate.getValue();
         if (!org.apache.commons.lang3.StringUtils.isEmpty(groupTypeValue)) {
             if (!ValidationUtils.validateDescriptionLength(groupTypeValue)) {
-                throw new ByActionStatusComponentException(ActionStatus.COMPONENT_DESCRIPTION_EXCEEDS_LIMIT,
-                        NodeTypeEnum.Property.getName(),
-                        String.valueOf(ValidationUtils.COMPONENT_DESCRIPTION_MAX_LENGTH));
+                throw new ByActionStatusComponentException(ActionStatus.COMPONENT_DESCRIPTION_EXCEEDS_LIMIT, NodeTypeEnum.Property.getName(),
+                    String.valueOf(ValidationUtils.COMPONENT_DESCRIPTION_MAX_LENGTH));
             } else if (!ValidationUtils.validateIsEnglish(groupTypeValue)) {
-                throw new ByActionStatusComponentException(ActionStatus.COMPONENT_INVALID_DESCRIPTION,
-                        NodeTypeEnum.Property.getName());
+                throw new ByActionStatusComponentException(ActionStatus.COMPONENT_INVALID_DESCRIPTION, NodeTypeEnum.Property.getName());
             }
         }
     }
-
 }
index ee53c35..4a67b09 100644 (file)
  */
 package org.openecomp.sdc.be.components.impl;
 
+import static java.util.Collections.emptySet;
+
+import java.util.List;
+import java.util.Map;
+import java.util.Set;
 import org.apache.commons.lang3.StringUtils;
 import org.openecomp.sdc.be.components.impl.exceptions.ByActionStatusComponentException;
 import org.openecomp.sdc.be.components.validation.UserValidations;
@@ -33,12 +38,6 @@ import org.openecomp.sdc.be.model.operations.api.StorageOperationStatus;
 import org.openecomp.sdc.be.model.operations.impl.GroupTypeOperation;
 import org.springframework.stereotype.Component;
 
-import java.util.List;
-import java.util.Map;
-import java.util.Set;
-
-import static java.util.Collections.emptySet;
-
 @Component("groupTypeBusinessLogic")
 public class GroupTypeBusinessLogic {
 
@@ -47,14 +46,14 @@ public class GroupTypeBusinessLogic {
     private final UserValidations userValidations;
     private final ComponentsUtils componentsUtils;
 
-    public GroupTypeBusinessLogic(GroupTypeOperation groupTypeOperation, JanusGraphDao janusGraphDao, UserValidations userValidations, ComponentsUtils componentsUtils) {
+    public GroupTypeBusinessLogic(GroupTypeOperation groupTypeOperation, JanusGraphDao janusGraphDao, UserValidations userValidations,
+                                  ComponentsUtils componentsUtils) {
         this.groupTypeOperation = groupTypeOperation;
         this.janusGraphDao = janusGraphDao;
         this.userValidations = userValidations;
         this.componentsUtils = componentsUtils;
     }
 
-
     public List<GroupTypeDefinition> getAllGroupTypes(String userId, String internalComponentType) {
         try {
             userValidations.validateUserExists(userId);
@@ -66,16 +65,15 @@ public class GroupTypeBusinessLogic {
     }
 
     public GroupTypeDefinition getLatestGroupTypeByType(String groupTypeName) {
-        return groupTypeOperation.getLatestGroupTypeByType(groupTypeName, true)
-                .left()
-                .on(e -> failOnGetGroupType(e, groupTypeName));
+        return groupTypeOperation.getLatestGroupTypeByType(groupTypeName, true).left().on(e -> failOnGetGroupType(e, groupTypeName));
     }
 
     public Set<String> getExcludedGroupTypes(String internalComponentType) {
         if (StringUtils.isEmpty(internalComponentType)) {
             return emptySet();
         }
-        Map<String, Set<String>> excludedGroupTypesMapping = ConfigurationManager.getConfigurationManager().getConfiguration().getExcludedGroupTypesMapping();
+        Map<String, Set<String>> excludedGroupTypesMapping = ConfigurationManager.getConfigurationManager().getConfiguration()
+            .getExcludedGroupTypesMapping();
         Set<String> excludedTypes = excludedGroupTypesMapping.get(internalComponentType);
         return excludedTypes == null ? emptySet() : excludedTypes;
     }
index 24cbb3e..d3640a7 100644 (file)
@@ -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.
  * limitations under the License.
  * ============LICENSE_END=========================================================
  */
-
 package org.openecomp.sdc.be.components.impl;
 
 import fj.data.Either;
+import java.util.Collections;
+import java.util.List;
+import java.util.Map;
+import java.util.stream.Collectors;
 import org.apache.commons.lang3.tuple.ImmutablePair;
 import org.openecomp.sdc.be.components.impl.CommonImportManager.ElementTypeEnum;
 import org.openecomp.sdc.be.components.impl.model.ToscaTypeImportData;
@@ -41,11 +44,6 @@ import org.openecomp.sdc.common.log.wrappers.Logger;
 import org.openecomp.sdc.exception.ResponseFormat;
 import org.springframework.stereotype.Component;
 
-import java.util.Collections;
-import java.util.List;
-import java.util.Map;
-import java.util.stream.Collectors;
-
 @Component("groupTypeImportManager")
 public class GroupTypeImportManager {
 
@@ -55,7 +53,8 @@ public class GroupTypeImportManager {
     private final ToscaOperationFacade toscaOperationFacade;
     private final CommonImportManager commonImportManager;
 
-    public GroupTypeImportManager(GroupTypeOperation groupTypeOperation, ComponentsUtils componentsUtils, ToscaOperationFacade toscaOperationFacade, CommonImportManager commonImportManager) {
+    public GroupTypeImportManager(GroupTypeOperation groupTypeOperation, ComponentsUtils componentsUtils, ToscaOperationFacade toscaOperationFacade,
+                                  CommonImportManager commonImportManager) {
         this.groupTypeOperation = groupTypeOperation;
         this.componentsUtils = componentsUtils;
         this.toscaOperationFacade = toscaOperationFacade;
@@ -70,22 +69,23 @@ public class GroupTypeImportManager {
         return commonImportManager.createElementTypesFromYml(groupTypesYml, this::createGroupType);
     }
 
-    private Either<List<ImmutablePair<GroupTypeDefinition, Boolean>>, ResponseFormat> upsertGroupTypesByDao(List<GroupTypeDefinition> groupTypesToCreate) {
-        return commonImportManager.createElementTypesByDao(groupTypesToCreate, this::validateGroupType, groupType -> new ImmutablePair<>(ElementTypeEnum.GROUP_TYPE, groupType.getType()),
-                groupTypeOperation::getLatestGroupTypeByType, groupTypeOperation::addGroupType, this::updateGroupType);
+    private Either<List<ImmutablePair<GroupTypeDefinition, Boolean>>, ResponseFormat> upsertGroupTypesByDao(
+        List<GroupTypeDefinition> groupTypesToCreate) {
+        return commonImportManager.createElementTypesByDao(groupTypesToCreate, this::validateGroupType,
+            groupType -> new ImmutablePair<>(ElementTypeEnum.GROUP_TYPE, groupType.getType()), groupTypeOperation::getLatestGroupTypeByType,
+            groupTypeOperation::addGroupType, this::updateGroupType);
     }
 
     private Either<GroupTypeDefinition, StorageOperationStatus> updateGroupType(GroupTypeDefinition newGroupType, GroupTypeDefinition oldGroupType) {
         Either<GroupTypeDefinition, StorageOperationStatus> validationRes = groupTypeOperation.validateUpdateProperties(newGroupType);
         if (validationRes.isRight()) {
-            log.error("#updateGroupType - One or all properties of group type {} not valid. status is {}", newGroupType, validationRes.right().value());
+            log.error("#updateGroupType - One or all properties of group type {} not valid. status is {}", newGroupType,
+                validationRes.right().value());
             return validationRes;
         }
-        
         if (TypeCompareUtils.isGroupTypesEquals(newGroupType, oldGroupType)) {
             return TypeCompareUtils.typeAlreadyExists();
         }
-        
         return groupTypeOperation.updateGroupType(newGroupType, oldGroupType);
     }
 
@@ -98,7 +98,8 @@ public class GroupTypeImportManager {
             } else {
                 for (String member : groupType.getMembers()) {
                     // Verify that such Resource exist
-                    Either<org.openecomp.sdc.be.model.Resource, StorageOperationStatus> eitherMemberExist = toscaOperationFacade.getLatestByToscaResourceName(member);
+                    Either<org.openecomp.sdc.be.model.Resource, StorageOperationStatus> eitherMemberExist = toscaOperationFacade
+                        .getLatestByToscaResourceName(member);
                     if (eitherMemberExist.isRight()) {
                         StorageOperationStatus operationStatus = eitherMemberExist.right().value();
                         log.debug("Error when fetching parent resource {}, error: {}", member, operationStatus);
@@ -108,16 +109,13 @@ public class GroupTypeImportManager {
                         break;
                     }
                 }
-
             }
         }
         return result;
     }
 
     private GroupTypeDefinition createGroupType(String groupTypeName, Map<String, Object> toscaJson) {
-
         GroupTypeDefinition groupType = new GroupTypeDefinition();
-
         if (toscaJson != null) {
             // Description
             commonImportManager.setField(toscaJson, TypeUtils.ToscaTagNamesEnum.DESCRIPTION.getElementName(), groupType::setDescription);
@@ -132,11 +130,8 @@ public class GroupTypeImportManager {
             groupType.setCapabilities(capabilities);
             // Members
             commonImportManager.setField(toscaJson, TypeUtils.ToscaTagNamesEnum.MEMBERS.getElementName(), groupType::setMembers);
-
             groupType.setType(groupTypeName);
-
             groupType.setHighestVersion(true);
-
             groupType.setVersion(TypeUtils.getFirstCertifiedVersionVersion());
         }
         return groupType;
@@ -148,41 +143,24 @@ public class GroupTypeImportManager {
      */
     private Map<String, CapabilityDefinition> createCapabilities(Map<String, Object> toscaJson) {
         CapabilityTypeToscaJsonHolder capabilityTypeToscaJsonHolder = new CapabilityTypeToscaJsonHolder();
-        commonImportManager.setField(toscaJson, TypeUtils.ToscaTagNamesEnum.CAPABILITIES.getElementName(), capabilityTypeToscaJsonHolder::setCapabilityTypeToscaJson);
+        commonImportManager.setField(toscaJson, TypeUtils.ToscaTagNamesEnum.CAPABILITIES.getElementName(),
+            capabilityTypeToscaJsonHolder::setCapabilityTypeToscaJson);
         Map<String, CapabilityDefinition> capabilities;
         if (capabilityTypeToscaJsonHolder.isEmpty()) {
             capabilities = Collections.emptyMap();
-        }
-        else {
-            capabilities = commonImportManager.createElementTypesMapFromToscaJsonMap(this::createCapability, capabilityTypeToscaJsonHolder.getCapabilityTypeToscaJson());
+        } else {
+            capabilities = commonImportManager
+                .createElementTypesMapFromToscaJsonMap(this::createCapability, capabilityTypeToscaJsonHolder.getCapabilityTypeToscaJson());
         }
         return capabilities;
     }
-    
-    private class CapabilityTypeToscaJsonHolder {
-        private Map<String, Object> capabilityTypeToscaJson;
-
-        public Map<String, Object> getCapabilityTypeToscaJson() {
-            return capabilityTypeToscaJson;
-        }
-        
-        public boolean isEmpty() {
-            return capabilityTypeToscaJson == null;
-        }
 
-        public void setCapabilityTypeToscaJson(Map<String, Object> capabilityTypeToscaJson) {
-            this.capabilityTypeToscaJson = capabilityTypeToscaJson;
-        }
-    }
-    
     private CapabilityDefinition createCapability(String capabilityName, Map<String, Object> toscaJson) {
         CapabilityDefinition capability = new CapabilityDefinition();
-
         capability.setName(capabilityName);
         commonImportManager.setField(toscaJson, ToscaTagNamesEnum.TYPE.getElementName(), capability::setType);
         // Properties
         CommonImportManager.setProperties(toscaJson, pl -> capability.setProperties(map(pl)));
-
         return capability;
     }
 
@@ -191,9 +169,23 @@ public class GroupTypeImportManager {
      * @return
      */
     private List<ComponentInstanceProperty> map(List<PropertyDefinition> pl) {
-        return pl.stream()
-                .map(ComponentInstanceProperty::new)
-                .collect(Collectors.toList());
+        return pl.stream().map(ComponentInstanceProperty::new).collect(Collectors.toList());
     }
 
+    private class CapabilityTypeToscaJsonHolder {
+
+        private Map<String, Object> capabilityTypeToscaJson;
+
+        public Map<String, Object> getCapabilityTypeToscaJson() {
+            return capabilityTypeToscaJson;
+        }
+
+        public void setCapabilityTypeToscaJson(Map<String, Object> capabilityTypeToscaJson) {
+            this.capabilityTypeToscaJson = capabilityTypeToscaJson;
+        }
+
+        public boolean isEmpty() {
+            return capabilityTypeToscaJson == null;
+        }
+    }
 }
index ddf4626..ccc7feb 100644 (file)
@@ -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.
@@ -17,7 +17,6 @@
  * limitations under the License.
  * ============LICENSE_END=========================================================
  */
-
 package org.openecomp.sdc.be.components.impl;
 
 import org.openecomp.sdc.common.api.HealthCheckInfo;
index 57e6eb5..ea41995 100644 (file)
@@ -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.
  * limitations under the License.
  * ============LICENSE_END=========================================================
  */
-
 package org.openecomp.sdc.be.components.impl;
 
 import org.openecomp.sdc.be.config.Configuration.ArtifactTypeConfig;
 
 public interface IDeploymentArtifactTypeConfigGetter {
+
     ArtifactTypeConfig getDeploymentArtifactConfig();
 }
index ed26ead..f537267 100644 (file)
@@ -17,7 +17,6 @@
  * limitations under the License.
  * ============LICENSE_END=========================================================
  */
-
 package org.openecomp.sdc.be.components.impl;
 
 import static org.apache.commons.collections.CollectionUtils.isEmpty;
@@ -86,10 +85,8 @@ public final class ImportUtils {
 
     private static final CustomResolver customResolver = new CustomResolver();
     private static final Yaml strictYamlLoader = new YamlLoader().getStrictYamlLoader();
-
-    private static ComponentsUtils componentsUtils;
-
     private static final Logger log = Logger.getLogger(ImportUtils.class);
+    private static ComponentsUtils componentsUtils;
 
     private ImportUtils() {
     }
@@ -99,21 +96,6 @@ public final class ImportUtils {
         componentsUtils = componentsUtils;
     }
 
-    private static class CustomResolver extends Resolver {
-
-        @Override
-        protected void addImplicitResolvers() {
-            // avoid implicit resolvers for strings that can be interpreted as boolean values
-            addImplicitResolver(Tag.STR, EMPTY, "");
-            addImplicitResolver(Tag.STR, NULL, null);
-            addImplicitResolver(Tag.NULL, NULL, "~nN\0");
-            addImplicitResolver(Tag.NULL, EMPTY, null);
-            addImplicitResolver(Tag.INT, INT, "-+0123456789");
-            addImplicitResolver(Tag.FLOAT, FLOAT, "-+0123456789.");
-            addImplicitResolver(Tag.YAML, YAML, "!&*");
-        }
-    }
-
     private static void buildMap(Map<String, Object> output, Map<String, Object> map) {
         for (Entry<String, Object> entry : map.entrySet()) {
             String key = entry.getKey();
@@ -142,56 +124,17 @@ public final class ImportUtils {
         return result;
     }
 
-    private static class YamlLoader extends YamlProcessor {
-
-        public Yaml getStrictYamlLoader() {
-            return createYaml();
-        }
-    }
-
     @SuppressWarnings("unchecked")
-    public static Either<List<HeatParameterDefinition>, ResultStatusEnum> getHeatParamsWithoutImplicitTypes(
-        String heatDecodedPayload, String artifactType) {
-        Map<String, Object> heatData = (Map<String, Object>) new Yaml(new Constructor(), new Representer(),
-            new DumperOptions(), customResolver).load(heatDecodedPayload);
+    public static Either<List<HeatParameterDefinition>, ResultStatusEnum> getHeatParamsWithoutImplicitTypes(String heatDecodedPayload,
+                                                                                                            String artifactType) {
+        Map<String, Object> heatData = (Map<String, Object>) new Yaml(new Constructor(), new Representer(), new DumperOptions(), customResolver)
+            .load(heatDecodedPayload);
         return getHeatParameters(heatData, artifactType);
     }
 
-    public static class Constants {
-
-        public static final String FIRST_NON_CERTIFIED_VERSION = "0.1";
-        public static final String VENDOR_NAME = "ONAP (Tosca)";
-        public static final String VENDOR_RELEASE = "1.0.0.wd03";
-        public static final LifecycleStateEnum NORMATIVE_TYPE_LIFE_CYCLE = LifecycleStateEnum.CERTIFIED;
-        public static final LifecycleStateEnum NORMATIVE_TYPE_LIFE_CYCLE_NOT_CERTIFIED_CHECKOUT = LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT;
-        public static final boolean NORMATIVE_TYPE_HIGHEST_VERSION = true;
-        public static final String ABSTRACT_CATEGORY_NAME = "Generic";
-        public static final String ABSTRACT_SUBCATEGORY = "Abstract";
-        public static final String DEFAULT_ICON = "defaulticon";
-        public static final String INNER_VFC_DESCRIPTION = "Not reusable inner VFC";
-        public static final String USER_DEFINED_RESOURCE_NAMESPACE_PREFIX = "org.openecomp.resource.";
-        public static final String UI_JSON_PAYLOAD_NAME = "payloadName";
-        public static final String CVFC_DESCRIPTION = "Complex node type that is used as nested type in VF";
-        public static final String ESCAPED_DOUBLE_QUOTE = "\"";
-        public static final String QUOTE = "'";
-        public static final String VF_DESCRIPTION = "Nested VF in service";
-
-        private Constants() {
-        }
-    }
-
-    public enum ResultStatusEnum {
-        ELEMENT_NOT_FOUND, GENERAL_ERROR, OK, INVALID_PROPERTY_DEFAULT_VALUE, INVALID_PROPERTY_TYPE,
-        INVALID_PROPERTY_VALUE, MISSING_ENTRY_SCHEMA_TYPE, INVALID_PROPERTY_NAME, INVALID_ATTRIBUTE_NAME
-    }
-
-    public enum ToscaElementTypeEnum {
-        BOOLEAN, STRING, MAP, LIST, ALL
-    }
-
     @SuppressWarnings("unchecked")
-    private static void handleElementNameNotFound(String elementName, Object elementValue,
-                                                  ToscaElementTypeEnum elementType, List<Object> returnedList) {
+    private static void handleElementNameNotFound(String elementName, Object elementValue, ToscaElementTypeEnum elementType,
+                                                  List<Object> returnedList) {
         if (elementValue instanceof Map) {
             findToscaElements((Map<String, Object>) elementValue, elementName, elementType, returnedList);
         } else if (elementValue instanceof List) {
@@ -200,9 +143,8 @@ public final class ImportUtils {
     }
 
     @SuppressWarnings("unchecked")
-    private static void addFoundElementAccordingToItsType(String elementName, ToscaElementTypeEnum elementType,
-                                                          List<Object> returnedList, Object elementValue) {
-
+    private static void addFoundElementAccordingToItsType(String elementName, ToscaElementTypeEnum elementType, List<Object> returnedList,
+                                                          Object elementValue) {
         if (elementValue instanceof Boolean) {
             if (elementType == ToscaElementTypeEnum.BOOLEAN || elementType == ToscaElementTypeEnum.ALL) {
                 returnedList.add(elementValue);
@@ -216,13 +158,11 @@ public final class ImportUtils {
                 returnedList.add(elementValue);
             }
             findToscaElements((Map<String, Object>) elementValue, elementName, elementType, returnedList);
-
         } else if (elementValue instanceof List) {
             if (elementType == ToscaElementTypeEnum.LIST || elementType == ToscaElementTypeEnum.ALL) {
                 returnedList.add(elementValue);
             }
             findAllToscaElementsInList((List<Object>) elementValue, elementName, elementType, returnedList);
-
         }
         // For Integer, Double etc...
         else if (elementType == ToscaElementTypeEnum.ALL && elementValue != null) {
@@ -230,13 +170,12 @@ public final class ImportUtils {
         }
     }
 
-    private static void findAllToscaElementsInList(List<Object> list, String elementName,
-                                                   ToscaElementTypeEnum elementType, List<Object> returnedList) {
+    private static void findAllToscaElementsInList(List<Object> list, String elementName, ToscaElementTypeEnum elementType,
+                                                   List<Object> returnedList) {
         list.forEach(elementValue -> handleElementNameNotFound(elementName, elementValue, elementType, returnedList));
     }
 
-    public static Either<Object, ResultStatusEnum> findToscaElement(Map<String, Object> toscaJson,
-                                                                    TypeUtils.ToscaTagNamesEnum elementName,
+    public static Either<Object, ResultStatusEnum> findToscaElement(Map<String, Object> toscaJson, TypeUtils.ToscaTagNamesEnum elementName,
                                                                     ToscaElementTypeEnum elementType) {
         List<Object> foundElements = new ArrayList<>();
         findToscaElements(toscaJson, elementName.getElementName(), elementType, foundElements);
@@ -247,22 +186,19 @@ public final class ImportUtils {
     }
 
     /**
-     * Recursively searches for all tosca elements with key equals to elementName and value equals to elementType. <br>
-     * Returns Either element with:<br> List with all value if values found<br> Or ELEMENT_NOT_FOUND ActionStatus
+     * Recursively searches for all tosca elements with key equals to elementName and value equals to elementType. <br> Returns Either element
+     * with:<br> List with all value if values found<br> Or ELEMENT_NOT_FOUND ActionStatus
      *
      * @param toscaJson
      * @return
      */
-    public static Either<List<Object>, ResultStatusEnum> findToscaElements(Map<String, Object> toscaJson,
-                                                                           String elementName,
-                                                                           ToscaElementTypeEnum elementType,
-                                                                           List<Object> returnedList) {
+    public static Either<List<Object>, ResultStatusEnum> findToscaElements(Map<String, Object> toscaJson, String elementName,
+                                                                           ToscaElementTypeEnum elementType, List<Object> returnedList) {
         Either<List<Object>, ResultStatusEnum> returnedElement = Either.right(ResultStatusEnum.ELEMENT_NOT_FOUND);
         String skipKey = null;
         if (toscaJson.containsKey(elementName)) {
             skipKey = handleFoundElement(toscaJson, elementName, elementType, returnedList);
         }
-
         Iterator<Entry<String, Object>> keyValItr = toscaJson.entrySet().iterator();
         while (keyValItr.hasNext()) {
             Entry<String, Object> keyValEntry = keyValItr.next();
@@ -270,53 +206,45 @@ public final class ImportUtils {
                 handleElementNameNotFound(elementName, keyValEntry.getValue(), elementType, returnedList);
             }
         }
-
         if (!isEmpty(returnedList)) {
             returnedElement = Either.left(returnedList);
         }
-
         return returnedElement;
     }
 
-    private static String handleFoundElement(Map<String, Object> toscaJson, String elementName,
-                                             ToscaElementTypeEnum elementType, List<Object> returnedList) {
+    private static String handleFoundElement(Map<String, Object> toscaJson, String elementName, ToscaElementTypeEnum elementType,
+                                             List<Object> returnedList) {
         Object elementValue = toscaJson.get(elementName);
         addFoundElementAccordingToItsType(elementName, elementType, returnedList, elementValue);
         return elementName;
-
     }
 
     @SuppressWarnings("unchecked")
     public static <T> Either<List<T>, ResultStatusEnum> findFirstToscaListElement(Map<String, Object> toscaJson,
                                                                                   TypeUtils.ToscaTagNamesEnum toscaTagName) {
         Either<List<T>, ResultStatusEnum> returnedElement = Either.right(ResultStatusEnum.ELEMENT_NOT_FOUND);
-        Either<Object, ResultStatusEnum> findFirstToscaElement = findToscaElement(toscaJson, toscaTagName,
-            ToscaElementTypeEnum.LIST);
+        Either<Object, ResultStatusEnum> findFirstToscaElement = findToscaElement(toscaJson, toscaTagName, ToscaElementTypeEnum.LIST);
         if (findFirstToscaElement.isLeft()) {
             returnedElement = Either.left((List<T>) findFirstToscaElement.left().value());
         }
         return returnedElement;
-
     }
 
     @SuppressWarnings("unchecked")
     public static <T> Either<Map<String, T>, ResultStatusEnum> findFirstToscaMapElement(Map<String, Object> toscaJson,
                                                                                         TypeUtils.ToscaTagNamesEnum toscaTagName) {
         Either<Map<String, T>, ResultStatusEnum> returnedElement = Either.right(ResultStatusEnum.ELEMENT_NOT_FOUND);
-        Either<Object, ResultStatusEnum> findFirstToscaElement = findToscaElement(toscaJson, toscaTagName,
-            ToscaElementTypeEnum.MAP);
+        Either<Object, ResultStatusEnum> findFirstToscaElement = findToscaElement(toscaJson, toscaTagName, ToscaElementTypeEnum.MAP);
         if (findFirstToscaElement.isLeft()) {
             returnedElement = Either.left((Map<String, T>) findFirstToscaElement.left().value());
         }
         return returnedElement;
-
     }
 
     public static Either<String, ResultStatusEnum> findFirstToscaStringElement(Map<String, Object> toscaJson,
                                                                                TypeUtils.ToscaTagNamesEnum toscaTagName) {
         Either<String, ResultStatusEnum> returnedElement = Either.right(ResultStatusEnum.ELEMENT_NOT_FOUND);
-        Either<Object, ResultStatusEnum> findFirstToscaElements = findToscaElement(toscaJson, toscaTagName,
-            ToscaElementTypeEnum.STRING);
+        Either<Object, ResultStatusEnum> findFirstToscaElements = findToscaElement(toscaJson, toscaTagName, ToscaElementTypeEnum.STRING);
         if (findFirstToscaElements.isLeft()) {
             returnedElement = Either.left((String) findFirstToscaElements.left().value());
         }
@@ -324,8 +252,7 @@ public final class ImportUtils {
     }
 
     /**
-     * searches for first Tosca in Json map (toscaJson) boolean element by name (toscaTagName) returns found element or
-     * ELEMENT_NOT_FOUND status
+     * searches for first Tosca in Json map (toscaJson) boolean element by name (toscaTagName) returns found element or ELEMENT_NOT_FOUND status
      *
      * @param toscaJson
      * @param toscaTagName
@@ -334,8 +261,7 @@ public final class ImportUtils {
     public static Either<String, ResultStatusEnum> findFirstToscaBooleanElement(Map<String, Object> toscaJson,
                                                                                 TypeUtils.ToscaTagNamesEnum toscaTagName) {
         Either<String, ResultStatusEnum> returnedElement = Either.right(ResultStatusEnum.ELEMENT_NOT_FOUND);
-        Either<Object, ResultStatusEnum> findFirstToscaElements = findToscaElement(toscaJson, toscaTagName,
-            ToscaElementTypeEnum.BOOLEAN);
+        Either<Object, ResultStatusEnum> findFirstToscaElements = findToscaElement(toscaJson, toscaTagName, ToscaElementTypeEnum.BOOLEAN);
         if (findFirstToscaElements.isLeft()) {
             returnedElement = Either.left(String.valueOf(findFirstToscaElements.left().value()));
         }
@@ -349,8 +275,7 @@ public final class ImportUtils {
         }
     }
 
-    private static List<PropertyConstraint> getPropertyConstraints(final Map<String, Object> propertyValue,
-                                                                   final String propertyType) {
+    private static List<PropertyConstraint> getPropertyConstraints(final Map<String, Object> propertyValue, final String propertyType) {
         final List<Object> propertyFieldConstraints = findCurrentLevelConstraintsElement(propertyValue);
         if (CollectionUtils.isEmpty(propertyFieldConstraints)) {
             return Collections.emptyList();
@@ -358,12 +283,9 @@ public final class ImportUtils {
         final List<PropertyConstraint> constraintList = new ArrayList<>();
         final Type constraintType = new TypeToken<PropertyConstraint>() {
         }.getType();
-        final Gson gson = new GsonBuilder().registerTypeAdapter(constraintType, new PropertyConstraintDeserialiser())
-            .create();
-
+        final Gson gson = new GsonBuilder().registerTypeAdapter(constraintType, new PropertyConstraintDeserialiser()).create();
         for (final Object constraintJson : propertyFieldConstraints) {
-            final PropertyConstraint propertyConstraint = validateAndGetPropertyConstraint(propertyType, constraintType,
-                gson, constraintJson);
+            final PropertyConstraint propertyConstraint = validateAndGetPropertyConstraint(propertyType, constraintType, gson, constraintJson);
             constraintList.add(propertyConstraint);
         }
         return constraintList;
@@ -380,26 +302,22 @@ public final class ImportUtils {
             }
         }
         return constraints;
-
     }
 
-    private static PropertyConstraint validateAndGetPropertyConstraint(String propertyType, Type constraintType,
-                                                                       Gson gson, Object constraintJson) {
+    private static PropertyConstraint validateAndGetPropertyConstraint(String propertyType, Type constraintType, Gson gson, Object constraintJson) {
         PropertyConstraint propertyConstraint;
         try {
             propertyConstraint = gson.fromJson(gson.toJson(constraintJson), constraintType);
         } catch (ClassCastException | JsonParseException e) {
-            throw new ByActionStatusComponentException(ActionStatus.INVALID_PROPERTY_CONSTRAINTS_FORMAT,
-                constraintJson.toString());
+            throw new ByActionStatusComponentException(ActionStatus.INVALID_PROPERTY_CONSTRAINTS_FORMAT, constraintJson.toString());
         }
         if (propertyConstraint != null && propertyConstraint instanceof ValidValuesConstraint) {
             try {
                 ((ValidValuesConstraint) propertyConstraint).validateType(propertyType);
             } catch (ConstraintValueDoNotMatchPropertyTypeException e) {
-                BeEcompErrorManager.getInstance().logInternalFlowError("GetInitializedPropertyConstraint",
-                    e.getMessage(), BeEcompErrorManager.ErrorSeverity.ERROR);
-                throw new ByActionStatusComponentException(ActionStatus.INVALID_PROPERTY_CONSTRAINTS,
-                    ConstraintType.VALID_VALUES.name(),
+                BeEcompErrorManager.getInstance()
+                    .logInternalFlowError("GetInitializedPropertyConstraint", e.getMessage(), BeEcompErrorManager.ErrorSeverity.ERROR);
+                throw new ByActionStatusComponentException(ActionStatus.INVALID_PROPERTY_CONSTRAINTS, ConstraintType.VALID_VALUES.name(),
                     ((ValidValuesConstraint) propertyConstraint).getValidValues().toString(), propertyType);
             }
         }
@@ -407,41 +325,29 @@ public final class ImportUtils {
     }
 
     public static PropertyDefinition createModuleProperty(Map<String, Object> propertyValue) {
-
         PropertyDefinition propertyDef = new PropertyDefinition();
         setField(propertyValue, TypeUtils.ToscaTagNamesEnum.TYPE, propertyDef::setType);
-        setFieldBoolean(propertyValue, ToscaTagNamesEnum.REQUIRED,
-            req -> propertyDef.setRequired(Boolean.parseBoolean(req)));
+        setFieldBoolean(propertyValue, ToscaTagNamesEnum.REQUIRED, req -> propertyDef.setRequired(Boolean.parseBoolean(req)));
         setField(propertyValue, TypeUtils.ToscaTagNamesEnum.DESCRIPTION, propertyDef::setDescription);
-
-        setJsonStringField(propertyValue, TypeUtils.ToscaTagNamesEnum.DEFAULT_VALUE, propertyDef.getType(),
-            propertyDef::setDefaultValue);
-        setJsonStringField(propertyValue, TypeUtils.ToscaTagNamesEnum.VALUE, propertyDef.getType(),
-            propertyDef::setValue);
-
-        setFieldBoolean(propertyValue, TypeUtils.ToscaTagNamesEnum.IS_PASSWORD,
-            pass -> propertyDef.setPassword(Boolean.parseBoolean(pass)));
+        setJsonStringField(propertyValue, TypeUtils.ToscaTagNamesEnum.DEFAULT_VALUE, propertyDef.getType(), propertyDef::setDefaultValue);
+        setJsonStringField(propertyValue, TypeUtils.ToscaTagNamesEnum.VALUE, propertyDef.getType(), propertyDef::setValue);
+        setFieldBoolean(propertyValue, TypeUtils.ToscaTagNamesEnum.IS_PASSWORD, pass -> propertyDef.setPassword(Boolean.parseBoolean(pass)));
         setField(propertyValue, TypeUtils.ToscaTagNamesEnum.STATUS, propertyDef::setStatus);
         setSchema(propertyValue, propertyDef);
         setPropertyConstraints(propertyValue, propertyDef);
-
         return propertyDef;
     }
 
-    private static void setJsonStringField(Map<String, Object> propertyValue, ToscaTagNamesEnum elementName,
-                                           String type, Consumer<String> setter) {
-        Either<Object, ResultStatusEnum> eitherValue = findToscaElement(propertyValue, elementName,
-            ToscaElementTypeEnum.ALL);
+    private static void setJsonStringField(Map<String, Object> propertyValue, ToscaTagNamesEnum elementName, String type, Consumer<String> setter) {
+        Either<Object, ResultStatusEnum> eitherValue = findToscaElement(propertyValue, elementName, ToscaElementTypeEnum.ALL);
         if (eitherValue.isLeft()) {
             String propertyJsonStringValue = getPropertyJsonStringValue(eitherValue.left().value(), type);
             setter.accept(propertyJsonStringValue);
         }
     }
 
-    public static Annotation createModuleAnnotation(Map<String, Object> annotationMap,
-                                                    AnnotationTypeOperations annotationTypeOperations) {
-        String parsedAnnotationType = findFirstToscaStringElement(annotationMap, TypeUtils.ToscaTagNamesEnum.TYPE)
-            .left().value();
+    public static Annotation createModuleAnnotation(Map<String, Object> annotationMap, AnnotationTypeOperations annotationTypeOperations) {
+        String parsedAnnotationType = findFirstToscaStringElement(annotationMap, TypeUtils.ToscaTagNamesEnum.TYPE).left().value();
         AnnotationTypeDefinition annotationTypeObject = annotationTypeOperations.getLatestType(parsedAnnotationType);
         if (annotationTypeObject != null) {
             Annotation annotation = new Annotation();
@@ -464,11 +370,9 @@ public final class ImportUtils {
                 for (Entry<String, PropertyDefinition> entry : value.entrySet()) {
                     String name = entry.getKey();
                     if (!PROPERTY_NAME_PATTERN_IGNORE_LENGTH.matcher(name).matches()) {
-                        log.debug("The property with invalid name {} occurred upon import resource {}. ", name,
-                            annotation.getName());
-                        result = Either.right(componentsUtils.getResponseFormat(componentsUtils
-                            .convertFromResultStatusEnum(ResultStatusEnum.INVALID_PROPERTY_NAME,
-                                JsonPresentationFields.PROPERTY)));
+                        log.debug("The property with invalid name {} occurred upon import resource {}. ", name, annotation.getName());
+                        result = Either.right(componentsUtils.getResponseFormat(
+                            componentsUtils.convertFromResultStatusEnum(ResultStatusEnum.INVALID_PROPERTY_NAME, JsonPresentationFields.PROPERTY)));
                     }
                     PropertyDefinition propertyDefinition = entry.getValue();
                     propertyDefinition.setValue(propertyDefinition.getName());
@@ -478,16 +382,13 @@ public final class ImportUtils {
             }
             annotation.setProperties(propertiesList);
         } else if (properties.right().value() != ResultStatusEnum.ELEMENT_NOT_FOUND) {
-            result = Either
-                .right(componentsUtils.getResponseFormat(componentsUtils.convertFromResultStatusEnum(properties
-                    .right()
-                    .value(), JsonPresentationFields.PROPERTY)));
+            result = Either.right(componentsUtils
+                .getResponseFormat(componentsUtils.convertFromResultStatusEnum(properties.right().value(), JsonPresentationFields.PROPERTY)));
         }
         return result;
     }
 
-    public static InputDefinition createModuleInput(final Map<String, Object> inputValue,
-                                                    final AnnotationTypeOperations annotationTypeOperations) {
+    public static InputDefinition createModuleInput(final Map<String, Object> inputValue, final AnnotationTypeOperations annotationTypeOperations) {
         return parseAnnotationsAndAddItToInput(createModuleInput(inputValue), inputValue, annotationTypeOperations);
     }
 
@@ -496,66 +397,52 @@ public final class ImportUtils {
         setField(inputValue, TypeUtils.ToscaTagNamesEnum.TYPE, inputDef::setType);
         setFieldBoolean(inputValue, ToscaTagNamesEnum.REQUIRED, req -> inputDef.setRequired(Boolean.parseBoolean(req)));
         setField(inputValue, TypeUtils.ToscaTagNamesEnum.DESCRIPTION, inputDef::setDescription);
-
-        setJsonStringField(inputValue, TypeUtils.ToscaTagNamesEnum.DEFAULT_VALUE, inputDef.getType(),
-            inputDef::setDefaultValue);
-
+        setJsonStringField(inputValue, TypeUtils.ToscaTagNamesEnum.DEFAULT_VALUE, inputDef.getType(), inputDef::setDefaultValue);
         setFieldBoolean(inputValue, TypeUtils.ToscaTagNamesEnum.IS_PASSWORD, pass -> inputDef.setPassword(Boolean.parseBoolean(pass)));
         setField(inputValue, TypeUtils.ToscaTagNamesEnum.STATUS, inputDef::setStatus);
         setField(inputValue, TypeUtils.ToscaTagNamesEnum.LABEL, inputDef::setLabel);
         setFieldBoolean(inputValue, TypeUtils.ToscaTagNamesEnum.HIDDEN, hidden -> inputDef.setHidden(Boolean.parseBoolean(hidden)));
         setFieldBoolean(inputValue, TypeUtils.ToscaTagNamesEnum.IMMUTABLE, immutable -> inputDef.setImmutable(Boolean.parseBoolean(immutable)));
-
         setSchema(inputValue, inputDef);
         setPropertyConstraints(inputValue, inputDef);
         return inputDef;
     }
 
-    public static InputDefinition parseAnnotationsAndAddItToInput(InputDefinition inputDef,
-                                                                  Map<String, Object> inputValue,
+    public static InputDefinition parseAnnotationsAndAddItToInput(InputDefinition inputDef, Map<String, Object> inputValue,
                                                                   AnnotationTypeOperations annotationTypeOperations) {
         Function<String, Annotation> elementGenByName = ImportUtils::createAnnotation;
-        Function<Map<String, Object>, Annotation> func = annotation -> createModuleAnnotation(annotation,
-            annotationTypeOperations);
-        return getElements(inputValue, TypeUtils.ToscaTagNamesEnum.ANNOTATIONS, elementGenByName, func).
-            left().map(annotations -> modifyInputWithAnnotations(inputDef, annotations)).
-            left().on(err -> {
-            log.error("Parsing annotations or adding them to the PropertyDataDefinition object failed");
-            return inputDef;
-        });
-    }
-
-    private static InputDefinition modifyInputWithAnnotations(InputDefinition inputDef,
-                                                              Map<String, Annotation> annotationsMap) {
+        Function<Map<String, Object>, Annotation> func = annotation -> createModuleAnnotation(annotation, annotationTypeOperations);
+        return getElements(inputValue, TypeUtils.ToscaTagNamesEnum.ANNOTATIONS, elementGenByName, func).left()
+            .map(annotations -> modifyInputWithAnnotations(inputDef, annotations)).left().on(err -> {
+                log.error("Parsing annotations or adding them to the PropertyDataDefinition object failed");
+                return inputDef;
+            });
+    }
+
+    private static InputDefinition modifyInputWithAnnotations(InputDefinition inputDef, Map<String, Annotation> annotationsMap) {
         setAnnotationsName(annotationsMap);
         inputDef.setAnnotationsToInput(annotationsMap.values());
         return inputDef;
     }
 
     public static AttributeDefinition createModuleAttribute(Map<String, Object> attributeMap) {
-
         AttributeDefinition attributeDef = new AttributeDefinition();
         setField(attributeMap, TypeUtils.ToscaTagNamesEnum.TYPE, attributeDef::setType);
         setField(attributeMap, TypeUtils.ToscaTagNamesEnum.DESCRIPTION, attributeDef::setDescription);
         setField(attributeMap, TypeUtils.ToscaTagNamesEnum.STATUS, attributeDef::setStatus);
-
-        setJsonStringField(attributeMap, TypeUtils.ToscaTagNamesEnum.DEFAULT_VALUE, attributeDef.getType(),
-            attributeDef::set_default);
-
+        setJsonStringField(attributeMap, TypeUtils.ToscaTagNamesEnum.DEFAULT_VALUE, attributeDef.getType(), attributeDef::set_default);
         setEntrySchema(attributeMap, attributeDef);
         return attributeDef;
     }
 
-    private static void setSchema(final Map<String, Object> propertyValue,
-                                  final PropertyDefinition propertyDefinition) {
+    private static void setSchema(final Map<String, Object> propertyValue, final PropertyDefinition propertyDefinition) {
         final Either<Object, ResultStatusEnum> schemaElementRes = findEntrySchemaElement(propertyValue);
         if (schemaElementRes.isLeft()) {
             propertyDefinition.setSchema(getSchema(schemaElementRes.left().value()));
         }
     }
 
-    private static void setEntrySchema(final Map<String, Object> toscaJsonMap,
-                                       final AttributeDefinition attributeDefinition) {
+    private static void setEntrySchema(final Map<String, Object> toscaJsonMap, final AttributeDefinition attributeDefinition) {
         final Either<Object, ResultStatusEnum> schemaElementRes = findEntrySchemaElement(toscaJsonMap);
         if (schemaElementRes.isLeft()) {
             attributeDefinition.setEntry_schema(createEntrySchema(schemaElementRes.left().value()));
@@ -592,62 +479,48 @@ public final class ImportUtils {
         return entrySchema;
     }
 
-    private static void setField(Map<String, Object> toscaJson, TypeUtils.ToscaTagNamesEnum tagName,
-                                 Consumer<String> setter) {
+    private static void setField(Map<String, Object> toscaJson, TypeUtils.ToscaTagNamesEnum tagName, Consumer<String> setter) {
         Either<String, ResultStatusEnum> fieldStringValue = findFirstToscaStringElement(toscaJson, tagName);
         if (fieldStringValue.isLeft()) {
             setter.accept(fieldStringValue.left().value());
         }
-
     }
 
-    public static void setFieldBoolean(Map<String, Object> toscaJson, TypeUtils.ToscaTagNamesEnum tagName,
-                                       Consumer<String> setter) {
+    public static void setFieldBoolean(Map<String, Object> toscaJson, TypeUtils.ToscaTagNamesEnum tagName, Consumer<String> setter) {
         Either<String, ResultStatusEnum> fieldStringValue = findFirstToscaBooleanElement(toscaJson, tagName);
         if (fieldStringValue.isLeft()) {
             setter.accept(fieldStringValue.left().value());
         }
-
     }
 
-    public static Either<Map<String, PropertyDefinition>, ResultStatusEnum> getProperties(
-        Map<String, Object> toscaJson) {
+    public static Either<Map<String, PropertyDefinition>, ResultStatusEnum> getProperties(Map<String, Object> toscaJson) {
         Function<String, PropertyDefinition> elementGenByName = ImportUtils::createProperties;
         Function<Map<String, Object>, PropertyDefinition> func = ImportUtils::createModuleProperty;
-
         return getElements(toscaJson, TypeUtils.ToscaTagNamesEnum.PROPERTIES, elementGenByName, func);
-
     }
 
     public static Either<Map<String, AttributeDefinition>, ResultStatusEnum> getAttributes(final Map<String, Object> toscaJson) {
         final Function<String, AttributeDefinition> elementGenByName = ImportUtils::createAttribute;
         final Function<Map<String, Object>, AttributeDefinition> func = ImportUtils::createModuleAttribute;
-
         return getElements(toscaJson, ToscaTagNamesEnum.ATTRIBUTES, elementGenByName, func);
     }
 
     public static Either<Map<String, InputDefinition>, ResultStatusEnum> getInputs(Map<String, Object> toscaJson,
                                                                                    AnnotationTypeOperations annotationTypeOperations) {
         Function<String, InputDefinition> elementGenByName = ImportUtils::createInputs;
-        Function<Map<String, Object>, InputDefinition> func = object -> createModuleInput(object,
-            annotationTypeOperations);
-
+        Function<Map<String, Object>, InputDefinition> func = object -> createModuleInput(object, annotationTypeOperations);
         return getElements(toscaJson, TypeUtils.ToscaTagNamesEnum.INPUTS, elementGenByName, func);
-
     }
 
     public static Either<Map<String, InputDefinition>, ResultStatusEnum> getInputs(final Map<String, Object> toscaJson) {
-        return getElements(toscaJson, TypeUtils.ToscaTagNamesEnum.INPUTS, ImportUtils::createInputs,
-            ImportUtils::createModuleInput);
+        return getElements(toscaJson, TypeUtils.ToscaTagNamesEnum.INPUTS, ImportUtils::createInputs, ImportUtils::createModuleInput);
     }
 
-    public static <T> Either<Map<String, T>, ResultStatusEnum> getElements(Map<String, Object> toscaJson,
-                                                                           TypeUtils.ToscaTagNamesEnum elementTagName,
+    public static <T> Either<Map<String, T>, ResultStatusEnum> getElements(Map<String, Object> toscaJson, TypeUtils.ToscaTagNamesEnum elementTagName,
                                                                            Function<String, T> elementGenByName,
                                                                            Function<Map<String, Object>, T> func) {
         Either<Map<String, T>, ResultStatusEnum> eitherResult = Either.right(ResultStatusEnum.ELEMENT_NOT_FOUND);
-        Either<Map<String, Object>, ResultStatusEnum> toscaAttributes = findFirstToscaMapElement(toscaJson,
-            elementTagName);
+        Either<Map<String, Object>, ResultStatusEnum> toscaAttributes = findFirstToscaMapElement(toscaJson, elementTagName);
         if (toscaAttributes.isLeft()) {
             Map<String, Object> jsonAttributes = toscaAttributes.left().value();
             Map<String, T> moduleAttributes = new HashMap<>();
@@ -655,8 +528,7 @@ public final class ImportUtils {
             while (propertiesNameValue.hasNext()) {
                 Entry<String, Object> attributeNameValue = propertiesNameValue.next();
                 if (attributeNameValue.getValue() instanceof Map) {
-                    @SuppressWarnings("unchecked")
-                    T attribute = func.apply((Map<String, Object>) attributeNameValue.getValue());
+                    @SuppressWarnings("unchecked") T attribute = func.apply((Map<String, Object>) attributeNameValue.getValue());
                     if (attribute != null) {
                         moduleAttributes.put(String.valueOf(attributeNameValue.getKey()), attribute);
                     }
@@ -668,15 +540,12 @@ public final class ImportUtils {
             if (moduleAttributes.size() > 0) {
                 eitherResult = Either.left(moduleAttributes);
             }
-
         }
         return eitherResult;
-
     }
 
     private static AttributeDefinition createAttribute(String name) {
         AttributeDefinition attribute = new AttributeDefinition();
-
         attribute.setName(name);
         return attribute;
     }
@@ -690,7 +559,6 @@ public final class ImportUtils {
 
     private static InputDefinition createInputs(String name) {
         InputDefinition input = new InputDefinition();
-
         input.setName(name);
         return input;
     }
@@ -702,11 +570,8 @@ public final class ImportUtils {
     }
 
     public static Either<List<HeatParameterDefinition>, ResultStatusEnum> getHeatParameters(Map<String, Object> heatData, String artifactType) {
-
-        Either<List<HeatParameterDefinition>, ResultStatusEnum> eitherResult = Either
-            .right(ResultStatusEnum.ELEMENT_NOT_FOUND);
-        Either<Map<String, Object>, ResultStatusEnum> toscaProperties = findFirstToscaMapElement(heatData,
-            TypeUtils.ToscaTagNamesEnum.PARAMETERS);
+        Either<List<HeatParameterDefinition>, ResultStatusEnum> eitherResult = Either.right(ResultStatusEnum.ELEMENT_NOT_FOUND);
+        Either<Map<String, Object>, ResultStatusEnum> toscaProperties = findFirstToscaMapElement(heatData, TypeUtils.ToscaTagNamesEnum.PARAMETERS);
         if (toscaProperties.isLeft()) {
             Map<String, Object> jsonProperties = toscaProperties.left().value();
             List<HeatParameterDefinition> moduleProperties = new ArrayList<>();
@@ -715,8 +580,7 @@ public final class ImportUtils {
                 Entry<String, Object> propertyNameValue = propertiesNameValue.next();
                 if (propertyNameValue.getValue() instanceof Map || propertyNameValue.getValue() instanceof List) {
                     if (!artifactType.equals(ArtifactTypeEnum.HEAT_ENV.getType())) {
-                        @SuppressWarnings("unchecked")
-                        Either<HeatParameterDefinition, ResultStatusEnum> propertyStatus = createModuleHeatParameter(
+                        @SuppressWarnings("unchecked") Either<HeatParameterDefinition, ResultStatusEnum> propertyStatus = createModuleHeatParameter(
                             (Map<String, Object>) propertyNameValue.getValue());
                         if (propertyStatus.isRight()) {
                             return Either.right(propertyStatus.right().value());
@@ -730,36 +594,29 @@ public final class ImportUtils {
                 } else {
                     addHeatParamDefinition(moduleProperties, propertyNameValue, false);
                 }
-
             }
-
             if (!isEmpty(moduleProperties)) {
                 eitherResult = Either.left(moduleProperties);
             }
-
         }
         return eitherResult;
-
     }
 
-    private static void addHeatParamDefinition(List<HeatParameterDefinition> moduleProperties,
-                                               Entry<String, Object> propertyNameValue, boolean isJson) {
+    private static void addHeatParamDefinition(List<HeatParameterDefinition> moduleProperties, Entry<String, Object> propertyNameValue,
+                                               boolean isJson) {
         HeatParameterDefinition property = new HeatParameterDefinition();
         Object value = propertyNameValue.getValue();
         if (value != null) {
-            property.setDefaultValue(
-                isJson ? new Gson().toJson(value) : StringEscapeUtils.escapeJava(String.valueOf(value)));
+            property.setDefaultValue(isJson ? new Gson().toJson(value) : StringEscapeUtils.escapeJava(String.valueOf(value)));
         }
         property.setName(String.valueOf(propertyNameValue.getKey()));
         moduleProperties.add(property);
     }
 
-    private static Either<HeatParameterDefinition, ResultStatusEnum> createModuleHeatParameter(
-        Map<String, Object> propertyValue) {
+    private static Either<HeatParameterDefinition, ResultStatusEnum> createModuleHeatParameter(Map<String, Object> propertyValue) {
         HeatParameterDefinition propertyDef = new HeatParameterDefinition();
         String type;
-        Either<String, ResultStatusEnum> propertyFieldType = findFirstToscaStringElement(propertyValue,
-            TypeUtils.ToscaTagNamesEnum.TYPE);
+        Either<String, ResultStatusEnum> propertyFieldType = findFirstToscaStringElement(propertyValue, TypeUtils.ToscaTagNamesEnum.TYPE);
         if (propertyFieldType.isLeft()) {
             type = propertyFieldType.left().value();
             propertyDef.setType(type);
@@ -771,20 +628,18 @@ public final class ImportUtils {
         if (propertyFieldDescription.isLeft()) {
             propertyDef.setDescription(propertyFieldDescription.left().value());
         }
-
-        Either<Object, ResultStatusEnum> propertyFieldDefaultVal = findToscaElement(propertyValue,
-            TypeUtils.ToscaTagNamesEnum.DEFAULT_VALUE, ToscaElementTypeEnum.ALL);
+        Either<Object, ResultStatusEnum> propertyFieldDefaultVal = findToscaElement(propertyValue, TypeUtils.ToscaTagNamesEnum.DEFAULT_VALUE,
+            ToscaElementTypeEnum.ALL);
         if (propertyFieldDefaultVal.isLeft()) {
             if (propertyFieldDefaultVal.left().value() == null) {
                 return Either.right(ResultStatusEnum.INVALID_PROPERTY_VALUE);
             }
             Object value = propertyFieldDefaultVal.left().value();
-            String defaultValue = type.equals(HeatParameterType.JSON.getType()) ? new Gson().toJson(value)
-                : StringEscapeUtils.escapeJava(String.valueOf(value));
+            String defaultValue =
+                type.equals(HeatParameterType.JSON.getType()) ? new Gson().toJson(value) : StringEscapeUtils.escapeJava(String.valueOf(value));
             propertyDef.setDefaultValue(defaultValue);
             propertyDef.setCurrentValue(defaultValue);
         }
-
         return Either.left(propertyDef);
     }
 
@@ -799,16 +654,14 @@ public final class ImportUtils {
             return null;
         }
         ToscaPropertyType validType = ToscaPropertyType.isValidType(type);
-        if (validType == null || validType == ToscaPropertyType.JSON || validType == ToscaPropertyType.MAP
-            || validType == ToscaPropertyType.LIST) {
+        if (validType == null || validType == ToscaPropertyType.JSON || validType == ToscaPropertyType.MAP || validType == ToscaPropertyType.LIST) {
             return gson.toJson(value);
         }
         return value.toString();
     }
 
     /**
-     * removes from Json map (toscaJson) first element found by name (elementName) note that this method could update
-     * the received argument toscaJson
+     * removes from Json map (toscaJson) first element found by name (elementName) note that this method could update the received argument toscaJson
      *
      * @param toscaJson
      * @param elementName
@@ -825,4 +678,57 @@ public final class ImportUtils {
             }
         }
     }
+
+    public enum ResultStatusEnum {
+        ELEMENT_NOT_FOUND, GENERAL_ERROR, OK, INVALID_PROPERTY_DEFAULT_VALUE, INVALID_PROPERTY_TYPE, INVALID_PROPERTY_VALUE, MISSING_ENTRY_SCHEMA_TYPE, INVALID_PROPERTY_NAME, INVALID_ATTRIBUTE_NAME
+    }
+
+    public enum ToscaElementTypeEnum {
+        BOOLEAN, STRING, MAP, LIST, ALL
+    }
+
+    private static class CustomResolver extends Resolver {
+
+        @Override
+        protected void addImplicitResolvers() {
+            // avoid implicit resolvers for strings that can be interpreted as boolean values
+            addImplicitResolver(Tag.STR, EMPTY, "");
+            addImplicitResolver(Tag.STR, NULL, null);
+            addImplicitResolver(Tag.NULL, NULL, "~nN\0");
+            addImplicitResolver(Tag.NULL, EMPTY, null);
+            addImplicitResolver(Tag.INT, INT, "-+0123456789");
+            addImplicitResolver(Tag.FLOAT, FLOAT, "-+0123456789.");
+            addImplicitResolver(Tag.YAML, YAML, "!&*");
+        }
+    }
+
+    private static class YamlLoader extends YamlProcessor {
+
+        public Yaml getStrictYamlLoader() {
+            return createYaml();
+        }
+    }
+
+    public static class Constants {
+
+        public static final String FIRST_NON_CERTIFIED_VERSION = "0.1";
+        public static final String VENDOR_NAME = "ONAP (Tosca)";
+        public static final String VENDOR_RELEASE = "1.0.0.wd03";
+        public static final LifecycleStateEnum NORMATIVE_TYPE_LIFE_CYCLE = LifecycleStateEnum.CERTIFIED;
+        public static final LifecycleStateEnum NORMATIVE_TYPE_LIFE_CYCLE_NOT_CERTIFIED_CHECKOUT = LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT;
+        public static final boolean NORMATIVE_TYPE_HIGHEST_VERSION = true;
+        public static final String ABSTRACT_CATEGORY_NAME = "Generic";
+        public static final String ABSTRACT_SUBCATEGORY = "Abstract";
+        public static final String DEFAULT_ICON = "defaulticon";
+        public static final String INNER_VFC_DESCRIPTION = "Not reusable inner VFC";
+        public static final String USER_DEFINED_RESOURCE_NAMESPACE_PREFIX = "org.openecomp.resource.";
+        public static final String UI_JSON_PAYLOAD_NAME = "payloadName";
+        public static final String CVFC_DESCRIPTION = "Complex node type that is used as nested type in VF";
+        public static final String ESCAPED_DOUBLE_QUOTE = "\"";
+        public static final String QUOTE = "'";
+        public static final String VF_DESCRIPTION = "Nested VF in service";
+
+        private Constants() {
+        }
+    }
 }
index 2f43a5b..da84921 100644 (file)
@@ -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.
  * Modifications copyright (c) 2019 Nokia
  * ================================================================================
  */
-
 package org.openecomp.sdc.be.components.impl;
 
 import fj.data.Either;
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.Collections;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+import java.util.Objects;
+import java.util.Optional;
+import java.util.stream.Collectors;
 import org.apache.commons.collections.CollectionUtils;
 import org.apache.commons.collections4.ListUtils;
 import org.apache.commons.collections4.MapUtils;
@@ -76,22 +84,11 @@ import org.openecomp.sdc.common.log.wrappers.Logger;
 import org.openecomp.sdc.exception.ResponseFormat;
 import org.springframework.beans.factory.annotation.Autowired;
 
-import java.util.ArrayList;
-import java.util.Arrays;
-import java.util.Collections;
-import java.util.HashMap;
-import java.util.List;
-import java.util.Map;
-import java.util.Objects;
-import java.util.Optional;
-import java.util.stream.Collectors;
-
 @org.springframework.stereotype.Component("inputsBusinessLogic")
 public class InputsBusinessLogic extends BaseBusinessLogic {
 
     private static final String CREATE_INPUT = "CreateInput";
     private static final String UPDATE_INPUT = "UpdateInput";
-
     private static final Logger log = Logger.getLogger(InputsBusinessLogic.class);
     private static final String FAILED_TO_FOUND_COMPONENT_ERROR = "Failed to found component {}, error: {}";
     private static final String GET_PROPERTIES_BY_INPUT = "get Properties by input";
@@ -101,23 +98,19 @@ public class InputsBusinessLogic extends BaseBusinessLogic {
     private static final String GOING_TO_EXECUTE_ROLLBACK_ON_UPDATE_INPUT = "Going to execute rollback on update input.";
     private static final String GOING_TO_EXECUTE_COMMIT_ON_UPDATE_INPUT = "Going to execute commit on update input.";
     private static final LoggerSupportability loggerSupportability = LoggerSupportability.getLogger(InputsBusinessLogic.class.getName());
-
     private final PropertyDeclarationOrchestrator propertyDeclarationOrchestrator;
     private final ComponentInstanceBusinessLogic componentInstanceBusinessLogic;
     private final DataTypeBusinessLogic dataTypeBusinessLogic;
 
     @Autowired
-    public InputsBusinessLogic(IElementOperation elementDao,
-        IGroupOperation groupOperation,
-        IGroupInstanceOperation groupInstanceOperation,
-        IGroupTypeOperation groupTypeOperation,
-        InterfaceOperation interfaceOperation,
-        InterfaceLifecycleOperation interfaceLifecycleTypeOperation,
-        PropertyDeclarationOrchestrator propertyDeclarationOrchestrator,
-        ComponentInstanceBusinessLogic componentInstanceBusinessLogic, DataTypeBusinessLogic dataTypeBusinessLogic,
-        ArtifactsOperations artifactToscaOperation) {
-        super(elementDao, groupOperation, groupInstanceOperation, groupTypeOperation,
-            interfaceOperation, interfaceLifecycleTypeOperation, artifactToscaOperation);
+    public InputsBusinessLogic(IElementOperation elementDao, IGroupOperation groupOperation, IGroupInstanceOperation groupInstanceOperation,
+                               IGroupTypeOperation groupTypeOperation, InterfaceOperation interfaceOperation,
+                               InterfaceLifecycleOperation interfaceLifecycleTypeOperation,
+                               PropertyDeclarationOrchestrator propertyDeclarationOrchestrator,
+                               ComponentInstanceBusinessLogic componentInstanceBusinessLogic, DataTypeBusinessLogic dataTypeBusinessLogic,
+                               ArtifactsOperations artifactToscaOperation) {
+        super(elementDao, groupOperation, groupInstanceOperation, groupTypeOperation, interfaceOperation, interfaceLifecycleTypeOperation,
+            artifactToscaOperation);
         this.propertyDeclarationOrchestrator = propertyDeclarationOrchestrator;
         this.componentInstanceBusinessLogic = componentInstanceBusinessLogic;
         this.dataTypeBusinessLogic = dataTypeBusinessLogic;
@@ -131,59 +124,50 @@ public class InputsBusinessLogic extends BaseBusinessLogic {
      * @return
      */
     public Either<List<InputDefinition>, ResponseFormat> getInputs(String userId, String componentId) {
-
         validateUserExists(userId);
-
         ComponentParametersView filters = new ComponentParametersView();
         filters.disableAll();
         filters.setIgnoreInputs(false);
-
-        Either<org.openecomp.sdc.be.model.Component, StorageOperationStatus> getComponentEither = toscaOperationFacade.getToscaElement(componentId, filters);
-        if(getComponentEither.isRight()){
+        Either<org.openecomp.sdc.be.model.Component, StorageOperationStatus> getComponentEither = toscaOperationFacade
+            .getToscaElement(componentId, filters);
+        if (getComponentEither.isRight()) {
             ActionStatus actionStatus = componentsUtils.convertFromStorageResponse(getComponentEither.right().value());
             log.debug(FAILED_TO_FOUND_COMPONENT_ERROR, componentId, actionStatus);
             return Either.right(componentsUtils.getResponseFormat(actionStatus));
-
         }
         org.openecomp.sdc.be.model.Component component = getComponentEither.left().value();
         List<InputDefinition> inputs = component.getInputs();
-
         return Either.left(inputs);
-
     }
 
-    public Either<List<ComponentInstanceInput>, ResponseFormat> getComponentInstanceInputs(String userId, String componentId, String componentInstanceId) {
-
+    public Either<List<ComponentInstanceInput>, ResponseFormat> getComponentInstanceInputs(String userId, String componentId,
+                                                                                           String componentInstanceId) {
         validateUserExists(userId);
         ComponentParametersView filters = new ComponentParametersView();
         filters.disableAll();
         filters.setIgnoreInputs(false);
         filters.setIgnoreComponentInstances(false);
         filters.setIgnoreComponentInstancesInputs(false);
-
-        Either<org.openecomp.sdc.be.model.Component, StorageOperationStatus> getComponentEither = toscaOperationFacade.getToscaElement(componentId, filters);
-        if(getComponentEither.isRight()){
+        Either<org.openecomp.sdc.be.model.Component, StorageOperationStatus> getComponentEither = toscaOperationFacade
+            .getToscaElement(componentId, filters);
+        if (getComponentEither.isRight()) {
             ActionStatus actionStatus = componentsUtils.convertFromStorageResponse(getComponentEither.right().value());
             log.debug(FAILED_TO_FOUND_COMPONENT_ERROR, componentId, actionStatus);
             return Either.right(componentsUtils.getResponseFormat(actionStatus));
-
         }
         org.openecomp.sdc.be.model.Component component = getComponentEither.left().value();
-
-        if(!ComponentValidations.validateComponentInstanceExist(component, componentInstanceId)){
+        if (!ComponentValidations.validateComponentInstanceExist(component, componentInstanceId)) {
             ActionStatus actionStatus = ActionStatus.COMPONENT_INSTANCE_NOT_FOUND;
             log.debug("Failed to found component instance inputs {}, error: {}", componentInstanceId, actionStatus);
-            loggerSupportability.log(LoggerSupportabilityActions.CREATE_INPUTS,component.getComponentMetadataForSupportLog(),
-                StatusCode.ERROR,"Failed to found component instance inputs componentInstanceId: {}",componentInstanceId);
+            loggerSupportability.log(LoggerSupportabilityActions.CREATE_INPUTS, component.getComponentMetadataForSupportLog(), StatusCode.ERROR,
+                "Failed to found component instance inputs componentInstanceId: {}", componentInstanceId);
             return Either.right(componentsUtils.getResponseFormat(actionStatus));
         }
-               Map<String, List<ComponentInstanceInput>> ciInputs =
-                               Optional.ofNullable(component.getComponentInstancesInputs()).orElse(Collections.emptyMap());
-
-               // Set Constraints on Input
-               MapUtils.emptyIfNull(ciInputs).values()
-                               .forEach(inputs -> ListUtils.emptyIfNull(inputs)
-                                               .forEach(input -> input.setConstraints(setInputConstraint(input))));
+        Map<String, List<ComponentInstanceInput>> ciInputs = Optional.ofNullable(component.getComponentInstancesInputs())
+            .orElse(Collections.emptyMap());
+        // Set Constraints on Input
+        MapUtils.emptyIfNull(ciInputs).values()
+            .forEach(inputs -> ListUtils.emptyIfNull(inputs).forEach(input -> input.setConstraints(setInputConstraint(input))));
         return Either.left(ciInputs.getOrDefault(componentInstanceId, Collections.emptyList()));
     }
 
@@ -195,59 +179,47 @@ public class InputsBusinessLogic extends BaseBusinessLogic {
      * @param inputId
      * @return
      */
-
-    public Either<List<ComponentInstanceProperty>, ResponseFormat> getComponentInstancePropertiesByInputId(String userId, String componentId, String instanceId, String inputId) {
+    public Either<List<ComponentInstanceProperty>, ResponseFormat> getComponentInstancePropertiesByInputId(String userId, String componentId,
+                                                                                                           String instanceId, String inputId) {
         validateUserExists(userId);
         String parentId = componentId;
         org.openecomp.sdc.be.model.Component component;
         ComponentParametersView filters = new ComponentParametersView();
         filters.disableAll();
         filters.setIgnoreComponentInstances(false);
-
-        if(!instanceId.equals(inputId)){
-
-
-            Either<org.openecomp.sdc.be.model.Component, StorageOperationStatus> getComponentEither = toscaOperationFacade.getToscaElement(parentId, filters);
-
-            if(getComponentEither.isRight()){
+        if (!instanceId.equals(inputId)) {
+            Either<org.openecomp.sdc.be.model.Component, StorageOperationStatus> getComponentEither = toscaOperationFacade
+                .getToscaElement(parentId, filters);
+            if (getComponentEither.isRight()) {
                 ActionStatus actionStatus = componentsUtils.convertFromStorageResponse(getComponentEither.right().value());
                 log.debug(FAILED_TO_FOUND_COMPONENT_ERROR, parentId, actionStatus);
                 return Either.right(componentsUtils.getResponseFormat(actionStatus));
-
             }
             component = getComponentEither.left().value();
-            Optional<ComponentInstance> ciOp = component.getComponentInstances().stream().filter(ci ->ci.getUniqueId().equals(instanceId)).findAny();
-            if(ciOp.isPresent()){
+            Optional<ComponentInstance> ciOp = component.getComponentInstances().stream().filter(ci -> ci.getUniqueId().equals(instanceId)).findAny();
+            if (ciOp.isPresent()) {
                 parentId = ciOp.get().getComponentUid();
             }
-
         }
-
         filters.setIgnoreInputs(false);
-
         filters.setIgnoreComponentInstancesProperties(false);
         filters.setIgnoreComponentInstancesInputs(false);
         filters.setIgnoreProperties(false);
-
-        Either<org.openecomp.sdc.be.model.Component, StorageOperationStatus> getComponentEither = toscaOperationFacade.getToscaElement(parentId, filters);
-
-        if(getComponentEither.isRight()){
+        Either<org.openecomp.sdc.be.model.Component, StorageOperationStatus> getComponentEither = toscaOperationFacade
+            .getToscaElement(parentId, filters);
+        if (getComponentEither.isRight()) {
             ActionStatus actionStatus = componentsUtils.convertFromStorageResponse(getComponentEither.right().value());
             log.debug(FAILED_TO_FOUND_COMPONENT_ERROR, parentId, actionStatus);
             return Either.right(componentsUtils.getResponseFormat(actionStatus));
-
         }
         component = getComponentEither.left().value();
-
         Optional<InputDefinition> op = component.getInputs().stream().filter(in -> in.getUniqueId().equals(inputId)).findFirst();
-        if(!op.isPresent()){
+        if (!op.isPresent()) {
             ActionStatus actionStatus = componentsUtils.convertFromStorageResponse(getComponentEither.right().value());
             log.debug(FAILED_TO_FOUND_INPUT_UNDER_COMPONENT_ERROR, inputId, parentId, actionStatus);
             return Either.right(componentsUtils.getResponseFormat(actionStatus));
         }
-
         return Either.left(componentInstanceBusinessLogic.getComponentInstancePropertiesByInputId(component, inputId));
-
     }
 
     private String updateInputObjectValue(InputDefinition currentInput, InputDefinition newInput, Map<String, DataTypeDefinition> dataTypes) {
@@ -255,7 +227,6 @@ public class InputsBusinessLogic extends BaseBusinessLogic {
         String propertyType = currentInput.getType();
         ToscaPropertyType type = ToscaPropertyType.isValidType(propertyType);
         log.debug("The type of the property {} is {}", currentInput.getUniqueId(), propertyType);
-
         if (type == ToscaPropertyType.LIST || type == ToscaPropertyType.MAP) {
             SchemaDefinition def = currentInput.getSchema();
             if (def == null) {
@@ -270,14 +241,14 @@ public class InputsBusinessLogic extends BaseBusinessLogic {
             innerType = propDef.getType();
         }
         // Specific Update Logic
-
-        Either<Object, Boolean> isValid = propertyOperation.validateAndUpdatePropertyValue(propertyType, newInput.getDefaultValue(), true, innerType, dataTypes);
-
+        Either<Object, Boolean> isValid = propertyOperation
+            .validateAndUpdatePropertyValue(propertyType, newInput.getDefaultValue(), true, innerType, dataTypes);
         String newValue = newInput.getDefaultValue();
         if (isValid.isRight()) {
             Boolean res = isValid.right().value();
             if (Boolean.FALSE.equals(res)) {
-                throw new ByActionStatusComponentException(componentsUtils.convertFromStorageResponse(DaoStatusConverter.convertJanusGraphStatusToStorageStatus(JanusGraphOperationStatus.ILLEGAL_ARGUMENT)));
+                throw new ByActionStatusComponentException(componentsUtils.convertFromStorageResponse(
+                    DaoStatusConverter.convertJanusGraphStatusToStorageStatus(JanusGraphOperationStatus.ILLEGAL_ARGUMENT)));
             }
         } else {
             Object object = isValid.left().value();
@@ -292,25 +263,22 @@ public class InputsBusinessLogic extends BaseBusinessLogic {
         return componentsOldInputs.stream().filter(in -> in.getUniqueId().equals(input.getUniqueId())).findFirst().orElse(null);
     }
 
-    public Either<List<InputDefinition>, ResponseFormat> updateInputsValue(ComponentTypeEnum componentType, String componentId, List<InputDefinition> inputs, String userId, boolean shouldLockComp, boolean inTransaction) {
-
+    public Either<List<InputDefinition>, ResponseFormat> updateInputsValue(ComponentTypeEnum componentType, String componentId,
+                                                                           List<InputDefinition> inputs, String userId, boolean shouldLockComp,
+                                                                           boolean inTransaction) {
         List<InputDefinition> returnInputs = new ArrayList<>();
         Either<List<InputDefinition>, ResponseFormat> result = null;
         org.openecomp.sdc.be.model.Component component = null;
-
         try {
             validateUserExists(userId);
-
             ComponentParametersView componentParametersView = new ComponentParametersView();
             componentParametersView.disableAll();
             componentParametersView.setIgnoreInputs(false);
             componentParametersView.setIgnoreUsers(false);
-                       componentParametersView.setIgnoreProperties(false);
-                       componentParametersView.setIgnoreComponentInstancesProperties(false);
-                       componentParametersView.setIgnoreComponentInstances(false);
-
+            componentParametersView.setIgnoreProperties(false);
+            componentParametersView.setIgnoreComponentInstancesProperties(false);
+            componentParametersView.setIgnoreComponentInstances(false);
             component = validateComponentExists(componentId, componentType, componentParametersView);
-
             if (shouldLockComp) {
                 try {
                     lockComponent(component, UPDATE_INPUT);
@@ -320,21 +288,17 @@ public class InputsBusinessLogic extends BaseBusinessLogic {
                     return result;
                 }
             }
-
             //Validate value and Constraint of input
-                       Either<Boolean, ResponseFormat> constraintValidatorResponse = validateInputValueConstraint(inputs);
+            Either<Boolean, ResponseFormat> constraintValidatorResponse = validateInputValueConstraint(inputs);
             if (constraintValidatorResponse.isRight()) {
-                log.error("Failed validation value and constraint of property: {}",
-                        constraintValidatorResponse.right().value());
+                log.error("Failed validation value and constraint of property: {}", constraintValidatorResponse.right().value());
                 return Either.right(constraintValidatorResponse.right().value());
             }
-
             validateCanWorkOnComponent(component, userId);
             Map<String, DataTypeDefinition> dataTypes;
             dataTypes = getAllDataTypes(applicationDataTypeCache);
-
             List<InputDefinition> componentsOldInputs = Optional.ofNullable(component.getInputs()).orElse(Collections.emptyList());
-            for (InputDefinition newInput: inputs) {
+            for (InputDefinition newInput : inputs) {
                 InputDefinition currInput = getInputFromInputsListById(componentsOldInputs, newInput);
                 if (currInput == null) {
                     ActionStatus actionStatus = ActionStatus.COMPONENT_NOT_FOUND;
@@ -350,7 +314,7 @@ public class InputsBusinessLogic extends BaseBusinessLogic {
                     currInput.setRequired(newInput.isRequired());
                 }
                 Either<InputDefinition, StorageOperationStatus> status = toscaOperationFacade.updateInputOfComponent(component, currInput);
-                if(status.isRight()){
+                if (status.isRight()) {
                     ActionStatus actionStatus = componentsUtils.convertFromStorageResponseForResourceInstanceProperty(status.right().value());
                     result = Either.right(componentsUtils.getResponseFormat(actionStatus, ""));
                     return result;
@@ -362,37 +326,32 @@ public class InputsBusinessLogic extends BaseBusinessLogic {
         } catch (ComponentException e) {
             log.debug(GOING_TO_EXECUTE_ROLLBACK_ON_UPDATE_INPUT);
             unlockRollbackWithException(component, e);
-        } catch (Exception e){
+        } catch (Exception e) {
             log.debug(GOING_TO_EXECUTE_ROLLBACK_ON_UPDATE_INPUT);
             unlockRollbackWithException(component, new ByActionStatusComponentException(ActionStatus.GENERAL_ERROR));
         }
         log.debug(GOING_TO_EXECUTE_COMMIT_ON_UPDATE_INPUT);
         unlockWithCommit(component);
         return result;
-
     }
 
     private Either<Boolean, ResponseFormat> validateInputValueConstraint(List<InputDefinition> inputs) {
-               PropertyValueConstraintValidationUtil propertyValueConstraintValidationUtil =
-                               PropertyValueConstraintValidationUtil.getInstance();
-               List<InputDefinition> inputDefinitions = new ArrayList<>();
-               for (InputDefinition inputDefinition : inputs) {
-                       InputDefinition inputDef = new InputDefinition();
-                       inputDefinition.setDefaultValue(inputDefinition.getDefaultValue());
-                       inputDefinition.setInputPath(inputDefinition.getSubPropertyInputPath());
-                       inputDefinition.setType(inputDefinition.getType());
-                       if (Objects.nonNull(inputDefinition.getParentPropertyType())) {
-                               ComponentInstanceProperty propertyDefinition = new ComponentInstanceProperty();
-                               propertyDefinition.setType(inputDefinition.getParentPropertyType());
-
-                               inputDefinition.setProperties(Collections.singletonList(propertyDefinition));
-                       }
-
-                       inputDefinitions.add(inputDef);
-               }
-
-               return propertyValueConstraintValidationUtil.validatePropertyConstraints(inputDefinitions, applicationDataTypeCache);
-       }
+        PropertyValueConstraintValidationUtil propertyValueConstraintValidationUtil = PropertyValueConstraintValidationUtil.getInstance();
+        List<InputDefinition> inputDefinitions = new ArrayList<>();
+        for (InputDefinition inputDefinition : inputs) {
+            InputDefinition inputDef = new InputDefinition();
+            inputDefinition.setDefaultValue(inputDefinition.getDefaultValue());
+            inputDefinition.setInputPath(inputDefinition.getSubPropertyInputPath());
+            inputDefinition.setType(inputDefinition.getType());
+            if (Objects.nonNull(inputDefinition.getParentPropertyType())) {
+                ComponentInstanceProperty propertyDefinition = new ComponentInstanceProperty();
+                propertyDefinition.setType(inputDefinition.getParentPropertyType());
+                inputDefinition.setProperties(Collections.singletonList(propertyDefinition));
+            }
+            inputDefinitions.add(inputDef);
+        }
+        return propertyValueConstraintValidationUtil.validatePropertyConstraints(inputDefinitions, applicationDataTypeCache);
+    }
 
     public Either<List<ComponentInstanceInput>, ResponseFormat> getInputsForComponentInput(String userId, String componentId, String inputId) {
         validateUserExists(userId);
@@ -403,59 +362,46 @@ public class InputsBusinessLogic extends BaseBusinessLogic {
         filters.setIgnoreInputs(false);
         filters.setIgnoreComponentInstancesInputs(false);
         filters.setIgnoreProperties(false);
-
-        Either<org.openecomp.sdc.be.model.Component, StorageOperationStatus> getComponentEither = toscaOperationFacade.getToscaElement(componentId, filters);
-
-        if(getComponentEither.isRight()){
+        Either<org.openecomp.sdc.be.model.Component, StorageOperationStatus> getComponentEither = toscaOperationFacade
+            .getToscaElement(componentId, filters);
+        if (getComponentEither.isRight()) {
             ActionStatus actionStatus = componentsUtils.convertFromStorageResponse(getComponentEither.right().value());
             log.debug(FAILED_TO_FOUND_COMPONENT_ERROR, componentId, actionStatus);
             return Either.right(componentsUtils.getResponseFormat(actionStatus));
-
         }
         component = getComponentEither.left().value();
-
         Optional<InputDefinition> op = component.getInputs().stream().filter(in -> in.getUniqueId().equals(inputId)).findFirst();
-        if(!op.isPresent()){
+        if (!op.isPresent()) {
             ActionStatus actionStatus = componentsUtils.convertFromStorageResponse(getComponentEither.right().value());
             log.debug(FAILED_TO_FOUND_INPUT_UNDER_COMPONENT_ERROR, inputId, componentId, actionStatus);
             return Either.right(componentsUtils.getResponseFormat(actionStatus));
         }
-
         return Either.left(componentInstanceBusinessLogic.getComponentInstanceInputsByInputId(component, inputId));
-
     }
 
     @Override
-    public Either<List<InputDefinition>, ResponseFormat> declareProperties(String userId, String componentId,
-            ComponentTypeEnum componentTypeEnum, ComponentInstInputsMap componentInstInputsMap) {
-
+    public Either<List<InputDefinition>, ResponseFormat> declareProperties(String userId, String componentId, ComponentTypeEnum componentTypeEnum,
+                                                                           ComponentInstInputsMap componentInstInputsMap) {
         return createMultipleInputs(userId, componentId, componentTypeEnum, componentInstInputsMap, true, false);
     }
 
-    public Either<List<InputDefinition>, ResponseFormat> createMultipleInputs(String userId, String componentId, ComponentTypeEnum componentType, ComponentInstInputsMap componentInstInputsMapUi, boolean shouldLockComp, boolean inTransaction) {
-
+    public Either<List<InputDefinition>, ResponseFormat> createMultipleInputs(String userId, String componentId, ComponentTypeEnum componentType,
+                                                                              ComponentInstInputsMap componentInstInputsMapUi, boolean shouldLockComp,
+                                                                              boolean inTransaction) {
         Either<List<InputDefinition>, ResponseFormat> result = null;
         org.openecomp.sdc.be.model.Component component = null;
-
         try {
             validateUserExists(userId);
-
             component = getAndValidateComponentForCreate(userId, componentId, componentType, shouldLockComp);
-
-            result =  propertyDeclarationOrchestrator.declarePropertiesToInputs(component, componentInstInputsMapUi)
-                    .left()
-                    .bind(inputsToCreate -> prepareInputsForCreation(userId, componentId, inputsToCreate))
-                    .right()
-                                       .map(componentsUtils::getResponseFormat);
-
+            result = propertyDeclarationOrchestrator.declarePropertiesToInputs(component, componentInstInputsMapUi).left()
+                .bind(inputsToCreate -> prepareInputsForCreation(userId, componentId, inputsToCreate)).right()
+                .map(componentsUtils::getResponseFormat);
             return result;
-
         } catch (ByResponseFormatComponentException e) {
             log.error("#createMultipleInputs: Exception thrown: ", e);
             result = Either.right(e.getResponseFormat());
             return result;
         } finally {
-
             if (!inTransaction) {
                 if (result == null || result.isRight()) {
                     log.debug(GOING_TO_EXECUTE_ROLLBACK_ON_CREATE_GROUP);
@@ -469,29 +415,25 @@ public class InputsBusinessLogic extends BaseBusinessLogic {
             if (shouldLockComp && component != null) {
                 graphLockOperation.unlockComponent(componentId, componentType.getNodeType());
             }
-
         }
     }
 
     /**
      * Creates a list input with a data type which has properties specified.
      *
-     * @param userId User ID
-     * @param componentId Component ID
-     * @param componentType Component type
+     * @param userId             User ID
+     * @param componentId        Component ID
+     * @param componentType      Component type
      * @param componentListInput Properties to be declared and input to be created
-     * @param shouldLockComp true if the component should be locked
-     * @param inTransaction true if already in transaction
+     * @param shouldLockComp     true if the component should be locked
+     * @param inTransaction      true if already in transaction
      */
-    public Either<List<InputDefinition>, ResponseFormat> createListInput(String userId, String componentId,
-        ComponentTypeEnum componentType, ComponentInstListInput componentListInput, boolean shouldLockComp,
-        boolean inTransaction) {
-
+    public Either<List<InputDefinition>, ResponseFormat> createListInput(String userId, String componentId, ComponentTypeEnum componentType,
+                                                                         ComponentInstListInput componentListInput, boolean shouldLockComp,
+                                                                         boolean inTransaction) {
         Either<List<InputDefinition>, ResponseFormat> result = null;
         org.openecomp.sdc.be.model.Component component = null;
-
         log.trace("#createListInput: enter");
-
         try {
             /* check if user exists */
             validateUserExists(userId);
@@ -608,22 +550,24 @@ public class InputsBusinessLogic extends BaseBusinessLogic {
         return dataType;
     }
 
-    private  Either<List<InputDefinition>, StorageOperationStatus> prepareInputsForCreation(String userId, String cmptId, List<InputDefinition> inputsToCreate) {
+    private Either<List<InputDefinition>, StorageOperationStatus> prepareInputsForCreation(String userId, String cmptId,
+                                                                                           List<InputDefinition> inputsToCreate) {
         Map<String, InputDefinition> inputsToPersist = MapUtil.toMap(inputsToCreate, InputDefinition::getName);
         assignOwnerIdToInputs(userId, inputsToPersist);
-               inputsToPersist.values()
-                               .forEach(input -> input.setConstraints(componentInstanceBusinessLogic.setInputConstraint(input)));
+        inputsToPersist.values()
+            .forEach(input -> input.setConstraints(componentInstanceBusinessLogic.setInputConstraint(input)));
 
         return toscaOperationFacade.addInputsToComponent(inputsToPersist, cmptId)
-                .left()
-                .map(persistedInputs -> inputsToCreate);
+            .left()
+            .map(persistedInputs -> inputsToCreate);
     }
 
     private void assignOwnerIdToInputs(String userId, Map<String, InputDefinition> inputsToCreate) {
         inputsToCreate.values().forEach(inputDefinition -> inputDefinition.setOwnerId(userId));
     }
 
-    public Either<List<InputDefinition>, ResponseFormat> createInputsInGraph(Map<String, InputDefinition> inputs, org.openecomp.sdc.be.model.Component component) {
+    public Either<List<InputDefinition>, ResponseFormat> createInputsInGraph(Map<String, InputDefinition> inputs,
+                                                                             org.openecomp.sdc.be.model.Component component) {
 
         List<InputDefinition> resourceProperties = component.getInputs();
 
@@ -634,22 +578,24 @@ public class InputsBusinessLogic extends BaseBusinessLogic {
             inputDefinition.getValue().setName(inputName);
 
             Either<InputDefinition, ResponseFormat> preparedInputEither = prepareAndValidateInputBeforeCreate(inputDefinition.getValue(), dataTypes);
-            if(preparedInputEither.isRight()){
+            if (preparedInputEither.isRight()) {
                 return Either.right(preparedInputEither.right().value());
             }
 
         }
         if (resourceProperties != null) {
-            Map<String, InputDefinition> generatedInputs = resourceProperties.stream().collect(Collectors.toMap(PropertyDataDefinition::getName, i -> i));
+            Map<String, InputDefinition> generatedInputs = resourceProperties.stream()
+                .collect(Collectors.toMap(PropertyDataDefinition::getName, i -> i));
             Either<Map<String, InputDefinition>, String> mergeEither = ToscaDataDefinition.mergeDataMaps(generatedInputs, inputs);
-            if(mergeEither.isRight()){
+            if (mergeEither.isRight()) {
                 return Either.right(componentsUtils.getResponseFormat(ActionStatus.PROPERTY_ALREADY_EXIST, mergeEither.right().value()));
             }
             inputs = mergeEither.left().value();
         }
 
-        Either<List<InputDefinition>, StorageOperationStatus> associateInputsEither = toscaOperationFacade.createAndAssociateInputs(inputs, component.getUniqueId());
-        if(associateInputsEither.isRight()){
+        Either<List<InputDefinition>, StorageOperationStatus> associateInputsEither = toscaOperationFacade
+            .createAndAssociateInputs(inputs, component.getUniqueId());
+        if (associateInputsEither.isRight()) {
             log.debug("Failed to create inputs under component {}. Status is {}", component.getUniqueId(), associateInputsEither.right().value());
 
             return Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(associateInputsEither.right().value())));
@@ -658,12 +604,13 @@ public class InputsBusinessLogic extends BaseBusinessLogic {
     }
 
     private Either<List<InputDefinition>, ResponseFormat> createListInputsInGraph(Map<String, InputDefinition> inputs,
-        Map<String, DataTypeDefinition> privateDataTypes, org.openecomp.sdc.be.model.Component component) {
+                                                                                  Map<String, DataTypeDefinition> privateDataTypes,
+                                                                                  org.openecomp.sdc.be.model.Component component) {
 
         log.trace("#createListInputsInGraph: enter");
 
         Map<String, DataTypeDefinition> dataTypes = getAllDataTypes(
-                applicationDataTypeCache);
+            applicationDataTypeCache);
         dataTypes.putAll(privateDataTypes);
 
         for (Map.Entry<String, InputDefinition> inputDefinition : inputs.entrySet()) {
@@ -698,99 +645,86 @@ public class InputsBusinessLogic extends BaseBusinessLogic {
      * @return
      */
     public InputDefinition deleteInput(String componentId, String userId, String inputId) {
-
         Either<InputDefinition, ResponseFormat> deleteEither = null;
         if (log.isDebugEnabled()) {
             log.debug("Going to delete input id: {}", inputId);
         }
-
         validateUserExists(userId);
-
         ComponentParametersView componentParametersView = getBaseComponentParametersView();
         componentParametersView.setIgnoreInterfaces(false);
         componentParametersView.setIgnoreDataType(false);
         componentParametersView.setIgnoreProperties(false);
-
-        Either<org.openecomp.sdc.be.model.Component, StorageOperationStatus> componentEither =
-            toscaOperationFacade.getToscaElement(componentId, componentParametersView);
+        Either<org.openecomp.sdc.be.model.Component, StorageOperationStatus> componentEither = toscaOperationFacade
+            .getToscaElement(componentId, componentParametersView);
         if (componentEither.isRight()) {
             throw new ByActionStatusComponentException(componentsUtils.convertFromStorageResponse(componentEither.right().value()));
         }
         org.openecomp.sdc.be.model.Component component = componentEither.left().value();
-
         // Validate inputId is child of the component
         Optional<InputDefinition> optionalInput = component.getInputs().stream().
-                // filter by ID
-                        filter(input -> input.getUniqueId().equals(inputId)).
-                // Get the input
-                        findAny();
+            // filter by ID
+                filter(input -> input.getUniqueId().equals(inputId)).
+            // Get the input
+                findAny();
         if (!optionalInput.isPresent()) {
             throw new ByActionStatusComponentException(ActionStatus.INPUT_IS_NOT_CHILD_OF_COMPONENT, inputId, componentId);
         }
-
         InputDefinition inputForDelete = optionalInput.get();
-
         // Lock component
         lockComponent(componentId, component, "deleteInput");
         // Delete input operations
         boolean failed = false;
         try {
-            StorageOperationStatus status =
-                toscaOperationFacade.deleteInputOfResource(component, inputForDelete.getName());
+            StorageOperationStatus status = toscaOperationFacade.deleteInputOfResource(component, inputForDelete.getName());
             if (status != StorageOperationStatus.OK) {
                 log.debug("Component id: {} delete input id: {} failed", componentId, inputId);
                 throw new ByActionStatusComponentException(componentsUtils.convertFromStorageResponse(status), component.getName());
             }
-
-            if (BooleanUtils.isTrue(inputForDelete.getIsDeclaredListInput())){
+            if (BooleanUtils.isTrue(inputForDelete.getIsDeclaredListInput())) {
                 deleteEither = deleteListInput(componentId, inputId, component, inputForDelete, status);
-                if (deleteEither.isRight()){
+                if (deleteEither.isRight()) {
                     throw new ByResponseFormatComponentException(deleteEither.right().value());
                 }
                 return deleteEither.left().value();
             }
-
-            StorageOperationStatus storageOperationStatus =
-                propertyDeclarationOrchestrator.unDeclarePropertiesAsInputs(component, inputForDelete);
+            StorageOperationStatus storageOperationStatus = propertyDeclarationOrchestrator.unDeclarePropertiesAsInputs(component, inputForDelete);
             if (storageOperationStatus != StorageOperationStatus.OK) {
                 log.debug("Component id: {} update properties declared as input for input id: {} failed", componentId, inputId);
                 throw new ByActionStatusComponentException(componentsUtils.convertFromStorageResponse(storageOperationStatus), component.getName());
             }
-            return  inputForDelete;
-        }catch (ComponentException e){
+            return inputForDelete;
+        } catch (ComponentException e) {
             failed = true;
             throw e;
-        }finally {
+        } finally {
             unlockComponent(failed, component);
         }
     }
 
     private Either<InputDefinition, ResponseFormat> deleteListInput(String componentId, String inputId,
-        org.openecomp.sdc.be.model.Component component,
-        InputDefinition inputForDelete, StorageOperationStatus status) {
+                                                                    org.openecomp.sdc.be.model.Component component, InputDefinition inputForDelete,
+                                                                    StorageOperationStatus status) {
         // the input is created by 'Declare List'.
-        // need to 1. undeclare properties, 2. delete input, 3. delete private data type
 
-        StorageOperationStatus storageOperationStatus =
-            propertyDeclarationOrchestrator.unDeclarePropertiesAsListInputs(component, inputForDelete);
+        // need to 1. undeclare properties, 2. delete input, 3. delete private data type
+        StorageOperationStatus storageOperationStatus = propertyDeclarationOrchestrator.unDeclarePropertiesAsListInputs(component, inputForDelete);
         if (storageOperationStatus != StorageOperationStatus.OK) {
             log.debug("Component id: {} update properties declared as input for input id: {} failed", componentId, inputId);
-            return Either.right(componentsUtils.getResponseFormat(
-                componentsUtils.convertFromStorageResponse(status), component.getName()));
+            return Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(status), component.getName()));
         }
-        Either<DataTypeDefinition, StorageOperationStatus> deleteResult =
-            dataTypeBusinessLogic.deletePrivateDataType(component, inputForDelete.getSchemaType());
+        Either<DataTypeDefinition, StorageOperationStatus> deleteResult = dataTypeBusinessLogic
+            .deletePrivateDataType(component, inputForDelete.getSchemaType());
         if (deleteResult.isRight()) {
             log.debug("Component id: {} delete datatype name: {} failed", componentId, inputForDelete.getSchemaType());
-            return Either.right(componentsUtils.getResponseFormat(
-                componentsUtils.convertFromStorageResponse(deleteResult.right().value()), component.getName()));
+            return Either.right(
+                componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(deleteResult.right().value()), component.getName()));
         }
         log.trace("deleteInput: deletePrivateDataType (OK)");
         return Either.left(inputForDelete);
     }
 
-    private Either<InputDefinition, ResponseFormat> prepareAndValidateInputBeforeCreate(InputDefinition newInputDefinition, Map<String, DataTypeDefinition> dataTypes) {
-
+    private Either<InputDefinition, ResponseFormat> prepareAndValidateInputBeforeCreate(InputDefinition newInputDefinition,
+                                                                                        Map<String, DataTypeDefinition> dataTypes) {
         // validate input default values
         Either<Boolean, ResponseFormat> defaultValuesValidation = validatePropertyDefaultValue(newInputDefinition, dataTypes);
         if (defaultValuesValidation.isRight()) {
@@ -818,10 +752,10 @@ public class InputsBusinessLogic extends BaseBusinessLogic {
         return Either.left(newInputDefinition);
     }
 
-    public Either<InputDefinition, ResponseFormat> getInputsAndPropertiesForComponentInput(String userId, String componentId, String inputId, boolean inTransaction) {
+    public Either<InputDefinition, ResponseFormat> getInputsAndPropertiesForComponentInput(String userId, String componentId, String inputId,
+                                                                                           boolean inTransaction) {
         Either<InputDefinition, ResponseFormat> result = null;
         try {
-
             validateUserExists(userId);
             ComponentParametersView filters = new ComponentParametersView();
             filters.disableAll();
@@ -830,41 +764,29 @@ public class InputsBusinessLogic extends BaseBusinessLogic {
             filters.setIgnoreComponentInstancesInputs(false);
             filters.setIgnoreComponentInstancesProperties(false);
             filters.setIgnoreProperties(false);
-            Either<org.openecomp.sdc.be.model.Component, StorageOperationStatus> getComponentEither = toscaOperationFacade.getToscaElement(componentId, filters);
-            if(getComponentEither.isRight()){
+            Either<org.openecomp.sdc.be.model.Component, StorageOperationStatus> getComponentEither = toscaOperationFacade
+                .getToscaElement(componentId, filters);
+            if (getComponentEither.isRight()) {
                 ActionStatus actionStatus = componentsUtils.convertFromStorageResponse(getComponentEither.right().value());
                 log.debug(FAILED_TO_FOUND_COMPONENT_ERROR, componentId, actionStatus);
                 return Either.right(componentsUtils.getResponseFormat(actionStatus));
-
             }
             org.openecomp.sdc.be.model.Component component = getComponentEither.left().value();
             Optional<InputDefinition> op = component.getInputs().stream().filter(in -> in.getUniqueId().equals(inputId)).findFirst();
-            if(!op.isPresent()){
+            if (!op.isPresent()) {
                 ActionStatus actionStatus = componentsUtils.convertFromStorageResponse(getComponentEither.right().value());
                 log.debug(FAILED_TO_FOUND_INPUT_UNDER_COMPONENT_ERROR, inputId, componentId, actionStatus);
                 return Either.right(componentsUtils.getResponseFormat(actionStatus));
             }
-
             InputDefinition resObj = op.get();
-
-            List<ComponentInstanceInput> inputCIInput = componentInstanceBusinessLogic.getComponentInstanceInputsByInputId(component, inputId) ;
-
+            List<ComponentInstanceInput> inputCIInput = componentInstanceBusinessLogic.getComponentInstanceInputsByInputId(component, inputId);
             resObj.setInputs(inputCIInput);
-
-
-            List<ComponentInstanceProperty> inputProps = componentInstanceBusinessLogic.getComponentInstancePropertiesByInputId(component, inputId) ;
-
+            List<ComponentInstanceProperty> inputProps = componentInstanceBusinessLogic.getComponentInstancePropertiesByInputId(component, inputId);
             resObj.setProperties(inputProps);
-
-
             result = Either.left(resObj);
-
             return result;
-
         } finally {
-
             if (!inTransaction) {
-
                 if (result == null || result.isRight()) {
                     log.debug(GOING_TO_EXECUTE_ROLLBACK_ON_CREATE_GROUP);
                     janusGraphDao.rollback();
@@ -872,69 +794,48 @@ public class InputsBusinessLogic extends BaseBusinessLogic {
                     log.debug(GOING_TO_EXECUTE_COMMIT_ON_CREATE_GROUP);
                     janusGraphDao.commit();
                 }
-
             }
-
         }
-
     }
 
-    public Either<EntryData<String, InputDefinition>, ResponseFormat> addInputToComponent(String componentId,
-                                                                                          String inputName,
-                                                                                          InputDefinition newInputDefinition,
-                                                                                          String userId) {
+    public Either<EntryData<String, InputDefinition>, ResponseFormat> addInputToComponent(String componentId, String inputName,
+                                                                                          InputDefinition newInputDefinition, String userId) {
         Either<EntryData<String, InputDefinition>, ResponseFormat> result = null;
-
         validateUserExists(userId);
-
-        Either<Component, StorageOperationStatus> serviceElement =
-            toscaOperationFacade.getToscaElement(componentId);
+        Either<Component, StorageOperationStatus> serviceElement = toscaOperationFacade.getToscaElement(componentId);
         if (serviceElement.isRight()) {
             result = Either.right(componentsUtils.getResponseFormat(ActionStatus.RESOURCE_NOT_FOUND, ""));
             return result;
         }
-
         Component component = serviceElement.left().value();
         NodeTypeEnum nodeType = component.getComponentType().getNodeType();
-
         StorageOperationStatus lockResult = graphLockOperation.lockComponent(componentId, nodeType);
         if (!lockResult.equals(StorageOperationStatus.OK)) {
-            BeEcompErrorManager.getInstance()
-                .logBeFailedLockObjectError(CREATE_INPUT, nodeType.name().toLowerCase(), componentId);
+            BeEcompErrorManager.getInstance().logBeFailedLockObjectError(CREATE_INPUT, nodeType.name().toLowerCase(), componentId);
             log.info("Failed to lock component {}. Error - {}", componentId, lockResult);
             result = Either.right(componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR));
             return result;
         }
-
         try {
             if (!ComponentValidationUtils.canWorkOnComponent(component, userId)) {
                 result = Either.right(componentsUtils.getResponseFormat(ActionStatus.RESTRICTED_OPERATION));
                 return result;
             }
-
             List<InputDefinition> inputs = component.getInputs();
-
             if (CollectionUtils.isEmpty(inputs)) {
                 inputs = new ArrayList<>();
             }
-
             if (isInputExistInComponent(inputs, inputName)) {
-
-                result = Either.right(componentsUtils.getResponseFormat(ActionStatus
-                    .INPUT_ALREADY_EXIST, inputName));
+                result = Either.right(componentsUtils.getResponseFormat(ActionStatus.INPUT_ALREADY_EXIST, inputName));
                 return result;
             }
-
             Map<String, DataTypeDefinition> allDataTypes = getAllDataTypes(applicationDataTypeCache);
-
             // validate input default values
-            Either<Boolean, ResponseFormat> defaultValuesValidation = validatePropertyDefaultValue(
-                newInputDefinition, allDataTypes);
+            Either<Boolean, ResponseFormat> defaultValuesValidation = validatePropertyDefaultValue(newInputDefinition, allDataTypes);
             if (defaultValuesValidation.isRight()) {
                 result = Either.right(defaultValuesValidation.right().value());
                 return result;
             }
-
             // convert Input
             ToscaPropertyType type = getType(newInputDefinition.getType());
             if (type != null) {
@@ -949,24 +850,18 @@ public class InputsBusinessLogic extends BaseBusinessLogic {
                     }
                 }
                 if (newInputDefinition.getDefaultValue() != null) {
-                    String convertedValue = converter
-                        .convert(newInputDefinition.getDefaultValue(), innerType, allDataTypes);
+                    String convertedValue = converter.convert(newInputDefinition.getDefaultValue(), innerType, allDataTypes);
                     newInputDefinition.setDefaultValue(convertedValue);
                 }
             }
-
             newInputDefinition.setMappedToComponentProperty(false);
-            Either<InputDefinition, StorageOperationStatus> addInputEither =
-                toscaOperationFacade.addInputToComponent(inputName, newInputDefinition, component);
-
+            Either<InputDefinition, StorageOperationStatus> addInputEither = toscaOperationFacade
+                .addInputToComponent(inputName, newInputDefinition, component);
             if (addInputEither.isRight()) {
-                log.info("Failed to add new input {}. Error - {}", componentId,
-                    addInputEither.right().value());
-                result = Either.right(componentsUtils.getResponseFormat(ActionStatus
-                    .GENERAL_ERROR));
+                log.info("Failed to add new input {}. Error - {}", componentId, addInputEither.right().value());
+                result = Either.right(componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR));
                 return result;
             }
-
             result = Either.left(new EntryData<>(inputName, newInputDefinition));
             return result;
         } finally {
@@ -977,8 +872,6 @@ public class InputsBusinessLogic extends BaseBusinessLogic {
     }
 
     private boolean isInputExistInComponent(List<InputDefinition> inputs, String inputName) {
-        return CollectionUtils.isNotEmpty(inputs) &&
-            inputs.stream().anyMatch(input -> input.getName().equals(inputName));
+        return CollectionUtils.isNotEmpty(inputs) && inputs.stream().anyMatch(input -> input.getName().equals(inputName));
     }
-
 }
index 71005ef..62e6ce5 100644 (file)
@@ -16,7 +16,6 @@
  *  SPDX-License-Identifier: Apache-2.0
  *  ============LICENSE_END=========================================================
  */
-
 package org.openecomp.sdc.be.components.impl;
 
 import static org.openecomp.sdc.be.components.impl.ImportUtils.Constants.QUOTE;
@@ -64,7 +63,6 @@ import org.springframework.stereotype.Component;
 public class InterfaceDefinitionHandler {
 
     private static final Logger LOGGER = LoggerFactory.getLogger(InterfaceDefinitionHandler.class);
-
     private final InterfaceOperationBusinessLogic interfaceOperationBusinessLogic;
 
     public InterfaceDefinitionHandler(final InterfaceOperationBusinessLogic interfaceOperationBusinessLogic) {
@@ -78,9 +76,7 @@ public class InterfaceDefinitionHandler {
      * @return an interface definition representation
      */
     public InterfaceDefinition create(final Map<String, Object> interfaceDefinitionToscaMap) {
-
         final InterfaceDefinition interfaceDefinition = new InterfaceDefinition();
-
         if (interfaceDefinitionToscaMap.containsKey(TYPE.getElementName())) {
             final Object typeObj = interfaceDefinitionToscaMap.get(TYPE.getElementName());
             if (!(typeObj instanceof String)) {
@@ -90,11 +86,10 @@ public class InterfaceDefinitionHandler {
             interfaceDefinition.setType(type);
             interfaceDefinition.setUniqueId(type.toLowerCase());
         }
-
         final Map<String, InputDefinition> inputDefinitionMap = handleInputs(interfaceDefinitionToscaMap);
         if (!inputDefinitionMap.isEmpty()) {
-            final Map<String, InputDataDefinition> collect = inputDefinitionMap.entrySet().stream().
-                collect(Collectors.toMap(Entry::getKey, value -> new InputDataDefinition(value.getValue())));
+            final Map<String, InputDataDefinition> collect = inputDefinitionMap.entrySet().stream()
+                .collect(Collectors.toMap(Entry::getKey, value -> new InputDataDefinition(value.getValue())));
             interfaceDefinition.setInputs(collect);
         }
         final Map<String, OperationDataDefinition> operationMap;
@@ -109,88 +104,63 @@ public class InterfaceDefinitionHandler {
             validateOperations(interfaceDefinition.getType(), operationMap);
             interfaceDefinition.setOperations(operationMap);
         }
-
         return interfaceDefinition;
     }
 
-    private void validateOperations(final String interfaceType,
-                                    final Map<String, OperationDataDefinition> operationMap) {
+    private void validateOperations(final String interfaceType, final Map<String, OperationDataDefinition> operationMap) {
         if (MapUtils.isEmpty(operationMap)) {
             return;
         }
-        Either<Map<String, InterfaceDefinition>, ResponseFormat> interfaceDefinitionMapEither =
-            interfaceOperationBusinessLogic.getAllInterfaceLifecycleTypes();
+        Either<Map<String, InterfaceDefinition>, ResponseFormat> interfaceDefinitionMapEither = interfaceOperationBusinessLogic
+            .getAllInterfaceLifecycleTypes();
         if (interfaceDefinitionMapEither.isRight() || MapUtils.isEmpty(interfaceDefinitionMapEither.left().value())) {
             throw new ByActionStatusComponentException(ActionStatus.INTERFACE_UNKNOWN, interfaceType);
         }
-
         final Map<String, InterfaceDefinition> interfaceDefinitionMap = interfaceDefinitionMapEither.left().value();
         final Optional<InterfaceDefinition> interfaceDefinitionOptional = interfaceDefinitionMap.entrySet().stream()
-            .filter(interfaceDefinitionEntry -> interfaceDefinitionEntry.getKey().equalsIgnoreCase(interfaceType))
-            .map(Entry::getValue).findFirst();
+            .filter(interfaceDefinitionEntry -> interfaceDefinitionEntry.getKey().equalsIgnoreCase(interfaceType)).map(Entry::getValue).findFirst();
         if (interfaceDefinitionOptional.isEmpty()) {
             throw new ByActionStatusComponentException(ActionStatus.INTERFACE_UNKNOWN, interfaceType);
         }
         final InterfaceDefinition interfaceDefinition = interfaceDefinitionOptional.get();
         operationMap.keySet().forEach(operation1 -> {
             if (!interfaceDefinition.hasOperation(operation1)) {
-                throw new ByActionStatusComponentException(ActionStatus.INTERFACE_OPERATION_NOT_DEFINED,
-                    operation1, interfaceType);
+                throw new ByActionStatusComponentException(ActionStatus.INTERFACE_OPERATION_NOT_DEFINED, operation1, interfaceType);
             }
         });
     }
 
-    private Map<String, OperationDataDefinition> handleOperations(
-        final Map<String, Object> interfaceDefinitionToscaMap) {
+    private Map<String, OperationDataDefinition> handleOperations(final Map<String, Object> interfaceDefinitionToscaMap) {
         if (!interfaceDefinitionToscaMap.containsKey(OPERATIONS.getElementName())) {
             return Collections.emptyMap();
         }
-        final Map<String, Object> operationMap =
-            (Map<String, Object>) interfaceDefinitionToscaMap.get(OPERATIONS.getElementName());
+        final Map<String, Object> operationMap = (Map<String, Object>) interfaceDefinitionToscaMap.get(OPERATIONS.getElementName());
         return operationMap.entrySet().stream()
-            .map(interfaceEntry -> createOperation(interfaceEntry.getKey(),
-                (Map<String, Object>) interfaceEntry.getValue()))
-            .collect(
-                Collectors.toMap(OperationDataDefinition::getName, operationDataDefinition -> operationDataDefinition));
+            .map(interfaceEntry -> createOperation(interfaceEntry.getKey(), (Map<String, Object>) interfaceEntry.getValue()))
+            .collect(Collectors.toMap(OperationDataDefinition::getName, operationDataDefinition -> operationDataDefinition));
     }
 
-    private Map<String, OperationDataDefinition> handleLegacyOperations(
-        final Map<String, Object> interfaceDefinitionToscaMap) {
+    private Map<String, OperationDataDefinition> handleLegacyOperations(final Map<String, Object> interfaceDefinitionToscaMap) {
         final List<String> notALegacyOperationEntry = Arrays
-            .asList(OPERATIONS.getElementName(),
-                TYPE.getElementName(),
-                INPUTS.getElementName(),
-                NOTIFICATIONS.getElementName());
-        return interfaceDefinitionToscaMap.entrySet().stream()
-            .filter(interfaceEntry -> !notALegacyOperationEntry.contains(interfaceEntry.getKey()))
-            .map(interfaceEntry -> createOperation(interfaceEntry.getKey(),
-                (Map<String, Object>) interfaceEntry.getValue()))
-            .collect(
-                Collectors.toMap(OperationDataDefinition::getName, operationDataDefinition -> operationDataDefinition));
+            .asList(OPERATIONS.getElementName(), TYPE.getElementName(), INPUTS.getElementName(), NOTIFICATIONS.getElementName());
+        return interfaceDefinitionToscaMap.entrySet().stream().filter(interfaceEntry -> !notALegacyOperationEntry.contains(interfaceEntry.getKey()))
+            .map(interfaceEntry -> createOperation(interfaceEntry.getKey(), (Map<String, Object>) interfaceEntry.getValue()))
+            .collect(Collectors.toMap(OperationDataDefinition::getName, operationDataDefinition -> operationDataDefinition));
     }
 
-
-    private OperationDataDefinition createOperation(final String operationName,
-                                                    final Map<String, Object> operationDefinitionMap) {
+    private OperationDataDefinition createOperation(final String operationName, final Map<String, Object> operationDefinitionMap) {
         final OperationDataDefinition operation = new OperationDataDefinition();
         operation.setUniqueId(UUID.randomUUID().toString());
         operation.setName(operationName);
-
-        operation.setImplementation(
-            handleOperationImplementation(operationDefinitionMap)
-                .orElse(new ArtifactDataDefinition())
-        );
+        operation.setImplementation(handleOperationImplementation(operationDefinitionMap).orElse(new ArtifactDataDefinition()));
         if (operationDefinitionMap.containsKey(INPUTS.getElementName())) {
-            final Map<String, Object> interfaceInputs =
-                (Map<String, Object>) operationDefinitionMap.get(INPUTS.getElementName());
+            final Map<String, Object> interfaceInputs = (Map<String, Object>) operationDefinitionMap.get(INPUTS.getElementName());
             operation.setInputs(handleInterfaceOperationInputs(interfaceInputs));
         }
-
         return operation;
     }
 
-    private ListDataDefinition<OperationInputDefinition> handleInterfaceOperationInputs(
-        final Map<String, Object> interfaceInputs) {
+    private ListDataDefinition<OperationInputDefinition> handleInterfaceOperationInputs(final Map<String, Object> interfaceInputs) {
         final ListDataDefinition<OperationInputDefinition> inputs = new ListDataDefinition<>();
         for (final Entry<String, Object> interfaceInput : interfaceInputs.entrySet()) {
             final OperationInputDefinition operationInput = new OperationInputDefinition();
@@ -198,10 +168,9 @@ public class InterfaceDefinitionHandler {
             operationInput.setInputId(operationInput.getUniqueId());
             operationInput.setName(interfaceInput.getKey());
             if (interfaceInput.getValue() instanceof Map) {
-                final LinkedHashMap<String, Object> inputPropertyValue =
-                    (LinkedHashMap<String, Object>) interfaceInput.getValue();
-                LOGGER.info("createModuleInterface: i interfaceInput.getKey() {}, {} , {}  ",
-                    interfaceInput.getKey(), inputPropertyValue.keySet(), inputPropertyValue.values());
+                final LinkedHashMap<String, Object> inputPropertyValue = (LinkedHashMap<String, Object>) interfaceInput.getValue();
+                LOGGER.info("createModuleInterface: i interfaceInput.getKey() {}, {} , {}  ", interfaceInput.getKey(), inputPropertyValue.keySet(),
+                    inputPropertyValue.values());
                 if (inputPropertyValue.get(TYPE.getElementName()) != null) {
                     operationInput.setType(inputPropertyValue.get(TYPE.getElementName()).toString());
                 }
@@ -209,8 +178,7 @@ public class InterfaceDefinitionHandler {
                     operationInput.setDescription(inputPropertyValue.get(DESCRIPTION.getElementName()).toString());
                 }
                 if (inputPropertyValue.get(REQUIRED.getElementName()) != null) {
-                    operationInput.setRequired(
-                        Boolean.getBoolean(inputPropertyValue.get(REQUIRED.getElementName()).toString()));
+                    operationInput.setRequired(Boolean.getBoolean(inputPropertyValue.get(REQUIRED.getElementName()).toString()));
                 }
                 if (inputPropertyValue.get(DEFAULT.getElementName()) != null) {
                     operationInput.setToscaDefaultValue(inputPropertyValue.get(DEFAULT.getElementName()).toString());
@@ -218,7 +186,6 @@ public class InterfaceDefinitionHandler {
                 if (inputPropertyValue.get(STATUS.getElementName()) != null) {
                     operationInput.setStatus(inputPropertyValue.get(STATUS.getElementName()).toString());
                 }
-
             } else if (interfaceInput.getValue() instanceof String) {
                 final String value = (String) interfaceInput.getValue();
                 operationInput.setDefaultValue(value);
@@ -230,8 +197,7 @@ public class InterfaceDefinitionHandler {
         return inputs;
     }
 
-    private Optional<ArtifactDataDefinition> handleOperationImplementation(
-        final Map<String, Object> operationDefinitionMap) {
+    private Optional<ArtifactDataDefinition> handleOperationImplementation(final Map<String, Object> operationDefinitionMap) {
         if (!operationDefinitionMap.containsKey(IMPLEMENTATION.getElementName())) {
             return Optional.empty();
         }
@@ -249,14 +215,10 @@ public class InterfaceDefinitionHandler {
         if (!interfaceDefinitionToscaMap.containsKey(INPUTS.getElementName())) {
             return Collections.emptyMap();
         }
-
-        final Either<Map<String, InputDefinition>, ResultStatusEnum> inputMapEither =
-            ImportUtils.getInputs(interfaceDefinitionToscaMap);
+        final Either<Map<String, InputDefinition>, ResultStatusEnum> inputMapEither = ImportUtils.getInputs(interfaceDefinitionToscaMap);
         if (inputMapEither.isRight()) {
             return Collections.emptyMap();
         }
-
         return inputMapEither.left().value();
     }
-
 }
index f1b4442..1c54114 100644 (file)
@@ -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.
@@ -17,7 +17,6 @@
  * limitations under the License.
  * ============LICENSE_END=========================================================
  */
-
 package org.openecomp.sdc.be.components.impl;
 
 import fj.data.Either;
@@ -46,18 +45,15 @@ import org.springframework.stereotype.Component;
 @Component("interfaceLifecycleTypeImportManager")
 public class InterfaceLifecycleTypeImportManager {
 
+    private static final Logger log = Logger.getLogger(InterfaceLifecycleTypeImportManager.class);
     @Resource
     private IInterfaceLifecycleOperation interfaceLifecycleOperation;
-
     @Resource
     private ComponentsUtils componentsUtils;
     @Resource
     private CommonImportManager commonImportManager;
 
-    private static final Logger log = Logger.getLogger(InterfaceLifecycleTypeImportManager.class);
-
     public Either<List<InterfaceDefinition>, ResponseFormat> createLifecycleTypes(String interfaceLifecycleTypesYml) {
-
         Either<List<InterfaceDefinition>, ActionStatus> interfaces = createInterfaceTypeFromYml(interfaceLifecycleTypesYml);
         if (interfaces.isRight()) {
             ActionStatus status = interfaces.right().value();
@@ -65,12 +61,10 @@ public class InterfaceLifecycleTypeImportManager {
             return Either.right(responseFormat);
         }
         return createInterfacesByDao(interfaces.left().value());
-
     }
 
     private Either<List<InterfaceDefinition>, ActionStatus> createInterfaceTypeFromYml(final String interfaceTypesYml) {
         return commonImportManager.createElementTypesFromYml(interfaceTypesYml, this::createInterfaceDefinition);
-
     }
 
     private Either<List<InterfaceDefinition>, ResponseFormat> createInterfacesByDao(List<InterfaceDefinition> interfacesToCreate) {
@@ -80,18 +74,17 @@ public class InterfaceLifecycleTypeImportManager {
         boolean stopDao = false;
         while (interfaceItr.hasNext() && !stopDao) {
             InterfaceDefinition interfaceDef = interfaceItr.next();
-
             log.info("send interfaceDefinition {} to dao for create", interfaceDef.getType());
-
             Either<InterfaceDefinition, StorageOperationStatus> dataModelResponse = interfaceLifecycleOperation.createInterfaceType(interfaceDef);
             if (dataModelResponse.isRight()) {
                 log.info("failed to create interface : {}  error: {}", interfaceDef.getType(), dataModelResponse.right().value().name());
                 if (dataModelResponse.right().value() != StorageOperationStatus.SCHEMA_VIOLATION) {
-                    ResponseFormat responseFormat = componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponseForLifecycleType(dataModelResponse.right().value()), interfaceDef.getType());
+                    ResponseFormat responseFormat = componentsUtils
+                        .getResponseFormat(componentsUtils.convertFromStorageResponseForLifecycleType(dataModelResponse.right().value()),
+                            interfaceDef.getType());
                     eitherResult = Either.right(responseFormat);
                     stopDao = true;
                 }
-
             } else {
                 createdInterfaces.add(dataModelResponse.left().value());
             }
@@ -102,8 +95,7 @@ public class InterfaceLifecycleTypeImportManager {
         return eitherResult;
     }
 
-    private InterfaceDefinition createInterfaceDefinition(final String interfaceDefinition,
-                                                          final Map<String, Object> toscaJson) {
+    private InterfaceDefinition createInterfaceDefinition(final String interfaceDefinition, final Map<String, Object> toscaJson) {
         final InterfaceDefinition interfaceDef = new InterfaceDefinition();
         interfaceDef.setType(interfaceDefinition);
         final Object descriptionObj = toscaJson.get(ToscaTagNamesEnum.DESCRIPTION.getElementName());
@@ -118,25 +110,19 @@ public class InterfaceLifecycleTypeImportManager {
         if (versionObj instanceof String) {
             interfaceDef.setVersion((String) versionObj);
         }
-
         final Object metadataObj = toscaJson.get(ToscaTagNamesEnum.METADATA.getElementName());
         if (metadataObj instanceof Map) {
             interfaceDef.setToscaPresentationValue(JsonPresentationFields.METADATA, metadataObj);
         }
-
         final Map<String, Object> operationsMap;
         if (toscaJson.containsKey(ToscaTagNamesEnum.OPERATIONS.getElementName())) {
             operationsMap = (Map<String, Object>) toscaJson.get(ToscaTagNamesEnum.OPERATIONS.getElementName());
         } else {
             final List<String> entitySchemaEntryList = Arrays
-                .asList(ToscaTagNamesEnum.DERIVED_FROM.getElementName(),
-                    ToscaTagNamesEnum.DESCRIPTION.getElementName(),
-                    ToscaTagNamesEnum.VERSION.getElementName(),
-                    ToscaTagNamesEnum.METADATA.getElementName(),
-                    ToscaTagNamesEnum.INPUTS.getElementName(),
-                    ToscaTagNamesEnum.NOTIFICATIONS.getElementName());
-            operationsMap = toscaJson.entrySet().stream()
-                .filter(interfaceEntry -> !entitySchemaEntryList.contains(interfaceEntry.getKey()))
+                .asList(ToscaTagNamesEnum.DERIVED_FROM.getElementName(), ToscaTagNamesEnum.DESCRIPTION.getElementName(),
+                    ToscaTagNamesEnum.VERSION.getElementName(), ToscaTagNamesEnum.METADATA.getElementName(),
+                    ToscaTagNamesEnum.INPUTS.getElementName(), ToscaTagNamesEnum.NOTIFICATIONS.getElementName());
+            operationsMap = toscaJson.entrySet().stream().filter(interfaceEntry -> !entitySchemaEntryList.contains(interfaceEntry.getKey()))
                 .collect(Collectors.toMap(Entry::getKey, Entry::getValue));
         }
         interfaceDef.setOperationsMap(handleOperations(operationsMap));
@@ -148,8 +134,7 @@ public class InterfaceLifecycleTypeImportManager {
             return Collections.emptyMap();
         }
         return operationsToscaEntry.entrySet().stream()
-            .collect(Collectors.toMap(Entry::getKey,
-                operationEntry -> createOperation((Map<String, Object>) operationEntry.getValue())));
+            .collect(Collectors.toMap(Entry::getKey, operationEntry -> createOperation((Map<String, Object>) operationEntry.getValue())));
     }
 
     private Operation createOperation(final Map<String, Object> toscaOperationMap) {
index 3aabe82..e23818c 100644 (file)
  * See the License for the specific language governing permissions and
  * limitations under the License.
  */
-
-
 package org.openecomp.sdc.be.components.impl;
 
+import static org.openecomp.sdc.be.components.utils.InterfaceOperationUtils.createMappedCapabilityPropertyDefaultValue;
+import static org.openecomp.sdc.be.components.utils.InterfaceOperationUtils.createMappedInputPropertyDefaultValue;
+import static org.openecomp.sdc.be.components.utils.InterfaceOperationUtils.createMappedOutputDefaultValue;
+import static org.openecomp.sdc.be.components.utils.InterfaceOperationUtils.getInterfaceDefinitionFromComponentByInterfaceId;
+import static org.openecomp.sdc.be.components.utils.InterfaceOperationUtils.getInterfaceDefinitionFromComponentByInterfaceType;
+import static org.openecomp.sdc.be.components.utils.InterfaceOperationUtils.getOperationFromInterfaceDefinition;
+import static org.openecomp.sdc.be.components.utils.InterfaceOperationUtils.isOperationInputMappedToComponentInput;
+import static org.openecomp.sdc.be.components.utils.PropertiesUtils.getPropertyCapabilityFromAllCapProps;
+import static org.openecomp.sdc.be.components.utils.PropertiesUtils.isCapabilityProperty;
+import static org.openecomp.sdc.be.tosca.InterfacesOperationsConverter.SELF;
+
 import com.google.gson.Gson;
 import fj.data.Either;
+import java.util.ArrayList;
+import java.util.Collection;
+import java.util.Collections;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+import java.util.Objects;
+import java.util.Optional;
+import java.util.UUID;
+import java.util.stream.Collectors;
 import org.apache.commons.collections4.CollectionUtils;
 import org.apache.commons.collections4.MapUtils;
 import org.apache.commons.lang3.tuple.ImmutablePair;
@@ -57,147 +76,101 @@ import org.slf4j.LoggerFactory;
 import org.springframework.beans.factory.annotation.Autowired;
 import org.springframework.stereotype.Component;
 
-import java.util.ArrayList;
-import java.util.Collection;
-import java.util.Collections;
-import java.util.HashMap;
-import java.util.List;
-import java.util.Map;
-import java.util.Objects;
-import java.util.Optional;
-import java.util.UUID;
-import java.util.stream.Collectors;
-
-import static org.openecomp.sdc.be.components.utils.InterfaceOperationUtils.createMappedCapabilityPropertyDefaultValue;
-import static org.openecomp.sdc.be.components.utils.InterfaceOperationUtils.createMappedInputPropertyDefaultValue;
-import static org.openecomp.sdc.be.components.utils.InterfaceOperationUtils.createMappedOutputDefaultValue;
-import static org.openecomp.sdc.be.components.utils.InterfaceOperationUtils.getInterfaceDefinitionFromComponentByInterfaceId;
-import static org.openecomp.sdc.be.components.utils.InterfaceOperationUtils.getInterfaceDefinitionFromComponentByInterfaceType;
-import static org.openecomp.sdc.be.components.utils.InterfaceOperationUtils.getOperationFromInterfaceDefinition;
-import static org.openecomp.sdc.be.components.utils.InterfaceOperationUtils.isOperationInputMappedToComponentInput;
-import static org.openecomp.sdc.be.components.utils.PropertiesUtils.getPropertyCapabilityFromAllCapProps;
-import static org.openecomp.sdc.be.components.utils.PropertiesUtils.isCapabilityProperty;
-import static org.openecomp.sdc.be.tosca.InterfacesOperationsConverter.SELF;
-
 @Component("interfaceOperationBusinessLogic")
 public class InterfaceOperationBusinessLogic extends BaseBusinessLogic {
 
     private static final Logger LOGGER = LoggerFactory.getLogger(InterfaceOperationBusinessLogic.class);
-    private static final String EXCEPTION_OCCURRED_DURING_INTERFACE_OPERATION =
-            "Exception occurred during {}. Response is {}";
+    private static final String EXCEPTION_OCCURRED_DURING_INTERFACE_OPERATION = "Exception occurred during {}. Response is {}";
     private static final String DELETE_INTERFACE_OPERATION = "deleteInterfaceOperation";
     private static final String GET_INTERFACE_OPERATION = "getInterfaceOperation";
     private static final String CREATE_INTERFACE_OPERATION = "createInterfaceOperation";
     private static final String UPDATE_INTERFACE_OPERATION = "updateInterfaceOperation";
-
     private final ArtifactCassandraDao artifactCassandraDao;
     private final InterfaceOperationValidation interfaceOperationValidation;
 
     @Autowired
-    public InterfaceOperationBusinessLogic(IElementOperation elementDao,
-        IGroupOperation groupOperation,
-        IGroupInstanceOperation groupInstanceOperation,
-        IGroupTypeOperation groupTypeOperation,
-        InterfaceOperation interfaceOperation,
-        InterfaceLifecycleOperation interfaceLifecycleTypeOperation, ArtifactCassandraDao artifactCassandraDao,
-        InterfaceOperationValidation interfaceOperationValidation, ArtifactsOperations artifactToscaOperation) {
-        super(elementDao, groupOperation, groupInstanceOperation, groupTypeOperation,
-            interfaceOperation, interfaceLifecycleTypeOperation, artifactToscaOperation);
+    public InterfaceOperationBusinessLogic(IElementOperation elementDao, IGroupOperation groupOperation,
+                                           IGroupInstanceOperation groupInstanceOperation, IGroupTypeOperation groupTypeOperation,
+                                           InterfaceOperation interfaceOperation, InterfaceLifecycleOperation interfaceLifecycleTypeOperation,
+                                           ArtifactCassandraDao artifactCassandraDao, InterfaceOperationValidation interfaceOperationValidation,
+                                           ArtifactsOperations artifactToscaOperation) {
+        super(elementDao, groupOperation, groupInstanceOperation, groupTypeOperation, interfaceOperation, interfaceLifecycleTypeOperation,
+            artifactToscaOperation);
         this.artifactCassandraDao = artifactCassandraDao;
         this.interfaceOperationValidation = interfaceOperationValidation;
     }
 
-    public Either<List<InterfaceDefinition>, ResponseFormat> deleteInterfaceOperation(String componentId,
-            String interfaceId, List<String> operationsToDelete, User user, boolean lock) {
+    public Either<List<InterfaceDefinition>, ResponseFormat> deleteInterfaceOperation(String componentId, String interfaceId,
+                                                                                      List<String> operationsToDelete, User user, boolean lock) {
         validateUserExists(user.getUserId());
-
         Either<org.openecomp.sdc.be.model.Component, ResponseFormat> componentEither = getComponentDetails(componentId);
         if (componentEither.isRight()) {
             return Either.right(componentEither.right().value());
         }
         org.openecomp.sdc.be.model.Component storedComponent = componentEither.left().value();
-
         lockComponentResult(lock, storedComponent, DELETE_INTERFACE_OPERATION);
-
-
         try {
-            Optional<InterfaceDefinition> optionalInterface = getInterfaceDefinitionFromComponentByInterfaceId(
-                    storedComponent, interfaceId);
+            Optional<InterfaceDefinition> optionalInterface = getInterfaceDefinitionFromComponentByInterfaceId(storedComponent, interfaceId);
             if (!optionalInterface.isPresent()) {
-                return Either.right(
-                        componentsUtils.getResponseFormat(ActionStatus.INTERFACE_NOT_FOUND_IN_COMPONENT, interfaceId));
+                return Either.right(componentsUtils.getResponseFormat(ActionStatus.INTERFACE_NOT_FOUND_IN_COMPONENT, interfaceId));
             }
             InterfaceDefinition interfaceDefinition = optionalInterface.get();
-
             Map<String, Operation> operationsCollection = new HashMap<>();
             for (String operationId : operationsToDelete) {
-                Optional<Map.Entry<String, Operation>> optionalOperation =
-                        getOperationFromInterfaceDefinition(interfaceDefinition, operationId);
+                Optional<Map.Entry<String, Operation>> optionalOperation = getOperationFromInterfaceDefinition(interfaceDefinition, operationId);
                 if (!optionalOperation.isPresent()) {
-                    return Either.right(componentsUtils.getResponseFormat(ActionStatus.INTERFACE_OPERATION_NOT_FOUND,
-                            storedComponent.getUniqueId()));
+                    return Either.right(componentsUtils.getResponseFormat(ActionStatus.INTERFACE_OPERATION_NOT_FOUND, storedComponent.getUniqueId()));
                 }
-
                 Operation storedOperation = optionalOperation.get().getValue();
-                Either<Boolean, ResponseFormat> validateDeleteOperationContainsNoMappedOutputResponse =
-                        interfaceOperationValidation.validateDeleteOperationContainsNoMappedOutput(storedOperation,
-                                storedComponent, interfaceDefinition);
+                Either<Boolean, ResponseFormat> validateDeleteOperationContainsNoMappedOutputResponse = interfaceOperationValidation
+                    .validateDeleteOperationContainsNoMappedOutput(storedOperation, storedComponent, interfaceDefinition);
                 if (validateDeleteOperationContainsNoMappedOutputResponse.isRight()) {
                     return Either.right(validateDeleteOperationContainsNoMappedOutputResponse.right().value());
                 }
-
                 String artifactUniqueId = storedOperation.getImplementation().getUniqueId();
-                if(!InterfaceOperationUtils.isArtifactInUse(storedComponent, operationId, artifactUniqueId)){
-                    Either<ArtifactDefinition, StorageOperationStatus> getArtifactEither =
-                            artifactToscaOperation.getArtifactById(storedComponent.getUniqueId(), artifactUniqueId);
-                    if(getArtifactEither.isLeft()){
-                        Either<ArtifactDefinition, StorageOperationStatus> removeArifactFromComponent =
-                                artifactToscaOperation.removeArifactFromResource(componentId, artifactUniqueId,
-                                        NodeTypeEnum.getByNameIgnoreCase(storedComponent.getComponentType().getValue()),
-                                        true);
-                        if(removeArifactFromComponent.isRight()){
+                if (!InterfaceOperationUtils.isArtifactInUse(storedComponent, operationId, artifactUniqueId)) {
+                    Either<ArtifactDefinition, StorageOperationStatus> getArtifactEither = artifactToscaOperation
+                        .getArtifactById(storedComponent.getUniqueId(), artifactUniqueId);
+                    if (getArtifactEither.isLeft()) {
+                        Either<ArtifactDefinition, StorageOperationStatus> removeArifactFromComponent = artifactToscaOperation
+                            .removeArifactFromResource(componentId, artifactUniqueId,
+                                NodeTypeEnum.getByNameIgnoreCase(storedComponent.getComponentType().getValue()), true);
+                        if (removeArifactFromComponent.isRight()) {
                             janusGraphDao.rollback();
-                            ResponseFormat responseFormatByArtifactId = componentsUtils.getResponseFormatByArtifactId(
-                                    componentsUtils.convertFromStorageResponse(removeArifactFromComponent.right().value()),
+                            ResponseFormat responseFormatByArtifactId = componentsUtils
+                                .getResponseFormatByArtifactId(componentsUtils.convertFromStorageResponse(removeArifactFromComponent.right().value()),
                                     storedOperation.getImplementation().getArtifactDisplayName());
                             return Either.right(responseFormatByArtifactId);
                         }
-
                         CassandraOperationStatus cassandraStatus = artifactCassandraDao.deleteArtifact(artifactUniqueId);
                         if (cassandraStatus != CassandraOperationStatus.OK) {
                             janusGraphDao.rollback();
                             ResponseFormat responseFormatByArtifactId = componentsUtils.getResponseFormatByArtifactId(
-                                    componentsUtils.convertFromStorageResponse(
-                                            componentsUtils.convertToStorageOperationStatus(cassandraStatus)),
-                                    storedOperation.getImplementation().getArtifactDisplayName());
+                                componentsUtils.convertFromStorageResponse(componentsUtils.convertToStorageOperationStatus(cassandraStatus)),
+                                storedOperation.getImplementation().getArtifactDisplayName());
                             return Either.right(responseFormatByArtifactId);
                         }
                     }
                 }
-
                 operationsCollection.put(operationId, interfaceDefinition.getOperationsMap().get(operationId));
                 interfaceDefinition.getOperations().remove(operationId);
             }
-
-            Either<List<InterfaceDefinition>, StorageOperationStatus> deleteOperationEither =
-                    interfaceOperation.updateInterfaces(storedComponent.getUniqueId(),
-                            Collections.singletonList(interfaceDefinition));
+            Either<List<InterfaceDefinition>, StorageOperationStatus> deleteOperationEither = interfaceOperation
+                .updateInterfaces(storedComponent.getUniqueId(), Collections.singletonList(interfaceDefinition));
             if (deleteOperationEither.isRight()) {
                 janusGraphDao.rollback();
-                return Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(
-                        deleteOperationEither.right().value(), storedComponent.getComponentType())));
+                return Either.right(componentsUtils.getResponseFormat(
+                    componentsUtils.convertFromStorageResponse(deleteOperationEither.right().value(), storedComponent.getComponentType())));
             }
-
             if (interfaceDefinition.getOperations().isEmpty()) {
-                Either<String, StorageOperationStatus> deleteInterfaceEither = interfaceOperation.deleteInterface(
-                        storedComponent.getUniqueId(), interfaceDefinition.getUniqueId());
+                Either<String, StorageOperationStatus> deleteInterfaceEither = interfaceOperation
+                    .deleteInterface(storedComponent.getUniqueId(), interfaceDefinition.getUniqueId());
                 if (deleteInterfaceEither.isRight()) {
                     janusGraphDao.rollback();
-                    return Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(
-                            deleteInterfaceEither.right().value(), storedComponent.getComponentType())));
+                    return Either.right(componentsUtils.getResponseFormat(
+                        componentsUtils.convertFromStorageResponse(deleteInterfaceEither.right().value(), storedComponent.getComponentType())));
                 }
             }
-
             janusGraphDao.commit();
             interfaceDefinition.getOperations().putAll(operationsCollection);
             interfaceDefinition.getOperations().keySet().removeIf(key -> !(operationsToDelete.contains(key)));
@@ -207,177 +180,144 @@ public class InterfaceOperationBusinessLogic extends BaseBusinessLogic {
             janusGraphDao.rollback();
             return Either.right(componentsUtils.getResponseFormat(ActionStatus.INTERFACE_OPERATION_NOT_DELETED));
         } finally {
-            graphLockOperation.unlockComponent(storedComponent.getUniqueId(),
-                    NodeTypeEnum.getByNameIgnoreCase(storedComponent.getComponentType().getValue()));
+            graphLockOperation
+                .unlockComponent(storedComponent.getUniqueId(), NodeTypeEnum.getByNameIgnoreCase(storedComponent.getComponentType().getValue()));
         }
     }
 
     private Either<org.openecomp.sdc.be.model.Component, ResponseFormat> getComponentDetails(String componentId) {
-        Either<org.openecomp.sdc.be.model.Component, StorageOperationStatus> componentStorageOperationStatusEither =
-                toscaOperationFacade.getToscaElement(componentId);
+        Either<org.openecomp.sdc.be.model.Component, StorageOperationStatus> componentStorageOperationStatusEither = toscaOperationFacade
+            .getToscaElement(componentId);
         if (componentStorageOperationStatusEither.isRight()) {
-            return Either.right(componentsUtils.getResponseFormat(
-                    componentsUtils.convertFromStorageResponse(componentStorageOperationStatusEither.right().value())));
+            return Either.right(
+                componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(componentStorageOperationStatusEither.right().value())));
         }
         return Either.left(componentStorageOperationStatusEither.left().value());
     }
 
-    private Either<Boolean, ResponseFormat> lockComponentResult(boolean lock,
-            org.openecomp.sdc.be.model.Component component, String action) {
+    private Either<Boolean, ResponseFormat> lockComponentResult(boolean lock, org.openecomp.sdc.be.model.Component component, String action) {
         if (lock) {
             try {
                 lockComponent(component.getUniqueId(), component, action);
             } catch (ComponentException e) {
-            janusGraphDao.rollback();
-            throw e;
+                janusGraphDao.rollback();
+                throw e;
+            }
         }
-    }
         return Either.left(true);
     }
 
-    public Either<List<InterfaceDefinition>, ResponseFormat> getInterfaceOperation(String componentId,
-            String interfaceId, List<String> operationsToGet, User user, boolean lock) {
+    public Either<List<InterfaceDefinition>, ResponseFormat> getInterfaceOperation(String componentId, String interfaceId,
+                                                                                   List<String> operationsToGet, User user, boolean lock) {
         validateUserExists(user);
-
         Either<org.openecomp.sdc.be.model.Component, ResponseFormat> componentEither = getComponentDetails(componentId);
         if (componentEither.isRight()) {
             return Either.right(componentEither.right().value());
         }
         org.openecomp.sdc.be.model.Component storedComponent = componentEither.left().value();
-
         lockComponentResult(lock, storedComponent, GET_INTERFACE_OPERATION);
-
         try {
-            Optional<InterfaceDefinition> optionalInterface = getInterfaceDefinitionFromComponentByInterfaceId(
-                    storedComponent, interfaceId);
+            Optional<InterfaceDefinition> optionalInterface = getInterfaceDefinitionFromComponentByInterfaceId(storedComponent, interfaceId);
             if (!optionalInterface.isPresent()) {
-                return Either.right(
-                        componentsUtils.getResponseFormat(ActionStatus.INTERFACE_NOT_FOUND_IN_COMPONENT, interfaceId));
+                return Either.right(componentsUtils.getResponseFormat(ActionStatus.INTERFACE_NOT_FOUND_IN_COMPONENT, interfaceId));
             }
             InterfaceDefinition interfaceDefinition = optionalInterface.get();
-
             for (String operationId : operationsToGet) {
-                Optional<Map.Entry<String, Operation>> optionalOperation =
-                        getOperationFromInterfaceDefinition(interfaceDefinition, operationId);
+                Optional<Map.Entry<String, Operation>> optionalOperation = getOperationFromInterfaceDefinition(interfaceDefinition, operationId);
                 if (!optionalOperation.isPresent()) {
-                    return Either.right(componentsUtils.getResponseFormat(ActionStatus.INTERFACE_OPERATION_NOT_FOUND,
-                            storedComponent.getUniqueId()));
+                    return Either.right(componentsUtils.getResponseFormat(ActionStatus.INTERFACE_OPERATION_NOT_FOUND, storedComponent.getUniqueId()));
                 }
             }
-
             janusGraphDao.commit();
             interfaceDefinition.getOperations().keySet().removeIf(key -> !(operationsToGet.contains(key)));
             return Either.left(Collections.singletonList(interfaceDefinition));
         } catch (Exception e) {
             LOGGER.error(EXCEPTION_OCCURRED_DURING_INTERFACE_OPERATION, "get", e);
             janusGraphDao.rollback();
-            return Either.right(
-                    componentsUtils.getResponseFormat(ActionStatus.INTERFACE_OPERATION_NOT_FOUND, componentId));
+            return Either.right(componentsUtils.getResponseFormat(ActionStatus.INTERFACE_OPERATION_NOT_FOUND, componentId));
         } finally {
-            graphLockOperation.unlockComponent(storedComponent.getUniqueId(),
-                    NodeTypeEnum.getByNameIgnoreCase(storedComponent.getComponentType().getValue()));
+            graphLockOperation
+                .unlockComponent(storedComponent.getUniqueId(), NodeTypeEnum.getByNameIgnoreCase(storedComponent.getComponentType().getValue()));
         }
     }
 
     public Either<List<InterfaceDefinition>, ResponseFormat> createInterfaceOperation(String componentId,
-            List<InterfaceDefinition> interfaceDefinitions, User user, boolean lock) {
-        return createOrUpdateInterfaceOperation(componentId, interfaceDefinitions, user, false,
-                CREATE_INTERFACE_OPERATION, lock);
+                                                                                      List<InterfaceDefinition> interfaceDefinitions, User user,
+                                                                                      boolean lock) {
+        return createOrUpdateInterfaceOperation(componentId, interfaceDefinitions, user, false, CREATE_INTERFACE_OPERATION, lock);
     }
 
     private Either<List<InterfaceDefinition>, ResponseFormat> createOrUpdateInterfaceOperation(String componentId,
-            List<InterfaceDefinition> interfaceDefinitions, User user, boolean isUpdate, String errorContext,
-            boolean lock) {
+                                                                                               List<InterfaceDefinition> interfaceDefinitions,
+                                                                                               User user, boolean isUpdate, String errorContext,
+                                                                                               boolean lock) {
         validateUserExists(user);
-
         Either<org.openecomp.sdc.be.model.Component, ResponseFormat> componentEither = getComponentDetails(componentId);
         if (componentEither.isRight()) {
             return Either.right(componentEither.right().value());
         }
         org.openecomp.sdc.be.model.Component storedComponent = componentEither.left().value();
-
         lockComponentResult(lock, storedComponent, errorContext);
-
-
-        Either<Map<String, InterfaceDefinition>, ResponseFormat> interfaceLifecycleTypes =
-                getAllInterfaceLifecycleTypes();
+        Either<Map<String, InterfaceDefinition>, ResponseFormat> interfaceLifecycleTypes = getAllInterfaceLifecycleTypes();
         if (interfaceLifecycleTypes.isRight()) {
             return Either.right(interfaceLifecycleTypes.right().value());
         }
-
         try {
             List<InterfaceDefinition> interfacesCollection = new ArrayList<>();
             Map<String, Operation> operationsCollection = new HashMap<>();
             for (InterfaceDefinition inputInterfaceDefinition : interfaceDefinitions) {
-                Optional<InterfaceDefinition> optionalInterface =
-                        getInterfaceDefinitionFromComponentByInterfaceType(
-                                storedComponent, inputInterfaceDefinition.getType());
-                Either<Boolean, ResponseFormat> interfaceOperationValidationResponseEither =
-                        interfaceOperationValidation
-                                .validateInterfaceOperations(inputInterfaceDefinition, storedComponent,
-                                        optionalInterface.orElse(null), interfaceLifecycleTypes.left().value(),
-                                        isUpdate);
+                Optional<InterfaceDefinition> optionalInterface = getInterfaceDefinitionFromComponentByInterfaceType(storedComponent,
+                    inputInterfaceDefinition.getType());
+                Either<Boolean, ResponseFormat> interfaceOperationValidationResponseEither = interfaceOperationValidation
+                    .validateInterfaceOperations(inputInterfaceDefinition, storedComponent, optionalInterface.orElse(null),
+                        interfaceLifecycleTypes.left().value(), isUpdate);
                 if (interfaceOperationValidationResponseEither.isRight()) {
                     return Either.right(interfaceOperationValidationResponseEither.right().value());
                 }
-
                 Map<String, Operation> operationsToAddOrUpdate = inputInterfaceDefinition.getOperationsMap();
                 operationsCollection.putAll(operationsToAddOrUpdate);
                 inputInterfaceDefinition.getOperations().clear();
-
-                Either<InterfaceDefinition, ResponseFormat> getInterfaceEither =
-                        getOrCreateInterfaceDefinition(storedComponent, inputInterfaceDefinition,
-                                optionalInterface.orElse(null));
+                Either<InterfaceDefinition, ResponseFormat> getInterfaceEither = getOrCreateInterfaceDefinition(storedComponent,
+                    inputInterfaceDefinition, optionalInterface.orElse(null));
                 if (getInterfaceEither.isRight()) {
                     return Either.right(getInterfaceEither.right().value());
                 }
                 InterfaceDefinition interfaceDef = getInterfaceEither.left().value();
-
                 updateOperationInputDefs(storedComponent, operationsToAddOrUpdate.values());
-
                 for (Operation operation : operationsToAddOrUpdate.values()) {
                     if (!isUpdate) {
                         addOperationToInterface(interfaceDef, operation);
                     } else {
-                        Optional<Map.Entry<String, Operation>> optionalOperation =
-                                getOperationFromInterfaceDefinition(interfaceDef,
-                                        operation.getUniqueId());
+                        Optional<Map.Entry<String, Operation>> optionalOperation = getOperationFromInterfaceDefinition(interfaceDef,
+                            operation.getUniqueId());
                         if (!optionalOperation.isPresent()) {
                             janusGraphDao.rollback();
-                            return Either.right(componentsUtils
-                                                        .getResponseFormat(ActionStatus.INTERFACE_OPERATION_NOT_FOUND,
-                                                                storedComponent.getUniqueId()));
+                            return Either
+                                .right(componentsUtils.getResponseFormat(ActionStatus.INTERFACE_OPERATION_NOT_FOUND, storedComponent.getUniqueId()));
                         }
-
                         Operation storedOperation = optionalOperation.get().getValue();
                         String artifactUuId = storedOperation.getImplementation().getArtifactUUID();
                         String artifactUniqueId = storedOperation.getImplementation().getUniqueId();
-
-                        if(!InterfaceOperationUtils.isArtifactInUse(storedComponent, storedOperation.getUniqueId(), artifactUniqueId)){
-                            Either<ArtifactDefinition, StorageOperationStatus> getArtifactEither =
-                                    artifactToscaOperation.getArtifactById(storedComponent.getUniqueId(), artifactUniqueId);
-                            if(getArtifactEither.isLeft()){
-                                Either<ArtifactDefinition, StorageOperationStatus> removeArifactFromComponent =
-                                        artifactToscaOperation.removeArifactFromResource(componentId, artifactUniqueId,
-                                                NodeTypeEnum.getByNameIgnoreCase(storedComponent.getComponentType().getValue()),
-                                                true);
-                                if(removeArifactFromComponent.isRight()){
+                        if (!InterfaceOperationUtils.isArtifactInUse(storedComponent, storedOperation.getUniqueId(), artifactUniqueId)) {
+                            Either<ArtifactDefinition, StorageOperationStatus> getArtifactEither = artifactToscaOperation
+                                .getArtifactById(storedComponent.getUniqueId(), artifactUniqueId);
+                            if (getArtifactEither.isLeft()) {
+                                Either<ArtifactDefinition, StorageOperationStatus> removeArifactFromComponent = artifactToscaOperation
+                                    .removeArifactFromResource(componentId, artifactUniqueId,
+                                        NodeTypeEnum.getByNameIgnoreCase(storedComponent.getComponentType().getValue()), true);
+                                if (removeArifactFromComponent.isRight()) {
                                     janusGraphDao.rollback();
                                     ResponseFormat responseFormatByArtifactId = componentsUtils.getResponseFormatByArtifactId(
-                                            componentsUtils.convertFromStorageResponse(removeArifactFromComponent.right().value()),
-                                            storedOperation.getImplementation().getArtifactDisplayName());
+                                        componentsUtils.convertFromStorageResponse(removeArifactFromComponent.right().value()),
+                                        storedOperation.getImplementation().getArtifactDisplayName());
                                     return Either.right(responseFormatByArtifactId);
                                 }
-
                                 CassandraOperationStatus cassandraStatus = artifactCassandraDao.deleteArtifact(artifactUniqueId);
                                 if (cassandraStatus != CassandraOperationStatus.OK) {
                                     janusGraphDao.rollback();
-                                    ResponseFormat responseFormatByArtifactId =
-                                            componentsUtils.getResponseFormatByArtifactId(
-                                                    componentsUtils.convertFromStorageResponse(
-                                                            componentsUtils.convertToStorageOperationStatus(
-                                                                    cassandraStatus)),
-                                                    storedOperation.getImplementation().getArtifactDisplayName());
+                                    ResponseFormat responseFormatByArtifactId = componentsUtils.getResponseFormatByArtifactId(
+                                        componentsUtils.convertFromStorageResponse(componentsUtils.convertToStorageOperationStatus(cassandraStatus)),
+                                        storedOperation.getImplementation().getArtifactDisplayName());
                                     return Either.right(responseFormatByArtifactId);
                                 }
                             }
@@ -387,73 +327,64 @@ public class InterfaceOperationBusinessLogic extends BaseBusinessLogic {
                 }
                 interfacesCollection.add(interfaceDef);
             }
-
-            Either<List<InterfaceDefinition>, StorageOperationStatus> addCreateOperationEither =
-                    interfaceOperation.updateInterfaces(storedComponent.getUniqueId(), interfacesCollection);
+            Either<List<InterfaceDefinition>, StorageOperationStatus> addCreateOperationEither = interfaceOperation
+                .updateInterfaces(storedComponent.getUniqueId(), interfacesCollection);
             if (addCreateOperationEither.isRight()) {
                 janusGraphDao.rollback();
-                return Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(
-                        addCreateOperationEither.right().value(), storedComponent.getComponentType())));
+                return Either.right(componentsUtils.getResponseFormat(
+                    componentsUtils.convertFromStorageResponse(addCreateOperationEither.right().value(), storedComponent.getComponentType())));
             }
-
             janusGraphDao.commit();
             interfacesCollection.forEach(interfaceDefinition -> interfaceDefinition.getOperations().entrySet().removeIf(
-                    entry -> !operationsCollection.values().stream().map(OperationDataDefinition::getName)
-                                      .collect(Collectors.toList()).contains(entry.getValue().getName())));
+                entry -> !operationsCollection.values().stream().map(OperationDataDefinition::getName).collect(Collectors.toList())
+                    .contains(entry.getValue().getName())));
             return Either.left(interfacesCollection);
         } catch (Exception e) {
             janusGraphDao.rollback();
             LOGGER.error(EXCEPTION_OCCURRED_DURING_INTERFACE_OPERATION, "addOrUpdate", e);
             return Either.right(componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR));
         } finally {
-            graphLockOperation.unlockComponent(storedComponent.getUniqueId(),
-                    NodeTypeEnum.getByNameIgnoreCase(storedComponent.getComponentType().getValue()));
+            graphLockOperation
+                .unlockComponent(storedComponent.getUniqueId(), NodeTypeEnum.getByNameIgnoreCase(storedComponent.getComponentType().getValue()));
         }
     }
 
     public Either<Map<String, InterfaceDefinition>, ResponseFormat> getAllInterfaceLifecycleTypes() {
-
-        Either<Map<String, InterfaceDefinition>, StorageOperationStatus> interfaceLifecycleTypes =
-                interfaceLifecycleTypeOperation.getAllInterfaceLifecycleTypes();
+        Either<Map<String, InterfaceDefinition>, StorageOperationStatus> interfaceLifecycleTypes = interfaceLifecycleTypeOperation
+            .getAllInterfaceLifecycleTypes();
         if (interfaceLifecycleTypes.isRight()) {
             return Either.right(componentsUtils.getResponseFormat(ActionStatus.INTERFACE_LIFECYCLE_TYPES_NOT_FOUND));
         }
-        interfaceLifecycleTypes.left().value().values().forEach(id -> id.setOperations(
-                id.getOperations().keySet().stream().collect(Collectors.toMap(key -> key.replaceFirst(
-                        id.getUniqueId() + ".", ""), i -> id.getOperations().get(i)))));
-
+        interfaceLifecycleTypes.left().value().values().forEach(id -> id.setOperations(id.getOperations().keySet().stream()
+            .collect(Collectors.toMap(key -> key.replaceFirst(id.getUniqueId() + ".", ""), i -> id.getOperations().get(i)))));
         return Either.left(interfaceLifecycleTypes.left().value());
     }
 
-    private Either<InterfaceDefinition, ResponseFormat> getOrCreateInterfaceDefinition(
-            org.openecomp.sdc.be.model.Component component, InterfaceDefinition interfaceDefinition,
-            InterfaceDefinition storedInterfaceDef) {
+    private Either<InterfaceDefinition, ResponseFormat> getOrCreateInterfaceDefinition(org.openecomp.sdc.be.model.Component component,
+                                                                                       InterfaceDefinition interfaceDefinition,
+                                                                                       InterfaceDefinition storedInterfaceDef) {
         if (storedInterfaceDef != null) {
             return Either.left(storedInterfaceDef);
         }
         interfaceDefinition.setUniqueId(UUID.randomUUID().toString());
         interfaceDefinition.setToscaResourceName(interfaceDefinition.getType());
-        Either<List<InterfaceDefinition>, StorageOperationStatus> interfaceCreateEither =
-                interfaceOperation.addInterfaces(component.getUniqueId(),
-                        Collections.singletonList(interfaceDefinition));
+        Either<List<InterfaceDefinition>, StorageOperationStatus> interfaceCreateEither = interfaceOperation
+            .addInterfaces(component.getUniqueId(), Collections.singletonList(interfaceDefinition));
         if (interfaceCreateEither.isRight()) {
             janusGraphDao.rollback();
-            return Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(
-                    interfaceCreateEither.right().value(), component.getComponentType())));
+            return Either.right(componentsUtils
+                .getResponseFormat(componentsUtils.convertFromStorageResponse(interfaceCreateEither.right().value(), component.getComponentType())));
         }
         return Either.left(interfaceCreateEither.left().value().get(0));
     }
 
-    private void updateOperationInputDefs(org.openecomp.sdc.be.model.Component component,
-                                          Collection<Operation> interfaceOperations) {
+    private void updateOperationInputDefs(org.openecomp.sdc.be.model.Component component, Collection<Operation> interfaceOperations) {
         interfaceOperations.stream().filter(operation -> Objects.nonNull(operation.getInputs())).forEach(
-                operation -> operation.getInputs().getListToscaDataDefinition().forEach(
-                        inp -> component.getInputs()
-                                .forEach(in -> updateOperationInputDefinition(component, inp, in))));
+            operation -> operation.getInputs().getListToscaDataDefinition()
+                .forEach(inp -> component.getInputs().forEach(in -> updateOperationInputDefinition(component, inp, in))));
     }
 
-    private void updateOperationInputDefinition(org.openecomp.sdc.be.model.Component component,
-                                                OperationInputDefinition operationInput,
+    private void updateOperationInputDefinition(org.openecomp.sdc.be.model.Component component, OperationInputDefinition operationInput,
                                                 InputDefinition componentInput) {
         if (operationInput.getInputId().equals(componentInput.getUniqueId())) {
             //Set the default value, value and schema only for inputs mapped to component inputs
@@ -461,41 +392,32 @@ public class InterfaceOperationBusinessLogic extends BaseBusinessLogic {
             operationInput.setToscaDefaultValue(getInputToscaDefaultValue(operationInput, component));
             operationInput.setValue(componentInput.getValue());
             operationInput.setSchema(componentInput.getSchema());
-                       operationInput.setParentPropertyType(componentInput.getParentPropertyType());
-                       operationInput.setSubPropertyInputPath(componentInput.getSubPropertyInputPath());
+            operationInput.setParentPropertyType(componentInput.getParentPropertyType());
+            operationInput.setSubPropertyInputPath(componentInput.getSubPropertyInputPath());
         }
         //Set the tosca default value for inputs mapped to component inputs as well as other outputs
         operationInput.setToscaDefaultValue(getInputToscaDefaultValue(operationInput, component));
     }
 
-    private String getInputToscaDefaultValue(OperationInputDefinition input,
-                                             org.openecomp.sdc.be.model.Component component) {
+    private String getInputToscaDefaultValue(OperationInputDefinition input, org.openecomp.sdc.be.model.Component component) {
         Map<String, List<String>> defaultInputValue = null;
         if (isOperationInputMappedToComponentInput(input, component.getInputs())) {
             String propertyName = input.getInputId().substring(input.getInputId().indexOf('.') + 1);
-                       setParentPropertyTypeAndInputPath(input, component);
+            setParentPropertyTypeAndInputPath(input, component);
             defaultInputValue = createMappedInputPropertyDefaultValue(propertyName);
         } else if (isCapabilityProperty(input.getInputId(), component).isPresent()) {
-            Optional<ComponentInstanceProperty> instancePropertyOpt = isCapabilityProperty(input.getInputId(),
-                component);
+            Optional<ComponentInstanceProperty> instancePropertyOpt = isCapabilityProperty(input.getInputId(), component);
             Optional<String> parentPropertyIdOpt = instancePropertyOpt.map(PropertyDataDefinition::getParentUniqueId);
             Map<String, List<CapabilityDefinition>> componentCapabilities = component.getCapabilities();
-            if(MapUtils.isNotEmpty(componentCapabilities)) {
-                List<CapabilityDefinition> capabilityDefinitionList = componentCapabilities.values().stream()
-                    .flatMap(Collection::stream)
-                    .filter(capabilityDefinition -> capabilityDefinition.getOwnerId().equals(component.getUniqueId()))
-                    .collect(Collectors.toList());
-
+            if (MapUtils.isNotEmpty(componentCapabilities)) {
+                List<CapabilityDefinition> capabilityDefinitionList = componentCapabilities.values().stream().flatMap(Collection::stream)
+                    .filter(capabilityDefinition -> capabilityDefinition.getOwnerId().equals(component.getUniqueId())).collect(Collectors.toList());
                 defaultInputValue = parentPropertyIdOpt
-                    .flatMap(parentPropertyId ->
-                        getPropertyCapabilityFromAllCapProps(parentPropertyId, capabilityDefinitionList))
-                    .flatMap(capability ->
-                        instancePropertyOpt.map(instanceProperty ->
-                            new ImmutablePair<>(capability.getName(), instanceProperty.getName())))
-                    .map(tuple -> {
+                    .flatMap(parentPropertyId -> getPropertyCapabilityFromAllCapProps(parentPropertyId, capabilityDefinitionList)).flatMap(
+                        capability -> instancePropertyOpt
+                            .map(instanceProperty -> new ImmutablePair<>(capability.getName(), instanceProperty.getName()))).map(tuple -> {
                         String propertyName = tuple.right;
                         String capabilityName = tuple.left;
-
                         return createMappedCapabilityPropertyDefaultValue(capabilityName, propertyName);
                     }).orElse(null);
             }
@@ -506,36 +428,28 @@ public class InterfaceOperationBusinessLogic extends BaseBusinessLogic {
         return new Gson().toJson(defaultInputValue);
     }
 
-       private void setParentPropertyTypeAndInputPath(OperationInputDefinition input,
-                                                                                                  org.openecomp.sdc.be.model.Component component) {
-               if (CollectionUtils.isEmpty(component.getInputs())) {
-                       return;
-               }
-
-               component.getInputs()
-                               .stream()
-                               .filter(inp -> inp.getUniqueId().equals(
-                                               input.getInputId().substring(0, input.getInputId().lastIndexOf('.'))))
-                               .forEach(inp -> {
-                                       input.setParentPropertyType(inp.getParentPropertyType());
-                                       if (Objects.nonNull(input.getName())) {
-                                               input.setSubPropertyInputPath(input.getName().replaceAll("\\.", "#"));
-                                       }
-                               });
-       }
+    private void setParentPropertyTypeAndInputPath(OperationInputDefinition input, org.openecomp.sdc.be.model.Component component) {
+        if (CollectionUtils.isEmpty(component.getInputs())) {
+            return;
+        }
+        component.getInputs().stream().filter(inp -> inp.getUniqueId().equals(input.getInputId().substring(0, input.getInputId().lastIndexOf('.'))))
+            .forEach(inp -> {
+                input.setParentPropertyType(inp.getParentPropertyType());
+                if (Objects.nonNull(input.getName())) {
+                    input.setSubPropertyInputPath(input.getName().replaceAll("\\.", "#"));
+                }
+            });
+    }
 
     private void addOperationToInterface(InterfaceDefinition interfaceDefinition, Operation interfaceOperation) {
         interfaceOperation.setUniqueId(UUID.randomUUID().toString());
         interfaceOperation.setImplementation(createArtifactDefinition(UUID.randomUUID().toString(), interfaceOperation));
-        interfaceDefinition.getOperations()
-                .put(interfaceOperation.getUniqueId(), new OperationDataDefinition(interfaceOperation));
+        interfaceDefinition.getOperations().put(interfaceOperation.getUniqueId(), new OperationDataDefinition(interfaceOperation));
     }
 
-    private void updateOperationOnInterface(InterfaceDefinition interfaceDefinition, Operation interfaceOperation,
-            String artifactUuId) {
+    private void updateOperationOnInterface(InterfaceDefinition interfaceDefinition, Operation interfaceOperation, String artifactUuId) {
         interfaceOperation.setImplementation(createArtifactDefinition(artifactUuId, interfaceOperation));
-        interfaceDefinition.getOperations()
-                .put(interfaceOperation.getUniqueId(), new OperationDataDefinition(interfaceOperation));
+        interfaceDefinition.getOperations().put(interfaceOperation.getUniqueId(), new OperationDataDefinition(interfaceOperation));
     }
 
     private ArtifactDefinition createArtifactDefinition(String artifactUuId, Operation operation) {
@@ -551,60 +465,50 @@ public class InterfaceOperationBusinessLogic extends BaseBusinessLogic {
     }
 
     public Either<List<InterfaceDefinition>, ResponseFormat> updateInterfaceOperation(String componentId,
-            List<InterfaceDefinition> interfaceDefinitions, User user, boolean lock) {
-        return createOrUpdateInterfaceOperation(componentId, interfaceDefinitions, user, true,
-                UPDATE_INTERFACE_OPERATION, lock);
+                                                                                      List<InterfaceDefinition> interfaceDefinitions, User user,
+                                                                                      boolean lock) {
+        return createOrUpdateInterfaceOperation(componentId, interfaceDefinitions, user, true, UPDATE_INTERFACE_OPERATION, lock);
     }
 
-    public Either<List<OperationInputDefinition>, ResponseFormat> getInputsListForOperation(String componentId,
-                                                                                            String componentInstanceId, String interfaceId, String operationId, User user) {
+    public Either<List<OperationInputDefinition>, ResponseFormat> getInputsListForOperation(String componentId, String componentInstanceId,
+                                                                                            String interfaceId, String operationId, User user) {
         Either<org.openecomp.sdc.be.model.Component, ResponseFormat> componentEither = getComponentDetails(componentId);
-        if (componentEither.isRight()){
+        if (componentEither.isRight()) {
             return Either.right(componentEither.right().value());
         }
-
         org.openecomp.sdc.be.model.Component storedComponent = componentEither.left().value();
         validateUserExists(user.getUserId());
-
         Either<Boolean, ResponseFormat> lockResult = lockComponentResult(true, storedComponent, GET_INTERFACE_OPERATION);
         if (lockResult.isRight()) {
             return Either.right(lockResult.right().value());
         }
-
-        try{
+        try {
             org.openecomp.sdc.be.model.Component parentComponent = componentEither.left().value();
-            Map<String, List<ComponentInstanceInterface>> componentInstanceInterfaces =
-                    parentComponent.getComponentInstancesInterfaces();
-            if(MapUtils.isEmpty(componentInstanceInterfaces)) {
-                return Either.right(componentsUtils.getResponseFormat(ActionStatus.INTERFACE_OPERATION_NOT_FOUND,
-                        componentInstanceId));
+            Map<String, List<ComponentInstanceInterface>> componentInstanceInterfaces = parentComponent.getComponentInstancesInterfaces();
+            if (MapUtils.isEmpty(componentInstanceInterfaces)) {
+                return Either.right(componentsUtils.getResponseFormat(ActionStatus.INTERFACE_OPERATION_NOT_FOUND, componentInstanceId));
             }
-
-            List<ComponentInstanceInterface> componentInstanceInterfaceList =
-                    componentInstanceInterfaces.get(componentInstanceId);
-            for(ComponentInstanceInterface componentInstanceInterface : componentInstanceInterfaceList) {
-                if(componentInstanceInterface.getInterfaceId().equals(interfaceId)){
+            List<ComponentInstanceInterface> componentInstanceInterfaceList = componentInstanceInterfaces.get(componentInstanceId);
+            for (ComponentInstanceInterface componentInstanceInterface : componentInstanceInterfaceList) {
+                if (componentInstanceInterface.getInterfaceId().equals(interfaceId)) {
                     Map<String, OperationDataDefinition> operations = componentInstanceInterface.getOperations();
-                    if(MapUtils.isNotEmpty(operations) && operations.containsKey(operationId)) {
+                    if (MapUtils.isNotEmpty(operations) && operations.containsKey(operationId)) {
                         ListDataDefinition<OperationInputDefinition> inputs = operations.get(operationId).getInputs();
-                        return Either.left(CollectionUtils.isEmpty(inputs.getListToscaDataDefinition())
-                                ? new ArrayList<>() : inputs.getListToscaDataDefinition());
+                        return Either.left(
+                            CollectionUtils.isEmpty(inputs.getListToscaDataDefinition()) ? new ArrayList<>() : inputs.getListToscaDataDefinition());
                     }
                 }
             }
             return Either.left(new ArrayList<>());
-        }
-        catch (Exception e) {
+        } catch (Exception e) {
             LOGGER.error(EXCEPTION_OCCURRED_DURING_INTERFACE_OPERATION, "get", e);
             janusGraphDao.rollback();
             return Either.right(componentsUtils.getResponseFormat(ActionStatus.INTERFACE_OPERATION_NOT_FOUND));
-        }
-        finally {
+        } finally {
             if (lockResult.isLeft() && lockResult.left().value()) {
-                graphLockOperation.unlockComponent(storedComponent.getUniqueId(),
-                        NodeTypeEnum.getByNameIgnoreCase(storedComponent.getComponentType().getValue()));
+                graphLockOperation
+                    .unlockComponent(storedComponent.getUniqueId(), NodeTypeEnum.getByNameIgnoreCase(storedComponent.getComponentType().getValue()));
             }
         }
     }
-
 }
index 927c8b1..9d72eec 100644 (file)
  * See the License for the specific language governing permissions and
  * limitations under the License.
  */
-
 package org.openecomp.sdc.be.components.impl;
 
-import org.onap.sdc.tosca.services.YamlUtil;
-import org.openecomp.sdc.be.model.UploadNodeFilterCapabilitiesInfo;
-import org.openecomp.sdc.be.model.UploadNodeFilterInfo;
-import org.openecomp.sdc.be.model.UploadNodeFilterPropertyInfo;
-import org.openecomp.sdc.be.utils.TypeUtils;
-
 import java.util.ArrayList;
 import java.util.HashMap;
 import java.util.List;
 import java.util.Map;
 import java.util.stream.Collectors;
+import org.onap.sdc.tosca.services.YamlUtil;
+import org.openecomp.sdc.be.model.UploadNodeFilterCapabilitiesInfo;
+import org.openecomp.sdc.be.model.UploadNodeFilterInfo;
+import org.openecomp.sdc.be.model.UploadNodeFilterPropertyInfo;
+import org.openecomp.sdc.be.utils.TypeUtils;
 
 public class NodeFilterUploadCreator {
 
@@ -35,7 +33,6 @@ public class NodeFilterUploadCreator {
             return null;
         }
         Map<String, Object> nodeFilterMap = (Map<String, Object>) obj;
-
         UploadNodeFilterInfo uploadNodeFilterInfo = new UploadNodeFilterInfo();
         final String propertiesElementName = TypeUtils.ToscaTagNamesEnum.PROPERTIES.getElementName();
         if (nodeFilterMap.containsKey(propertiesElementName)) {
@@ -43,8 +40,7 @@ public class NodeFilterUploadCreator {
         }
         final String capabilitiesElementName = TypeUtils.ToscaTagNamesEnum.CAPABILITIES.getElementName();
         if (nodeFilterMap.containsKey(capabilitiesElementName)) {
-            uploadNodeFilterInfo
-                    .setCapabilities(createNodeFilterCapabilities(nodeFilterMap.get(capabilitiesElementName)));
+            uploadNodeFilterInfo.setCapabilities(createNodeFilterCapabilities(nodeFilterMap.get(capabilitiesElementName)));
         }
         final String toscaId = TypeUtils.ToscaTagNamesEnum.TOSCA_ID.getElementName();
         if (nodeFilterMap.containsKey(toscaId)) {
@@ -67,8 +63,7 @@ public class NodeFilterUploadCreator {
                 valueList.add(valueToProperty(entry.getValue()));
                 retVal.add(new UploadNodeFilterPropertyInfo(entry.getKey(), valueList));
             } else if (value instanceof List) {
-                List<String> propertiesVals =
-                        (List<String>) ((List) value).stream().map(this::valueToProperty).collect(Collectors.toList());
+                List<String> propertiesVals = (List<String>) ((List) value).stream().map(this::valueToProperty).collect(Collectors.toList());
                 retVal.add(new UploadNodeFilterPropertyInfo(entry.getKey(), propertiesVals));
             }
         }
@@ -76,7 +71,6 @@ public class NodeFilterUploadCreator {
     }
 
     private String valueToProperty(Object o) {
-
         if (o instanceof Map) {
             return new YamlUtil().objectToYaml(o);
         }
@@ -97,7 +91,6 @@ public class NodeFilterUploadCreator {
             retVal.put(entry.getKey(), uploadNodeFilterCapabilitiesInfo);
         }
         return retVal;
-
     }
 
     private List<UploadNodeFilterPropertyInfo> createCapabilitiesProperties(Object o) {
@@ -112,6 +105,4 @@ public class NodeFilterUploadCreator {
         }
         return null;
     }
-
-
 }
index f64c11a..2a9157a 100644 (file)
@@ -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.
@@ -17,7 +17,6 @@
  * limitations under the License.
  * ============LICENSE_END=========================================================
  */
-
 package org.openecomp.sdc.be.components.impl;
 
 import org.openecomp.sdc.be.dao.api.ActionStatus;
@@ -27,10 +26,10 @@ public interface OnDeleteEntityOperation {
 
     /**
      * side effect operation to be executed when a given entity is deleted
-     * @param container the container which holds the entity to be deleted
+     *
+     * @param container       the container which holds the entity to be deleted
      * @param deletedEntityId the id of the entity that was deleted
      * @return the status of the on delete operation
      */
     ActionStatus onDelete(Component container, String deletedEntityId);
-
 }
index cfb6004..2d6a619 100644 (file)
@@ -17,7 +17,6 @@
  * limitations under the License.
  * ============LICENSE_END=========================================================
  */
-
 package org.openecomp.sdc.be.components.impl;
 
 import fj.data.Either;
@@ -57,7 +56,6 @@ import org.springframework.beans.factory.annotation.Autowired;
 public class OutputsBusinessLogic extends BaseBusinessLogic {
 
     private static final String CREATE_OUTPUT = "CreateOutput";
-
     private static final Logger log = Logger.getLogger(OutputsBusinessLogic.class);
     private static final String FAILED_TO_FOUND_COMPONENT_ERROR = "Failed to found component {}, error: {}";
     private static final String GOING_TO_EXECUTE_ROLLBACK_ON_CREATE_GROUP = "Going to execute rollback on create group.";
@@ -65,16 +63,12 @@ public class OutputsBusinessLogic extends BaseBusinessLogic {
     private static final LoggerSupportability loggerSupportability = LoggerSupportability.getLogger(OutputsBusinessLogic.class);
     private static final String FAILED_TO_FOUND_COMPONENT_INSTANCE_OUTPUTS_COMPONENT_INSTANCE_ID = "Failed to found component instance outputs componentInstanceId: {}";
     private static final String FAILED_TO_FOUND_COMPONENT_INSTANCE_OUTPUTS_ERROR = "Failed to found component instance outputs {}, error: {}";
-
     private final AttributeDeclarationOrchestrator attributeDeclarationOrchestrator;
 
     @Autowired
-    public OutputsBusinessLogic(final IElementOperation elementDao,
-                                final IGroupOperation groupOperation,
-                                final IGroupInstanceOperation groupInstanceOperation,
-                                final IGroupTypeOperation groupTypeOperation,
-                                final InterfaceOperation interfaceOperation,
-                                final InterfaceLifecycleOperation interfaceLifecycleTypeOperation,
+    public OutputsBusinessLogic(final IElementOperation elementDao, final IGroupOperation groupOperation,
+                                final IGroupInstanceOperation groupInstanceOperation, final IGroupTypeOperation groupTypeOperation,
+                                final InterfaceOperation interfaceOperation, final InterfaceLifecycleOperation interfaceLifecycleTypeOperation,
                                 final AttributeDeclarationOrchestrator attributeDeclarationOrchestrator,
                                 final ArtifactsOperations artifactToscaOperation) {
         super(elementDao, groupOperation, groupInstanceOperation, groupTypeOperation, interfaceOperation, interfaceLifecycleTypeOperation,
@@ -82,76 +76,58 @@ public class OutputsBusinessLogic extends BaseBusinessLogic {
         this.attributeDeclarationOrchestrator = attributeDeclarationOrchestrator;
     }
 
-    public Either<List<ComponentInstanceOutput>, ResponseFormat> getComponentInstanceOutputs(final String userId,
-                                                                                             final String componentId,
+    public Either<List<ComponentInstanceOutput>, ResponseFormat> getComponentInstanceOutputs(final String userId, final String componentId,
                                                                                              final String componentInstanceId) {
-
         validateUserExists(userId);
         final ComponentParametersView filters = new ComponentParametersView();
         filters.disableAll();
         filters.setIgnoreOutputs(false);
         filters.setIgnoreComponentInstances(false);
         filters.setIgnoreComponentInstancesOutputs(false);
-
         final Either<Component, StorageOperationStatus> getComponentEither = toscaOperationFacade.getToscaElement(componentId, filters);
-        if(getComponentEither.isRight()){
+        if (getComponentEither.isRight()) {
             ActionStatus actionStatus = componentsUtils.convertFromStorageResponse(getComponentEither.right().value());
             log.debug(FAILED_TO_FOUND_COMPONENT_ERROR, componentId, actionStatus);
             return Either.right(componentsUtils.getResponseFormat(actionStatus));
-
         }
         final Component component = getComponentEither.left().value();
-
         if (!ComponentValidations.validateComponentInstanceExist(component, componentInstanceId)) {
             final ActionStatus actionStatus = ActionStatus.COMPONENT_INSTANCE_NOT_FOUND;
             log.debug(FAILED_TO_FOUND_COMPONENT_INSTANCE_OUTPUTS_ERROR, componentInstanceId, actionStatus);
-            loggerSupportability.log(LoggerSupportabilityActions.CREATE_INPUTS, component.getComponentMetadataForSupportLog(),
-                StatusCode.ERROR, FAILED_TO_FOUND_COMPONENT_INSTANCE_OUTPUTS_COMPONENT_INSTANCE_ID, componentInstanceId);
+            loggerSupportability.log(LoggerSupportabilityActions.CREATE_INPUTS, component.getComponentMetadataForSupportLog(), StatusCode.ERROR,
+                FAILED_TO_FOUND_COMPONENT_INSTANCE_OUTPUTS_COMPONENT_INSTANCE_ID, componentInstanceId);
             return Either.right(componentsUtils.getResponseFormat(actionStatus));
         }
         final Map<String, List<ComponentInstanceOutput>> ciOutputs = Optional.ofNullable(component.getComponentInstancesOutputs())
             .orElse(Collections.emptyMap());
-
         return Either.left(ciOutputs.getOrDefault(componentInstanceId, Collections.emptyList()));
     }
 
     @Override
-    public Either<List<OutputDefinition>, ResponseFormat> declareAttributes(final String userId,
-                                                                            final String componentId,
+    public Either<List<OutputDefinition>, ResponseFormat> declareAttributes(final String userId, final String componentId,
                                                                             final ComponentTypeEnum componentTypeEnum,
                                                                             final ComponentInstOutputsMap componentInstOutputsMap) {
-
         return createMultipleOutputs(userId, componentId, componentTypeEnum, componentInstOutputsMap, true, false);
     }
 
-    public Either<List<OutputDefinition>, ResponseFormat> createMultipleOutputs(final String userId,
-                                                                                final String componentId,
+    public Either<List<OutputDefinition>, ResponseFormat> createMultipleOutputs(final String userId, final String componentId,
                                                                                 final ComponentTypeEnum componentType,
                                                                                 final ComponentInstOutputsMap componentInstOutputsMapUi,
-                                                                                final boolean shouldLockComp,
-                                                                                final boolean inTransaction) {
-
+                                                                                final boolean shouldLockComp, final boolean inTransaction) {
         Either<List<OutputDefinition>, ResponseFormat> result = null;
         org.openecomp.sdc.be.model.Component component = null;
-
         try {
             validateUserExists(userId);
-
             component = getAndValidateComponentForCreate(userId, componentId, componentType, shouldLockComp);
-
-            result = attributeDeclarationOrchestrator.declareAttributesToOutputs(component, componentInstOutputsMapUi)
-                .left()
-                .bind(outputsToCreate -> prepareOutputsForCreation(userId, componentId, outputsToCreate))
-                .right()
+            result = attributeDeclarationOrchestrator.declareAttributesToOutputs(component, componentInstOutputsMapUi).left()
+                .bind(outputsToCreate -> prepareOutputsForCreation(userId, componentId, outputsToCreate)).right()
                 .map(componentsUtils::getResponseFormat);
             return result;
-
         } catch (final ByResponseFormatComponentException e) {
             log.error("#createMultipleOutputs: Exception thrown: ", e);
             result = Either.right(e.getResponseFormat());
             return result;
         } finally {
-
             if (!inTransaction) {
                 if (result == null || result.isRight()) {
                     log.debug(GOING_TO_EXECUTE_ROLLBACK_ON_CREATE_GROUP);
@@ -165,12 +141,10 @@ public class OutputsBusinessLogic extends BaseBusinessLogic {
             if (shouldLockComp && component != null) {
                 graphLockOperation.unlockComponent(componentId, componentType.getNodeType());
             }
-
         }
     }
 
-    private org.openecomp.sdc.be.model.Component getAndValidateComponentForCreate(final String userId,
-                                                                                  final String componentId,
+    private org.openecomp.sdc.be.model.Component getAndValidateComponentForCreate(final String userId, final String componentId,
                                                                                   final ComponentTypeEnum componentType,
                                                                                   final boolean shouldLockComp) {
         final ComponentParametersView componentParametersView = getBaseComponentParametersView();
@@ -183,15 +157,11 @@ public class OutputsBusinessLogic extends BaseBusinessLogic {
         return component;
     }
 
-    private Either<List<OutputDefinition>, StorageOperationStatus> prepareOutputsForCreation(final String userId,
-                                                                                             final String cmptId,
+    private Either<List<OutputDefinition>, StorageOperationStatus> prepareOutputsForCreation(final String userId, final String cmptId,
                                                                                              final List<OutputDefinition> outputsToCreate) {
         final Map<String, OutputDefinition> outputsToPersist = MapUtil.toMap(outputsToCreate, OutputDefinition::getName);
         assignOwnerIdToOutputs(userId, outputsToPersist);
-
-        return toscaOperationFacade.addOutputsToComponent(outputsToPersist, cmptId)
-            .left()
-            .map(persistedOutputs -> outputsToCreate);
+        return toscaOperationFacade.addOutputsToComponent(outputsToPersist, cmptId).left().map(persistedOutputs -> outputsToCreate);
     }
 
     private void assignOwnerIdToOutputs(final String userId, final Map<String, OutputDefinition> outputsToCreate) {
@@ -219,24 +189,19 @@ public class OutputsBusinessLogic extends BaseBusinessLogic {
      * @return
      */
     public OutputDefinition deleteOutput(final String componentId, final String userId, final String outputId) {
-
         Either<OutputDefinition, ResponseFormat> deleteEither = null;
         if (log.isDebugEnabled()) {
             log.debug("Going to delete output id: {}", outputId);
         }
-
         validateUserExists(userId);
-
         final ComponentParametersView componentParametersView = getBaseComponentParametersView();
         componentParametersView.setIgnoreAttributes(false);
-
-        final Either<org.openecomp.sdc.be.model.Component, StorageOperationStatus> componentEither =
-            toscaOperationFacade.getToscaElement(componentId, componentParametersView);
+        final Either<org.openecomp.sdc.be.model.Component, StorageOperationStatus> componentEither = toscaOperationFacade
+            .getToscaElement(componentId, componentParametersView);
         if (componentEither.isRight()) {
             throw new ByActionStatusComponentException(componentsUtils.convertFromStorageResponse(componentEither.right().value()));
         }
         final org.openecomp.sdc.be.model.Component component = componentEither.left().value();
-
         // Validate outputId is child of the component
         final Optional<OutputDefinition> optionalOutput = component.getOutputs().stream().
             // filter by ID
@@ -246,23 +211,19 @@ public class OutputsBusinessLogic extends BaseBusinessLogic {
         if (!optionalOutput.isPresent()) {
             throw new ByActionStatusComponentException(ActionStatus.OUTPUT_IS_NOT_CHILD_OF_COMPONENT, outputId, componentId);
         }
-
         final OutputDefinition outputForDelete = optionalOutput.get();
-
         // Lock component
         lockComponent(componentId, component, "deleteOutput");
         // Delete output operations
         boolean failed = false;
         try {
-            final StorageOperationStatus status =
-                toscaOperationFacade.deleteOutputOfResource(component, outputForDelete.getName());
+            final StorageOperationStatus status = toscaOperationFacade.deleteOutputOfResource(component, outputForDelete.getName());
             if (status != StorageOperationStatus.OK) {
                 log.debug("Component id: {} delete output id: {} failed", componentId, outputId);
                 throw new ByActionStatusComponentException(componentsUtils.convertFromStorageResponse(status), component.getName());
             }
-
-            final StorageOperationStatus storageOperationStatus =
-                attributeDeclarationOrchestrator.unDeclareAttributesAsOutputs(component, outputForDelete);
+            final StorageOperationStatus storageOperationStatus = attributeDeclarationOrchestrator
+                .unDeclareAttributesAsOutputs(component, outputForDelete);
             if (storageOperationStatus != StorageOperationStatus.OK) {
                 log.debug("Component id: {} update attributes declared as output for outputId: {} failed", componentId, outputId);
                 throw new ByActionStatusComponentException(componentsUtils.convertFromStorageResponse(storageOperationStatus), component.getName());
@@ -275,5 +236,4 @@ public class OutputsBusinessLogic extends BaseBusinessLogic {
             unlockComponent(failed, component);
         }
     }
-
 }
index f872074..70e3879 100644 (file)
@@ -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.
  * limitations under the License.
  * ============LICENSE_END=========================================================
  */
-
 package org.openecomp.sdc.be.components.impl;
 
+import static java.util.stream.Collectors.toMap;
+import static org.openecomp.sdc.be.components.validation.PolicyUtils.getExcludedPolicyTypesByComponent;
+import static org.openecomp.sdc.be.components.validation.PolicyUtils.getNextPolicyCounter;
+import static org.openecomp.sdc.be.components.validation.PolicyUtils.validatePolicyFields;
+
 import fj.data.Either;
 import java.util.ArrayList;
+import java.util.Arrays;
 import java.util.Collections;
 import java.util.EnumMap;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+import java.util.Optional;
+import java.util.Set;
+import java.util.function.Function;
+import java.util.stream.Collectors;
 import org.apache.commons.collections.CollectionUtils;
 import org.apache.commons.collections.MapUtils;
 import org.apache.commons.lang.StringUtils;
@@ -62,20 +74,6 @@ import org.openecomp.sdc.common.log.wrappers.Logger;
 import org.openecomp.sdc.exception.ResponseFormat;
 import org.springframework.beans.factory.annotation.Autowired;
 
-import java.util.Arrays;
-import java.util.HashMap;
-import java.util.List;
-import java.util.Map;
-import java.util.Optional;
-import java.util.Set;
-import java.util.function.Function;
-import java.util.stream.Collectors;
-
-import static java.util.stream.Collectors.toMap;
-import static org.openecomp.sdc.be.components.validation.PolicyUtils.getExcludedPolicyTypesByComponent;
-import static org.openecomp.sdc.be.components.validation.PolicyUtils.getNextPolicyCounter;
-import static org.openecomp.sdc.be.components.validation.PolicyUtils.validatePolicyFields;
-
 /**
  * Provides specified business logic to create, retrieve, update, delete a policy
  */
@@ -85,20 +83,15 @@ public class PolicyBusinessLogic extends BaseBusinessLogic {
     private static final String FAILED_TO_VALIDATE_COMPONENT = "#{} - failed to validate the component {} before policy processing. ";
     private static final String DECLARE_PROPERTIES_TO_POLICIES = "declare properties to policies";
     private static final Logger log = Logger.getLogger(PolicyBusinessLogic.class);
-    private static final LoggerSupportability loggerSupportability= LoggerSupportability.getLogger(PolicyBusinessLogic.class.getName());
-
+    private static final LoggerSupportability loggerSupportability = LoggerSupportability.getLogger(PolicyBusinessLogic.class.getName());
     private PropertyDeclarationOrchestrator propertyDeclarationOrchestrator;
 
     @Autowired
-    public PolicyBusinessLogic(IElementOperation elementDao,
-        IGroupOperation groupOperation,
-        IGroupInstanceOperation groupInstanceOperation,
-        IGroupTypeOperation groupTypeOperation,
-        InterfaceOperation interfaceOperation,
-        InterfaceLifecycleOperation interfaceLifecycleTypeOperation,
-        ArtifactsOperations artifactToscaOperation) {
-        super(elementDao, groupOperation, groupInstanceOperation, groupTypeOperation,
-            interfaceOperation, interfaceLifecycleTypeOperation, artifactToscaOperation);
+    public PolicyBusinessLogic(IElementOperation elementDao, IGroupOperation groupOperation, IGroupInstanceOperation groupInstanceOperation,
+                               IGroupTypeOperation groupTypeOperation, InterfaceOperation interfaceOperation,
+                               InterfaceLifecycleOperation interfaceLifecycleTypeOperation, ArtifactsOperations artifactToscaOperation) {
+        super(elementDao, groupOperation, groupInstanceOperation, groupTypeOperation, interfaceOperation, interfaceLifecycleTypeOperation,
+            artifactToscaOperation);
     }
 
     @Autowired
@@ -116,25 +109,24 @@ public class PolicyBusinessLogic extends BaseBusinessLogic {
      * @param shouldLock     the flag defining if the component should be locked
      * @return a policy or an error in a response format
      */
-
-    public PolicyDefinition createPolicy(ComponentTypeEnum componentType, String componentId, String policyTypeName, String userId, boolean shouldLock) {
-
+    public PolicyDefinition createPolicy(ComponentTypeEnum componentType, String componentId, String policyTypeName, String userId,
+                                         boolean shouldLock) {
         log.trace("#createPolicy - starting to create policy of the type {} on the component {}. ", policyTypeName, componentId);
         Component component = null;
         boolean failed = false;
         try {
             component = validateAndLockComponentAndUserBeforeWriteOperation(componentType, componentId, userId, shouldLock);
             return createPolicy(policyTypeName, component);
-        }catch (ComponentException e){
+        } catch (ComponentException e) {
             failed = true;
             throw e;
-        }finally {
+        } finally {
             unlockComponent(shouldLock, failed, component);
         }
     }
 
     public Map<String, PolicyDefinition> createPoliciesFromParsedCsar(Component component,
-            final Map<String, PolicyDefinition> incomingPolicyDefinitions) {
+                                                                      final Map<String, PolicyDefinition> incomingPolicyDefinitions) {
         if (MapUtils.isEmpty(incomingPolicyDefinitions)) {
             return Collections.emptyMap();
         }
@@ -143,8 +135,9 @@ public class PolicyBusinessLogic extends BaseBusinessLogic {
             PolicyDefinition incomingPolicyDefinition = policyEntry.getValue();
             String policyName = incomingPolicyDefinition.getName();
             log.trace("Going to create policy {}", incomingPolicyDefinition);
-            loggerSupportability.log(LoggerSupportabilityActions.CREATE_GROUP_POLICY,component.getComponentMetadataForSupportLog(),
-                    StatusCode.STARTED,"Start to create policy: {} for component {}", policyName, component.getName());
+            loggerSupportability
+                .log(LoggerSupportabilityActions.CREATE_GROUP_POLICY, component.getComponentMetadataForSupportLog(), StatusCode.STARTED,
+                    "Start to create policy: {} for component {}", policyName, component.getName());
             String policyType = incomingPolicyDefinition.getType();
             if (StringUtils.isEmpty(policyType)) {
                 log.debug("Policy type '{}' for policy '{}' not found.", policyType, policyName);
@@ -164,26 +157,25 @@ public class PolicyBusinessLogic extends BaseBusinessLogic {
             List<PropertyDataDefinition> properties = incomingPolicyDefinition.getProperties();
             createdPolicyDefinition = setUpdatePolicyProperties(component, createdPolicyDefinition, properties);
             createdPolicies.put(policyName, createdPolicyDefinition);
-            loggerSupportability.log(LoggerSupportabilityActions.CREATE_POLICIES,component.getComponentMetadataForSupportLog(), StatusCode.COMPLETE,"policy {} has been created ", policyName);
+            loggerSupportability.log(LoggerSupportabilityActions.CREATE_POLICIES, component.getComponentMetadataForSupportLog(), StatusCode.COMPLETE,
+                "policy {} has been created ", policyName);
         }
         return createdPolicies;
     }
 
-    private PolicyDefinition setUpdatePolicyProperties(Component component, PolicyDefinition policyDefinition, List<PropertyDataDefinition> properties) {
+    private PolicyDefinition setUpdatePolicyProperties(Component component, PolicyDefinition policyDefinition,
+                                                       List<PropertyDataDefinition> properties) {
         if (CollectionUtils.isNotEmpty(properties)) {
             PropertyDataDefinition[] propertiesArray = properties.toArray(new PropertyDataDefinition[properties.size()]);
-            List<PropertyDataDefinition> updatedPropertiesList = setComponentValidateUpdatePolicyProperties(
-                    policyDefinition.getUniqueId(),
-                    propertiesArray,
-                    component
-            );
+            List<PropertyDataDefinition> updatedPropertiesList = setComponentValidateUpdatePolicyProperties(policyDefinition.getUniqueId(),
+                propertiesArray, component);
             policyDefinition.setProperties(updatedPropertiesList);
         }
         return policyDefinition;
     }
 
     private PolicyDefinition setUpdatePolicyTargets(Component component, PolicyDefinition policyDefinition,
-            Map<PolicyTargetType, List<String>> targets) {
+                                                    Map<PolicyTargetType, List<String>> targets) {
         if (MapUtils.isEmpty(targets)) {
             return policyDefinition;
         }
@@ -196,19 +188,13 @@ public class PolicyBusinessLogic extends BaseBusinessLogic {
         for (String targetName : targetsToUpdate) {
             Optional<ComponentInstance> componentInstance = component.getComponentInstanceByName(targetName);
             String componentUniqueId = componentInstance
-                                               .orElseThrow(
-                                                       () -> new ByActionStatusComponentException(
-                                                               ActionStatus.COMPONENT_INSTANCE_NOT_FOUND
-                                                       )
-                                               )
-                                               .getUniqueId();
+                .orElseThrow(() -> new ByActionStatusComponentException(ActionStatus.COMPONENT_INSTANCE_NOT_FOUND)).getUniqueId();
             targetsUniqueIds.add(componentUniqueId);
         }
         EnumMap<PolicyTargetType, List<String>> updatedTargets = new EnumMap<>(PolicyTargetType.class);
         updatedTargets.put(PolicyTargetType.COMPONENT_INSTANCES, targetsUniqueIds);
         policyDefinition.setTargets(updatedTargets);
-        policyDefinition = validateAndUpdatePolicyTargets(component, policyDefinition.getUniqueId(),
-                policyDefinition.getTargets());
+        policyDefinition = validateAndUpdatePolicyTargets(component, policyDefinition.getUniqueId(), policyDefinition.getTargets());
         return policyDefinition;
     }
 
@@ -236,7 +222,6 @@ public class PolicyBusinessLogic extends BaseBusinessLogic {
         }
         return result;
     }*/
-
     public Either<List<PolicyDefinition>, ResponseFormat> getPoliciesList(ComponentTypeEnum componentType, String componentId, String userId) {
         Either<List<PolicyDefinition>, ResponseFormat> result;
         log.trace("#getPolicies - starting to retrieve policies of component {}. ", componentId);
@@ -250,8 +235,6 @@ public class PolicyBusinessLogic extends BaseBusinessLogic {
         return result;
     }
 
-
-
     /**
      * Retrieves the policy of the component by UniqueId
      *
@@ -266,7 +249,6 @@ public class PolicyBusinessLogic extends BaseBusinessLogic {
         Component component = validateContainerComponentAndUserBeforeReadOperation(componentType, componentId, userId);
         return getPolicyById(component, policyId);
     }
-
     /*public Either<PolicyDefinition, ResponseFormat> getPolicy(ComponentTypeEnum componentType, String componentId, String policyId, String userId) {
         Either<PolicyDefinition, ResponseFormat> result;
         log.trace("#getPolicy - starting to retrieve the policy {} of the component {}. ", policyId, componentId);
@@ -291,7 +273,8 @@ public class PolicyBusinessLogic extends BaseBusinessLogic {
      * @param shouldLock    the flag defining if the component should be locked
      * @return a policy or an error in a response format
      */
-    public PolicyDefinition updatePolicy(ComponentTypeEnum componentType, String componentId, PolicyDefinition policy, String userId, boolean shouldLock) {
+    public PolicyDefinition updatePolicy(ComponentTypeEnum componentType, String componentId, PolicyDefinition policy, String userId,
+                                         boolean shouldLock) {
         Component component = null;
         boolean failed = false;
         log.trace("#updatePolicy - starting to update the policy {} on the component {}. ", policy.getUniqueId(), componentId);
@@ -300,15 +283,14 @@ public class PolicyBusinessLogic extends BaseBusinessLogic {
             return validateAndUpdatePolicy(component, policy);
         } catch (ComponentException e) {
             failed = true;
-            log.error("#updatePolicy - the exception occurred upon update of a policy of the type {} for the component {}: ", policy.getUniqueId(), componentId, e);
+            log.error("#updatePolicy - the exception occurred upon update of a policy of the type {} for the component {}: ", policy.getUniqueId(),
+                componentId, e);
             throw e;
         } finally {
             //TODO Andrey result = boolean
             unlockComponent(shouldLock, failed, component);
         }
     }
-
-
     /*public Either<PolicyDefinition, ResponseFormat> updatePolicy(ComponentTypeEnum componentType, String componentId, PolicyDefinition policy, String userId, boolean shouldLock) {
         Either<PolicyDefinition, ResponseFormat> result = null;
         log.trace("#updatePolicy - starting to update the policy {} on the component {}. ", policy.getUniqueId(), componentId);
@@ -344,20 +326,20 @@ public class PolicyBusinessLogic extends BaseBusinessLogic {
         PolicyDefinition result = null;
         log.trace("#deletePolicy - starting to update the policy {} on the component {}. ", policyId, componentId);
         Component component = null;
-        boolean failed= false;
+        boolean failed = false;
         try {
             component = validateAndLockComponentAndUserBeforeWriteOperation(componentType, componentId, userId, shouldLock);
             return deletePolicy(component, policyId);
         } catch (ComponentException e) {
             failed = true;
-            log.error("#deletePolicy - the exception occurred upon update of a policy of the type {} for the component {}: ", policyId, componentId, e);
+            log.error("#deletePolicy - the exception occurred upon update of a policy of the type {} for the component {}: ", policyId, componentId,
+                e);
             throw e;
         } finally {
             unlockComponent(shouldLock, failed, component);
         }
     }
 
-
     /*public Either<PolicyDefinition, ResponseFormat> deletePolicy(ComponentTypeEnum componentType, String componentId, String policyId, String userId, boolean shouldLock) {
         Either<PolicyDefinition, ResponseFormat> result = null;
         log.trace("#deletePolicy - starting to update the policy {} on the component {}. ", policyId, componentId);
@@ -409,39 +391,35 @@ public class PolicyBusinessLogic extends BaseBusinessLogic {
             unlockComponent(shouldLock, result, component);
         }
     }*/
-
-    public Either<PolicyDefinition, ResponseFormat> undeclarePolicy(ComponentTypeEnum componentType, String componentId, String policyId, String userId, boolean shouldLock) {
+    public Either<PolicyDefinition, ResponseFormat> undeclarePolicy(ComponentTypeEnum componentType, String componentId, String policyId,
+                                                                    String userId, boolean shouldLock) {
         Either<PolicyDefinition, ResponseFormat> result = null;
         log.trace("#undeclarePolicy - starting to undeclare policy {} on component {}. ", policyId, componentId);
         Wrapper<Component> component = new Wrapper<>();
         try {
             validateAndLockComponentAndUserBeforeWriteOperation(componentType, componentId, userId, shouldLock);
-
             ComponentParametersView componentParametersView = new ComponentParametersView();
             componentParametersView.disableAll();
             componentParametersView.setIgnoreComponentInstances(false);
             componentParametersView.setIgnoreComponentInstancesProperties(false);
             componentParametersView.setIgnorePolicies(false);
-
-            Either<Component, StorageOperationStatus> componentWithFilters =
-                    toscaOperationFacade.getToscaElement(componentId, componentParametersView);
+            Either<Component, StorageOperationStatus> componentWithFilters = toscaOperationFacade
+                .getToscaElement(componentId, componentParametersView);
             if (componentWithFilters.isRight()) {
-                return Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(componentWithFilters.right().value())));
+                return Either
+                    .right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(componentWithFilters.right().value())));
             }
-
             Component containerComponent = componentWithFilters.left().value();
-
             Optional<PolicyDefinition> policyCandidate = getPolicyForUndeclaration(policyId, containerComponent);
-            if(policyCandidate.isPresent()) {
+            if (policyCandidate.isPresent()) {
                 result = undeclarePolicy(policyCandidate.get(), containerComponent);
             }
-
             return result;
-    }catch (Exception e) {
+        } catch (Exception e) {
             log.error("#undeclarePolicy - the exception occurred upon update of a policy of type {} for component {}: ", policyId, componentId, e);
             return Either.right(componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR, e.getMessage()));
         } finally {
-            if (result == null || result.isRight()){
+            if (result == null || result.isRight()) {
                 unlockComponent(shouldLock, true, component);
             } else {
                 unlockComponent(shouldLock, false, component);
@@ -449,56 +427,45 @@ public class PolicyBusinessLogic extends BaseBusinessLogic {
         }
     }
 
-        private Either<PolicyDefinition, ResponseFormat> undeclarePolicy(PolicyDefinition policyDefinition, Component containerComponent) {
-            StorageOperationStatus undeclareStatus = propertyDeclarationOrchestrator
-                    .unDeclarePropertiesAsPolicies(containerComponent, policyDefinition);
-            if(undeclareStatus != StorageOperationStatus.OK){
-                return Either.right(componentsUtils.getResponseFormat(undeclareStatus));
-            } else {
-                return Either.left(policyDefinition);
-            }
+    private Either<PolicyDefinition, ResponseFormat> undeclarePolicy(PolicyDefinition policyDefinition, Component containerComponent) {
+        StorageOperationStatus undeclareStatus = propertyDeclarationOrchestrator.unDeclarePropertiesAsPolicies(containerComponent, policyDefinition);
+        if (undeclareStatus != StorageOperationStatus.OK) {
+            return Either.right(componentsUtils.getResponseFormat(undeclareStatus));
+        } else {
+            return Either.left(policyDefinition);
         }
+    }
 
-
-        private Optional<PolicyDefinition> getPolicyForUndeclaration(String policyId, Component component) {
-            Map<String, PolicyDefinition> policies = component.getPolicies();
-            if(MapUtils.isNotEmpty(policies) && policies.containsKey(policyId)) {
-                return Optional.of(policies.get(policyId));
-            }
-
-            Map<String, List<ComponentInstanceProperty>> componentInstancesProperties =
-                    MapUtils.isEmpty(component.getComponentInstancesProperties()) ? new HashMap<>() : component.getComponentInstancesProperties();
-
-            for(Map.Entry<String, List<ComponentInstanceProperty>> instancePropertyEntry : componentInstancesProperties.entrySet()) {
-                Optional<ComponentInstanceProperty> propertyCandidate = getPropertyForDeclaredPolicy(policyId, instancePropertyEntry.getValue());
-
-                if(propertyCandidate.isPresent()) {
-                    return Optional.of(
-                            PolicyUtils.getDeclaredPolicyDefinition(instancePropertyEntry.getKey(), propertyCandidate.get()));
-                }
+    private Optional<PolicyDefinition> getPolicyForUndeclaration(String policyId, Component component) {
+        Map<String, PolicyDefinition> policies = component.getPolicies();
+        if (MapUtils.isNotEmpty(policies) && policies.containsKey(policyId)) {
+            return Optional.of(policies.get(policyId));
+        }
+        Map<String, List<ComponentInstanceProperty>> componentInstancesProperties =
+            MapUtils.isEmpty(component.getComponentInstancesProperties()) ? new HashMap<>() : component.getComponentInstancesProperties();
+        for (Map.Entry<String, List<ComponentInstanceProperty>> instancePropertyEntry : componentInstancesProperties.entrySet()) {
+            Optional<ComponentInstanceProperty> propertyCandidate = getPropertyForDeclaredPolicy(policyId, instancePropertyEntry.getValue());
+            if (propertyCandidate.isPresent()) {
+                return Optional.of(PolicyUtils.getDeclaredPolicyDefinition(instancePropertyEntry.getKey(), propertyCandidate.get()));
             }
-
-            return Optional.empty();
         }
+        return Optional.empty();
+    }
 
-        private Optional<ComponentInstanceProperty> getPropertyForDeclaredPolicy(String policyId, List<ComponentInstanceProperty> componentInstanceProperties) {
-            for(ComponentInstanceProperty property : componentInstanceProperties) {
-                Optional<GetPolicyValueDataDefinition> getPolicyCandidate = property.safeGetGetPolicyValues().stream()
-                        .filter(getPolicyValue -> getPolicyValue.getPolicyId()
-                                .equals(policyId))
-                        .findAny();
-
-                if(getPolicyCandidate.isPresent()) {
-                    return Optional.of(property);
-                }
+    private Optional<ComponentInstanceProperty> getPropertyForDeclaredPolicy(String policyId,
+                                                                             List<ComponentInstanceProperty> componentInstanceProperties) {
+        for (ComponentInstanceProperty property : componentInstanceProperties) {
+            Optional<GetPolicyValueDataDefinition> getPolicyCandidate = property.safeGetGetPolicyValues().stream()
+                .filter(getPolicyValue -> getPolicyValue.getPolicyId().equals(policyId)).findAny();
+            if (getPolicyCandidate.isPresent()) {
+                return Optional.of(property);
             }
-
-            return Optional.empty();
         }
+        return Optional.empty();
+    }
 
-
-        public PolicyDefinition updatePolicyTargets(ComponentTypeEnum componentTypeEnum, String componentId, String policyId, Map<PolicyTargetType, List<String>> targets, String userId) {
-
+    public PolicyDefinition updatePolicyTargets(ComponentTypeEnum componentTypeEnum, String componentId, String policyId,
+                                                Map<PolicyTargetType, List<String>> targets, String userId) {
         Either<PolicyDefinition, ResponseFormat> result = null;
         log.debug("updating the policy id {} targets with the components {}. ", policyId, componentId);
         boolean failed = false;
@@ -506,10 +473,10 @@ public class PolicyBusinessLogic extends BaseBusinessLogic {
             //not right error response
             Component component = validateAndLockComponentAndUserBeforeWriteOperation(componentTypeEnum, componentId, userId, true);
             return validateAndUpdatePolicyTargets(component, policyId, targets);
-        }catch (ComponentException e){
+        } catch (ComponentException e) {
             failed = true;
             throw e;
-        }finally {
+        } finally {
             unlockComponentById(failed, componentId);
         }
     }
@@ -528,7 +495,6 @@ public class PolicyBusinessLogic extends BaseBusinessLogic {
         return validateTargetExists(parentComponent, targets.entrySet());
     }
 
-
     private Component validateTargetExists(Component parentComponent, Set<Map.Entry<PolicyTargetType, List<String>>> entries) {
         for (Map.Entry<PolicyTargetType, List<String>> entry : entries) {
             checkTargetNotExistOnComponentByType(parentComponent, entry);
@@ -537,7 +503,6 @@ public class PolicyBusinessLogic extends BaseBusinessLogic {
     }
 
     private Component checkTargetNotExistOnComponentByType(Component parentComponent, Map.Entry<PolicyTargetType, List<String>> targetEntry) {
-
         for (String id : targetEntry.getValue()) {
             if (checkNotPresenceInComponentByType(parentComponent, id, targetEntry.getKey().getName())) {
                 throw new ByActionStatusComponentException(ActionStatus.POLICY_TARGET_DOES_NOT_EXIST, id);
@@ -560,7 +525,6 @@ public class PolicyBusinessLogic extends BaseBusinessLogic {
         return policyDefinition;
     }
 
-
     /**
      * @param componentType the type of the component
      * @param componentId   the id of the component which the policy resides under
@@ -577,7 +541,6 @@ public class PolicyBusinessLogic extends BaseBusinessLogic {
             janusGraphDao.commit();
         }
     }
-
     /*public Either<List<PropertyDataDefinition>, ResponseFormat> getPolicyProperties(ComponentTypeEnum componentType, String componentId, String policyId, String userId) {
         log.debug("#getPolicyProperties - fetching policy properties for component {} and policy {}", componentId, policyId);
         try {
@@ -600,7 +563,8 @@ public class PolicyBusinessLogic extends BaseBusinessLogic {
      * @param shouldLock    the flag defining if the component should be locked
      * @return a list of policy properties or anerrorin a response format
      */
-    public List<PropertyDataDefinition> updatePolicyProperties(ComponentTypeEnum componentType, String componentId, String policyId, PropertyDataDefinition[] properties, String userId, boolean shouldLock) {
+    public List<PropertyDataDefinition> updatePolicyProperties(ComponentTypeEnum componentType, String componentId, String policyId,
+                                                               PropertyDataDefinition[] properties, String userId, boolean shouldLock) {
         List<PropertyDataDefinition> result;
         Component component = null;
         log.trace("#updatePolicyProperties - starting to update properties of the policy {} on the component {}. ", policyId, componentId);
@@ -618,47 +582,39 @@ public class PolicyBusinessLogic extends BaseBusinessLogic {
     }
 
     @Override
-    public  Either<List<PolicyDefinition>, ResponseFormat> declareProperties(String userId, String componentId,
-            ComponentTypeEnum componentTypeEnum, ComponentInstInputsMap componentInstInputsMap) {
+    public Either<List<PolicyDefinition>, ResponseFormat> declareProperties(String userId, String componentId, ComponentTypeEnum componentTypeEnum,
+                                                                            ComponentInstInputsMap componentInstInputsMap) {
         return declarePropertiesToPolicies(userId, componentId, componentTypeEnum, componentInstInputsMap, true, false);
-
     }
 
     private Either<List<PolicyDefinition>, ResponseFormat> declarePropertiesToPolicies(String userId, String componentId,
-            ComponentTypeEnum componentTypeEnum, ComponentInstInputsMap componentInstInputsMap, boolean shouldLock,
-            boolean inTransaction) {
+                                                                                       ComponentTypeEnum componentTypeEnum,
+                                                                                       ComponentInstInputsMap componentInstInputsMap,
+                                                                                       boolean shouldLock, boolean inTransaction) {
         Either<List<PolicyDefinition>, ResponseFormat> result = null;
         org.openecomp.sdc.be.model.Component component = null;
-
         try {
             validateUserExists(userId);
-
             ComponentParametersView componentParametersView = new ComponentParametersView();
             componentParametersView.disableAll();
             componentParametersView.setIgnoreComponentInstances(false);
             componentParametersView.setIgnoreComponentInstancesProperties(false);
             componentParametersView.setIgnorePolicies(false);
             componentParametersView.setIgnoreUsers(false);
-
             component = validateComponentExists(componentId, componentTypeEnum, componentParametersView);
-
             if (shouldLock) {
                 lockComponent(component, DECLARE_PROPERTIES_TO_POLICIES);
             }
-
             validateCanWorkOnComponent(component, userId);
-
-            Either<List<PolicyDefinition>, StorageOperationStatus> declarePropertiesEither =
-                    propertyDeclarationOrchestrator.declarePropertiesToPolicies(component, componentInstInputsMap);
-
-            if(declarePropertiesEither.isRight()) {
+            Either<List<PolicyDefinition>, StorageOperationStatus> declarePropertiesEither = propertyDeclarationOrchestrator
+                .declarePropertiesToPolicies(component, componentInstInputsMap);
+            if (declarePropertiesEither.isRight()) {
                 return Either.right(componentsUtils.getResponseFormat(declarePropertiesEither.right().value()));
             }
-
             result = Either.left(declarePropertiesEither.left().value());
             return result;
         } finally {
-            if(!inTransaction) {
+            if (!inTransaction) {
                 commitOrRollback(result);
             }
             // unlock resource
@@ -668,9 +624,9 @@ public class PolicyBusinessLogic extends BaseBusinessLogic {
         }
     }
 
-    private List<PropertyDataDefinition> setComponentValidateUpdatePolicyProperties(String policyId, PropertyDataDefinition[] properties, Component component) {
+    private List<PropertyDataDefinition> setComponentValidateUpdatePolicyProperties(String policyId, PropertyDataDefinition[] properties,
+                                                                                    Component component) {
         Set<String> updatedPropertyNames = Arrays.stream(properties).map(PropertyDataDefinition::getName).collect(Collectors.toSet());
-
         PolicyDefinition policyDefinition = validateAndUpdatePolicyProperties(component, policyId, properties);
         return getFilteredProperties(policyDefinition.getProperties(), updatedPropertyNames);
     }
@@ -685,7 +641,6 @@ public class PolicyBusinessLogic extends BaseBusinessLogic {
         }
     }
 
-
     private void unlockComponent(boolean shouldLock, boolean result, Wrapper<Component> component) {
         if (shouldLock && !component.isEmpty()) {
             unlockComponent(result, component.getInnerElement());
@@ -710,11 +665,10 @@ public class PolicyBusinessLogic extends BaseBusinessLogic {
     /*private Either<PolicyDefinition, ResponseFormat> createPolicy(String policyTypeName, Component component) {
         return validatePolicyTypeOnCreatePolicy(policyTypeName, component).left().bind(type -> addPolicyToComponent(type, component));
     }*/
-
     private PolicyDefinition addPolicyToComponent(PolicyTypeDefinition policyType, Component component) {
-        Either<PolicyDefinition, StorageOperationStatus> associatePolicyToComponent =
-                toscaOperationFacade.associatePolicyToComponent(component.getUniqueId(), new PolicyDefinition(policyType), getNextPolicyCounter(component.getPolicies()));
-        if(associatePolicyToComponent.isRight()){
+        Either<PolicyDefinition, StorageOperationStatus> associatePolicyToComponent = toscaOperationFacade
+            .associatePolicyToComponent(component.getUniqueId(), new PolicyDefinition(policyType), getNextPolicyCounter(component.getPolicies()));
+        if (associatePolicyToComponent.isRight()) {
             throw new ByActionStatusComponentException(componentsUtils.convertFromStorageResponse(associatePolicyToComponent.right().value()));
         }
         return associatePolicyToComponent.left().value();
@@ -724,10 +678,9 @@ public class PolicyBusinessLogic extends BaseBusinessLogic {
         return toscaOperationFacade.associatePolicyToComponent(component.getUniqueId(), new PolicyDefinition(policyType), getNextPolicyCounter(component.getPolicies()))
                 .either(Either::left, r -> Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(r))));
     }*/
-
     private PolicyTypeDefinition validatePolicyTypeOnCreatePolicy(String policyTypeName, Component component) {
         Either<PolicyTypeDefinition, StorageOperationStatus> latestPolicyTypeByType = policyTypeOperation.getLatestPolicyTypeByType(policyTypeName);
-        if(latestPolicyTypeByType.isRight()){
+        if (latestPolicyTypeByType.isRight()) {
             throw new ByActionStatusComponentException(componentsUtils.convertFromStorageResponse(latestPolicyTypeByType.right().value()));
         }
         return validatePolicyTypeNotExcluded(latestPolicyTypeByType.left().value(), component);
@@ -737,19 +690,21 @@ public class PolicyBusinessLogic extends BaseBusinessLogic {
         return policyTypeOperation.getLatestPolicyTypeByType(policyTypeName)
                 .either(l -> validatePolicyTypeNotExcluded(l, component), r -> Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(r))));
     }*/
-
     private PolicyTypeDefinition validatePolicyTypeNotExcluded(PolicyTypeDefinition policyType, Component component) {
         if (getExcludedPolicyTypesByComponent(component).contains(policyType.getType())) {
-            throw new ByActionStatusComponentException(ActionStatus.EXCLUDED_POLICY_TYPE, policyType.getType(), getComponentOrResourceTypeName(component));
+            throw new ByActionStatusComponentException(ActionStatus.EXCLUDED_POLICY_TYPE, policyType.getType(),
+                getComponentOrResourceTypeName(component));
         }
         return policyType;
     }
 
     private String getComponentOrResourceTypeName(Component component) {
-        return component.getComponentType() == ComponentTypeEnum.SERVICE ? ComponentTypeEnum.SERVICE.name() : ((Resource) component).getResourceType().name();
+        return component.getComponentType() == ComponentTypeEnum.SERVICE ? ComponentTypeEnum.SERVICE.name()
+            : ((Resource) component).getResourceType().name();
     }
 
-    private Component validateAndLockComponentAndUserBeforeWriteOperation(ComponentTypeEnum componentType, String componentId, String userId, boolean shouldLock) {
+    private Component validateAndLockComponentAndUserBeforeWriteOperation(ComponentTypeEnum componentType, String componentId, String userId,
+                                                                          boolean shouldLock) {
         Component component = validateContainerComponentAndUserBeforeReadOperation(componentType, componentId, userId);
         validateComponentIsTopologyTemplate(component);
         validateCanWorkOnComponent(component, userId);
@@ -775,13 +730,12 @@ public class PolicyBusinessLogic extends BaseBusinessLogic {
                     return Either.right(r);
                 });
     }*/
-
     private Component validateComponentIsTopologyTemplate(Component component) {
         if (!component.isTopologyTemplate()) {
             log.error("#validateComponentIsTopologyTemplate - policy association to a component of Tosca type {} is not allowed. ",
-                    component.getToscaType());
+                component.getToscaType());
             throw new ByActionStatusComponentException(ActionStatus.RESOURCE_CANNOT_CONTAIN_POLICIES,
-                    "#validateAndLockComponentAndUserBeforeWriteOperation", component.getUniqueId(), component.getToscaType());
+                "#validateAndLockComponentAndUserBeforeWriteOperation", component.getUniqueId(), component.getToscaType());
         }
         return component;
     }
@@ -800,7 +754,6 @@ public class PolicyBusinessLogic extends BaseBusinessLogic {
     }
 
     private Component validateComponentExists(ComponentTypeEnum componentType, String componentId) {
-
         ComponentParametersView filter = new ComponentParametersView(true);
         filter.setIgnorePolicies(false);
         filter.setIgnoreUsers(false);
@@ -809,7 +762,6 @@ public class PolicyBusinessLogic extends BaseBusinessLogic {
         return validateComponentExists(componentId, componentType, filter);
     }
 
-
     private PolicyDefinition validateAndUpdatePolicy(Component component, PolicyDefinition policy) {
         PolicyDefinition policyById = getPolicyById(component, policy.getUniqueId());
         PolicyDefinition policyDefinition = validateUpdatePolicyBeforeUpdate(policy, policyById, component.getPolicies());
@@ -823,34 +775,33 @@ public class PolicyBusinessLogic extends BaseBusinessLogic {
                 .left()
                 .bind(p -> updatePolicyOfComponent(component, p));
     }*/
-
     private PolicyDefinition validateAndUpdatePolicyProperties(Component component, String policyId, PropertyDataDefinition[] properties) {
-
         PolicyDefinition policyById = getPolicyById(component, policyId);
         policyById = validateUpdatePolicyPropertiesBeforeUpdate(policyById, properties);
         return updatePolicyOfComponent(component.getUniqueId(), policyById);
     }
 
     private PolicyDefinition updatePolicyOfComponent(String componentId, PolicyDefinition policy) {
-        return toscaOperationFacade.updatePolicyOfComponent(componentId, policy, PromoteVersionEnum.MINOR)
-                .left()
-                .on(ce->componentExceptionPolicyDefinition(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(ce))));
+        return toscaOperationFacade.updatePolicyOfComponent(componentId, policy, PromoteVersionEnum.MINOR).left()
+            .on(ce -> componentExceptionPolicyDefinition(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(ce))));
     }
 
     private PolicyDefinition validateUpdatePolicyPropertiesBeforeUpdate(PolicyDefinition policy, PropertyDataDefinition[] newProperties) {
         if (CollectionUtils.isEmpty(policy.getProperties())) {
-            log.error("#validateUpdatePolicyPropertiesBeforeUpdate - failed to update properites of the policy. Properties were not found on the policy. ");
+            log.error(
+                "#validateUpdatePolicyPropertiesBeforeUpdate - failed to update properites of the policy. Properties were not found on the policy. ");
             throw new ByActionStatusComponentException(ActionStatus.PROPERTY_NOT_FOUND);
         }
         return updatePropertyValues(policy, newProperties);
     }
 
     private PolicyDefinition updatePropertyValues(PolicyDefinition policy, PropertyDataDefinition[] newProperties) {
-
-        Map<String, PropertyDataDefinition> oldProperties = policy.getProperties().stream().collect(toMap(PropertyDataDefinition::getName, Function.identity()));
+        Map<String, PropertyDataDefinition> oldProperties = policy.getProperties().stream()
+            .collect(toMap(PropertyDataDefinition::getName, Function.identity()));
         for (PropertyDataDefinition newProperty : newProperties) {
             if (!oldProperties.containsKey(newProperty.getName())) {
-                log.error("#updatePropertyValues - failed to update properites of the policy {}. Properties were not found on the policy. ", policy.getName());
+                log.error("#updatePropertyValues - failed to update properites of the policy {}. Properties were not found on the policy. ",
+                    policy.getName());
                 throw new ByActionStatusComponentException(ActionStatus.PROPERTY_NOT_FOUND, newProperty.getName());
             }
             String newPropertyValueEither = updateInputPropertyObjectValue(newProperty);
@@ -865,10 +816,11 @@ public class PolicyBusinessLogic extends BaseBusinessLogic {
     }
 
     private PolicyDefinition updatePolicyOfComponent(Component component, PolicyDefinition policy) {
-
-        Either<PolicyDefinition, StorageOperationStatus> updatePolicyRes = toscaOperationFacade.updatePolicyOfComponent(component.getUniqueId(), policy, PromoteVersionEnum.MINOR);
+        Either<PolicyDefinition, StorageOperationStatus> updatePolicyRes = toscaOperationFacade
+            .updatePolicyOfComponent(component.getUniqueId(), policy, PromoteVersionEnum.MINOR);
         if (updatePolicyRes.isRight()) {
-            log.error("#updatePolicyOfComponent - failed to update policy {} of the component {}. The status is {}. ", policy.getUniqueId(), component.getName(), updatePolicyRes.right().value());
+            log.error("#updatePolicyOfComponent - failed to update policy {} of the component {}. The status is {}. ", policy.getUniqueId(),
+                component.getName(), updatePolicyRes.right().value());
             throw new ByActionStatusComponentException(componentsUtils.convertFromStorageResponse(updatePolicyRes.right().value()));
         } else {
             log.trace("#updatePolicyOfComponent - the policy with the name {} was updated. ", updatePolicyRes.left().value().getName());
@@ -879,7 +831,8 @@ public class PolicyBusinessLogic extends BaseBusinessLogic {
     private PolicyDefinition removePolicyFromComponent(Component component, PolicyDefinition policy) {
         StorageOperationStatus updatePolicyStatus = toscaOperationFacade.removePolicyFromComponent(component.getUniqueId(), policy.getUniqueId());
         if (updatePolicyStatus != StorageOperationStatus.OK) {
-            log.error("#removePolicyFromComponent - failed to remove policy {} from the component {}. The status is {}. ", policy.getUniqueId(), component.getName(), updatePolicyStatus);
+            log.error("#removePolicyFromComponent - failed to remove policy {} from the component {}. The status is {}. ", policy.getUniqueId(),
+                component.getName(), updatePolicyStatus);
             throw new ByActionStatusComponentException(componentsUtils.convertFromStorageResponse(updatePolicyStatus));
         } else {
             log.trace("#removePolicyFromComponent - the policy with the name {} was deleted. ", updatePolicyStatus);
@@ -887,10 +840,11 @@ public class PolicyBusinessLogic extends BaseBusinessLogic {
         }
     }
 
-    private PolicyDefinition validateUpdatePolicyBeforeUpdate(PolicyDefinition recievedPolicy, PolicyDefinition oldPolicy, Map<String, PolicyDefinition> policies) {
-
-        Either<PolicyDefinition, ActionStatus> policyDefinitionActionStatusEither = validatePolicyFields(recievedPolicy, new PolicyDefinition(oldPolicy), policies);
-        if(policyDefinitionActionStatusEither.isRight()){
+    private PolicyDefinition validateUpdatePolicyBeforeUpdate(PolicyDefinition recievedPolicy, PolicyDefinition oldPolicy,
+                                                              Map<String, PolicyDefinition> policies) {
+        Either<PolicyDefinition, ActionStatus> policyDefinitionActionStatusEither = validatePolicyFields(recievedPolicy,
+            new PolicyDefinition(oldPolicy), policies);
+        if (policyDefinitionActionStatusEither.isRight()) {
             throw new ByActionStatusComponentException(policyDefinitionActionStatusEither.right().value(), recievedPolicy.getName());
         }
         return policyDefinitionActionStatusEither.left().value();
@@ -901,13 +855,12 @@ public class PolicyBusinessLogic extends BaseBusinessLogic {
                 .right()
                 .bind(r -> Either.right(componentsUtils.getResponseFormat(r, recievedPolicy.getName())));
     }*/
-
-    private PolicyDefinition updateTargets(String componentId, PolicyDefinition policy, Map<PolicyTargetType, List<String>> targets, String policyId) {
+    private PolicyDefinition updateTargets(String componentId, PolicyDefinition policy, Map<PolicyTargetType, List<String>> targets,
+                                           String policyId) {
         if (policy == null) {
             throw new ByActionStatusComponentException(ActionStatus.POLICY_NOT_FOUND_ON_CONTAINER, policyId, componentId);
         }
         PolicyDefinition updatedPolicy = setPolicyTargets(policy, targets);
         return updatePolicyOfComponent(componentId, updatedPolicy);
     }
-
 }
index b8541f1..6070b9a 100644 (file)
@@ -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.
  * limitations under the License.
  * ============LICENSE_END=========================================================
  */
-
 package org.openecomp.sdc.be.components.impl;
 
+import static java.util.Collections.emptySet;
+
+import java.util.List;
+import java.util.Map;
+import java.util.Set;
 import org.apache.commons.lang.StringUtils;
 import org.openecomp.sdc.be.components.impl.exceptions.ByActionStatusComponentException;
 import org.openecomp.sdc.be.components.validation.UserValidations;
@@ -33,12 +37,6 @@ import org.openecomp.sdc.be.model.operations.impl.PolicyTypeOperation;
 import org.springframework.stereotype.Component;
 import org.springframework.transaction.annotation.Transactional;
 
-import java.util.List;
-import java.util.Map;
-import java.util.Set;
-
-import static java.util.Collections.emptySet;
-
 @Component
 public class PolicyTypeBusinessLogic {
 
@@ -47,7 +45,8 @@ public class PolicyTypeBusinessLogic {
     private ComponentsUtils componentsUtils;
     private UserValidations userValidations;
 
-    public PolicyTypeBusinessLogic(PolicyTypeOperation policyTypeOperation, JanusGraphDao janusGraphDao, ComponentsUtils componentsUtils, UserValidations userValidations) {
+    public PolicyTypeBusinessLogic(PolicyTypeOperation policyTypeOperation, JanusGraphDao janusGraphDao, ComponentsUtils componentsUtils,
+                                   UserValidations userValidations) {
         this.policyTypeOperation = policyTypeOperation;
         this.janusGraphDao = janusGraphDao;
         this.componentsUtils = componentsUtils;
@@ -62,16 +61,15 @@ public class PolicyTypeBusinessLogic {
     }
 
     public PolicyTypeDefinition getLatestPolicyTypeByType(String policyTypeName) {
-        return policyTypeOperation.getLatestPolicyTypeByType(policyTypeName)
-                       .left()
-                       .on(e -> failOnPolicyType(e, policyTypeName));
+        return policyTypeOperation.getLatestPolicyTypeByType(policyTypeName).left().on(e -> failOnPolicyType(e, policyTypeName));
     }
 
     public Set<String> getExcludedPolicyTypes(String internalComponentType) {
         if (StringUtils.isEmpty(internalComponentType)) {
             return emptySet();
         }
-        Map<String, Set<String>> excludedPolicyTypesMapping = ConfigurationManager.getConfigurationManager().getConfiguration().getExcludedPolicyTypesMapping();
+        Map<String, Set<String>> excludedPolicyTypesMapping = ConfigurationManager.getConfigurationManager().getConfiguration()
+            .getExcludedPolicyTypesMapping();
         Set<String> excludedTypes = excludedPolicyTypesMapping.get(internalComponentType);
         return excludedTypes == null ? emptySet() : excludedTypes;
     }
index 377feb4..2b9f58c 100644 (file)
@@ -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.
  * limitations under the License.
  * ============LICENSE_END=========================================================
  */
-
 package org.openecomp.sdc.be.components.impl;
 
 import fj.data.Either;
+import java.util.List;
+import java.util.Map;
+import java.util.function.Consumer;
 import org.apache.commons.lang3.tuple.ImmutablePair;
 import org.openecomp.sdc.be.components.impl.CommonImportManager.ElementTypeEnum;
 import org.openecomp.sdc.be.components.impl.model.ToscaTypeImportData;
@@ -38,10 +40,6 @@ import org.openecomp.sdc.be.utils.TypeUtils;
 import org.openecomp.sdc.exception.ResponseFormat;
 import org.springframework.stereotype.Component;
 
-import java.util.List;
-import java.util.Map;
-import java.util.function.Consumer;
-
 @Component("policyTypeImportManager")
 public class PolicyTypeImportManager {
 
@@ -52,9 +50,9 @@ public class PolicyTypeImportManager {
     private final CommonImportManager commonImportManager;
     private final GroupTypeOperation groupTypeOperation;
 
-    public PolicyTypeImportManager(IPolicyTypeOperation policyTypeOperation, ComponentsUtils componentsUtils,
-                                   GroupOperation groupOperation, ToscaOperationFacade toscaOperationFacade,
-                                   CommonImportManager commonImportManager, GroupTypeOperation groupTypeOperation) {
+    public PolicyTypeImportManager(IPolicyTypeOperation policyTypeOperation, ComponentsUtils componentsUtils, GroupOperation groupOperation,
+                                   ToscaOperationFacade toscaOperationFacade, CommonImportManager commonImportManager,
+                                   GroupTypeOperation groupTypeOperation) {
         this.policyTypeOperation = policyTypeOperation;
         this.componentsUtils = componentsUtils;
         this.groupOperation = groupOperation;
@@ -71,12 +69,15 @@ public class PolicyTypeImportManager {
         return commonImportManager.createElementTypesFromYml(policyTypesYml, this::createPolicyType);
     }
 
-    private Either<List<ImmutablePair<PolicyTypeDefinition, Boolean>>, ResponseFormat> upsertPolicyTypesByDao(List<PolicyTypeDefinition> policyTypesToCreate) {
-        return commonImportManager.createElementTypesByDao(policyTypesToCreate, this::validatePolicyType, policyType -> new ImmutablePair<>(ElementTypeEnum.POLICY_TYPE, policyType.getType()),
-                policyTypeOperation::getLatestPolicyTypeByType, policyTypeOperation::addPolicyType, this::updatePolicyType);
+    private Either<List<ImmutablePair<PolicyTypeDefinition, Boolean>>, ResponseFormat> upsertPolicyTypesByDao(
+        List<PolicyTypeDefinition> policyTypesToCreate) {
+        return commonImportManager.createElementTypesByDao(policyTypesToCreate, this::validatePolicyType,
+            policyType -> new ImmutablePair<>(ElementTypeEnum.POLICY_TYPE, policyType.getType()), policyTypeOperation::getLatestPolicyTypeByType,
+            policyTypeOperation::addPolicyType, this::updatePolicyType);
     }
 
-    private Either<PolicyTypeDefinition, StorageOperationStatus> updatePolicyType(PolicyTypeDefinition newPolicyType, PolicyTypeDefinition oldPolicyType) {
+    private Either<PolicyTypeDefinition, StorageOperationStatus> updatePolicyType(PolicyTypeDefinition newPolicyType,
+                                                                                  PolicyTypeDefinition oldPolicyType) {
         if (PolicyTypeImportUtils.isPolicyTypesEquals(newPolicyType, oldPolicyType)) {
             return policyTypeAlreadyExists();
         }
@@ -96,35 +97,29 @@ public class PolicyTypeImportManager {
             }
             if (result.isLeft()) {
                 for (String targetId : policyType.getTargets()) {
-                        boolean isValid = toscaOperationFacade.getLatestByToscaResourceName(targetId).isLeft();
-
-                        if (!isValid) { // check if it is a groupType
-                            final Either<GroupTypeDefinition, StorageOperationStatus> groupTypeFound = groupTypeOperation
-                                .getLatestGroupTypeByType(targetId, false);
-                            isValid = groupTypeFound.isLeft() && !groupTypeFound.left().value().isEmpty();
-                        }
-
-                        if (!isValid) {
-                            isValid = groupOperation.isGroupExist(targetId, false);
-                        }
-
-                        if (!isValid) {
-                            ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.TARGETS_NON_VALID, policyType.getType(), targetId);
-                            result = Either.right(responseFormat);
-                            break;
-                        }
+                    boolean isValid = toscaOperationFacade.getLatestByToscaResourceName(targetId).isLeft();
+                    if (!isValid) { // check if it is a groupType
+                        final Either<GroupTypeDefinition, StorageOperationStatus> groupTypeFound = groupTypeOperation
+                            .getLatestGroupTypeByType(targetId, false);
+                        isValid = groupTypeFound.isLeft() && !groupTypeFound.left().value().isEmpty();
+                    }
+                    if (!isValid) {
+                        isValid = groupOperation.isGroupExist(targetId, false);
+                    }
+                    if (!isValid) {
+                        ResponseFormat responseFormat = componentsUtils
+                            .getResponseFormat(ActionStatus.TARGETS_NON_VALID, policyType.getType(), targetId);
+                        result = Either.right(responseFormat);
+                        break;
                     }
                 }
             }
-
-
+        }
         return result;
     }
 
     private PolicyTypeDefinition createPolicyType(String groupTypeName, Map<String, Object> toscaJson) {
-
         PolicyTypeDefinition policyType = new PolicyTypeDefinition();
-
         if (toscaJson != null) {
             // Description
             final Consumer<String> descriptionSetter = policyType::setDescription;
@@ -138,16 +133,12 @@ public class PolicyTypeImportManager {
             final Consumer<Map<String, String>> metadataSetter = policyType::setMetadata;
             commonImportManager.setField(toscaJson, TypeUtils.ToscaTagNamesEnum.METADATA.getElementName(), metadataSetter);
             // Targets
-            final Consumer <List<String>> targetsSetter = policyType::setTargets;
+            final Consumer<List<String>> targetsSetter = policyType::setTargets;
             commonImportManager.setField(toscaJson, TypeUtils.ToscaTagNamesEnum.TARGETS.getElementName(), targetsSetter);
-
             policyType.setType(groupTypeName);
-
             policyType.setHighestVersion(true);
-
             policyType.setVersion(TypeUtils.getFirstCertifiedVersionVersion());
         }
         return policyType;
     }
-
 }
index c643d9f..aca2536 100644 (file)
@@ -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.
  * Modifications copyright (c) 2019 Nokia
  * ================================================================================
  */
-
 package org.openecomp.sdc.be.components.impl;
 
 import fj.data.Either;
+import java.util.ArrayList;
+import java.util.HashMap;
+import java.util.HashSet;
+import java.util.List;
+import java.util.Map;
+import java.util.Set;
+import java.util.stream.Collectors;
 import org.openecomp.sdc.be.components.impl.exceptions.ByActionStatusComponentException;
 import org.openecomp.sdc.be.components.impl.exceptions.ComponentException;
 import org.openecomp.sdc.be.components.validation.component.ComponentContactIdValidator;
@@ -61,14 +67,6 @@ import org.openecomp.sdc.common.util.ValidationUtils;
 import org.openecomp.sdc.exception.ResponseFormat;
 import org.springframework.beans.factory.annotation.Autowired;
 
-import java.util.ArrayList;
-import java.util.HashMap;
-import java.util.HashSet;
-import java.util.List;
-import java.util.Map;
-import java.util.Set;
-import java.util.stream.Collectors;
-
 @org.springframework.stereotype.Component("productBusinessLogic")
 public class ProductBusinessLogic extends ComponentBusinessLogic {
 
@@ -80,37 +78,24 @@ public class ProductBusinessLogic extends ComponentBusinessLogic {
     private static List<Role> creationRoles;
     private static List<Role> updateRoles;
     private static List<Role> contactsRoles;
-
     private final ComponentInstanceBusinessLogic componentInstanceBusinessLogic;
 
     @Autowired
-    public ProductBusinessLogic(IElementOperation elementDao,
-        IGroupOperation groupOperation,
-        IGroupInstanceOperation groupInstanceOperation,
-        IGroupTypeOperation groupTypeOperation,
-        GroupBusinessLogic groupBusinessLogic,
-        InterfaceOperation interfaceOperation,
-        InterfaceLifecycleOperation interfaceLifecycleTypeOperation,
-        ArtifactsBusinessLogic artifactsBusinessLogic,
-        ComponentInstanceBusinessLogic componentInstanceBusinessLogic,
-        ArtifactsOperations artifactToscaOperation,
-        ComponentContactIdValidator componentContactIdValidator,
-        ComponentNameValidator componentNameValidator,
-        ComponentTagsValidator componentTagsValidator,
-        ComponentValidator componentValidator,
-        ComponentIconValidator componentIconValidator,
-        ComponentProjectCodeValidator componentProjectCodeValidator,
-        ComponentDescriptionValidator componentDescriptionValidator){
-        super(elementDao, groupOperation, groupInstanceOperation, groupTypeOperation, groupBusinessLogic,
-            interfaceOperation, interfaceLifecycleTypeOperation, artifactsBusinessLogic, artifactToscaOperation,
-                componentContactIdValidator, componentNameValidator, componentTagsValidator, componentValidator,
-                componentIconValidator, componentProjectCodeValidator, componentDescriptionValidator);
+    public ProductBusinessLogic(IElementOperation elementDao, IGroupOperation groupOperation, IGroupInstanceOperation groupInstanceOperation,
+                                IGroupTypeOperation groupTypeOperation, GroupBusinessLogic groupBusinessLogic, InterfaceOperation interfaceOperation,
+                                InterfaceLifecycleOperation interfaceLifecycleTypeOperation, ArtifactsBusinessLogic artifactsBusinessLogic,
+                                ComponentInstanceBusinessLogic componentInstanceBusinessLogic, ArtifactsOperations artifactToscaOperation,
+                                ComponentContactIdValidator componentContactIdValidator, ComponentNameValidator componentNameValidator,
+                                ComponentTagsValidator componentTagsValidator, ComponentValidator componentValidator,
+                                ComponentIconValidator componentIconValidator, ComponentProjectCodeValidator componentProjectCodeValidator,
+                                ComponentDescriptionValidator componentDescriptionValidator) {
+        super(elementDao, groupOperation, groupInstanceOperation, groupTypeOperation, groupBusinessLogic, interfaceOperation,
+            interfaceLifecycleTypeOperation, artifactsBusinessLogic, artifactToscaOperation, componentContactIdValidator, componentNameValidator,
+            componentTagsValidator, componentValidator, componentIconValidator, componentProjectCodeValidator, componentDescriptionValidator);
         this.componentInstanceBusinessLogic = componentInstanceBusinessLogic;
-
         creationRoles = new ArrayList<>();
         updateRoles = new ArrayList<>();
         contactsRoles = new ArrayList<>();
-
         // only PM is allowed to create/update products
         creationRoles.add(Role.PRODUCT_MANAGER);
         updateRoles.add(Role.PRODUCT_MANAGER);
@@ -121,61 +106,49 @@ public class ProductBusinessLogic extends ComponentBusinessLogic {
     public Either<Product, ResponseFormat> createProduct(Product product, User user) {
         AuditingActionEnum actionEnum = AuditingActionEnum.CREATE_RESOURCE;
         ComponentTypeEnum typeEnum = ComponentTypeEnum.PRODUCT;
-
         // validate user - should be first to get the maximum auditing info in
+
         // case of subsequent failures
         log.debug("get user from DB");
         user = validateUser(user, CREATE_PRODUCT, product, actionEnum, false);
         // validate user role
         validateUserRole(user, product, creationRoles, actionEnum, null);
-
         if (product == null) {
             log.debug("Invalid product json. Check product servlet log for createProduct entry params");
             ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.INVALID_CONTENT);
             componentsUtils.auditComponentAdmin(responseFormat, user, product, actionEnum, typeEnum);
             return Either.right(responseFormat);
         }
-
         // warn about non-updatable fields
         checkUnupdatableProductFields(product);
-
         Either<Product, ResponseFormat> validateProductResponse = validateProductBeforeCreate(product, user, actionEnum);
         if (validateProductResponse.isRight()) {
             return Either.right(validateProductResponse.right().value());
         }
-
         log.debug("send product {} to dao for create", product.getComponentMetadataDefinition().getMetadataDataDefinition().getName());
-
         Either<Boolean, ResponseFormat> lockResult = lockComponentByName(product.getSystemName(), product, CREATE_PRODUCT);
         if (lockResult.isRight()) {
             ResponseFormat responseFormat = lockResult.right().value();
             componentsUtils.auditComponentAdmin(responseFormat, user, product, actionEnum, ComponentTypeEnum.PRODUCT);
             return Either.right(responseFormat);
         }
-
         log.debug("Product name locked is {}, status = {}", product.getSystemName(), lockResult);
-
         try {
             Either<Product, StorageOperationStatus> createProductEither = toscaOperationFacade.createToscaComponent(product);
-
             if (createProductEither.isRight()) {
-                ResponseFormat responseFormat = componentsUtils.getResponseFormatByComponent(componentsUtils.convertFromStorageResponse(createProductEither.right().value()), product, typeEnum);
+                ResponseFormat responseFormat = componentsUtils
+                    .getResponseFormatByComponent(componentsUtils.convertFromStorageResponse(createProductEither.right().value()), product, typeEnum);
                 componentsUtils.auditComponentAdmin(responseFormat, user, product, actionEnum, typeEnum);
                 return Either.right(responseFormat);
             }
-
             log.debug("Product created successfully");
             ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.CREATED);
             componentsUtils.auditComponentAdmin(responseFormat, user, product, actionEnum, typeEnum);
-
             Product createdProduct = createProductEither.left().value();
-
             return Either.left(createdProduct);
-
         } finally {
             graphLockOperation.unlockComponentByName(product.getSystemName(), product.getUniqueId(), NodeTypeEnum.Product);
         }
-
     }
 
     private void checkUnupdatableProductFields(Product product) {
@@ -186,60 +159,53 @@ public class ProductBusinessLogic extends ComponentBusinessLogic {
     }
 
     private Either<Product, ResponseFormat> validateProductBeforeCreate(Product product, User user, AuditingActionEnum actionEnum) {
-
         Either<Boolean, ResponseFormat> validateProductFields = validateProductFieldsBeforeCreate(user, product, actionEnum);
         if (validateProductFields.isRight()) {
             return Either.right(validateProductFields.right().value());
         }
-
         if (product.getIsActive() == null) {
             log.debug("no isActive value was provided, setting to default: false");
             product.setIsActive(false);
         }
-
         product.setCreatorUserId(user.getUserId());
-
         // enrich object
         log.debug("enrich product with version and state");
         product.setState(LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT);
         product.setVersion(INITIAL_VERSION);
-
         // Generate invariant UUID - must be here and not in operation since it
+
         // should stay constant during clone
         String invariantUUID = UniqueIdBuilder.buildInvariantUUID();
         product.setInvariantUUID(invariantUUID);
-
         return Either.left(product);
     }
 
     private Either<Boolean, ResponseFormat> validateProductFieldsBeforeCreate(User user, Product product, AuditingActionEnum actionEnum) {
-
         // To be removed in 1607
+
         // See below
         String oldName = product.getName();
-
         Either<Boolean, ResponseFormat> componentNameValidation = validateProductNameAndCleanup(user, product, actionEnum);
         if (componentNameValidation.isRight()) {
             return componentNameValidation;
         }
-
         try {
             componentNameValidator.validateComponentNameUnique(user, product, actionEnum);
         } catch (ComponentException exp) {
             return Either.right(exp.getResponseFormat());
         }
-
         // To be removed in 1607 and replaced with generic
+
         // validateTagsListAndRemoveDuplicates()
+
         // See comments on the validateTagsListAndRemoveDuplicates(user,
+
         // product, oldName, actionEnum) function
         Either<Boolean, ResponseFormat> tagsValidation = validateTagsListAndRemoveDuplicates(user, product, oldName, actionEnum);
         if (tagsValidation.isRight()) {
             return tagsValidation;
         }
-
         componentTagsValidator.validateAndCorrectField(user, product, actionEnum);
-
         try {
             componentProjectCodeValidator.validateAndCorrectField(user, product, actionEnum);
         } catch (ComponentException exp) {
@@ -249,38 +215,32 @@ public class ProductBusinessLogic extends ComponentBusinessLogic {
         if (categoryValidation.isRight()) {
             return categoryValidation;
         }
-
         Either<Boolean, ResponseFormat> contactsListValidation = validateAndUpdateProductContactsList(user, product, actionEnum);
         if (contactsListValidation.isRight()) {
             return contactsListValidation;
         }
-
         Either<Boolean, ResponseFormat> productFullNameValidation = validateProductFullNameAndCleanup(user, product, actionEnum);
         if (productFullNameValidation.isRight()) {
             return productFullNameValidation;
         }
-
         componentDescriptionValidator.validateAndCorrectField(user, product, actionEnum);
-
         return Either.left(true);
     }
 
     public Either<Map<String, Boolean>, ResponseFormat> validateProductNameExists(String productName, String userId) {
-
         validateUserExists(userId);
-        Either<Boolean, StorageOperationStatus> dataModelResponse = toscaOperationFacade.validateComponentNameUniqueness(productName, null, ComponentTypeEnum.PRODUCT);
+        Either<Boolean, StorageOperationStatus> dataModelResponse = toscaOperationFacade
+            .validateComponentNameUniqueness(productName, null, ComponentTypeEnum.PRODUCT);
         // DE242223
         janusGraphDao.commit();
-
         if (dataModelResponse.isLeft()) {
             Map<String, Boolean> result = new HashMap<>();
             result.put("isValid", dataModelResponse.left().value());
             log.debug("validation was successfully performed.");
             return Either.left(result);
         }
-
-        ResponseFormat responseFormat = componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(dataModelResponse.right().value()));
-
+        ResponseFormat responseFormat = componentsUtils
+            .getResponseFormat(componentsUtils.convertFromStorageResponse(dataModelResponse.right().value()));
         return Either.right(responseFormat);
     }
 
@@ -292,7 +252,6 @@ public class ProductBusinessLogic extends ComponentBusinessLogic {
             componentsUtils.auditComponentAdmin(responseFormat, user, product, actionEnum, ComponentTypeEnum.PRODUCT);
             return Either.right(responseFormat);
         }
-
         boolean isProductCreatorInContacts = false;
         String modifierUserId = user.getUserId();
         for (String contact : contacts) {
@@ -304,35 +263,30 @@ public class ProductBusinessLogic extends ComponentBusinessLogic {
             }
             if (!ValidationUtils.validateContactId(contact)) {
                 log.debug("Product contacts has invalid userId {} for product {}", contact, product.getName());
-                ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.COMPONENT_INVALID_CONTACT, ComponentTypeEnum.PRODUCT.getValue());
+                ResponseFormat responseFormat = componentsUtils
+                    .getResponseFormat(ActionStatus.COMPONENT_INVALID_CONTACT, ComponentTypeEnum.PRODUCT.getValue());
                 componentsUtils.auditComponentAdmin(responseFormat, user, product, actionEnum, ComponentTypeEnum.PRODUCT);
                 return Either.right(responseFormat);
             }
-
             User contactUser;
-            try{
+            try {
                 contactUser = validateUserExists(contact);
                 validateUserRole(contactUser, contactsRoles);
-            } catch(ByActionStatusComponentException e){
+            } catch (ByActionStatusComponentException e) {
                 log.debug("Cannot set contact with userId {} as product contact, error: {}", contact, e.getActionStatus());
                 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.INVALID_PRODUCT_CONTACT, contact);
                 componentsUtils.auditComponentAdmin(responseFormat, user, product, actionEnum, ComponentTypeEnum.PRODUCT);
                 throw new ByActionStatusComponentException(e.getActionStatus(), e.getParams());
             }
         }
-
         if (!isProductCreatorInContacts) {
             log.debug("modifier userId {} not found in product contacts - adding it", modifierUserId);
             contacts.add(modifierUserId);
         }
-
         // passed - setting all contacts userIds to lowercase
-        List<String> tempContacts = contacts.stream()
-                .map(String::toLowerCase)
-                .collect(Collectors.toList());
+        List<String> tempContacts = contacts.stream().map(String::toLowerCase).collect(Collectors.toList());
         ValidationUtils.removeDuplicateFromList(tempContacts);
         product.setContacts(tempContacts);
-
         return Either.left(true);
     }
 
@@ -349,7 +303,8 @@ public class ProductBusinessLogic extends ComponentBusinessLogic {
             if (!ValidationUtils.validateStringNotEmpty(catName)) {
                 // error missing cat name
                 log.debug("Missing category name for product: {}", product.getName());
-                ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.COMPONENT_MISSING_CATEGORY, ComponentTypeEnum.PRODUCT.getValue());
+                ResponseFormat responseFormat = componentsUtils
+                    .getResponseFormat(ActionStatus.COMPONENT_MISSING_CATEGORY, ComponentTypeEnum.PRODUCT.getValue());
                 componentsUtils.auditComponentAdmin(responseFormat, user, product, actionEnum, ComponentTypeEnum.PRODUCT);
                 return Either.right(responseFormat);
             }
@@ -372,7 +327,7 @@ public class ProductBusinessLogic extends ComponentBusinessLogic {
                     // error missing sub cat name for cat
                     log.debug("Missing or empty sub-category for category {} in product {}", catName, product.getName());
                     ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.COMPONENT_MISSING_SUBCATEGORY);
-                    componentsUtils.auditComponentAdmin(responseFormat, user, product,  actionEnum, ComponentTypeEnum.PRODUCT);
+                    componentsUtils.auditComponentAdmin(responseFormat, user, product, actionEnum, ComponentTypeEnum.PRODUCT);
                     return Either.right(responseFormat);
                 }
                 Set<String> subcatEntry = catEntry.get(subCatName);
@@ -385,7 +340,8 @@ public class ProductBusinessLogic extends ComponentBusinessLogic {
                     String groupName = group.getName();
                     if (!ValidationUtils.validateStringNotEmpty(groupName)) {
                         // error missing grouping for sub cat name and cat
-                        log.debug("Missing or empty groupng name for sub-category: {} for categor: {} in product: {}", subCatName, catName, product.getName());
+                        log.debug("Missing or empty groupng name for sub-category: {} for categor: {} in product: {}", subCatName, catName,
+                            product.getName());
                         ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.COMPONENT_MISSING_SUBCATEGORY);
                         componentsUtils.auditComponentAdmin(responseFormat, user, product, actionEnum, ComponentTypeEnum.PRODUCT);
                         return Either.right(responseFormat);
@@ -398,9 +354,9 @@ public class ProductBusinessLogic extends ComponentBusinessLogic {
                 }
             }
         } // for end of checking duplicated
-            // validate existence
-        Either<List<CategoryDefinition>, ActionStatus> allProductCategories = elementDao.getAllProductCategories();
 
+        // validate existence
+        Either<List<CategoryDefinition>, ActionStatus> allProductCategories = elementDao.getAllProductCategories();
         if (allProductCategories.isRight()) {
             log.debug("No product categories {}", allProductCategories.right().value());
             ResponseFormat responseFormat = componentsUtils.getResponseFormat(allProductCategories.right().value());
@@ -409,9 +365,9 @@ public class ProductBusinessLogic extends ComponentBusinessLogic {
         }
         boolean catExist;
         // convert non-duplicated to data modeling format and update in the
+
         // input object
         List<CategoryDefinition> newCatList = new ArrayList<>();
-
         // over all categories from request
         for (Map.Entry<String, Map<String, Set<String>>> entry : nonDuplicatedCategories.entrySet()) {
             catExist = false;
@@ -426,7 +382,6 @@ public class ProductBusinessLogic extends ComponentBusinessLogic {
                         // copy data
                         categoryDefinition = new CategoryDefinition(catInDb);
                         SubCategoryDefinition subCategory = null;
-
                         Map<String, Set<String>> subcats = entry.getValue();
                         for (Map.Entry<String, Set<String>> subcat : subcats.entrySet()) {
                             subcatExist = false;
@@ -453,9 +408,13 @@ public class ProductBusinessLogic extends ComponentBusinessLogic {
                                             }
                                             if (!groupExist) {
                                                 // error grouping isn't defined
+
                                                 // in JanusGraph
-                                                ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.INVALID_GROUP_ASSOCIATION, CategoryTypeEnum.GROUPING.getValue(), group);
-                                                componentsUtils.auditComponentAdmin(responseFormat, user, product, actionEnum, ComponentTypeEnum.PRODUCT);
+                                                ResponseFormat responseFormat = componentsUtils
+                                                    .getResponseFormat(ActionStatus.INVALID_GROUP_ASSOCIATION, CategoryTypeEnum.GROUPING.getValue(),
+                                                        group);
+                                                componentsUtils
+                                                    .auditComponentAdmin(responseFormat, user, product, actionEnum, ComponentTypeEnum.PRODUCT);
                                                 return Either.right(responseFormat);
                                             }
                                             subCategory.addGrouping(groupingDefinition);
@@ -465,7 +424,9 @@ public class ProductBusinessLogic extends ComponentBusinessLogic {
                             }
                             if (!subcatExist) {
                                 // error sub category isn't defined in JanusGraph
-                                ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.INVALID_GROUP_ASSOCIATION, CategoryTypeEnum.SUBCATEGORY.getValue(), subcat.getKey());
+                                ResponseFormat responseFormat = componentsUtils
+                                    .getResponseFormat(ActionStatus.INVALID_GROUP_ASSOCIATION, CategoryTypeEnum.SUBCATEGORY.getValue(),
+                                        subcat.getKey());
                                 componentsUtils.auditComponentAdmin(responseFormat, user, product, actionEnum, ComponentTypeEnum.PRODUCT);
                                 return Either.right(responseFormat);
                             }
@@ -476,7 +437,8 @@ public class ProductBusinessLogic extends ComponentBusinessLogic {
             }
             if (!catExist) {
                 // error category isn't defined in JanusGraph
-                ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.INVALID_GROUP_ASSOCIATION, CategoryTypeEnum.CATEGORY.getValue(), entry.getKey());
+                ResponseFormat responseFormat = componentsUtils
+                    .getResponseFormat(ActionStatus.INVALID_GROUP_ASSOCIATION, CategoryTypeEnum.CATEGORY.getValue(), entry.getKey());
                 componentsUtils.auditComponentAdmin(responseFormat, user, product, actionEnum, ComponentTypeEnum.PRODUCT);
                 return Either.right(responseFormat);
             }
@@ -490,16 +452,15 @@ public class ProductBusinessLogic extends ComponentBusinessLogic {
         String ecompErrorContext = "Get product";
         validateUserNotEmpty(user, ecompErrorContext);
         validateUserExists(user);
-
         Either<Product, StorageOperationStatus> storageStatus = toscaOperationFacade.getToscaElement(productId);
-
         if (storageStatus.isRight()) {
             log.debug("failed to get resource by id {}", productId);
             if (storageStatus.right().value() == StorageOperationStatus.NOT_FOUND) {
                 // TODO check error
                 return Either.right(componentsUtils.getResponseFormat(ActionStatus.PRODUCT_NOT_FOUND, ComponentTypeEnum.PRODUCT.getValue()));
             } else {
-                return Either.right(componentsUtils.getResponseFormatByResource(componentsUtils.convertFromStorageResponse(storageStatus.right().value()), ""));
+                return Either.right(
+                    componentsUtils.getResponseFormatByResource(componentsUtils.convertFromStorageResponse(storageStatus.right().value()), ""));
             }
         }
         return Either.left(storageStatus.left().value());
@@ -509,12 +470,11 @@ public class ProductBusinessLogic extends ComponentBusinessLogic {
         String ecompErrorContext = "Delete product";
         validateUserNotEmpty(user, ecompErrorContext);
         validateUserExists(user);
-
         Either<Product, StorageOperationStatus> storageStatus = toscaOperationFacade.deleteToscaComponent(productId);
-
         if (storageStatus.isRight()) {
             log.debug("failed to delete resource by id {}", productId);
-            return Either.right(componentsUtils.getResponseFormatByResource(componentsUtils.convertFromStorageResponse(storageStatus.right().value()), ""));
+            return Either
+                .right(componentsUtils.getResponseFormatByResource(componentsUtils.convertFromStorageResponse(storageStatus.right().value()), ""));
         }
         return Either.left(storageStatus.left().value());
     }
@@ -522,28 +482,27 @@ public class ProductBusinessLogic extends ComponentBusinessLogic {
     private Either<Boolean, ResponseFormat> validateProductFullNameAndCleanup(User user, Product product, AuditingActionEnum actionEnum) {
         String fullName = product.getFullName();
         if (!ValidationUtils.validateStringNotEmpty(fullName)) {
-            ResponseFormat errorResponse = componentsUtils.getResponseFormat(ActionStatus.MISSING_ONE_OF_COMPONENT_NAMES, ComponentTypeEnum.PRODUCT.getValue(), PRODUCT_FULL_NAME);
+            ResponseFormat errorResponse = componentsUtils
+                .getResponseFormat(ActionStatus.MISSING_ONE_OF_COMPONENT_NAMES, ComponentTypeEnum.PRODUCT.getValue(), PRODUCT_FULL_NAME);
             componentsUtils.auditComponentAdmin(errorResponse, user, product, actionEnum, ComponentTypeEnum.PRODUCT);
             return Either.right(errorResponse);
         }
-
         fullName = ValidationUtils.removeNoneUtf8Chars(fullName);
         fullName = ValidationUtils.removeHtmlTags(fullName);
         fullName = ValidationUtils.normaliseWhitespace(fullName);
         fullName = ValidationUtils.stripOctets(fullName);
-
         if (!ValidationUtils.validateProductFullNameLength(fullName)) {
-            ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.COMPONENT_ELEMENT_INVALID_NAME_LENGTH, ComponentTypeEnum.PRODUCT.getValue(), PRODUCT_FULL_NAME);
+            ResponseFormat responseFormat = componentsUtils
+                .getResponseFormat(ActionStatus.COMPONENT_ELEMENT_INVALID_NAME_LENGTH, ComponentTypeEnum.PRODUCT.getValue(), PRODUCT_FULL_NAME);
             componentsUtils.auditComponentAdmin(responseFormat, user, product, actionEnum, ComponentTypeEnum.PRODUCT);
             return Either.right(responseFormat);
         }
-
         if (!ValidationUtils.validateIsEnglish(fullName)) {
-            ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.COMPONENT_ELEMENT_INVALID_NAME_FORMAT, ComponentTypeEnum.PRODUCT.getValue(), PRODUCT_FULL_NAME);
+            ResponseFormat responseFormat = componentsUtils
+                .getResponseFormat(ActionStatus.COMPONENT_ELEMENT_INVALID_NAME_FORMAT, ComponentTypeEnum.PRODUCT.getValue(), PRODUCT_FULL_NAME);
             componentsUtils.auditComponentAdmin(responseFormat, user, product, actionEnum, ComponentTypeEnum.PRODUCT);
             return Either.right(responseFormat);
         }
-
         product.setFullName(fullName);
         return Either.left(true);
     }
@@ -551,49 +510,55 @@ public class ProductBusinessLogic extends ComponentBusinessLogic {
     private Either<Boolean, ResponseFormat> validateProductNameAndCleanup(User user, Product product, AuditingActionEnum actionEnum) {
         String name = product.getName();
         if (!ValidationUtils.validateStringNotEmpty(name)) {
-            ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.MISSING_ONE_OF_COMPONENT_NAMES, ComponentTypeEnum.PRODUCT.getValue(), PRODUCT_ABBREVIATED_NAME);
+            ResponseFormat responseFormat = componentsUtils
+                .getResponseFormat(ActionStatus.MISSING_ONE_OF_COMPONENT_NAMES, ComponentTypeEnum.PRODUCT.getValue(), PRODUCT_ABBREVIATED_NAME);
             componentsUtils.auditComponentAdmin(responseFormat, user, product, actionEnum, ComponentTypeEnum.PRODUCT);
             return Either.right(responseFormat);
         }
-
         // Product name is required to have same validation and normalization as
+
         // category
         if (!ValidationUtils.validateCategoryDisplayNameFormat(name)) {
-            ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.COMPONENT_ELEMENT_INVALID_NAME_FORMAT, ComponentTypeEnum.PRODUCT.getValue(), PRODUCT_ABBREVIATED_NAME);
+            ResponseFormat responseFormat = componentsUtils
+                .getResponseFormat(ActionStatus.COMPONENT_ELEMENT_INVALID_NAME_FORMAT, ComponentTypeEnum.PRODUCT.getValue(),
+                    PRODUCT_ABBREVIATED_NAME);
             componentsUtils.auditComponentAdmin(responseFormat, user, product, actionEnum, ComponentTypeEnum.PRODUCT);
             return Either.right(responseFormat);
         }
-
         String normalizedName4Display = ValidationUtils.normalizeCategoryName4Display(name);
-
         if (!ValidationUtils.validateCategoryDisplayNameLength(normalizedName4Display)) {
-            ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.COMPONENT_ELEMENT_INVALID_NAME_LENGTH, ComponentTypeEnum.PRODUCT.getValue(), PRODUCT_ABBREVIATED_NAME);
+            ResponseFormat responseFormat = componentsUtils
+                .getResponseFormat(ActionStatus.COMPONENT_ELEMENT_INVALID_NAME_LENGTH, ComponentTypeEnum.PRODUCT.getValue(),
+                    PRODUCT_ABBREVIATED_NAME);
             componentsUtils.auditComponentAdmin(responseFormat, user, product, actionEnum, ComponentTypeEnum.PRODUCT);
             return Either.right(responseFormat);
         }
-
         product.setName(normalizedName4Display);
         String normalizedName4Uniqueness = ValidationUtils.normaliseComponentName(normalizedName4Display);
         product.setNormalizedName(normalizedName4Uniqueness);
-
         return Either.left(true);
     }
-
     // This is a workaround for a current tag--->product name behaviour, which
+
     // will be changed in 1607.
+
     // It was agreed with Ella on 23/2/16 that the tag validation of product
+
     // will be made against the old product name (before normalization),
+
     // and in 1607 US will be defined where UI will no longer pass tag of
+
     // component name, and BE will add it by itself after all needed
+
     // normalizations.
-    private Either<Boolean, ResponseFormat> validateTagsListAndRemoveDuplicates(User user, Product product, String oldProductName, AuditingActionEnum actionEnum) {
+    private Either<Boolean, ResponseFormat> validateTagsListAndRemoveDuplicates(User user, Product product, String oldProductName,
+                                                                                AuditingActionEnum actionEnum) {
         componentTagsValidator.validateAndCorrectField(user, product, actionEnum);
         return Either.left(true);
     }
 
     @Override
     public void setDeploymentArtifactsPlaceHolder(org.openecomp.sdc.be.model.Component component, User user) {
-
     }
 
     public Either<Product, ResponseFormat> updateProductMetadata(String productId, Product updatedProduct, User user) {
@@ -606,28 +571,25 @@ public class ProductBusinessLogic extends ComponentBusinessLogic {
             ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.INVALID_CONTENT);
             return Either.right(responseFormat);
         }
-
         Either<Product, StorageOperationStatus> storageStatus = toscaOperationFacade.getToscaElement(productId);
         if (storageStatus.isRight()) {
             if (storageStatus.right().value() == StorageOperationStatus.NOT_FOUND) {
-                return Either.right(componentsUtils.getResponseFormat(ActionStatus.PRODUCT_NOT_FOUND, ComponentTypeEnum.PRODUCT.name().toLowerCase()));
+                return Either
+                    .right(componentsUtils.getResponseFormat(ActionStatus.PRODUCT_NOT_FOUND, ComponentTypeEnum.PRODUCT.name().toLowerCase()));
             }
-            return Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(storageStatus.right().value(), typeEnum), ""));
+            return Either
+                .right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(storageStatus.right().value(), typeEnum), ""));
         }
-
         Product currentProduct = storageStatus.left().value();
-
         if (!ComponentValidationUtils.canWorkOnComponent(productId, toscaOperationFacade, user.getUserId())) {
-            log.info("Restricted operation for user: {}, on product: {}" , user.getUserId(), currentProduct.getCreatorUserId());
+            log.info("Restricted operation for user: {}, on product: {}", user.getUserId(), currentProduct.getCreatorUserId());
             return Either.right(componentsUtils.getResponseFormat(ActionStatus.RESTRICTED_OPERATION));
         }
-
         Either<Product, ResponseFormat> validationRsponse = validateAndUpdateProductMetadata(user, currentProduct, updatedProduct);
         if (validationRsponse.isRight()) {
             log.info("product update metadata: validations field.");
             return validationRsponse;
         }
-
         Product productToUpdate = validationRsponse.left().value();
         // lock resource
         lockComponent(currentProduct.getUniqueId(), currentProduct, "Update Product Metadata");
@@ -646,69 +608,57 @@ public class ProductBusinessLogic extends ComponentBusinessLogic {
     }
 
     private Either<Product, ResponseFormat> validateAndUpdateProductMetadata(User user, Product currentProduct, Product updatedProduct) {
-
         boolean hasBeenCertified = ValidationUtils.hasBeenCertified(currentProduct.getVersion());
         Either<Boolean, ResponseFormat> response = validateAndUpdateProductName(user, currentProduct, updatedProduct);
         if (response.isRight()) {
             ResponseFormat errorResponse = response.right().value();
             return Either.right(errorResponse);
         }
-
         response = validateAndUpdateFullName(user, currentProduct, updatedProduct);
         if (response.isRight()) {
             ResponseFormat errorResponse = response.right().value();
             return Either.right(errorResponse);
         }
-
         response = validateAndUpdateDescription(user, currentProduct, updatedProduct, null);
         if (response.isRight()) {
             ResponseFormat errorResponse = response.right().value();
             return Either.right(errorResponse);
         }
-
         response = validateAndUpdateCategory(user, currentProduct, updatedProduct);
         if (response.isRight()) {
             ResponseFormat errorResponse = response.right().value();
             return Either.right(errorResponse);
         }
-
         response = validateAndUpdateContactList(user, currentProduct, updatedProduct);
         if (response.isRight()) {
             ResponseFormat errorResponse = response.right().value();
             return Either.right(errorResponse);
         }
-
         response = validateAndUpdateTags(user, currentProduct, updatedProduct);
         if (response.isRight()) {
             ResponseFormat errorResponse = response.right().value();
             return Either.right(errorResponse);
         }
-
         response = validateAndUpdateProjectCode(user, currentProduct, updatedProduct);
         if (response.isRight()) {
             ResponseFormat errorResponse = response.right().value();
             return Either.right(errorResponse);
         }
-
         if (updatedProduct.getIsActive() != null) {
             currentProduct.setIsActive(updatedProduct.getIsActive());
         }
-
         response = validateAndUpdateIcon(user, currentProduct, updatedProduct, hasBeenCertified);
         if (response.isRight()) {
             ResponseFormat errorResponse = response.right().value();
             return Either.right(errorResponse);
         }
-
         String currentInvariantUuid = currentProduct.getInvariantUUID();
         String updatedInvariantUuid = updatedProduct.getInvariantUUID();
-
         if ((updatedInvariantUuid != null) && (!updatedInvariantUuid.equals(currentInvariantUuid))) {
             log.warn("Product invariant UUID is automatically set and cannot be updated");
             updatedProduct.setInvariantUUID(currentInvariantUuid);
         }
         return Either.left(currentProduct);
-
     }
 
     private Either<Boolean, ResponseFormat> validateAndUpdateProductName(User user, Product currentProduct, Product updatedProduct) {
@@ -731,9 +681,11 @@ public class ProductBusinessLogic extends ComponentBusinessLogic {
                 currentProduct.setName(updatedProductName);
                 tags = updatedProductName;
                 updatedProductName = ValidationUtils.normalizeCategoryName4Display(updatedProductName);
-                currentProduct.getComponentMetadataDefinition().getMetadataDataDefinition().setNormalizedName(ValidationUtils.normaliseComponentName(updatedProductName));
+                currentProduct.getComponentMetadataDefinition().getMetadataDataDefinition()
+                    .setNormalizedName(ValidationUtils.normaliseComponentName(updatedProductName));
                 List<String> updatedTags = updatedProduct.getTags();
                 // As discussed with Ella currently (1604) we are not removing
+
                 // the old name from tags.
                 if (updatedTags == null) {
                     updatedTags = currentProduct.getTags();
@@ -759,13 +711,11 @@ public class ProductBusinessLogic extends ComponentBusinessLogic {
     }
 
     private Either<Boolean, ResponseFormat> validateAndUpdateCategory(User user, Product currentProduct, Product updatedProduct) {
-
         Either<Boolean, ResponseFormat> validateCategoryResponse = validateGrouping(user, updatedProduct, null);
         if (validateCategoryResponse.isRight()) {
             ResponseFormat errorResponse = validateCategoryResponse.right().value();
             return Either.right(errorResponse);
         }
-
         List<CategoryDefinition> categoryUpdated = updatedProduct.getCategories();
         if (categoryUpdated != null) {
             currentProduct.setCategories(categoryUpdated);
@@ -794,7 +744,8 @@ public class ProductBusinessLogic extends ComponentBusinessLogic {
         List<String> tagsCurrent = currentProduct.getTags();
         if (tagsUpdated != null) {
             if (!(tagsCurrent.containsAll(tagsUpdated) && tagsUpdated.containsAll(tagsCurrent))) {
-                Either<Boolean, ResponseFormat> validatResponse = validateTagsListAndRemoveDuplicates(user, updatedProduct, currentProduct.getName(), null);
+                Either<Boolean, ResponseFormat> validatResponse = validateTagsListAndRemoveDuplicates(user, updatedProduct, currentProduct.getName(),
+                    null);
                 if (validatResponse.isRight()) {
                     ResponseFormat errorRespons = validatResponse.right().value();
                     return Either.right(errorRespons);
@@ -813,10 +764,13 @@ public class ProductBusinessLogic extends ComponentBusinessLogic {
 
     public Either<Product, ResponseFormat> getProductByNameAndVersion(String productName, String productVersion, String userId) {
         validateUserExists(userId);
-        Either<Product, StorageOperationStatus> storageStatus = toscaOperationFacade.getComponentByNameAndVersion(ComponentTypeEnum.PRODUCT, productName, productVersion);
+        Either<Product, StorageOperationStatus> storageStatus = toscaOperationFacade
+            .getComponentByNameAndVersion(ComponentTypeEnum.PRODUCT, productName, productVersion);
         if (storageStatus.isRight()) {
             log.debug("failed to get service by name {} and version {}", productName, productVersion);
-            return Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(storageStatus.right().value(), ComponentTypeEnum.PRODUCT), productName));
+            return Either.right(componentsUtils
+                .getResponseFormat(componentsUtils.convertFromStorageResponse(storageStatus.right().value(), ComponentTypeEnum.PRODUCT),
+                    productName));
         }
         Product product = storageStatus.left().value();
         return Either.left(product);
@@ -834,9 +788,8 @@ public class ProductBusinessLogic extends ComponentBusinessLogic {
 
     @Override
     public Either<UiComponentDataTransfer, ResponseFormat> getUiComponentDataTransferByComponentId(String componentId,
-            List<String> dataParamsToReturn) {
+                                                                                                   List<String> dataParamsToReturn) {
         // TODO Auto-generated method stub
         return null;
     }
-
 }
index 66a6a27..baab08d 100644 (file)
  * limitations under the License.
  * ============LICENSE_END=========================================================
  */
-
 package org.openecomp.sdc.be.components.impl;
 
 import com.google.gson.JsonElement;
 import fj.data.Either;
+import java.util.ArrayList;
+import java.util.List;
+import java.util.Map;
+import java.util.Objects;
+import java.util.Optional;
 import org.apache.commons.collections.CollectionUtils;
 import org.apache.commons.collections.MapUtils;
 import org.openecomp.sdc.be.components.impl.exceptions.BusinessLogicException;
@@ -59,32 +63,19 @@ import org.openecomp.sdc.common.log.wrappers.Logger;
 import org.openecomp.sdc.exception.ResponseFormat;
 import org.springframework.beans.factory.annotation.Autowired;
 
-import java.util.ArrayList;
-import java.util.List;
-import java.util.Map;
-import java.util.Objects;
-import java.util.Optional;
-
-
 @org.springframework.stereotype.Component("propertyBusinessLogic")
 public class PropertyBusinessLogic extends BaseBusinessLogic {
 
     private static final String CREATE_PROPERTY = "CreateProperty";
-
     private static final Logger log = Logger.getLogger(PropertyBusinessLogic.class);
-
     private static final String EMPTY_VALUE = null;
 
     @Autowired
-    public PropertyBusinessLogic(IElementOperation elementDao,
-        IGroupOperation groupOperation,
-        IGroupInstanceOperation groupInstanceOperation,
-        IGroupTypeOperation groupTypeOperation,
-        InterfaceOperation interfaceOperation,
-        InterfaceLifecycleOperation interfaceLifecycleTypeOperation,
-        ArtifactsOperations artifactToscaOperation) {
-        super(elementDao, groupOperation, groupInstanceOperation, groupTypeOperation,
-            interfaceOperation, interfaceLifecycleTypeOperation, artifactToscaOperation);
+    public PropertyBusinessLogic(IElementOperation elementDao, IGroupOperation groupOperation, IGroupInstanceOperation groupInstanceOperation,
+                                 IGroupTypeOperation groupTypeOperation, InterfaceOperation interfaceOperation,
+                                 InterfaceLifecycleOperation interfaceLifecycleTypeOperation, ArtifactsOperations artifactToscaOperation) {
+        super(elementDao, groupOperation, groupInstanceOperation, groupTypeOperation, interfaceOperation, interfaceLifecycleTypeOperation,
+            artifactToscaOperation);
     }
 
     public Map<String, DataTypeDefinition> getAllDataTypes() {
@@ -100,54 +91,39 @@ public class PropertyBusinessLogic extends BaseBusinessLogic {
      * @param userId
      * @return either properties or response format
      */
-
-    public Either<EntryData<String, PropertyDefinition>, ResponseFormat> addPropertyToComponent(String componentId,
-                                                                                                String propertyName,
+    public Either<EntryData<String, PropertyDefinition>, ResponseFormat> addPropertyToComponent(String componentId, String propertyName,
                                                                                                 PropertyDefinition newPropertyDefinition,
                                                                                                 String userId) {
         Either<EntryData<String, PropertyDefinition>, ResponseFormat> result = null;
-
         validateUserExists(userId);
-
-        Either<Component, StorageOperationStatus> serviceElement =
-                toscaOperationFacade.getToscaElement(componentId);
+        Either<Component, StorageOperationStatus> serviceElement = toscaOperationFacade.getToscaElement(componentId);
         if (serviceElement.isRight()) {
             result = Either.right(componentsUtils.getResponseFormat(ActionStatus.RESOURCE_NOT_FOUND, ""));
             return result;
         }
         Component component = serviceElement.left().value();
         NodeTypeEnum nodeType = component.getComponentType().getNodeType();
-        StorageOperationStatus lockResult = graphLockOperation.lockComponent(componentId, nodeType );
+        StorageOperationStatus lockResult = graphLockOperation.lockComponent(componentId, nodeType);
         if (!lockResult.equals(StorageOperationStatus.OK)) {
             BeEcompErrorManager.getInstance().logBeFailedLockObjectError(CREATE_PROPERTY, nodeType.name().toLowerCase(), componentId);
             log.info("Failed to lock component {}. Error - {}", componentId, lockResult);
             result = Either.right(componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR));
             return result;
         }
-
         try {
             if (!ComponentValidationUtils.canWorkOnComponent(component, userId)) {
                 result = Either.right(componentsUtils.getResponseFormat(ActionStatus.RESTRICTED_OPERATION));
                 return result;
             }
-
             List<PropertyDefinition> properties = component.getProperties();
-
-            if(CollectionUtils.isEmpty(properties)) {
+            if (CollectionUtils.isEmpty(properties)) {
                 properties = new ArrayList<>();
             }
-
-            if(isPropertyExistInComponent(properties, propertyName)) {
-
-                result =
-                    Either.right(componentsUtils.getResponseFormat(ActionStatus
-                        .PROPERTY_ALREADY_EXIST, propertyName));
+            if (isPropertyExistInComponent(properties, propertyName)) {
+                result = Either.right(componentsUtils.getResponseFormat(ActionStatus.PROPERTY_ALREADY_EXIST, propertyName));
                 return result;
-
             } else {
-
                 Map<String, DataTypeDefinition> allDataTypes = getAllDataTypes(applicationDataTypeCache);
-
                 // validate property default values
                 Either<Boolean, ResponseFormat> defaultValuesValidation = validatePropertyDefaultValue(newPropertyDefinition, allDataTypes);
                 if (defaultValuesValidation.isRight()) {
@@ -170,21 +146,16 @@ public class PropertyBusinessLogic extends BaseBusinessLogic {
                         }
                         String convertedValue = null;
                         if (newPropertyDefinition.getDefaultValue() != null) {
-                            convertedValue = converter.convert(
-                                newPropertyDefinition.getDefaultValue(), innerType, allDataTypes);
+                            convertedValue = converter.convert(newPropertyDefinition.getDefaultValue(), innerType, allDataTypes);
                             newPropertyDefinition.setDefaultValue(convertedValue);
                         }
                     }
                 }
-                Either<PropertyDefinition, StorageOperationStatus> addPropertyEither =
-                    toscaOperationFacade
-                        .addPropertyToComponent(propertyName, newPropertyDefinition, component);
-
+                Either<PropertyDefinition, StorageOperationStatus> addPropertyEither = toscaOperationFacade
+                    .addPropertyToComponent(propertyName, newPropertyDefinition, component);
                 if (addPropertyEither.isRight()) {
-                    log.info("Failed to add new property {}. Error - {}", componentId,
-                        addPropertyEither.right().value());
-                    result = Either.right(componentsUtils.getResponseFormat(ActionStatus
-                        .GENERAL_ERROR));
+                    log.info("Failed to add new property {}. Error - {}", componentId, addPropertyEither.right().value());
+                    result = Either.right(componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR));
                     return result;
                 }
             }
@@ -200,67 +171,58 @@ public class PropertyBusinessLogic extends BaseBusinessLogic {
     /**
      * Copies a list of properties to a component.
      *
-     * @param component the component to add the copied properties
+     * @param component            the component to add the copied properties
      * @param propertiesToCopyList the properties to be copied
      * @return the updated component with the copied properties.
      * @throws ToscaOperationException when a problem happens during the copy operation
      */
-    public Component copyPropertyToComponent(final Component component,
-                                             final List<PropertyDefinition> propertiesToCopyList) throws ToscaOperationException {
+    public Component copyPropertyToComponent(final Component component, final List<PropertyDefinition> propertiesToCopyList)
+        throws ToscaOperationException {
         return copyPropertyToComponent(component, propertiesToCopyList, true);
     }
 
     /**
      * Copies a list of properties to a component.
      *
-     * @param component the component to add the copied properties
+     * @param component            the component to add the copied properties
      * @param propertiesToCopyList the properties to be copied
-     * @param refreshComponent refresh the component from database after update
-     * @return the component refreshed from database if refreshComponent is {@code true}, the same component reference
-     * otherwise
+     * @param refreshComponent     refresh the component from database after update
+     * @return the component refreshed from database if refreshComponent is {@code true}, the same component reference otherwise
      * @throws ToscaOperationException when a problem happens during the copy operation
      */
-    public Component copyPropertyToComponent(final Component component,
-                                             final List<PropertyDefinition> propertiesToCopyList,
+    public Component copyPropertyToComponent(final Component component, final List<PropertyDefinition> propertiesToCopyList,
                                              final boolean refreshComponent) throws ToscaOperationException {
         if (CollectionUtils.isEmpty(propertiesToCopyList)) {
             return component;
         }
-
         for (final PropertyDefinition propertyDefinition : propertiesToCopyList) {
             copyPropertyToComponent(component, propertyDefinition);
         }
-
         if (refreshComponent) {
             return toscaOperationFacade.getToscaElement(component.getUniqueId()).left().value();
         }
-
         return component;
     }
 
     /**
      * Copies one property to a component.
      *
-     * @param component the component to add the copied property
+     * @param component          the component to add the copied property
      * @param propertyDefinition the property to be copied
      * @throws ToscaOperationException when a problem happens during the copy operation
      */
-    private void copyPropertyToComponent(final Component component,
-                                         final PropertyDefinition propertyDefinition) throws ToscaOperationException {
+    private void copyPropertyToComponent(final Component component, final PropertyDefinition propertyDefinition) throws ToscaOperationException {
         final PropertyDefinition copiedPropertyDefinition = new PropertyDefinition(propertyDefinition);
         final String componentId = component.getUniqueId();
         final String propertyName = copiedPropertyDefinition.getName();
-        copiedPropertyDefinition.setUniqueId(
-            UniqueIdBuilder.buildPropertyUniqueId(componentId, propertyName)
-        );
+        copiedPropertyDefinition.setUniqueId(UniqueIdBuilder.buildPropertyUniqueId(componentId, propertyName));
         copiedPropertyDefinition.setParentUniqueId(componentId);
         final Either<PropertyDefinition, StorageOperationStatus> operationResult = toscaOperationFacade
             .addPropertyToComponent(propertyName, copiedPropertyDefinition, component);
         if (operationResult.isRight()) {
-            final String error = String.format(
-                "Failed to add copied property '%s' to component '%s'. Operation status: '%s'",
-                propertyDefinition.getUniqueId(), componentId, operationResult.right().value()
-            );
+            final String error = String
+                .format("Failed to add copied property '%s' to component '%s'. Operation status: '%s'", propertyDefinition.getUniqueId(), componentId,
+                    operationResult.right().value());
             log.error(EcompLoggerErrorCode.BUSINESS_PROCESS_ERROR, PropertyBusinessLogic.class.getName(), "catalog-be", error);
             throw new ToscaOperationException(error, operationResult.right().value());
         }
@@ -274,50 +236,40 @@ public class PropertyBusinessLogic extends BaseBusinessLogic {
      * @param userId
      * @return either properties or response format
      */
-
     public Either<Map.Entry<String, PropertyDefinition>, ResponseFormat> getComponentProperty(String componentId, String propertyId, String userId) {
-
         validateUserExists(userId);
         // Get the resource from DB
-        Either<Component, StorageOperationStatus> status =
-            toscaOperationFacade.getToscaElement(componentId);
+        Either<Component, StorageOperationStatus> status = toscaOperationFacade.getToscaElement(componentId);
         if (status.isRight()) {
             return Either.right(componentsUtils.getResponseFormat(ActionStatus.RESOURCE_NOT_FOUND, ""));
         }
         Component component = status.left().value();
         List<PropertyDefinition> properties = component.getProperties();
-        if(CollectionUtils.isEmpty(properties)) {
+        if (CollectionUtils.isEmpty(properties)) {
             return Either.right(componentsUtils.getResponseFormat(ActionStatus.PROPERTY_NOT_FOUND, ""));
         }
-
-        for(PropertyDefinition property : properties) {
-            if(property.getUniqueId().equals(propertyId)) {
+        for (PropertyDefinition property : properties) {
+            if (property.getUniqueId().equals(propertyId)) {
                 return Either.left(new EntryData<>(property.getName(), property));
             }
         }
         return Either.right(componentsUtils.getResponseFormat(ActionStatus.PROPERTY_NOT_FOUND, ""));
     }
 
-
-    public Either<List<PropertyDefinition>, ResponseFormat> getPropertiesList(String componentId,
-                                                                              String userId) {
+    public Either<List<PropertyDefinition>, ResponseFormat> getPropertiesList(String componentId, String userId) {
         validateUserExists(userId);
-
         // Get the resource from DB
         ComponentParametersView filter = new ComponentParametersView(true);
         filter.setIgnoreProperties(false);
-        Either<Component, StorageOperationStatus> status =
-            toscaOperationFacade.getToscaElement(componentId);
+        Either<Component, StorageOperationStatus> status = toscaOperationFacade.getToscaElement(componentId);
         if (status.isRight()) {
             return Either.right(componentsUtils.getResponseFormat(ActionStatus.RESOURCE_NOT_FOUND, ""));
         }
         Component component = status.left().value();
         List<PropertyDefinition> properties = component.getProperties();
-
         return Either.left(properties);
     }
 
-
     /**
      * delete property of component from graph
      *
@@ -326,13 +278,10 @@ public class PropertyBusinessLogic extends BaseBusinessLogic {
      * @param userId
      * @return either properties or response format
      */
-
-    public Either<Map.Entry<String, PropertyDefinition>, ResponseFormat> deletePropertyFromComponent(String componentId, String propertyId, String userId) {
-
+    public Either<Map.Entry<String, PropertyDefinition>, ResponseFormat> deletePropertyFromComponent(String componentId, String propertyId,
+                                                                                                     String userId) {
         Either<Map.Entry<String, PropertyDefinition>, ResponseFormat> result = null;
-
         validateUserExists(userId);
-
         // Get the resource from DB
         Either<Component, StorageOperationStatus> getComponentRes = toscaOperationFacade.getToscaElement(componentId);
         if (getComponentRes.isRight()) {
@@ -343,46 +292,36 @@ public class PropertyBusinessLogic extends BaseBusinessLogic {
         NodeTypeEnum nodeType = component.getComponentType().getNodeType();
         StorageOperationStatus lockResult = graphLockOperation.lockComponent(componentId, nodeType);
         if (!lockResult.equals(StorageOperationStatus.OK)) {
-            BeEcompErrorManager.getInstance().logBeFailedLockObjectError(CREATE_PROPERTY, nodeType.name().toLowerCase(),
-                    componentId);
+            BeEcompErrorManager.getInstance().logBeFailedLockObjectError(CREATE_PROPERTY, nodeType.name().toLowerCase(), componentId);
             result = Either.right(componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR));
             return result;
         }
-
         try {
             // verify that resource is checked-out and the user is the last
+
             // updater
             if (!ComponentValidationUtils.canWorkOnComponent(component, userId)) {
                 result = Either.right(componentsUtils.getResponseFormat(ActionStatus.RESTRICTED_OPERATION));
                 return result;
             }
-
             // verify property exist in resource
-            Either<Map.Entry<String, PropertyDefinition>, ResponseFormat> statusGetProperty =
-                getComponentProperty(componentId, propertyId, userId);
+            Either<Map.Entry<String, PropertyDefinition>, ResponseFormat> statusGetProperty = getComponentProperty(componentId, propertyId, userId);
             if (statusGetProperty.isRight()) {
                 result = Either.right(statusGetProperty.right().value());
                 return result;
             }
-
             Map.Entry<String, PropertyDefinition> propertyDefinitionEntry = statusGetProperty.left().value();
-
             // verify that the property is not used by operation
             if (isPropertyUsedByOperation(component, propertyDefinitionEntry.getValue())) {
-                return Either.right(componentsUtils.getResponseFormat(ActionStatus
-                    .PROPERTY_USED_BY_OPERATION));
+                return Either.right(componentsUtils.getResponseFormat(ActionStatus.PROPERTY_USED_BY_OPERATION));
             }
-
-            StorageOperationStatus status =
-                toscaOperationFacade.deletePropertyOfComponent(component, propertyDefinitionEntry.getKey());
+            StorageOperationStatus status = toscaOperationFacade.deletePropertyOfComponent(component, propertyDefinitionEntry.getKey());
             if (status != StorageOperationStatus.OK) {
-                result = Either.right(componentsUtils.getResponseFormat(componentsUtils
-                    .convertFromStorageResponse(status), component.getName()));
+                result = Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(status), component.getName()));
                 return result;
             }
             result = Either.left(propertyDefinitionEntry);
             return result;
-
         } finally {
             commitOrRollback(result);
             // unlock component
@@ -390,58 +329,48 @@ public class PropertyBusinessLogic extends BaseBusinessLogic {
         }
     }
 
-    public boolean isPropertyUsedByOperation(Component component,
-                                             PropertyDefinition propertyDefinitionEntry) {
-
+    public boolean isPropertyUsedByOperation(Component component, PropertyDefinition propertyDefinitionEntry) {
         // Component's own interfaces
         Map<String, InterfaceDefinition> interfaces = component.getInterfaces();
-        if(MapUtils.isNotEmpty(interfaces)){
-          for(Map.Entry<String, InterfaceDefinition> interfaceEntry : interfaces.entrySet()) {
-            if (isPropertyExistInOperationInterface(propertyDefinitionEntry, interfaceEntry.getValue())) {
-              return true;
+        if (MapUtils.isNotEmpty(interfaces)) {
+            for (Map.Entry<String, InterfaceDefinition> interfaceEntry : interfaces.entrySet()) {
+                if (isPropertyExistInOperationInterface(propertyDefinitionEntry, interfaceEntry.getValue())) {
+                    return true;
+                }
             }
-          }
         }
-
         // Component's child's component interfaces
-        if(isPropertyUsedInCIInterfaces(component.getComponentInstancesInterfaces(), propertyDefinitionEntry)){
+        if (isPropertyUsedInCIInterfaces(component.getComponentInstancesInterfaces(), propertyDefinitionEntry)) {
             return true;
         }
-
         // Component's parent's component interfaces
         Either<List<Component>, StorageOperationStatus> componentList = toscaOperationFacade.getParentComponents(component.getUniqueId());
-        if(componentList.isLeft()){
+        if (componentList.isLeft()) {
             for (Component parentComponent : componentList.left().value()) {
-                if(isPropertyUsedInCIInterfaces(parentComponent.getComponentInstancesInterfaces(), propertyDefinitionEntry)){
+                if (isPropertyUsedInCIInterfaces(parentComponent.getComponentInstancesInterfaces(), propertyDefinitionEntry)) {
                     return true;
                 }
             }
         }
-
         return false;
     }
 
-    private boolean isPropertyUsedInCIInterfaces(Map<String, List<ComponentInstanceInterface>> componentInstanceInterfaces, PropertyDefinition propertyDefinitionEntry){
+    private boolean isPropertyUsedInCIInterfaces(Map<String, List<ComponentInstanceInterface>> componentInstanceInterfaces,
+                                                 PropertyDefinition propertyDefinitionEntry) {
         Optional<ComponentInstanceInterface> isPropertyExistInOperationInterface = Optional.empty();
-        if(MapUtils.isNotEmpty(componentInstanceInterfaces)){
+        if (MapUtils.isNotEmpty(componentInstanceInterfaces)) {
             isPropertyExistInOperationInterface = componentInstanceInterfaces.entrySet().stream()
-                    .flatMap(interfaceEntry -> interfaceEntry.getValue().stream())
-                    .filter(instanceInterface -> isPropertyExistInOperationInterface(propertyDefinitionEntry, instanceInterface))
-                    .findAny();
+                .flatMap(interfaceEntry -> interfaceEntry.getValue().stream())
+                .filter(instanceInterface -> isPropertyExistInOperationInterface(propertyDefinitionEntry, instanceInterface)).findAny();
         }
         return isPropertyExistInOperationInterface.isPresent();
     }
 
-    private boolean isPropertyExistInOperationInterface(PropertyDefinition propertyDefinition,
-                                                        InterfaceDefinition interfaceDefinition) {
-        Map<String, OperationDataDefinition> operations =
-            interfaceDefinition.getOperations();
-        for(Map.Entry<String, OperationDataDefinition> operationEntry : operations
-            .entrySet()) {
-            Optional<OperationInputDefinition> inputWithDeletedPropertyCandidate =
-                getInputWithDeclaredProperty(propertyDefinition, operationEntry);
-
-            if(inputWithDeletedPropertyCandidate.isPresent()) {
+    private boolean isPropertyExistInOperationInterface(PropertyDefinition propertyDefinition, InterfaceDefinition interfaceDefinition) {
+        Map<String, OperationDataDefinition> operations = interfaceDefinition.getOperations();
+        for (Map.Entry<String, OperationDataDefinition> operationEntry : operations.entrySet()) {
+            Optional<OperationInputDefinition> inputWithDeletedPropertyCandidate = getInputWithDeclaredProperty(propertyDefinition, operationEntry);
+            if (inputWithDeletedPropertyCandidate.isPresent()) {
                 return true;
             }
         }
@@ -450,17 +379,14 @@ public class PropertyBusinessLogic extends BaseBusinessLogic {
 
     private Optional<OperationInputDefinition> getInputWithDeclaredProperty(PropertyDefinition propertyDefinition,
                                                                             Map.Entry<String, OperationDataDefinition> operationEntry) {
-        ListDataDefinition<OperationInputDefinition> inputs =
-            operationEntry.getValue().getInputs();
-        List<OperationInputDefinition> operationInputsList =
-            Objects.isNull(inputs) ? null : inputs.getListToscaDataDefinition();
-
-        if(CollectionUtils.isEmpty(operationInputsList)) {
+        ListDataDefinition<OperationInputDefinition> inputs = operationEntry.getValue().getInputs();
+        List<OperationInputDefinition> operationInputsList = Objects.isNull(inputs) ? null : inputs.getListToscaDataDefinition();
+        if (CollectionUtils.isEmpty(operationInputsList)) {
             return Optional.empty();
         }
-
-        return operationInputsList.stream().filter(input -> input.getInputId().equals(propertyDefinition.getUniqueId())
-                || (input.getSourceProperty() != null && input.getSourceProperty().equals(propertyDefinition.getUniqueId()))).findAny();
+        return operationInputsList.stream().filter(
+            input -> input.getInputId().equals(propertyDefinition.getUniqueId()) || (input.getSourceProperty() != null && input.getSourceProperty()
+                .equals(propertyDefinition.getUniqueId()))).findAny();
     }
 
     /**
@@ -472,59 +398,46 @@ public class PropertyBusinessLogic extends BaseBusinessLogic {
      * @param userId
      * @return either properties or response format
      */
-
-    public Either<EntryData<String, PropertyDefinition>, ResponseFormat> updateComponentProperty(String componentId,
-                                                                        String propertyId,
-                                                                        PropertyDefinition newPropertyDefinition,
-                                                                        String userId) {
-
+    public Either<EntryData<String, PropertyDefinition>, ResponseFormat> updateComponentProperty(String componentId, String propertyId,
+                                                                                                 PropertyDefinition newPropertyDefinition,
+                                                                                                 String userId) {
         Either<EntryData<String, PropertyDefinition>, ResponseFormat> result = null;
-
-        Either<Component, StorageOperationStatus> status = toscaOperationFacade.getToscaElement(
-                componentId);
+        Either<Component, StorageOperationStatus> status = toscaOperationFacade.getToscaElement(componentId);
         if (status.isRight()) {
             return Either.right(componentsUtils.getResponseFormat(ActionStatus.RESOURCE_NOT_FOUND, ""));
         }
         Component component = status.left().value();
         NodeTypeEnum nodeType = component.getComponentType().getNodeType();
-
         if (!ComponentValidationUtils.canWorkOnComponent(component, userId)) {
             return Either.right(componentsUtils.getResponseFormat(ActionStatus.RESTRICTED_OPERATION));
         }
-
         StorageOperationStatus lockResult = graphLockOperation.lockComponent(componentId, nodeType);
         if (!lockResult.equals(StorageOperationStatus.OK)) {
-            BeEcompErrorManager.getInstance().logBeFailedLockObjectError(CREATE_PROPERTY, nodeType.name().toLowerCase(),
-                    componentId);
+            BeEcompErrorManager.getInstance().logBeFailedLockObjectError(CREATE_PROPERTY, nodeType.name().toLowerCase(), componentId);
             result = Either.right(componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR));
             return result;
         }
-
         try {
-            Either<Map.Entry<String, PropertyDefinition>, ResponseFormat> statusGetProperty =
-                getComponentProperty(componentId, propertyId, userId);
+            Either<Map.Entry<String, PropertyDefinition>, ResponseFormat> statusGetProperty = getComponentProperty(componentId, propertyId, userId);
             if (statusGetProperty.isRight()) {
                 result = Either.right(statusGetProperty.right().value());
                 return result;
             }
             String propertyName = statusGetProperty.left().value().getKey();
-
-            Either<PropertyDefinition, StorageOperationStatus> either =
-                toscaOperationFacade.updatePropertyOfComponent(component, newPropertyDefinition);
+            Either<PropertyDefinition, StorageOperationStatus> either = toscaOperationFacade
+                .updatePropertyOfComponent(component, newPropertyDefinition);
             if (either.isRight()) {
-                result = Either.right(componentsUtils.getResponseFormatByResource(componentsUtils.convertFromStorageResponse(either.right().value()), component.getName()));
+                result = Either.right(componentsUtils
+                    .getResponseFormatByResource(componentsUtils.convertFromStorageResponse(either.right().value()), component.getName()));
                 return result;
             }
-
             EntryData<String, PropertyDefinition> property = new EntryData<>(propertyName, either.left().value());
             result = Either.left(property);
             return result;
-
         } finally {
             commitOrRollback(result);
             graphLockOperation.unlockComponent(componentId, nodeType);
         }
-
     }
 
     /**
@@ -550,41 +463,32 @@ public class PropertyBusinessLogic extends BaseBusinessLogic {
     /**
      * Updates a component property.
      *
-     * @param componentId the component id that owns the property
+     * @param componentId        the component id that owns the property
      * @param propertyDefinition the existing property to update
      * @return the updated property
-     * @throws BusinessLogicException if the component was not found or if there was a problem during the update
-     * operation.
+     * @throws BusinessLogicException if the component was not found or if there was a problem during the update operation.
      */
-    public PropertyDefinition updateComponentProperty(final String componentId,
-                                                      final PropertyDefinition propertyDefinition)
-            throws BusinessLogicException {
+    public PropertyDefinition updateComponentProperty(final String componentId, final PropertyDefinition propertyDefinition)
+        throws BusinessLogicException {
         final Component component = findComponentById(componentId).orElse(null);
         if (component == null) {
-            throw new BusinessLogicException(
-                componentsUtils.getResponseFormatByResource(ActionStatus.RESOURCE_NOT_FOUND, componentId));
+            throw new BusinessLogicException(componentsUtils.getResponseFormatByResource(ActionStatus.RESOURCE_NOT_FOUND, componentId));
         }
-        final Either<PropertyDefinition, StorageOperationStatus> updateResultEither =
-            toscaOperationFacade.updatePropertyOfComponent(component, propertyDefinition);
+        final Either<PropertyDefinition, StorageOperationStatus> updateResultEither = toscaOperationFacade
+            .updatePropertyOfComponent(component, propertyDefinition);
         if (updateResultEither.isRight()) {
-            final ResponseFormat responseFormat = componentsUtils.getResponseFormatByResource(
-                componentsUtils.convertFromStorageResponse(updateResultEither.right().value()), component.getName()
-            );
+            final ResponseFormat responseFormat = componentsUtils
+                .getResponseFormatByResource(componentsUtils.convertFromStorageResponse(updateResultEither.right().value()), component.getName());
             throw new BusinessLogicException(responseFormat);
         }
-
         return updateResultEither.left().value();
     }
 
     private boolean isPropertyExistInComponent(List<PropertyDefinition> properties, String propertyName) {
-        if(CollectionUtils.isEmpty(properties)) {
+        if (CollectionUtils.isEmpty(properties)) {
             return false;
         }
-
-        Optional<PropertyDefinition> propertyCandidate =
-                properties.stream().filter(property -> property.getName().equals(propertyName))
-                        .findAny();
-
+        Optional<PropertyDefinition> propertyCandidate = properties.stream().filter(property -> property.getName().equals(propertyName)).findAny();
         return propertyCandidate.isPresent();
     }
 
@@ -593,7 +497,7 @@ public class PropertyBusinessLogic extends BaseBusinessLogic {
         if (jsonElement == null || jsonElement.isJsonNull()) {
             return EMPTY_VALUE;
         }
-        if(jsonElement.toString().isEmpty()){
+        if (jsonElement.toString().isEmpty()) {
             return "";
         }
         return jsonElement.toString();
index e231ed7..9a83566 100644 (file)
  * See the License for the specific language governing permissions and
  * limitations under the License.
  */
-
 package org.openecomp.sdc.be.components.impl;
 
 import fj.data.Either;
+import java.util.Map;
 import org.openecomp.sdc.be.config.BeEcompErrorManager;
 import org.openecomp.sdc.be.dao.api.ActionStatus;
 import org.openecomp.sdc.be.dao.janusgraph.JanusGraphOperationStatus;
@@ -27,40 +27,33 @@ import org.openecomp.sdc.exception.ResponseFormat;
 import org.springframework.beans.factory.annotation.Autowired;
 import org.springframework.stereotype.Component;
 
-import java.util.Map;
-
 @Component("relationshipTypeBusinessLogic")
 public class RelationshipTypeBusinessLogic {
 
-    private final RelationshipTypeOperation relationshipTypeOperation;
     protected final ComponentsUtils componentsUtils;
+    private final RelationshipTypeOperation relationshipTypeOperation;
 
     @Autowired
-    public RelationshipTypeBusinessLogic(RelationshipTypeOperation relationshipTypeOperation,
-        ComponentsUtils componentsUtils) {
+    public RelationshipTypeBusinessLogic(RelationshipTypeOperation relationshipTypeOperation, ComponentsUtils componentsUtils) {
         this.relationshipTypeOperation = relationshipTypeOperation;
         this.componentsUtils = componentsUtils;
     }
 
     public Either<Map<String, RelationshipTypeDefinition>, ResponseFormat> getAllRelationshipTypes() {
-        Either<Map<String, RelationshipTypeDefinition>, JanusGraphOperationStatus> allRelationshipTypes =
-                relationshipTypeOperation.getAllRelationshipTypes();
+        Either<Map<String, RelationshipTypeDefinition>, JanusGraphOperationStatus> allRelationshipTypes = relationshipTypeOperation
+            .getAllRelationshipTypes();
         if (allRelationshipTypes.isRight()) {
             JanusGraphOperationStatus operationStatus = allRelationshipTypes.right().value();
             if (JanusGraphOperationStatus.NOT_FOUND == operationStatus) {
-                BeEcompErrorManager.getInstance().logInternalDataError("FetchRelationshipTypes", "Relationship types "
-                                + "are "
-                                + "not loaded",
-                        BeEcompErrorManager.ErrorSeverity.ERROR);
+                BeEcompErrorManager.getInstance().logInternalDataError("FetchRelationshipTypes", "Relationship types " + "are " + "not loaded",
+                    BeEcompErrorManager.ErrorSeverity.ERROR);
                 return Either.right(componentsUtils.getResponseFormat(ActionStatus.DATA_TYPE_CANNOT_BE_EMPTY));
             } else {
-                BeEcompErrorManager.getInstance().logInternalFlowError("FetchRelationshipTypes", "Failed to fetch "
-                                + "relationship types",
-                        BeEcompErrorManager.ErrorSeverity.ERROR);
+                BeEcompErrorManager.getInstance().logInternalFlowError("FetchRelationshipTypes", "Failed to fetch " + "relationship types",
+                    BeEcompErrorManager.ErrorSeverity.ERROR);
                 return Either.right(componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR));
             }
         }
         return Either.left(allRelationshipTypes.left().value());
     }
-
 }
index 993d013..6e4d554 100644 (file)
  * See the License for the specific language governing permissions and
  * limitations under the License.
  */
-
 package org.openecomp.sdc.be.components.impl;
 
 import fj.data.Either;
+import java.util.List;
+import java.util.Map;
 import org.apache.commons.lang3.tuple.ImmutablePair;
 import org.openecomp.sdc.be.components.impl.CommonImportManager.ElementTypeEnum;
 import org.openecomp.sdc.be.dao.api.ActionStatus;
@@ -29,9 +30,6 @@ import org.openecomp.sdc.exception.ResponseFormat;
 import org.springframework.beans.factory.annotation.Autowired;
 import org.springframework.stereotype.Component;
 
-import java.util.List;
-import java.util.Map;
-
 @Component("relationshipTypeImportManager")
 public class RelationshipTypeImportManager {
 
@@ -40,73 +38,62 @@ public class RelationshipTypeImportManager {
     private final ComponentsUtils componentsUtils;
 
     @Autowired
-    public RelationshipTypeImportManager(RelationshipTypeOperation relationshipTypeOperation,
-        CommonImportManager commonImportManager, ComponentsUtils componentsUtils) {
+    public RelationshipTypeImportManager(RelationshipTypeOperation relationshipTypeOperation, CommonImportManager commonImportManager,
+                                         ComponentsUtils componentsUtils) {
         this.relationshipTypeOperation = relationshipTypeOperation;
         this.commonImportManager = commonImportManager;
         this.componentsUtils = componentsUtils;
     }
 
-    public Either<List<ImmutablePair<RelationshipTypeDefinition, Boolean>>, ResponseFormat> createRelationshipTypes(
-            String relationshipYml) {
+    public Either<List<ImmutablePair<RelationshipTypeDefinition, Boolean>>, ResponseFormat> createRelationshipTypes(String relationshipYml) {
         return createRelationshipTypes(relationshipYml, false);
     }
 
-    private Either<List<ImmutablePair<RelationshipTypeDefinition, Boolean>>, ResponseFormat> createRelationshipTypes(
-            String relationshipTypeYml, boolean inTransaction) {
-        return commonImportManager.createElementTypes(relationshipTypeYml,
-                relationshipTypesFromYml -> createRelationshipTypesFromYml(relationshipTypeYml),
-                relationshipTypesToCreate -> createRelationshipTypesByDao(relationshipTypesToCreate,
-                        inTransaction), ElementTypeEnum.RELATIONSHIP_TYPE);
+    private Either<List<ImmutablePair<RelationshipTypeDefinition, Boolean>>, ResponseFormat> createRelationshipTypes(String relationshipTypeYml,
+                                                                                                                     boolean inTransaction) {
+        return commonImportManager
+            .createElementTypes(relationshipTypeYml, relationshipTypesFromYml -> createRelationshipTypesFromYml(relationshipTypeYml),
+                relationshipTypesToCreate -> createRelationshipTypesByDao(relationshipTypesToCreate, inTransaction),
+                ElementTypeEnum.RELATIONSHIP_TYPE);
     }
 
-    private Either<List<RelationshipTypeDefinition>, ActionStatus> createRelationshipTypesFromYml(
-            String relationshipTypeYml) {
-        return commonImportManager.createElementTypesFromYml(relationshipTypeYml,
-                this::createRelationshipType);
+    private Either<List<RelationshipTypeDefinition>, ActionStatus> createRelationshipTypesFromYml(String relationshipTypeYml) {
+        return commonImportManager.createElementTypesFromYml(relationshipTypeYml, this::createRelationshipType);
     }
 
     private Either<List<ImmutablePair<RelationshipTypeDefinition, Boolean>>, ResponseFormat> createRelationshipTypesByDao(
-            List<RelationshipTypeDefinition> relationshipTypesToCreate, boolean inTransaction) {
+        List<RelationshipTypeDefinition> relationshipTypesToCreate, boolean inTransaction) {
         return commonImportManager.createElementTypesByDao(relationshipTypesToCreate, this::validateRelationshipType,
-                relationshipType -> new ImmutablePair<>(ElementTypeEnum.RELATIONSHIP_TYPE, relationshipType.getType()),
-                relationshipTypeName -> relationshipTypeOperation.getRelationshipTypeByName(relationshipTypeName)
-                        .right().map(DaoStatusConverter::convertJanusGraphStatusToStorageStatus),
-                relationshipType -> relationshipTypeOperation.addRelationshipType(relationshipType, inTransaction),
-                (newRelationshipType, oldRelationshipType) -> relationshipTypeOperation
-                        .updateRelationshipType(newRelationshipType, oldRelationshipType, inTransaction));
+            relationshipType -> new ImmutablePair<>(ElementTypeEnum.RELATIONSHIP_TYPE, relationshipType.getType()),
+            relationshipTypeName -> relationshipTypeOperation.getRelationshipTypeByName(relationshipTypeName).right()
+                .map(DaoStatusConverter::convertJanusGraphStatusToStorageStatus),
+            relationshipType -> relationshipTypeOperation.addRelationshipType(relationshipType, inTransaction),
+            (newRelationshipType, oldRelationshipType) -> relationshipTypeOperation
+                .updateRelationshipType(newRelationshipType, oldRelationshipType, inTransaction));
     }
 
-
     private Either<ActionStatus, ResponseFormat> validateRelationshipType(RelationshipTypeDefinition relationshipType) {
         Either<ActionStatus, ResponseFormat> result = Either.left(ActionStatus.OK);
         if (relationshipType.getType() == null) {
-            ResponseFormat responseFormat =
-                    componentsUtils.getResponseFormat(ActionStatus.MISSING_RELATIONSHIP_TYPE, relationshipType.getType());
+            ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.MISSING_RELATIONSHIP_TYPE, relationshipType.getType());
             result = Either.right(responseFormat);
         }
         return result;
     }
 
-    private RelationshipTypeDefinition createRelationshipType(String relationshipTypeName,
-                                                              Map<String, Object> toscaJson) {
+    private RelationshipTypeDefinition createRelationshipType(String relationshipTypeName, Map<String, Object> toscaJson) {
         RelationshipTypeDefinition relationshipType = new RelationshipTypeDefinition();
-
         relationshipType.setType(relationshipTypeName);
-
         // Description
-        commonImportManager.setField(toscaJson, TypeUtils.ToscaTagNamesEnum.DESCRIPTION.getElementName(),
-                relationshipType::setDescription);
+        commonImportManager.setField(toscaJson, TypeUtils.ToscaTagNamesEnum.DESCRIPTION.getElementName(), relationshipType::setDescription);
         // Derived From
-        commonImportManager.setField(toscaJson, TypeUtils.ToscaTagNamesEnum.DERIVED_FROM.getElementName(),
-                relationshipType::setDerivedFrom);
+        commonImportManager.setField(toscaJson, TypeUtils.ToscaTagNamesEnum.DERIVED_FROM.getElementName(), relationshipType::setDerivedFrom);
         // Properties
         commonImportManager.setPropertiesMap(toscaJson, relationshipType::setProperties);
         //valid-target-types
-        if(toscaJson.get("valid_target_types") instanceof List)
+        if (toscaJson.get("valid_target_types") instanceof List) {
             relationshipType.setValidTargetTypes((List<String>) toscaJson.get("valid_target_types"));
-
+        }
         return relationshipType;
     }
-
 }
index f3aca56..e5d7047 100644 (file)
  * See the License for the specific language governing permissions and
  * limitations under the License.
  */
-
 package org.openecomp.sdc.be.components.impl;
 
 import fj.data.Either;
+import java.util.ArrayList;
+import java.util.Collection;
+import java.util.Collections;
+import java.util.List;
+import java.util.Map;
+import java.util.Objects;
+import java.util.Optional;
+import java.util.UUID;
+import java.util.stream.Collectors;
 import org.apache.commons.collections.CollectionUtils;
 import org.apache.commons.lang.StringUtils;
 import org.openecomp.sdc.be.components.impl.exceptions.ComponentException;
@@ -41,39 +49,23 @@ import org.slf4j.LoggerFactory;
 import org.springframework.beans.factory.annotation.Autowired;
 import org.springframework.stereotype.Component;
 
-import java.util.ArrayList;
-import java.util.Collection;
-import java.util.Collections;
-import java.util.List;
-import java.util.Map;
-import java.util.Objects;
-import java.util.Optional;
-import java.util.UUID;
-import java.util.stream.Collectors;
-
 @Component("requirementBusinessLogic")
 public class RequirementBusinessLogic extends BaseBusinessLogic {
+
     private static final Logger LOGGER = LoggerFactory.getLogger(RequirementBusinessLogic.class);
-    private static final String FAILED_TO_LOCK_COMPONENT_RESPONSE_IS
-            = "Failed to lock component {}. Response is {}";
+    private static final String FAILED_TO_LOCK_COMPONENT_RESPONSE_IS = "Failed to lock component {}. Response is {}";
     private static final String DELETE_REQUIREMENTS = "deleteRequirement";
     private static final String GET_REQUIREMENTS = "getRequirements";
-    private static final String EXCEPTION_OCCURRED_DURING_REQUIREMENTS
-            = "Exception occurred during {}. Response is {}";
-
+    private static final String EXCEPTION_OCCURRED_DURING_REQUIREMENTS = "Exception occurred during {}. Response is {}";
     private RequirementOperation requirementOperation;
     private RequirementValidation requirementValidation;
 
     @Autowired
-    public RequirementBusinessLogic(IElementOperation elementDao,
-        IGroupOperation groupOperation,
-        IGroupInstanceOperation groupInstanceOperation,
-        IGroupTypeOperation groupTypeOperation,
-        InterfaceOperation interfaceOperation,
-        InterfaceLifecycleOperation interfaceLifecycleTypeOperation,
-        ArtifactsOperations artifactToscaOperation) {
-        super(elementDao, groupOperation, groupInstanceOperation, groupTypeOperation,
-            interfaceOperation, interfaceLifecycleTypeOperation, artifactToscaOperation);
+    public RequirementBusinessLogic(IElementOperation elementDao, IGroupOperation groupOperation, IGroupInstanceOperation groupInstanceOperation,
+                                    IGroupTypeOperation groupTypeOperation, InterfaceOperation interfaceOperation,
+                                    InterfaceLifecycleOperation interfaceLifecycleTypeOperation, ArtifactsOperations artifactToscaOperation) {
+        super(elementDao, groupOperation, groupInstanceOperation, groupTypeOperation, interfaceOperation, interfaceLifecycleTypeOperation,
+            artifactToscaOperation);
     }
 
     @Autowired
@@ -86,63 +78,52 @@ public class RequirementBusinessLogic extends BaseBusinessLogic {
         this.requirementValidation = requirementValidation;
     }
 
-    public Either<List<RequirementDefinition>, ResponseFormat> createRequirements(
-            String componentId, List<RequirementDefinition> requirementDefinitions,
-            User user, String errorContext, boolean lock) {
+    public Either<List<RequirementDefinition>, ResponseFormat> createRequirements(String componentId,
+                                                                                  List<RequirementDefinition> requirementDefinitions, User user,
+                                                                                  String errorContext, boolean lock) {
         validateUserExists(user.getUserId());
-        Either<org.openecomp.sdc.be.model.Component, ResponseFormat> componentEither
-                = getComponentDetails(componentId);
+        Either<org.openecomp.sdc.be.model.Component, ResponseFormat> componentEither = getComponentDetails(componentId);
         if (componentEither.isRight()) {
             return Either.right(componentEither.right().value());
         }
         org.openecomp.sdc.be.model.Component storedComponent = componentEither.left().value();
-
         Either<Boolean, ResponseFormat> requirementsValidationEither = requirementValidation
-                .validateRequirements(requirementDefinitions, storedComponent, false);
+            .validateRequirements(requirementDefinitions, storedComponent, false);
         if (requirementsValidationEither.isRight()) {
             return Either.right(requirementsValidationEither.right().value());
         }
-
-        Either<Boolean, ResponseFormat> lockResult = lockComponentResult(lock,
-                storedComponent, errorContext);
+        Either<Boolean, ResponseFormat> lockResult = lockComponentResult(lock, storedComponent, errorContext);
         if (lockResult.isRight()) {
             return Either.right(lockResult.right().value());
         }
-
         try {
             Either<List<RequirementDefinition>, StorageOperationStatus> result;
             List<RequirementDefinition> requirementsListStoredInComponent = null;
-            Map<String, List<RequirementDefinition>> storedComponentRequirements
-                    = storedComponent.getRequirements();
+            Map<String, List<RequirementDefinition>> storedComponentRequirements = storedComponent.getRequirements();
             if (org.apache.commons.collections.MapUtils.isNotEmpty(storedComponentRequirements)) {
                 RequirementDefinition requirementDefinitionToGetType = requirementDefinitions.get(0);
-                if(Objects.isNull(requirementDefinitionToGetType)) {
-                     return Either.right(componentsUtils.getResponseFormat(ActionStatus.INVALID_CONTENT));
+                if (Objects.isNull(requirementDefinitionToGetType)) {
+                    return Either.right(componentsUtils.getResponseFormat(ActionStatus.INVALID_CONTENT));
                 }
-                requirementsListStoredInComponent
-                        = getRequirementStoredInComponentByType(requirementDefinitionToGetType
-                        .getCapability(), storedComponentRequirements);
+                requirementsListStoredInComponent = getRequirementStoredInComponentByType(requirementDefinitionToGetType.getCapability(),
+                    storedComponentRequirements);
             }
             List<RequirementDefinition> requirementsToReturn;
-            if (org.apache.commons.collections.CollectionUtils
-                    .isNotEmpty(requirementsListStoredInComponent)) {
+            if (org.apache.commons.collections.CollectionUtils.isNotEmpty(requirementsListStoredInComponent)) {
                 List<RequirementDefinition> requirementDefToCreate = requirementDefinitions.stream()
-                        .map(requirementDefinition -> initiateNewRequirement(storedComponent, requirementDefinition))
-                        .collect(Collectors.toList());
+                    .map(requirementDefinition -> initiateNewRequirement(storedComponent, requirementDefinition)).collect(Collectors.toList());
                 requirementsToReturn = requirementDefToCreate;
                 requirementDefToCreate.addAll(requirementsListStoredInComponent);
                 result = requirementOperation.updateRequirement(componentId, requirementDefToCreate);
             } else {
-                requirementsToReturn = requirementDefinitions.stream().map(requirementDefinition ->
-                        initiateNewRequirement(storedComponent, requirementDefinition))
-                        .collect(Collectors.toList());
+                requirementsToReturn = requirementDefinitions.stream()
+                    .map(requirementDefinition -> initiateNewRequirement(storedComponent, requirementDefinition)).collect(Collectors.toList());
                 result = requirementOperation.addRequirement(componentId, requirementsToReturn);
             }
             if (result.isRight()) {
                 janusGraphDao.rollback();
-                return Either.right(componentsUtils.getResponseFormat(
-                        componentsUtils.convertFromStorageResponse(result.right().value(),
-                                storedComponent.getComponentType()), ""));
+                return Either.right(componentsUtils
+                    .getResponseFormat(componentsUtils.convertFromStorageResponse(result.right().value(), storedComponent.getComponentType()), ""));
             }
             janusGraphDao.commit();
             return Either.left(requirementsToReturn);
@@ -152,75 +133,63 @@ public class RequirementBusinessLogic extends BaseBusinessLogic {
             return Either.right(componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR));
         } finally {
             if (lockResult.isLeft() && lockResult.left().value()) {
-                graphLockOperation.unlockComponent(storedComponent.getUniqueId(),
-                        NodeTypeEnum.getByNameIgnoreCase(storedComponent.getComponentType().getValue()));
+                graphLockOperation
+                    .unlockComponent(storedComponent.getUniqueId(), NodeTypeEnum.getByNameIgnoreCase(storedComponent.getComponentType().getValue()));
             }
         }
     }
 
-    public Either<List<RequirementDefinition>, ResponseFormat> updateRequirements(
-            String componentId, List<RequirementDefinition> requirementDefinitions,
-            User user, String errorContext, boolean lock) {
+    public Either<List<RequirementDefinition>, ResponseFormat> updateRequirements(String componentId,
+                                                                                  List<RequirementDefinition> requirementDefinitions, User user,
+                                                                                  String errorContext, boolean lock) {
         validateUserExists(user.getUserId());
-        Either<org.openecomp.sdc.be.model.Component, ResponseFormat> componentEither
-                = getComponentDetails(componentId);
+        Either<org.openecomp.sdc.be.model.Component, ResponseFormat> componentEither = getComponentDetails(componentId);
         if (componentEither.isRight()) {
             return Either.right(componentEither.right().value());
         }
         org.openecomp.sdc.be.model.Component storedComponent = componentEither.left().value();
-
         Either<Boolean, ResponseFormat> requirementsValidationEither = requirementValidation
-                .validateRequirements(requirementDefinitions, storedComponent, true);
+            .validateRequirements(requirementDefinitions, storedComponent, true);
         if (requirementsValidationEither.isRight()) {
             return Either.right(requirementsValidationEither.right().value());
         }
-
-        Either<Boolean, ResponseFormat> lockResult = lockComponentResult(lock,
-                storedComponent, errorContext);
+        Either<Boolean, ResponseFormat> lockResult = lockComponentResult(lock, storedComponent, errorContext);
         if (lockResult.isRight()) {
             return Either.right(lockResult.right().value());
         }
         try {
             Either<List<RequirementDefinition>, StorageOperationStatus> result;
             List<RequirementDefinition> requirementsListStoredInComponent = null;
-            Map<String, List<RequirementDefinition>> storedComponentRequirements
-                    = storedComponent.getRequirements();
+            Map<String, List<RequirementDefinition>> storedComponentRequirements = storedComponent.getRequirements();
             if (org.apache.commons.collections.MapUtils.isNotEmpty(storedComponentRequirements)) {
                 RequirementDefinition requirementDefinitionToGetType = requirementDefinitions.get(0);
-                if(Objects.isNull(requirementDefinitionToGetType)) {
+                if (Objects.isNull(requirementDefinitionToGetType)) {
                     return Either.right(componentsUtils.getResponseFormat(ActionStatus.INVALID_CONTENT));
                 }
-                requirementsListStoredInComponent
-                        = getRequirementStoredInComponentByType(requirementDefinitionToGetType
-                        .getCapability(), storedComponentRequirements);
+                requirementsListStoredInComponent = getRequirementStoredInComponentByType(requirementDefinitionToGetType.getCapability(),
+                    storedComponentRequirements);
             }
             List<RequirementDefinition> requirementsToReturn = null;
-            if (org.apache.commons.collections.CollectionUtils
-                    .isNotEmpty(requirementsListStoredInComponent)) {
+            if (org.apache.commons.collections.CollectionUtils.isNotEmpty(requirementsListStoredInComponent)) {
                 List<RequirementDefinition> requirementDefToUpdate = new ArrayList<>();
-                if (requirementDefinitions.stream().anyMatch(requirementDefinition ->
-                        isRequirementUsedInServiceComposition(requirementDefinition, storedComponent))) {
+                if (requirementDefinitions.stream()
+                    .anyMatch(requirementDefinition -> isRequirementUsedInServiceComposition(requirementDefinition, storedComponent))) {
                     LOGGER.error("Requirement can't be edited, since it is used in service composition");
-                    return Either.right(componentsUtils.getResponseFormat(ActionStatus
-                            .REQUIREMENT_UPDATE_NOT_ALLOWED_USED_IN_COMPOSITION));
+                    return Either.right(componentsUtils.getResponseFormat(ActionStatus.REQUIREMENT_UPDATE_NOT_ALLOWED_USED_IN_COMPOSITION));
                 }
                 for (RequirementDefinition requirementDefinitionToUpdate : requirementDefinitions) {
                     requirementsToReturn = requirementsListStoredInComponent.stream()
-                            .filter(reqToUpdate -> reqToUpdate.getUniqueId()
-                                    .equals(requirementDefinitionToUpdate.getUniqueId()))
-                            .map(requirementDefinition -> updateRequirement(requirementDefinition,
-                                    requirementDefinitionToUpdate)).collect(Collectors.toList());
-                    requirementsListStoredInComponent.removeIf(reqToUpdate ->
-                            reqToUpdate.getUniqueId().equals(requirementDefinitionToUpdate.getUniqueId()));
-
+                        .filter(reqToUpdate -> reqToUpdate.getUniqueId().equals(requirementDefinitionToUpdate.getUniqueId()))
+                        .map(requirementDefinition -> updateRequirement(requirementDefinition, requirementDefinitionToUpdate))
+                        .collect(Collectors.toList());
+                    requirementsListStoredInComponent
+                        .removeIf(reqToUpdate -> reqToUpdate.getUniqueId().equals(requirementDefinitionToUpdate.getUniqueId()));
                     if (CollectionUtils.isNotEmpty(requirementsToReturn)) {
                         requirementsListStoredInComponent.addAll(requirementsToReturn);
                         requirementDefToUpdate.addAll(requirementsListStoredInComponent);
                     } else {
-                        Either<List<RequirementDefinition>, ResponseFormat> updateCapTypeEither
-                                = handleUpdateRequirementCapabilityWhenNewCapabilityExist(storedComponent,
-                                storedComponentRequirements,
-                                requirementsToReturn, requirementDefinitionToUpdate);
+                        Either<List<RequirementDefinition>, ResponseFormat> updateCapTypeEither = handleUpdateRequirementCapabilityWhenNewCapabilityExist(
+                            storedComponent, storedComponentRequirements, requirementsToReturn, requirementDefinitionToUpdate);
                         if (updateCapTypeEither.isRight()) {
                             return Either.right(updateCapTypeEither.right().value());
                         }
@@ -229,22 +198,19 @@ public class RequirementBusinessLogic extends BaseBusinessLogic {
                 }
                 result = requirementOperation.updateRequirement(componentId, requirementDefToUpdate);
             } else {
-                Either<List<RequirementDefinition>, ResponseFormat> requirementDefinitionToDelete
-                        = handleRequirementCapabilityUpdateWhenNewCapabilityNotExist(requirementDefinitions,
-                        storedComponent, storedComponentRequirements);
+                Either<List<RequirementDefinition>, ResponseFormat> requirementDefinitionToDelete = handleRequirementCapabilityUpdateWhenNewCapabilityNotExist(
+                    requirementDefinitions, storedComponent, storedComponentRequirements);
                 if (requirementDefinitionToDelete != null) {
                     return requirementDefinitionToDelete;
                 }
-                requirementsToReturn = requirementDefinitions.stream().map(requirementDefinition ->
-                        initiateNewRequirement(storedComponent, requirementDefinition))
-                        .collect(Collectors.toList());
+                requirementsToReturn = requirementDefinitions.stream()
+                    .map(requirementDefinition -> initiateNewRequirement(storedComponent, requirementDefinition)).collect(Collectors.toList());
                 result = requirementOperation.addRequirement(componentId, requirementsToReturn);
             }
             if (result.isRight()) {
                 janusGraphDao.rollback();
-                return Either.right(componentsUtils.getResponseFormat(
-                        componentsUtils.convertFromStorageResponse(result.right().value(),
-                                storedComponent.getComponentType()), ""));
+                return Either.right(componentsUtils
+                    .getResponseFormat(componentsUtils.convertFromStorageResponse(result.right().value(), storedComponent.getComponentType()), ""));
             }
             janusGraphDao.commit();
             return Either.left(requirementsToReturn);
@@ -254,70 +220,55 @@ public class RequirementBusinessLogic extends BaseBusinessLogic {
             return Either.right(componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR));
         } finally {
             if (lockResult.isLeft() && lockResult.left().value()) {
-                graphLockOperation.unlockComponent(storedComponent.getUniqueId(),
-                        NodeTypeEnum.getByNameIgnoreCase(storedComponent.getComponentType().getValue()));
+                graphLockOperation
+                    .unlockComponent(storedComponent.getUniqueId(), NodeTypeEnum.getByNameIgnoreCase(storedComponent.getComponentType().getValue()));
             }
         }
     }
 
     private Either<List<RequirementDefinition>, ResponseFormat> handleUpdateRequirementCapabilityWhenNewCapabilityExist(
-            org.openecomp.sdc.be.model.Component storedComponent,
-            Map<String, List<RequirementDefinition>> storedComponentRequirements,
-            List<RequirementDefinition> requirementsToReturn,
-            RequirementDefinition requirementDefinitionToUpdate) {
+        org.openecomp.sdc.be.model.Component storedComponent, Map<String, List<RequirementDefinition>> storedComponentRequirements,
+        List<RequirementDefinition> requirementsToReturn, RequirementDefinition requirementDefinitionToUpdate) {
         List<RequirementDefinition> requirementsListStoredInComponent;
         List<RequirementDefinition> requirementDefsToCreateOrUpdate = new ArrayList<>();
-        Optional<RequirementDefinition> definitionOptional = storedComponentRequirements
-                .values().stream().flatMap(Collection::stream)
-                .filter(requirementDefinition -> requirementDefinition.getUniqueId()
-                        .equals(requirementDefinitionToUpdate.getUniqueId())).findAny();
+        Optional<RequirementDefinition> definitionOptional = storedComponentRequirements.values().stream().flatMap(Collection::stream)
+            .filter(requirementDefinition -> requirementDefinition.getUniqueId().equals(requirementDefinitionToUpdate.getUniqueId())).findAny();
         if (!definitionOptional.isPresent()) {
-            return Either.right(componentsUtils.getResponseFormat(
-                    ActionStatus.REQUIREMENT_NOT_FOUND, storedComponent.getUniqueId()));
+            return Either.right(componentsUtils.getResponseFormat(ActionStatus.REQUIREMENT_NOT_FOUND, storedComponent.getUniqueId()));
         }
         RequirementDefinition requirementDefinitionToDelete = definitionOptional.get();
-
-        requirementsListStoredInComponent = getRequirementStoredInComponentByType(
-                requirementDefinitionToUpdate.getCapability(), storedComponentRequirements);
-        Either<List<RequirementDefinition>, StorageOperationStatus> deleteRequirementEither
-                = deleteRequirement(storedComponent, storedComponentRequirements, requirementDefinitionToDelete);
+        requirementsListStoredInComponent = getRequirementStoredInComponentByType(requirementDefinitionToUpdate.getCapability(),
+            storedComponentRequirements);
+        Either<List<RequirementDefinition>, StorageOperationStatus> deleteRequirementEither = deleteRequirement(storedComponent,
+            storedComponentRequirements, requirementDefinitionToDelete);
         if (deleteRequirementEither.isRight()) {
             janusGraphDao.rollback();
             return Either.right(componentsUtils.getResponseFormat(deleteRequirementEither.right().value()));
         }
         requirementsToReturn.add(initiateNewRequirement(storedComponent, requirementDefinitionToUpdate));
-
         requirementDefsToCreateOrUpdate.addAll(requirementsToReturn);
         requirementDefsToCreateOrUpdate.addAll(requirementsListStoredInComponent);
         return Either.left(requirementDefsToCreateOrUpdate);
     }
 
     private Either<List<RequirementDefinition>, ResponseFormat> handleRequirementCapabilityUpdateWhenNewCapabilityNotExist(
-            List<RequirementDefinition> requirementDefinitions,
-            org.openecomp.sdc.be.model.Component storedComponent,
-            Map<String, List<RequirementDefinition>> storedComponentRequirements) {
+        List<RequirementDefinition> requirementDefinitions, org.openecomp.sdc.be.model.Component storedComponent,
+        Map<String, List<RequirementDefinition>> storedComponentRequirements) {
         for (RequirementDefinition requirementDefinitionToUpdate : requirementDefinitions) {
-
-            Optional<RequirementDefinition> definitionOptional = storedComponentRequirements
-                    .values().stream().flatMap(Collection::stream)
-                    .filter(requirementDefinition -> requirementDefinition.getUniqueId()
-                            .equals(requirementDefinitionToUpdate.getUniqueId())).findAny();
+            Optional<RequirementDefinition> definitionOptional = storedComponentRequirements.values().stream().flatMap(Collection::stream)
+                .filter(requirementDefinition -> requirementDefinition.getUniqueId().equals(requirementDefinitionToUpdate.getUniqueId())).findAny();
             if (!definitionOptional.isPresent()) {
-                return Either.right(componentsUtils.getResponseFormat(
-                        ActionStatus.REQUIREMENT_NOT_FOUND, storedComponent.getUniqueId()));
+                return Either.right(componentsUtils.getResponseFormat(ActionStatus.REQUIREMENT_NOT_FOUND, storedComponent.getUniqueId()));
             }
             RequirementDefinition requirementDefinitionToDelete = definitionOptional.get();
-            Boolean isRequirementUsedInServiceComposition
-                    = isRequirementUsedInServiceComposition(requirementDefinitionToDelete, storedComponent);
+            Boolean isRequirementUsedInServiceComposition = isRequirementUsedInServiceComposition(requirementDefinitionToDelete, storedComponent);
             if (isRequirementUsedInServiceComposition) {
-                LOGGER.error("Requirement {} can't be edited, since it is used in service composition",
-                        requirementDefinitionToDelete.getUniqueId());
-                return Either.right(componentsUtils.getResponseFormat(ActionStatus
-                                .REQUIREMENT_UPDATE_NOT_ALLOWED_USED_IN_COMPOSITION,
-                        requirementDefinitionToDelete.getName()));
+                LOGGER.error("Requirement {} can't be edited, since it is used in service composition", requirementDefinitionToDelete.getUniqueId());
+                return Either.right(componentsUtils
+                    .getResponseFormat(ActionStatus.REQUIREMENT_UPDATE_NOT_ALLOWED_USED_IN_COMPOSITION, requirementDefinitionToDelete.getName()));
             }
-            Either<List<RequirementDefinition>, StorageOperationStatus> deleteRequirementEither
-                    = deleteRequirement(storedComponent, storedComponentRequirements, requirementDefinitionToDelete);
+            Either<List<RequirementDefinition>, StorageOperationStatus> deleteRequirementEither = deleteRequirement(storedComponent,
+                storedComponentRequirements, requirementDefinitionToDelete);
             if (deleteRequirementEither.isRight()) {
                 janusGraphDao.rollback();
                 return Either.right(componentsUtils.getResponseFormat(deleteRequirementEither.right().value()));
@@ -326,30 +277,26 @@ public class RequirementBusinessLogic extends BaseBusinessLogic {
         return null;
     }
 
-    public Either<RequirementDefinition, ResponseFormat> getRequirement(String componentId,
-                                                                        String requirementIdToGet, User user, boolean lock) {
+    public Either<RequirementDefinition, ResponseFormat> getRequirement(String componentId, String requirementIdToGet, User user, boolean lock) {
         validateUserExists(user.getUserId());
         Either<org.openecomp.sdc.be.model.Component, ResponseFormat> componentEither = getComponentDetails(componentId);
         if (componentEither.isRight()) {
             return Either.right(componentEither.right().value());
         }
         org.openecomp.sdc.be.model.Component storedComponent = componentEither.left().value();
-
         Either<Boolean, ResponseFormat> lockResult = lockComponentResult(lock, storedComponent, GET_REQUIREMENTS);
         if (lockResult.isRight()) {
             return Either.right(lockResult.right().value());
         }
         try {
-
-            List<RequirementDefinition> requirementDefinitions = storedComponent.getRequirements().values().stream()
-                    .flatMap(Collection::stream).collect(Collectors.toList());
+            List<RequirementDefinition> requirementDefinitions = storedComponent.getRequirements().values().stream().flatMap(Collection::stream)
+                .collect(Collectors.toList());
             if (requirementDefinitions.isEmpty()) {
                 return Either.right(componentsUtils.getResponseFormat(ActionStatus.REQUIREMENT_NOT_FOUND, componentId));
             }
-
             RequirementDefinition requirementDefinitionToReturn;
             Optional<RequirementDefinition> requirementDefinitionOptional = requirementDefinitions.stream()
-                    .filter(requirementDefinition -> requirementDefinition.getUniqueId().equals(requirementIdToGet)).findAny();
+                .filter(requirementDefinition -> requirementDefinition.getUniqueId().equals(requirementIdToGet)).findAny();
             if (requirementDefinitionOptional.isPresent()) {
                 requirementDefinitionToReturn = requirementDefinitionOptional.get();
             } else {
@@ -361,61 +308,48 @@ public class RequirementBusinessLogic extends BaseBusinessLogic {
             return Either.right(componentsUtils.getResponseFormat(ActionStatus.REQUIREMENT_NOT_FOUND, componentId));
         } finally {
             if (lockResult.isLeft() && lockResult.left().value()) {
-                graphLockOperation.unlockComponent(storedComponent.getUniqueId(),
-                        NodeTypeEnum.getByNameIgnoreCase(storedComponent.getComponentType().getValue()));
+                graphLockOperation
+                    .unlockComponent(storedComponent.getUniqueId(), NodeTypeEnum.getByNameIgnoreCase(storedComponent.getComponentType().getValue()));
             }
         }
     }
 
-    public Either<RequirementDefinition, ResponseFormat> deleteRequirement(String componentId,
-                                                                           String requirementIdToDelete,
-                                                                           User user, boolean lock) {
+    public Either<RequirementDefinition, ResponseFormat> deleteRequirement(String componentId, String requirementIdToDelete, User user,
+                                                                           boolean lock) {
         validateUserExists(user.getUserId());
-        Either<org.openecomp.sdc.be.model.Component, ResponseFormat> componentEither
-                = getComponentDetails(componentId);
+        Either<org.openecomp.sdc.be.model.Component, ResponseFormat> componentEither = getComponentDetails(componentId);
         if (componentEither.isRight()) {
             return Either.right(componentEither.right().value());
         }
         org.openecomp.sdc.be.model.Component storedComponent = componentEither.left().value();
-
         Either<Boolean, ResponseFormat> lockResult = lockComponentResult(lock, storedComponent, DELETE_REQUIREMENTS);
         if (lockResult.isRight()) {
             return Either.right(lockResult.right().value());
         }
-
         try {
             Map<String, List<RequirementDefinition>> storedComponentRequirements = storedComponent.getRequirements();
             if (storedComponentRequirements.isEmpty()) {
                 return Either.right(componentsUtils.getResponseFormat(ActionStatus.REQUIREMENT_NOT_FOUND, componentId));
             }
-
-            Optional<RequirementDefinition> definitionOptional = storedComponentRequirements
-                    .values().stream().flatMap(Collection::stream)
-                    .filter(requirementDefinition -> requirementDefinition.getUniqueId()
-                            .equals(requirementIdToDelete)).findAny();
+            Optional<RequirementDefinition> definitionOptional = storedComponentRequirements.values().stream().flatMap(Collection::stream)
+                .filter(requirementDefinition -> requirementDefinition.getUniqueId().equals(requirementIdToDelete)).findAny();
             if (!definitionOptional.isPresent()) {
                 return Either.right(componentsUtils.getResponseFormat(ActionStatus.REQUIREMENT_NOT_FOUND, componentId));
             }
             RequirementDefinition requirementDefinitionToDelete = definitionOptional.get();
-
-            Boolean isRequirementUsedInServiceComposition
-                    = isRequirementUsedInServiceComposition(requirementDefinitionToDelete, storedComponent);
+            Boolean isRequirementUsedInServiceComposition = isRequirementUsedInServiceComposition(requirementDefinitionToDelete, storedComponent);
             if (isRequirementUsedInServiceComposition) {
-                LOGGER.error("Requirement {} can't be deleted, since it is used in service composition",
-                        requirementDefinitionToDelete.getUniqueId());
-                return Either.right(componentsUtils.getResponseFormat(ActionStatus
-                                .CAPABILITY_DELETION_NOT_ALLOWED_USED_IN_COMPOSITION,
-                        requirementDefinitionToDelete.getName()));
+                LOGGER.error("Requirement {} can't be deleted, since it is used in service composition", requirementDefinitionToDelete.getUniqueId());
+                return Either.right(componentsUtils
+                    .getResponseFormat(ActionStatus.CAPABILITY_DELETION_NOT_ALLOWED_USED_IN_COMPOSITION, requirementDefinitionToDelete.getName()));
             }
-
-            Either<List<RequirementDefinition>, StorageOperationStatus> result
-                    = deleteRequirement(storedComponent, storedComponentRequirements, requirementDefinitionToDelete);
+            Either<List<RequirementDefinition>, StorageOperationStatus> result = deleteRequirement(storedComponent, storedComponentRequirements,
+                requirementDefinitionToDelete);
             if (result.isRight()) {
                 janusGraphDao.rollback();
-                LOGGER.error("Failed to delete requirement  from component {}. Response is {}",
-                        storedComponent.getName(), result.right().value());
-                return Either.right(componentsUtils.getResponseFormat(componentsUtils
-                        .convertFromStorageResponse(result.right().value(), storedComponent.getComponentType())));
+                LOGGER.error("Failed to delete requirement  from component {}. Response is {}", storedComponent.getName(), result.right().value());
+                return Either.right(componentsUtils
+                    .getResponseFormat(componentsUtils.convertFromStorageResponse(result.right().value(), storedComponent.getComponentType())));
             }
             janusGraphDao.commit();
             return Either.left(requirementDefinitionToDelete);
@@ -425,37 +359,33 @@ public class RequirementBusinessLogic extends BaseBusinessLogic {
             return Either.right(componentsUtils.getResponseFormat(ActionStatus.REQUIREMENT_NOT_FOUND));
         } finally {
             if (lockResult.isLeft() && lockResult.left().value()) {
-                graphLockOperation.unlockComponent(storedComponent.getUniqueId(),
-                        NodeTypeEnum.getByNameIgnoreCase(storedComponent.getComponentType().getValue()));
+                graphLockOperation
+                    .unlockComponent(storedComponent.getUniqueId(), NodeTypeEnum.getByNameIgnoreCase(storedComponent.getComponentType().getValue()));
             }
         }
     }
 
-    private Either<List<RequirementDefinition>, StorageOperationStatus> deleteRequirement(
-            org.openecomp.sdc.be.model.Component storedComponent, Map<String,
-            List<RequirementDefinition>> storedComponentRequirements,
-            RequirementDefinition requirementDefinitionToDelete) {
-        List<RequirementDefinition> requirementStoredInComponentByType =
-                getRequirementStoredInComponentByType(requirementDefinitionToDelete.getCapability(),
-                        storedComponentRequirements);
-        if(requirementStoredInComponentByType == null) {
+    private Either<List<RequirementDefinition>, StorageOperationStatus> deleteRequirement(org.openecomp.sdc.be.model.Component storedComponent,
+                                                                                          Map<String, List<RequirementDefinition>> storedComponentRequirements,
+                                                                                          RequirementDefinition requirementDefinitionToDelete) {
+        List<RequirementDefinition> requirementStoredInComponentByType = getRequirementStoredInComponentByType(
+            requirementDefinitionToDelete.getCapability(), storedComponentRequirements);
+        if (requirementStoredInComponentByType == null) {
             return Either.right(StorageOperationStatus.BAD_REQUEST);
         }
-        requirementStoredInComponentByType.removeIf(requirementDefinition ->
-                requirementDefinition.getUniqueId().equals(requirementDefinitionToDelete.getUniqueId()));
+        requirementStoredInComponentByType
+            .removeIf(requirementDefinition -> requirementDefinition.getUniqueId().equals(requirementDefinitionToDelete.getUniqueId()));
         Either<List<RequirementDefinition>, StorageOperationStatus> result;
         if (requirementStoredInComponentByType.isEmpty()) {
-
-            StorageOperationStatus operationStatus = requirementOperation.deleteRequirements(storedComponent,
-                    requirementDefinitionToDelete.getCapability());
+            StorageOperationStatus operationStatus = requirementOperation
+                .deleteRequirements(storedComponent, requirementDefinitionToDelete.getCapability());
             if (operationStatus.equals(StorageOperationStatus.OK)) {
                 result = Either.left(Collections.singletonList(requirementDefinitionToDelete));
             } else {
                 result = Either.right(operationStatus);
             }
         } else {
-            result = requirementOperation.updateRequirement(storedComponent.getUniqueId(),
-                    requirementStoredInComponentByType);
+            result = requirementOperation.updateRequirement(storedComponent.getUniqueId(), requirementStoredInComponentByType);
         }
         return result;
     }
@@ -463,8 +393,8 @@ public class RequirementBusinessLogic extends BaseBusinessLogic {
     private Either<org.openecomp.sdc.be.model.Component, ResponseFormat> getComponentDetails(String componentId) {
         ComponentParametersView filter = new ComponentParametersView(true);
         filter.setIgnoreRequirements(false);
-        Either<org.openecomp.sdc.be.model.Component, StorageOperationStatus> componentStorageOperationStatusEither
-                = toscaOperationFacade.getToscaElement(componentId, filter);
+        Either<org.openecomp.sdc.be.model.Component, StorageOperationStatus> componentStorageOperationStatusEither = toscaOperationFacade
+            .getToscaElement(componentId, filter);
         if (componentStorageOperationStatusEither.isRight()) {
             StorageOperationStatus errorStatus = componentStorageOperationStatusEither.right().value();
             LOGGER.error("Failed to fetch component information by component id {}, Response is {}", componentId, errorStatus);
@@ -473,15 +403,12 @@ public class RequirementBusinessLogic extends BaseBusinessLogic {
         return Either.left(componentStorageOperationStatusEither.left().value());
     }
 
-    private Either<Boolean, ResponseFormat> lockComponentResult(boolean lock,
-                                                                org.openecomp.sdc.be.model.Component component,
-                                                                String action) {
+    private Either<Boolean, ResponseFormat> lockComponentResult(boolean lock, org.openecomp.sdc.be.model.Component component, String action) {
         if (lock) {
-            try{
-            lockComponent(component.getUniqueId(), component, action);
-            } catch (ComponentException e){
-                LOGGER.debug(FAILED_TO_LOCK_COMPONENT_RESPONSE_IS, component.getName(),
-                        e.getMessage());
+            try {
+                lockComponent(component.getUniqueId(), component, action);
+            } catch (ComponentException e) {
+                LOGGER.debug(FAILED_TO_LOCK_COMPONENT_RESPONSE_IS, component.getName(), e.getMessage());
                 janusGraphDao.rollback();
                 throw e;
             }
@@ -489,30 +416,29 @@ public class RequirementBusinessLogic extends BaseBusinessLogic {
         return Either.left(true);
     }
 
-    private List<RequirementDefinition> getRequirementStoredInComponentByType(
-            String capabilityType, Map<String,
-            List<RequirementDefinition>> requirements) {
-
-        Optional<Map.Entry<String, List<RequirementDefinition>>> entryOptional
-                = requirements.entrySet().stream().filter(map -> map.getKey().equals(capabilityType)).findFirst();
+    private List<RequirementDefinition> getRequirementStoredInComponentByType(String capabilityType,
+                                                                              Map<String, List<RequirementDefinition>> requirements) {
+        Optional<Map.Entry<String, List<RequirementDefinition>>> entryOptional = requirements.entrySet().stream()
+            .filter(map -> map.getKey().equals(capabilityType)).findFirst();
         return entryOptional.map(Map.Entry::getValue).orElse(null);
-
     }
 
     private RequirementDefinition initiateNewRequirement(org.openecomp.sdc.be.model.Component component,
                                                          RequirementDefinition requirementDefinition) {
-        if (StringUtils.isEmpty(requirementDefinition.getUniqueId()))
+        if (StringUtils.isEmpty(requirementDefinition.getUniqueId())) {
             requirementDefinition.setUniqueId(UUID.randomUUID().toString());
-        if (StringUtils.isEmpty(requirementDefinition.getOwnerId()))
+        }
+        if (StringUtils.isEmpty(requirementDefinition.getOwnerId())) {
             requirementDefinition.setOwnerId(component.getUniqueId());
-        if (StringUtils.isEmpty(requirementDefinition.getOwnerName()))
+        }
+        if (StringUtils.isEmpty(requirementDefinition.getOwnerName())) {
             requirementDefinition.setOwnerName(component.getName());
+        }
         requirementDefinition.setLeftOccurrences(requirementDefinition.getMaxOccurrences());
         return requirementDefinition;
     }
 
-    private RequirementDefinition updateRequirement(RequirementDefinition storedRequirement,
-                                                    RequirementDefinition requirementToUpdate) {
+    private RequirementDefinition updateRequirement(RequirementDefinition storedRequirement, RequirementDefinition requirementToUpdate) {
         storedRequirement.setName(requirementToUpdate.getName());
         storedRequirement.setCapability(requirementToUpdate.getCapability());
         storedRequirement.setNode(requirementToUpdate.getNode());
@@ -524,15 +450,14 @@ public class RequirementBusinessLogic extends BaseBusinessLogic {
 
     private Boolean isRequirementUsedInServiceComposition(RequirementDefinition requirementDefinition,
                                                           org.openecomp.sdc.be.model.Component component) {
-        Either<List<org.openecomp.sdc.be.model.Component>, StorageOperationStatus> componentList
-                = toscaOperationFacade.getParentComponents(component.getUniqueId());
+        Either<List<org.openecomp.sdc.be.model.Component>, StorageOperationStatus> componentList = toscaOperationFacade
+            .getParentComponents(component.getUniqueId());
         if (componentList.isRight()) {
             return Boolean.FALSE;
         }
-        return componentList.left().value().stream()
-                .flatMap(parentComponent -> parentComponent.getComponentInstancesRelations()
-                        .stream()).flatMap(requirementCapabilityRelDef -> requirementCapabilityRelDef.getRelationships().stream())
-                .anyMatch(capabilityRequirementRelationship -> capabilityRequirementRelationship.getRelation()
-                        .getRequirementUid().equals(requirementDefinition.getUniqueId()));
+        return componentList.left().value().stream().flatMap(parentComponent -> parentComponent.getComponentInstancesRelations().stream())
+            .flatMap(requirementCapabilityRelDef -> requirementCapabilityRelDef.getRelationships().stream()).anyMatch(
+                capabilityRequirementRelationship -> capabilityRequirementRelationship.getRelation().getRequirementUid()
+                    .equals(requirementDefinition.getUniqueId()));
     }
 }
index eb4bb33..cc10da0 100644 (file)
@@ -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.
@@ -17,7 +17,6 @@
  * limitations under the License.
  * ============LICENSE_END=========================================================
  */
-
 package org.openecomp.sdc.be.components.impl;
 
 import org.openecomp.sdc.be.impl.ComponentsUtils;
@@ -26,13 +25,10 @@ import org.springframework.stereotype.Component;
 
 @Component("requirementsBusinessLogic")
 public class RequirementsBusinessLogic {
-    private static final Logger log = Logger.getLogger(RequirementsBusinessLogic.class);
 
+    private static final Logger log = Logger.getLogger(RequirementsBusinessLogic.class);
     @javax.annotation.Resource
     private ComponentsUtils componentsUtils;
-
     @javax.annotation.Resource
     private ResourceBusinessLogic resourceBusinessLogic;
-
-
 }
index a3d746d..22fdc3b 100644 (file)
@@ -17,7 +17,6 @@
  * limitations under the License.
  * ============LICENSE_END=========================================================
  */
-
 package org.openecomp.sdc.be.components.impl;
 
 import static java.util.stream.Collectors.joining;
@@ -190,154 +189,143 @@ import org.yaml.snakeyaml.Yaml;
 @org.springframework.stereotype.Component("resourceBusinessLogic")
 public class ResourceBusinessLogic extends ComponentBusinessLogic {
 
-       private static final String DELETE_RESOURCE = "Delete Resource";
-       private static final String IN_RESOURCE = "  in resource {} ";
-       private static final String PLACE_HOLDER_RESOURCE_TYPES = "validForResourceTypes";
-       private static final String INITIAL_VERSION = "0.1";
-       private static final Logger log = Logger.getLogger(ResourceBusinessLogic.class);
-       private static final String CERTIFICATION_ON_IMPORT = "certification on import";
-       private static final String CREATE_RESOURCE = "Create Resource";
-       private static final String VALIDATE_DERIVED_BEFORE_UPDATE = "validate derived before update";
-       private static final String CATEGORY_IS_EMPTY = "Resource category is empty";
-       private static final String CREATE_RESOURCE_VALIDATE_CAPABILITY_TYPES = "Create Resource - validateCapabilityTypesCreate";
-       private static final String COMPONENT_INSTANCE_WITH_NAME = "component instance with name ";
-       private static final String COMPONENT_INSTANCE_WITH_NAME_IN_RESOURCE = "component instance with name {}  in resource {} ";
-       private static final LoggerSupportability loggerSupportability = LoggerSupportability.getLogger(ResourceBusinessLogic.class.getName());
-
-       private IInterfaceLifecycleOperation interfaceTypeOperation;
-       private LifecycleBusinessLogic lifecycleBusinessLogic;
-
-       private final ComponentInstanceBusinessLogic componentInstanceBusinessLogic;
-       private final ResourceImportManager resourceImportManager;
-       private final InputsBusinessLogic inputsBusinessLogic;
-       private final OutputsBusinessLogic outputsBusinessLogic;
-       private final CompositionBusinessLogic compositionBusinessLogic;
-       private final ResourceDataMergeBusinessLogic resourceDataMergeBusinessLogic;
-       private final CsarArtifactsAndGroupsBusinessLogic csarArtifactsAndGroupsBusinessLogic;
-       private final MergeInstanceUtils mergeInstanceUtils;
-       private final UiComponentDataConverter uiComponentDataConverter;
-       private final CsarBusinessLogic csarBusinessLogic;
-       private final PropertyBusinessLogic propertyBusinessLogic;
-       private final PolicyBusinessLogic policyBusinessLogic;
-
-       @Autowired
-       public ResourceBusinessLogic(final IElementOperation elementDao,
-                                                                final IGroupOperation groupOperation,
-                                                                final IGroupInstanceOperation groupInstanceOperation,
-                                                                final IGroupTypeOperation groupTypeOperation,
-                                                                final GroupBusinessLogic groupBusinessLogic,
-                                                                final InterfaceOperation interfaceOperation,
-                                                                final InterfaceLifecycleOperation interfaceLifecycleTypeOperation,
-                                                                final ArtifactsBusinessLogic artifactsBusinessLogic,
-                                                                final ComponentInstanceBusinessLogic componentInstanceBusinessLogic,
-                                                                final @Lazy ResourceImportManager resourceImportManager,
-                                                                final InputsBusinessLogic inputsBusinessLogic,
-                                                                final OutputsBusinessLogic outputsBusinessLogic,
-                                                                final CompositionBusinessLogic compositionBusinessLogic,
-                                                                final ResourceDataMergeBusinessLogic resourceDataMergeBusinessLogic,
-                                                                final CsarArtifactsAndGroupsBusinessLogic csarArtifactsAndGroupsBusinessLogic,
-                                                                final MergeInstanceUtils mergeInstanceUtils,
-                                                                final UiComponentDataConverter uiComponentDataConverter,
-                                                                final CsarBusinessLogic csarBusinessLogic,
-                                                                final ArtifactsOperations artifactToscaOperation,
-                                                                final PropertyBusinessLogic propertyBusinessLogic,
-                                                                final ComponentContactIdValidator componentContactIdValidator,
-                                                                final ComponentNameValidator componentNameValidator,
-                                                                final ComponentTagsValidator componentTagsValidator,
-                                                                final ComponentValidator componentValidator,
-                                                                final ComponentIconValidator componentIconValidator,
-                                                                final ComponentProjectCodeValidator componentProjectCodeValidator,
-                                                                final ComponentDescriptionValidator componentDescriptionValidator,
-                                                                final PolicyBusinessLogic policyBusinessLogic) {
-               super(elementDao, groupOperation, groupInstanceOperation, groupTypeOperation, groupBusinessLogic, interfaceOperation,
-                       interfaceLifecycleTypeOperation, artifactsBusinessLogic, artifactToscaOperation, componentContactIdValidator,
-                       componentNameValidator, componentTagsValidator, componentValidator, componentIconValidator, componentProjectCodeValidator,
-                       componentDescriptionValidator);
-               this.componentInstanceBusinessLogic = componentInstanceBusinessLogic;
-               this.resourceImportManager = resourceImportManager;
-               this.inputsBusinessLogic = inputsBusinessLogic;
-               this.outputsBusinessLogic = outputsBusinessLogic;
-               this.compositionBusinessLogic = compositionBusinessLogic;
-               this.resourceDataMergeBusinessLogic = resourceDataMergeBusinessLogic;
-               this.csarArtifactsAndGroupsBusinessLogic = csarArtifactsAndGroupsBusinessLogic;
-               this.mergeInstanceUtils = mergeInstanceUtils;
-               this.uiComponentDataConverter = uiComponentDataConverter;
-               this.csarBusinessLogic = csarBusinessLogic;
-               this.propertyBusinessLogic = propertyBusinessLogic;
-               this.policyBusinessLogic = policyBusinessLogic;
-       }
-
-       @Autowired
-       private ICapabilityTypeOperation capabilityTypeOperation;
-
-       @Autowired
-       private TopologyComparator topologyComparator;
-
-       @Autowired
-       private ComponentValidator componentValidator;
-
-       @Autowired
-       private PropertyDataValueMergeBusinessLogic propertyDataValueMergeBusinessLogic;
-
-       @Autowired
-       private SoftwareInformationBusinessLogic softwareInformationBusinessLogic;
-
-       public LifecycleBusinessLogic getLifecycleBusinessLogic() {
-               return lifecycleBusinessLogic;
-       }
+    private static final String DELETE_RESOURCE = "Delete Resource";
+    private static final String IN_RESOURCE = "  in resource {} ";
+    private static final String PLACE_HOLDER_RESOURCE_TYPES = "validForResourceTypes";
+    private static final String INITIAL_VERSION = "0.1";
+    private static final Logger log = Logger.getLogger(ResourceBusinessLogic.class);
+    private static final String CERTIFICATION_ON_IMPORT = "certification on import";
+    private static final String CREATE_RESOURCE = "Create Resource";
+    private static final String VALIDATE_DERIVED_BEFORE_UPDATE = "validate derived before update";
+    private static final String CATEGORY_IS_EMPTY = "Resource category is empty";
+    private static final String CREATE_RESOURCE_VALIDATE_CAPABILITY_TYPES = "Create Resource - validateCapabilityTypesCreate";
+    private static final String COMPONENT_INSTANCE_WITH_NAME = "component instance with name ";
+    private static final String COMPONENT_INSTANCE_WITH_NAME_IN_RESOURCE = "component instance with name {}  in resource {} ";
+    private static final LoggerSupportability loggerSupportability = LoggerSupportability.getLogger(ResourceBusinessLogic.class.getName());
+    private final ComponentInstanceBusinessLogic componentInstanceBusinessLogic;
+    private final ResourceImportManager resourceImportManager;
+    private final InputsBusinessLogic inputsBusinessLogic;
+    private final OutputsBusinessLogic outputsBusinessLogic;
+    private final CompositionBusinessLogic compositionBusinessLogic;
+    private final ResourceDataMergeBusinessLogic resourceDataMergeBusinessLogic;
+    private final CsarArtifactsAndGroupsBusinessLogic csarArtifactsAndGroupsBusinessLogic;
+    private final MergeInstanceUtils mergeInstanceUtils;
+    private final UiComponentDataConverter uiComponentDataConverter;
+    private final CsarBusinessLogic csarBusinessLogic;
+    private final PropertyBusinessLogic propertyBusinessLogic;
+    private final PolicyBusinessLogic policyBusinessLogic;
+    private IInterfaceLifecycleOperation interfaceTypeOperation;
+    private LifecycleBusinessLogic lifecycleBusinessLogic;
+    @Autowired
+    private ICapabilityTypeOperation capabilityTypeOperation;
+    @Autowired
+    private TopologyComparator topologyComparator;
+    @Autowired
+    private ComponentValidator componentValidator;
+    @Autowired
+    private PropertyDataValueMergeBusinessLogic propertyDataValueMergeBusinessLogic;
+    @Autowired
+    private SoftwareInformationBusinessLogic softwareInformationBusinessLogic;
+
+    @Autowired
+    public ResourceBusinessLogic(final IElementOperation elementDao, final IGroupOperation groupOperation,
+                                 final IGroupInstanceOperation groupInstanceOperation, final IGroupTypeOperation groupTypeOperation,
+                                 final GroupBusinessLogic groupBusinessLogic, final InterfaceOperation interfaceOperation,
+                                 final InterfaceLifecycleOperation interfaceLifecycleTypeOperation,
+                                 final ArtifactsBusinessLogic artifactsBusinessLogic,
+                                 final ComponentInstanceBusinessLogic componentInstanceBusinessLogic,
+                                 final @Lazy ResourceImportManager resourceImportManager, final InputsBusinessLogic inputsBusinessLogic,
+                                 final OutputsBusinessLogic outputsBusinessLogic, final CompositionBusinessLogic compositionBusinessLogic,
+                                 final ResourceDataMergeBusinessLogic resourceDataMergeBusinessLogic,
+                                 final CsarArtifactsAndGroupsBusinessLogic csarArtifactsAndGroupsBusinessLogic,
+                                 final MergeInstanceUtils mergeInstanceUtils, final UiComponentDataConverter uiComponentDataConverter,
+                                 final CsarBusinessLogic csarBusinessLogic, final ArtifactsOperations artifactToscaOperation,
+                                 final PropertyBusinessLogic propertyBusinessLogic, final ComponentContactIdValidator componentContactIdValidator,
+                                 final ComponentNameValidator componentNameValidator, final ComponentTagsValidator componentTagsValidator,
+                                 final ComponentValidator componentValidator, final ComponentIconValidator componentIconValidator,
+                                 final ComponentProjectCodeValidator componentProjectCodeValidator,
+                                 final ComponentDescriptionValidator componentDescriptionValidator, final PolicyBusinessLogic policyBusinessLogic) {
+        super(elementDao, groupOperation, groupInstanceOperation, groupTypeOperation, groupBusinessLogic, interfaceOperation,
+            interfaceLifecycleTypeOperation, artifactsBusinessLogic, artifactToscaOperation, componentContactIdValidator, componentNameValidator,
+            componentTagsValidator, componentValidator, componentIconValidator, componentProjectCodeValidator, componentDescriptionValidator);
+        this.componentInstanceBusinessLogic = componentInstanceBusinessLogic;
+        this.resourceImportManager = resourceImportManager;
+        this.inputsBusinessLogic = inputsBusinessLogic;
+        this.outputsBusinessLogic = outputsBusinessLogic;
+        this.compositionBusinessLogic = compositionBusinessLogic;
+        this.resourceDataMergeBusinessLogic = resourceDataMergeBusinessLogic;
+        this.csarArtifactsAndGroupsBusinessLogic = csarArtifactsAndGroupsBusinessLogic;
+        this.mergeInstanceUtils = mergeInstanceUtils;
+        this.uiComponentDataConverter = uiComponentDataConverter;
+        this.csarBusinessLogic = csarBusinessLogic;
+        this.propertyBusinessLogic = propertyBusinessLogic;
+        this.policyBusinessLogic = policyBusinessLogic;
+    }
+
+    static <T> Either<T, RuntimeException> rollbackWithEither(final JanusGraphDao janusGraphDao, final ActionStatus actionStatus,
+                                                              final String... params) {
+        if (janusGraphDao != null) {
+            janusGraphDao.rollback();
+        }
+        return Either.right(new ByActionStatusComponentException(actionStatus, params));
+    }
+
+    public LifecycleBusinessLogic getLifecycleBusinessLogic() {
+        return lifecycleBusinessLogic;
+    }
 
     @Autowired
     public void setLifecycleManager(LifecycleBusinessLogic lifecycleBusinessLogic) {
         this.lifecycleBusinessLogic = lifecycleBusinessLogic;
     }
 
-       @VisibleForTesting
-       protected void setComponentValidator(ComponentValidator componentValidator) {
-               this.componentValidator = componentValidator;
-       }
+    @VisibleForTesting
+    protected void setComponentValidator(ComponentValidator componentValidator) {
+        this.componentValidator = componentValidator;
+    }
 
-       public IElementOperation getElementDao() {
-               return elementDao;
-       }
+    public IElementOperation getElementDao() {
+        return elementDao;
+    }
 
-       public void setElementDao(IElementOperation elementDao) {
-               this.elementDao = elementDao;
-       }
+    public void setElementDao(IElementOperation elementDao) {
+        this.elementDao = elementDao;
+    }
 
-       public UserBusinessLogic getUserAdmin() {
-               return this.userAdmin;
-       }
+    public UserBusinessLogic getUserAdmin() {
+        return this.userAdmin;
+    }
 
-       @Autowired
-       @Override
-       public void setUserAdmin(UserBusinessLogic userAdmin) {
-               this.userAdmin = userAdmin;
-       }
+    @Autowired
+    @Override
+    public void setUserAdmin(UserBusinessLogic userAdmin) {
+        this.userAdmin = userAdmin;
+    }
 
-       public ComponentsUtils getComponentsUtils() {
-               return this.componentsUtils;
-       }
+    public ComponentsUtils getComponentsUtils() {
+        return this.componentsUtils;
+    }
 
-       @Autowired
-       @Override
-       public void setComponentsUtils(ComponentsUtils componentsUtils) {
-               this.componentsUtils = componentsUtils;
-       }
+    @Autowired
+    @Override
+    public void setComponentsUtils(ComponentsUtils componentsUtils) {
+        this.componentsUtils = componentsUtils;
+    }
 
-       public ArtifactsBusinessLogic getArtifactsManager() {
-               return artifactsBusinessLogic;
-       }
+    public ArtifactsBusinessLogic getArtifactsManager() {
+        return artifactsBusinessLogic;
+    }
 
-       public void setArtifactsManager(ArtifactsBusinessLogic artifactsManager) {
-               this.artifactsBusinessLogic = artifactsManager;
-       }
+    public void setArtifactsManager(ArtifactsBusinessLogic artifactsManager) {
+        this.artifactsBusinessLogic = artifactsManager;
+    }
 
-       public ApplicationDataTypeCache getApplicationDataTypeCache() {
-               return applicationDataTypeCache;
-       }
+    public ApplicationDataTypeCache getApplicationDataTypeCache() {
+        return applicationDataTypeCache;
+    }
 
     @Autowired
-       @Override
+    @Override
     public void setApplicationDataTypeCache(ApplicationDataTypeCache applicationDataTypeCache) {
         this.applicationDataTypeCache = applicationDataTypeCache;
     }
@@ -347,1289 +335,1058 @@ public class ResourceBusinessLogic extends ComponentBusinessLogic {
         this.interfaceTypeOperation = interfaceTypeOperation;
     }
 
-       /**
-        * the method returns a list of all the resources that are certified, the
-        * returned resources are only abstract or only none abstract according to
-        * the given param
-        *
-        * @param getAbstract
-        * @param userId
-        *            TODO
-        * @return
-        */
-       public List<Resource> getAllCertifiedResources(boolean getAbstract, HighestFilterEnum highestFilter,
-                                                                                                  String userId) {
-               User user = validateUserExists(userId);
-               Boolean isHighest = null;
-               switch (highestFilter) {
-                       case ALL:
-                               break;
-                       case HIGHEST_ONLY:
-                               isHighest = true;
-                               break;
-                       case NON_HIGHEST_ONLY:
-                               isHighest = false;
-                               break;
-                       default:
-                               break;
-               }
-               Either<List<Resource>, StorageOperationStatus> getResponse = toscaOperationFacade
-                               .getAllCertifiedResources(getAbstract, isHighest);
-
-               if (getResponse.isRight()) {
-                       throw new StorageException(getResponse.right()
-                                       .value());
-               }
-
-               return getResponse.left()
-                               .value();
-       }
-
-       public Either<Map<String, Boolean>, ResponseFormat> validateResourceNameExists(String resourceName,
-                                                                                                                                                                  ResourceTypeEnum resourceTypeEnum, String userId) {
-
-               validateUserExists(userId);
-
-               Either<Boolean, StorageOperationStatus> dataModelResponse = toscaOperationFacade
-                               .validateComponentNameUniqueness(resourceName, resourceTypeEnum, ComponentTypeEnum.RESOURCE);
-               // DE242223
+    /**
+     * the method returns a list of all the resources that are certified, the returned resources are only abstract or only none abstract according to
+     * the given param
+     *
+     * @param getAbstract
+     * @param userId      TODO
+     * @return
+     */
+    public List<Resource> getAllCertifiedResources(boolean getAbstract, HighestFilterEnum highestFilter, String userId) {
+        User user = validateUserExists(userId);
+        Boolean isHighest = null;
+        switch (highestFilter) {
+            case ALL:
+                break;
+            case HIGHEST_ONLY:
+                isHighest = true;
+                break;
+            case NON_HIGHEST_ONLY:
+                isHighest = false;
+                break;
+            default:
+                break;
+        }
+        Either<List<Resource>, StorageOperationStatus> getResponse = toscaOperationFacade.getAllCertifiedResources(getAbstract, isHighest);
+        if (getResponse.isRight()) {
+            throw new StorageException(getResponse.right().value());
+        }
+        return getResponse.left().value();
+    }
+
+    public Either<Map<String, Boolean>, ResponseFormat> validateResourceNameExists(String resourceName, ResourceTypeEnum resourceTypeEnum,
+                                                                                   String userId) {
+        validateUserExists(userId);
+        Either<Boolean, StorageOperationStatus> dataModelResponse = toscaOperationFacade
+            .validateComponentNameUniqueness(resourceName, resourceTypeEnum, ComponentTypeEnum.RESOURCE);
+        // DE242223
         janusGraphDao.commit();
+        if (dataModelResponse.isLeft()) {
+            Map<String, Boolean> result = new HashMap<>();
+            result.put("isValid", dataModelResponse.left().value());
+            log.debug("validation was successfully performed.");
+            return Either.left(result);
+        }
+        ResponseFormat responseFormat = componentsUtils
+            .getResponseFormat(componentsUtils.convertFromStorageResponse(dataModelResponse.right().value()));
+        return Either.right(responseFormat);
+    }
+
+    public Resource createResource(Resource resource, AuditingActionEnum auditingAction, User user, Map<String, byte[]> csarUIPayload,
+                                   String payloadName) {
+        validateResourceBeforeCreate(resource, user, false);
+        String csarUUID = payloadName == null ? resource.getCsarUUID() : payloadName;
+        loggerSupportability.log(LoggerSupportabilityActions.CREATE_RESOURCE, resource.getComponentMetadataForSupportLog(), StatusCode.STARTED,
+            "Starting to create resource from CSAR by user {} ", user.getUserId());
+        if (StringUtils.isNotEmpty(csarUUID)) {
+            csarBusinessLogic.validateCsarBeforeCreate(resource, auditingAction, user, csarUUID);
+            log.debug("CsarUUID is {} - going to create resource from CSAR", csarUUID);
+            Resource createResourceFromCsar = createResourceFromCsar(resource, user, csarUIPayload, csarUUID);
+            return updateCatalog(createResourceFromCsar, ChangeTypeEnum.LIFECYCLE).left().map(r -> (Resource) r).left().value();
+        }
+        final Resource createResourceByDao = createResourceByDao(resource, user, auditingAction, false, false);
+        return updateCatalog(createResourceByDao, ChangeTypeEnum.LIFECYCLE).left().map(r -> (Resource) r).left().value();
+    }
+
+    public Resource validateAndUpdateResourceFromCsar(Resource resource, User user, Map<String, byte[]> csarUIPayload, String payloadName,
+                                                      String resourceUniqueId) {
+        String csarUUID = payloadName;
+        String csarVersion = null;
+        Resource updatedResource = null;
+        if (payloadName == null) {
+            csarUUID = resource.getCsarUUID();
+            csarVersion = resource.getCsarVersion();
+        }
+        if (csarUUID != null && !csarUUID.isEmpty()) {
+            Resource oldResource = getResourceByUniqueId(resourceUniqueId);
+            validateCsarUuidMatching(oldResource, resource, csarUUID, resourceUniqueId, user);
+            validateCsarIsNotAlreadyUsed(oldResource, resource, csarUUID, user);
+            if (oldResource != null && ValidationUtils.hasBeenCertified(oldResource.getVersion())) {
+                overrideImmutableMetadata(oldResource, resource);
+            }
+            validateResourceBeforeCreate(resource, user, false);
+            String oldCsarVersion = oldResource != null ? oldResource.getCsarVersion() : null;
+            log.debug("CsarUUID is {} - going to update resource with UniqueId {} from CSAR", csarUUID, resourceUniqueId);
+            // (on boarding flow): If the update includes same csarUUID and
+
+            // same csarVersion as already in the VF - no need to import the
+
+            // csar (do only metadata changes if there are).
+            if (csarVersion != null && oldCsarVersion != null && oldCsarVersion.equals(csarVersion)) {
+                updatedResource = updateResourceMetadata(resourceUniqueId, resource, oldResource, user, false);
+            } else {
+                updatedResource = updateResourceFromCsar(oldResource, resource, user, AuditingActionEnum.UPDATE_RESOURCE_METADATA, false,
+                    csarUIPayload, csarUUID);
+            }
+        } else {
+            log.debug("Failed to update resource {}, csarUUID or payload name is missing", resource.getSystemName());
+            ResponseFormat errorResponse = componentsUtils.getResponseFormat(ActionStatus.MISSING_CSAR_UUID, resource.getName());
+            componentsUtils.auditResource(errorResponse, user, resource, AuditingActionEnum.CREATE_RESOURCE);
+            throw new ByActionStatusComponentException(ActionStatus.MISSING_CSAR_UUID, resource.getName());
+        }
+        return updatedResource;
+    }
+
+    private void validateCsarIsNotAlreadyUsed(Resource oldResource, Resource resource, String csarUUID, User user) {
+        // (on boarding flow): If the update includes a csarUUID: verify this
+
+        // csarUUID is not in use by another VF, If it is - use same error as
+
+        // above:
+
+        // "Error: The VSP with UUID %1 was already imported for VF %2. Please
+
+        // select another or update the existing VF." %1 - csarUUID, %2 - VF
+
+        // name
+        Either<Resource, StorageOperationStatus> resourceLinkedToCsarRes = toscaOperationFacade
+            .getLatestComponentByCsarOrName(ComponentTypeEnum.RESOURCE, csarUUID, resource.getSystemName());
+        if (resourceLinkedToCsarRes.isRight()) {
+            if (StorageOperationStatus.NOT_FOUND != resourceLinkedToCsarRes.right().value()) {
+                log.debug("Failed to find previous resource by CSAR {} and system name {}", csarUUID, resource.getSystemName());
+                throw new StorageException(resourceLinkedToCsarRes.right().value());
+            }
+        } else if (!resourceLinkedToCsarRes.left().value().getUniqueId().equals(oldResource.getUniqueId()) && !resourceLinkedToCsarRes.left().value()
+            .getName().equals(oldResource.getName())) {
+            ResponseFormat errorResponse = componentsUtils
+                .getResponseFormat(ActionStatus.VSP_ALREADY_EXISTS, csarUUID, resourceLinkedToCsarRes.left().value().getName());
+            componentsUtils.auditResource(errorResponse, user, resource, AuditingActionEnum.UPDATE_RESOURCE_METADATA);
+            throw new ByActionStatusComponentException(ActionStatus.VSP_ALREADY_EXISTS, csarUUID, resourceLinkedToCsarRes.left().value().getName());
+        }
+    }
+
+    private void validateCsarUuidMatching(Resource resource, Resource oldResource, String csarUUID, String resourceUniqueId, User user) {
+        // (on boarding flow): If the update includes csarUUID which is
+
+        // different from the csarUUID of the VF - fail with
+
+        // error: "Error: Resource %1 cannot be updated using since it is linked
+
+        // to a different VSP" %1 - VF name
+        String oldCsarUUID = oldResource.getCsarUUID();
+        if (oldCsarUUID != null && !oldCsarUUID.isEmpty() && !csarUUID.equals(oldCsarUUID)) {
+            log.debug("Failed to update resource with UniqueId {} using Csar {}, since the resource is linked to a different VSP {}",
+                resourceUniqueId, csarUUID, oldCsarUUID);
+            ResponseFormat errorResponse = componentsUtils
+                .getResponseFormat(ActionStatus.RESOURCE_LINKED_TO_DIFFERENT_VSP, resource.getName(), csarUUID, oldCsarUUID);
+            componentsUtils.auditResource(errorResponse, user, resource, AuditingActionEnum.UPDATE_RESOURCE_METADATA);
+            throw new ByActionStatusComponentException(ActionStatus.RESOURCE_LINKED_TO_DIFFERENT_VSP, resource.getName(), csarUUID, oldCsarUUID);
+        }
+    }
+
+    private Resource getResourceByUniqueId(String resourceUniqueId) {
+        Either<Resource, StorageOperationStatus> oldResourceRes = toscaOperationFacade.getToscaFullElement(resourceUniqueId);
+        if (oldResourceRes.isRight()) {
+            log.debug("Failed to find previous resource by UniqueId {}, status: {}", resourceUniqueId, oldResourceRes.right().value());
+            throw new StorageException(oldResourceRes.right().value());
+        }
+        return oldResourceRes.left().value();
+    }
+
+    private void overrideImmutableMetadata(Resource oldResource, Resource resource) {
+        resource.setName(oldResource.getName());
+        resource.setIcon(oldResource.getIcon());
+        resource.setTags(oldResource.getTags());
+        resource.setCategories(oldResource.getCategories());
+        resource.setDerivedFrom(oldResource.getDerivedFrom());
+    }
 
-               if (dataModelResponse.isLeft()) {
-                       Map<String, Boolean> result = new HashMap<>();
-                       result.put("isValid", dataModelResponse.left()
-                                       .value());
-                       log.debug("validation was successfully performed.");
-                       return Either.left(result);
-               }
-
-               ResponseFormat responseFormat = componentsUtils
-                               .getResponseFormat(componentsUtils.convertFromStorageResponse(dataModelResponse.right()
-                                               .value()));
-
-               return Either.right(responseFormat);
-       }
-
-       public Resource createResource(Resource resource, AuditingActionEnum auditingAction, User user,
-                                                                  Map<String, byte[]> csarUIPayload, String payloadName) {
-               validateResourceBeforeCreate(resource, user, false);
-               String csarUUID = payloadName == null ? resource.getCsarUUID() : payloadName;
-               loggerSupportability.log(LoggerSupportabilityActions.CREATE_RESOURCE,resource.getComponentMetadataForSupportLog(), StatusCode.STARTED,"Starting to create resource from CSAR by user {} ", user.getUserId());
-               if (StringUtils.isNotEmpty(csarUUID)) {
-                       csarBusinessLogic.validateCsarBeforeCreate(resource, auditingAction, user, csarUUID);
-                       log.debug("CsarUUID is {} - going to create resource from CSAR", csarUUID);
-
-                       Resource createResourceFromCsar = createResourceFromCsar(resource, user, csarUIPayload, csarUUID);
-                       return updateCatalog(createResourceFromCsar, ChangeTypeEnum.LIFECYCLE).left()
-                                       .map(r -> (Resource) r)
-                                       .left()
-                                       .value();
-               }
-
-               final Resource createResourceByDao = createResourceByDao(resource, user, auditingAction, false, false);
-               return updateCatalog(createResourceByDao, ChangeTypeEnum.LIFECYCLE).left()
-                               .map(r -> (Resource) r)
-                               .left()
-                               .value();
-       }
-
-       public Resource validateAndUpdateResourceFromCsar(Resource resource, User user, Map<String, byte[]> csarUIPayload,
-                                                                                                         String payloadName, String resourceUniqueId) {
-               String csarUUID = payloadName;
-               String csarVersion = null;
-               Resource updatedResource = null;
-               if (payloadName == null) {
-                       csarUUID = resource.getCsarUUID();
-                       csarVersion = resource.getCsarVersion();
-               }
-               if (csarUUID != null && !csarUUID.isEmpty()) {
-                       Resource oldResource = getResourceByUniqueId(resourceUniqueId);
-                       validateCsarUuidMatching(oldResource, resource, csarUUID, resourceUniqueId, user);
-                       validateCsarIsNotAlreadyUsed(oldResource, resource, csarUUID, user);
-                       if (oldResource != null && ValidationUtils.hasBeenCertified(oldResource.getVersion())) {
-                               overrideImmutableMetadata(oldResource, resource);
-                       }
-                       validateResourceBeforeCreate(resource, user, false);
-                       String oldCsarVersion = oldResource != null ? oldResource.getCsarVersion() : null;
-                       log.debug("CsarUUID is {} - going to update resource with UniqueId {} from CSAR", csarUUID,
-                                       resourceUniqueId);
-                       // (on boarding flow): If the update includes same csarUUID and
-                       // same csarVersion as already in the VF - no need to import the
-                       // csar (do only metadata changes if there are).
-                       if (csarVersion != null && oldCsarVersion != null && oldCsarVersion.equals(csarVersion)) {
-                               updatedResource = updateResourceMetadata(resourceUniqueId, resource, oldResource, user, false);
-                       } else {
-                               updatedResource = updateResourceFromCsar(oldResource, resource, user,
-                                               AuditingActionEnum.UPDATE_RESOURCE_METADATA, false, csarUIPayload, csarUUID);
-                       }
-               } else {
-                       log.debug("Failed to update resource {}, csarUUID or payload name is missing", resource.getSystemName());
-                       ResponseFormat errorResponse = componentsUtils.getResponseFormat(ActionStatus.MISSING_CSAR_UUID,
-                                       resource.getName());
-                       componentsUtils.auditResource(errorResponse, user, resource, AuditingActionEnum.CREATE_RESOURCE);
-                       throw new ByActionStatusComponentException(ActionStatus.MISSING_CSAR_UUID, resource.getName());
-               }
-               return updatedResource;
-       }
-
-       private void validateCsarIsNotAlreadyUsed(Resource oldResource, Resource resource, String csarUUID, User user) {
-               // (on boarding flow): If the update includes a csarUUID: verify this
-               // csarUUID is not in use by another VF, If it is - use same error as
-               // above:
-               // "Error: The VSP with UUID %1 was already imported for VF %2. Please
-               // select another or update the existing VF." %1 - csarUUID, %2 - VF
-               // name
-               Either<Resource, StorageOperationStatus> resourceLinkedToCsarRes = toscaOperationFacade
-                               .getLatestComponentByCsarOrName(ComponentTypeEnum.RESOURCE, csarUUID, resource.getSystemName());
-               if (resourceLinkedToCsarRes.isRight()) {
-                       if (StorageOperationStatus.NOT_FOUND != resourceLinkedToCsarRes.right().value()) {
-                               log.debug("Failed to find previous resource by CSAR {} and system name {}", csarUUID,
-                                               resource.getSystemName());
-                               throw new StorageException(resourceLinkedToCsarRes.right()
-                                               .value());
-                       }
-               } else if (!resourceLinkedToCsarRes.left()
-                               .value()
-                               .getUniqueId()
-                               .equals(oldResource.getUniqueId())
-                               && !resourceLinkedToCsarRes.left()
-                               .value()
-                               .getName()
-                               .equals(oldResource.getName())) {
-                       ResponseFormat errorResponse = componentsUtils.getResponseFormat(ActionStatus.VSP_ALREADY_EXISTS, csarUUID,
-                                       resourceLinkedToCsarRes.left()
-                                                       .value()
-                                                       .getName());
-                       componentsUtils.auditResource(errorResponse, user, resource, AuditingActionEnum.UPDATE_RESOURCE_METADATA);
-                       throw new ByActionStatusComponentException(ActionStatus.VSP_ALREADY_EXISTS, csarUUID, resourceLinkedToCsarRes.left()
-                                       .value()
-                                       .getName());
-               }
-       }
-
-       private void validateCsarUuidMatching(Resource resource, Resource oldResource, String csarUUID,
-                                                                                 String resourceUniqueId, User user) {
-               // (on boarding flow): If the update includes csarUUID which is
-               // different from the csarUUID of the VF - fail with
-               // error: "Error: Resource %1 cannot be updated using since it is linked
-               // to a different VSP" %1 - VF name
-               String oldCsarUUID = oldResource.getCsarUUID();
-               if (oldCsarUUID != null && !oldCsarUUID.isEmpty() && !csarUUID.equals(oldCsarUUID)) {
-                       log.debug(
-                                       "Failed to update resource with UniqueId {} using Csar {}, since the resource is linked to a different VSP {}",
-                                       resourceUniqueId, csarUUID, oldCsarUUID);
-                       ResponseFormat errorResponse = componentsUtils.getResponseFormat(
-                                       ActionStatus.RESOURCE_LINKED_TO_DIFFERENT_VSP, resource.getName(), csarUUID, oldCsarUUID);
-                       componentsUtils.auditResource(errorResponse, user, resource, AuditingActionEnum.UPDATE_RESOURCE_METADATA);
-                       throw new ByActionStatusComponentException(ActionStatus.RESOURCE_LINKED_TO_DIFFERENT_VSP, resource.getName(), csarUUID,
-                                       oldCsarUUID);
-               }
-       }
-
-       private Resource getResourceByUniqueId(String resourceUniqueId) {
-               Either<Resource, StorageOperationStatus> oldResourceRes = toscaOperationFacade
-                               .getToscaFullElement(resourceUniqueId);
-               if (oldResourceRes.isRight()) {
-                       log.debug("Failed to find previous resource by UniqueId {}, status: {}", resourceUniqueId,
-                                       oldResourceRes.right()
-                                                       .value());
-                       throw new StorageException(oldResourceRes.right()
-                                       .value());
-               }
-               return oldResourceRes.left()
-                               .value();
-       }
-
-       private void overrideImmutableMetadata(Resource oldResource, Resource resource) {
-               resource.setName(oldResource.getName());
-               resource.setIcon(oldResource.getIcon());
-               resource.setTags(oldResource.getTags());
-               resource.setCategories(oldResource.getCategories());
-               resource.setDerivedFrom(oldResource.getDerivedFrom());
-       }
-
-       private Resource updateResourceFromCsar(Resource oldResource, Resource newResource, User user,
-                                                                                       AuditingActionEnum updateResource, boolean inTransaction, Map<String, byte[]> csarUIPayload,
-                                                                                       String csarUUID) {
-               Resource updatedResource = null;
-               validateLifecycleState(oldResource, user);
-               String lockedResourceId = oldResource.getUniqueId();
-               List<ArtifactDefinition> createdArtifacts = new ArrayList<>();
-               CsarInfo csarInfo = csarBusinessLogic.getCsarInfo(newResource, oldResource, user, csarUIPayload, csarUUID);
-               lockComponent(lockedResourceId, oldResource, "update Resource From Csar");
-
-               Map<String, NodeTypeInfo> nodeTypesInfo = csarInfo.extractNodeTypesInfo();
-
-               Either<Map<String, EnumMap<ArtifactOperationEnum, List<ArtifactDefinition>>>, ResponseFormat> findNodeTypesArtifactsToHandleRes = findNodeTypesArtifactsToHandle(
-                               nodeTypesInfo, csarInfo, oldResource);
-               if (findNodeTypesArtifactsToHandleRes.isRight()) {
-                       log.debug("failed to find node types for update with artifacts during import csar {}. ",
-                                       csarInfo.getCsarUUID());
-                       throw new ByResponseFormatComponentException(findNodeTypesArtifactsToHandleRes.right()
-                                       .value());
-               }
-               Map<String, EnumMap<ArtifactOperationEnum, List<ArtifactDefinition>>> nodeTypesArtifactsToHandle = findNodeTypesArtifactsToHandleRes
-                               .left()
-                               .value();
-               try {
-                       updatedResource = updateResourceFromYaml(oldResource, newResource, updateResource, createdArtifacts,
-                                       csarInfo.getMainTemplateName(), csarInfo.getMainTemplateContent(), csarInfo, nodeTypesInfo,
-                                       nodeTypesArtifactsToHandle, null, false);
-
-               } catch (ComponentException | StorageException e) {
-                       rollback(inTransaction, newResource, createdArtifacts, null);
-                       throw e;
-        }
-        finally {
+    private Resource updateResourceFromCsar(Resource oldResource, Resource newResource, User user, AuditingActionEnum updateResource,
+                                            boolean inTransaction, Map<String, byte[]> csarUIPayload, String csarUUID) {
+        Resource updatedResource = null;
+        validateLifecycleState(oldResource, user);
+        String lockedResourceId = oldResource.getUniqueId();
+        List<ArtifactDefinition> createdArtifacts = new ArrayList<>();
+        CsarInfo csarInfo = csarBusinessLogic.getCsarInfo(newResource, oldResource, user, csarUIPayload, csarUUID);
+        lockComponent(lockedResourceId, oldResource, "update Resource From Csar");
+        Map<String, NodeTypeInfo> nodeTypesInfo = csarInfo.extractNodeTypesInfo();
+        Either<Map<String, EnumMap<ArtifactOperationEnum, List<ArtifactDefinition>>>, ResponseFormat> findNodeTypesArtifactsToHandleRes = findNodeTypesArtifactsToHandle(
+            nodeTypesInfo, csarInfo, oldResource);
+        if (findNodeTypesArtifactsToHandleRes.isRight()) {
+            log.debug("failed to find node types for update with artifacts during import csar {}. ", csarInfo.getCsarUUID());
+            throw new ByResponseFormatComponentException(findNodeTypesArtifactsToHandleRes.right().value());
+        }
+        Map<String, EnumMap<ArtifactOperationEnum, List<ArtifactDefinition>>> nodeTypesArtifactsToHandle = findNodeTypesArtifactsToHandleRes.left()
+            .value();
+        try {
+            updatedResource = updateResourceFromYaml(oldResource, newResource, updateResource, createdArtifacts, csarInfo.getMainTemplateName(),
+                csarInfo.getMainTemplateContent(), csarInfo, nodeTypesInfo, nodeTypesArtifactsToHandle, null, false);
+        } catch (ComponentException | StorageException e) {
+            rollback(inTransaction, newResource, createdArtifacts, null);
+            throw e;
+        } finally {
             janusGraphDao.commit();
-                       log.debug("unlock resource {}", lockedResourceId);
-                       graphLockOperation.unlockComponent(lockedResourceId, NodeTypeEnum.Resource);
-               }
-               return updatedResource;
-
-       }
-
-       private void validateLifecycleState(Resource oldResource, User user) {
-               if (LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT == oldResource.getLifecycleState()
-                               && !oldResource.getLastUpdaterUserId()
-                               .equals(user.getUserId())) {
-                       log.debug(
-                                       "#validateLifecycleState - Current user is not last updater, last updater userId: {}, current user userId: {}",
-                                       oldResource.getLastUpdaterUserId(), user.getUserId());
-                       throw new ByActionStatusComponentException(ActionStatus.RESTRICTED_OPERATION);
-               }
-       }
-
-       private Resource updateResourceFromYaml(Resource oldResource, Resource newResource, AuditingActionEnum actionEnum,
-                                                                                       List<ArtifactDefinition> createdArtifacts, String yamlFileName, String yamlFileContent, CsarInfo csarInfo,
-                                                                                       Map<String, NodeTypeInfo> nodeTypesInfo,
-                                                                                       Map<String, EnumMap<ArtifactOperationEnum, List<ArtifactDefinition>>> nodeTypesArtifactsToHandle,
-                                                                                       String nodeName, boolean isNested) {
-               boolean inTransaction = true;
-               boolean shouldLock = false;
-               Resource preparedResource = null;
-               ParsedToscaYamlInfo uploadComponentInstanceInfoMap;
-               try {
-                       uploadComponentInstanceInfoMap = csarBusinessLogic.getParsedToscaYamlInfo(yamlFileContent, yamlFileName,
-                                       nodeTypesInfo, csarInfo, nodeName, oldResource);
-                       Map<String, UploadComponentInstanceInfo> instances = uploadComponentInstanceInfoMap.getInstances();
+            log.debug("unlock resource {}", lockedResourceId);
+            graphLockOperation.unlockComponent(lockedResourceId, NodeTypeEnum.Resource);
+        }
+        return updatedResource;
+    }
+
+    private void validateLifecycleState(Resource oldResource, User user) {
+        if (LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT == oldResource.getLifecycleState() && !oldResource.getLastUpdaterUserId()
+            .equals(user.getUserId())) {
+            log.debug("#validateLifecycleState - Current user is not last updater, last updater userId: {}, current user userId: {}",
+                oldResource.getLastUpdaterUserId(), user.getUserId());
+            throw new ByActionStatusComponentException(ActionStatus.RESTRICTED_OPERATION);
+        }
+    }
+
+    private Resource updateResourceFromYaml(Resource oldResource, Resource newResource, AuditingActionEnum actionEnum,
+                                            List<ArtifactDefinition> createdArtifacts, String yamlFileName, String yamlFileContent, CsarInfo csarInfo,
+                                            Map<String, NodeTypeInfo> nodeTypesInfo,
+                                            Map<String, EnumMap<ArtifactOperationEnum, List<ArtifactDefinition>>> nodeTypesArtifactsToHandle,
+                                            String nodeName, boolean isNested) {
+        boolean inTransaction = true;
+        boolean shouldLock = false;
+        Resource preparedResource = null;
+        ParsedToscaYamlInfo uploadComponentInstanceInfoMap;
+        try {
+            uploadComponentInstanceInfoMap = csarBusinessLogic
+                .getParsedToscaYamlInfo(yamlFileContent, yamlFileName, nodeTypesInfo, csarInfo, nodeName, oldResource);
+            Map<String, UploadComponentInstanceInfo> instances = uploadComponentInstanceInfoMap.getInstances();
             if (MapUtils.isEmpty(instances) && newResource.getResourceType() != ResourceTypeEnum.PNF) {
                 throw new ByActionStatusComponentException(ActionStatus.NOT_TOPOLOGY_TOSCA_TEMPLATE, yamlFileName);
             }
-            preparedResource = updateExistingResourceByImport(newResource, oldResource, csarInfo.getModifier(),
-                                       inTransaction, shouldLock, isNested).left;
-                       log.trace("YAML topology file found in CSAR, file name: {}, contents: {}", yamlFileName, yamlFileContent);
-                       handleResourceGenericType(preparedResource);
-                       handleNodeTypes(yamlFileName, preparedResource, yamlFileContent, shouldLock, nodeTypesArtifactsToHandle,
-                                       createdArtifacts, nodeTypesInfo, csarInfo, nodeName);
-                       preparedResource = createInputsOnResource(preparedResource, uploadComponentInstanceInfoMap.getInputs());
-                       Map<String, Resource> existingNodeTypesByResourceNames = new HashMap<>();
-                       preparedResource = createResourceInstances(yamlFileName, preparedResource, oldResource, instances, csarInfo.getCreatedNodes(), existingNodeTypesByResourceNames);
-                       preparedResource = createResourceInstancesRelations(csarInfo.getModifier(), yamlFileName, preparedResource, oldResource, instances, existingNodeTypesByResourceNames);
-               } catch (ComponentException e) {
-                       ResponseFormat responseFormat = e.getResponseFormat() == null
-                                       ? componentsUtils.getResponseFormat(e.getActionStatus(), e.getParams()) : e.getResponseFormat();
-                       log.debug("#updateResourceFromYaml - failed to update newResource from yaml {} .The error is {}", yamlFileName,
-                                       responseFormat);
-                       componentsUtils.auditResource(responseFormat, csarInfo.getModifier(),
-                                       preparedResource == null ? oldResource : preparedResource, actionEnum);
-                       throw e;
-               } catch (StorageException e) {
-                       ResponseFormat responseFormat = componentsUtils
-                                       .getResponseFormat(componentsUtils.convertFromStorageResponse(e.getStorageOperationStatus()));
-                       log.debug("#updateResourceFromYaml - failed to update newResource from yaml {} .The error is {}", yamlFileName,
-                                       responseFormat);
-                       componentsUtils.auditResource(responseFormat, csarInfo.getModifier(),
-                                       preparedResource == null ? oldResource : preparedResource, actionEnum);
-                       throw e;
-               }
-               Either<Map<String, GroupDefinition>, ResponseFormat> validateUpdateVfGroupNamesRes = groupBusinessLogic
-                               .validateUpdateVfGroupNames(uploadComponentInstanceInfoMap.getGroups(),
-                                               preparedResource.getSystemName());
-               if (validateUpdateVfGroupNamesRes.isRight()) {
-
-                       throw new ByResponseFormatComponentException(validateUpdateVfGroupNamesRes.right()
-                                       .value());
-               }
-               // add groups to newResource
-               Map<String, GroupDefinition> groups;
-
-               if (!validateUpdateVfGroupNamesRes.left()
-                               .value()
-                               .isEmpty()) {
-                       groups = validateUpdateVfGroupNamesRes.left()
-                                       .value();
-               } else {
-                       groups = uploadComponentInstanceInfoMap.getGroups();
-               }
-               handleGroupsProperties(preparedResource, groups);
-               Either<Boolean, ActionStatus> isTopologyChanged = topologyComparator.isTopologyChanged(oldResource, preparedResource);
-
-               preparedResource = updateGroupsOnResource(preparedResource, groups);
-
-               NodeTypeInfoToUpdateArtifacts nodeTypeInfoToUpdateArtifacts = new NodeTypeInfoToUpdateArtifacts(nodeName,
-                               nodeTypesArtifactsToHandle);
-
-               Either<Resource, ResponseFormat> updateArtifactsEither = createOrUpdateArtifacts(ArtifactOperationEnum.UPDATE,
-                               createdArtifacts, yamlFileName, csarInfo, preparedResource, nodeTypeInfoToUpdateArtifacts,
-                               inTransaction, shouldLock);
-               if (updateArtifactsEither.isRight()) {
-                       log.debug("failed to update artifacts {}", updateArtifactsEither.right()
-                                       .value());
-                       throw new ByResponseFormatComponentException(updateArtifactsEither.right()
-                                       .value());
-               }
-               preparedResource = getResourceWithGroups(updateArtifactsEither.left()
-                               .value()
-                               .getUniqueId());
-
-               updateGroupsName(oldResource, preparedResource, isTopologyChanged.left().value());
-               updateResourceInstancesNames(oldResource, csarInfo, preparedResource, isTopologyChanged.left().value());
-
-               final String preparedResourceId = preparedResource != null ? preparedResource.getUniqueId() : "";
-               preparedResource = getResourceWithGroups(preparedResourceId);
-
-               updateVolumeGroup(preparedResource);
-
-               ActionStatus mergingPropsAndInputsStatus = resourceDataMergeBusinessLogic.mergeResourceEntities(oldResource, preparedResource);
-               if (mergingPropsAndInputsStatus != ActionStatus.OK) {
-                       ResponseFormat responseFormat = componentsUtils.getResponseFormatByResource(mergingPropsAndInputsStatus,
-                                       preparedResource);
-                       throw new ByResponseFormatComponentException(responseFormat);
-               }
-               compositionBusinessLogic.setPositionsForComponentInstances(preparedResource, csarInfo.getModifier()
-                               .getUserId());
-               return preparedResource;
-       }
-
-       protected void updateVolumeGroup(Resource preparedResource) {
-               List<GroupDefinition> groups = preparedResource.safeGetGroups();
-               for (GroupDefinition group : groups) {
-                       Map<String, ArtifactDefinition> createdNewArtifacts = preparedResource.getDeploymentArtifacts();
-                       if (DEFAULT_GROUP_VF_MODULE.equals(group.getType())) {
-                               List<PropertyDataDefinition> volumePropList = group.getProperties().stream().filter(p -> "volume_group".equals(p.getName())).collect(Collectors.toList());
-                               if (!volumePropList.isEmpty()) {
-                                       PropertyDataDefinition volumeProp = volumePropList.get(0);
-                                       if (volumeProp != null) {
-                                               boolean isVolumeGroup = isVolumeGroup(group.getArtifacts(), new ArrayList<>(createdNewArtifacts.values()));
-
-                                               if (!volumePropList.get(0).getValue().equals(String.valueOf(isVolumeGroup))) {
-                                                       volumeProp.setValue(String.valueOf(isVolumeGroup));
-                                                       volumeProp.setDefaultValue(String.valueOf(isVolumeGroup));
-                                               }
-                                       }
-                               }
-                       }
-               }
-       }
-
-       private void updateGroupsName(Resource oldResource, Resource preparedResource, boolean isTopologyChanged) {
-               if (oldResource == null || preparedResource == null) {
-                       log.debug("Failed to update groups name : oldResource or preparedResource is null");
-               } else if (CollectionUtils.isNotEmpty(oldResource.getGroups())
-                       && CollectionUtils.isNotEmpty(preparedResource.getGroups())) {
-                       Map<String, String> oldGroups = oldResource.getGroups()
-                               .stream()
-                               .collect(toMap(GroupDataDefinition::getInvariantName, GroupDataDefinition::getName));
-
-                       List<GroupDefinition> updatedGroups = preparedResource.getGroups()
-                               .stream()
-                               .filter(group -> oldGroups.containsKey(group.getInvariantName()) && !group.getName()
-                                       .equals(oldGroups.get(group.getInvariantName())))
-                               .collect(toList());
-
-                       if (CollectionUtils.isNotEmpty(updatedGroups)) {
-                               if (isTopologyChanged) {
-                                       updatedGroups.stream().filter(group -> !group.isVspOriginated())
-                                               .forEach(group -> group.setName(oldGroups.get(group.getInvariantName())));
-                               } else {
-                                       updatedGroups.forEach(group -> group.setName(oldGroups.get(group.getInvariantName())));
-                               }
-                               groupBusinessLogic.updateGroups(preparedResource, updatedGroups, false);
-                       }
-               }
-       }
-
-       private void updateResourceInstancesNames(Resource oldResource, CsarInfo csarInfo, Resource preparedResource,
-               boolean isTopologyChanged) {
-               if (oldResource == null || preparedResource == null) {
-                       log.debug("Failed to update resource instances names : oldResource or preparedResource is null");
-               } else {
-                       if (CollectionUtils.isNotEmpty(oldResource.getComponentInstances())) {
-                               Map<String, String> oldInstances = oldResource.getComponentInstances()
-                                       .stream()
-                                       .collect(toMap(ComponentInstance::getInvariantName, ComponentInstance::getName));
-                               List<ComponentInstance> updatedInstances = preparedResource.getComponentInstances()
-                                       .stream()
-                                       .filter(i -> oldInstances.containsKey(i.getInvariantName()) && !i.getName()
-                                               .equals(oldInstances.get(i.getInvariantName())))
-                                       .collect(toList());
-                               if (CollectionUtils.isNotEmpty(updatedInstances)) {
-                                       if (isTopologyChanged) {
-                                               updatedInstances.stream().filter(i -> !i.isCreatedFromCsar())
-                                                       .forEach(i -> i.setName(oldInstances.get(i.getInvariantName())));
-                                       } else {
-                                               updatedInstances.forEach(i -> i.setName(oldInstances.get(i.getInvariantName())));
-                                       }
-                               }
-                       }
-
-                       componentInstanceBusinessLogic.updateComponentInstance(ComponentTypeEnum.RESOURCE_PARAM_NAME,
-                               null, preparedResource.getUniqueId(), csarInfo.getModifier()
-                                       .getUserId(),
-                               preparedResource.getComponentInstances(), false);
-               }
-       }
-
-       private Either<Resource, ResponseFormat> createOrUpdateArtifacts(ArtifactOperationEnum operation,
-                                                                                                                                        List<ArtifactDefinition> createdArtifacts, String yamlFileName, CsarInfo csarInfo,
-                                                                                                                                        Resource preparedResource, NodeTypeInfoToUpdateArtifacts nodeTypeInfoToUpdateArtifacts,
-                                                                                                                                        boolean inTransaction, boolean shouldLock) {
-
-               String nodeName = nodeTypeInfoToUpdateArtifacts.getNodeName();
-               Resource resource = preparedResource;
-
-               Map<String, EnumMap<ArtifactOperationEnum, List<ArtifactDefinition>>> nodeTypesArtifactsToHandle = nodeTypeInfoToUpdateArtifacts
-                               .getNodeTypesArtifactsToHandle();
-               if (preparedResource.getResourceType() == ResourceTypeEnum.CVFC) {
-                       if (nodeName != null && nodeTypesArtifactsToHandle.get(nodeName) != null
-                                       && !nodeTypesArtifactsToHandle.get(nodeName)
-                                       .isEmpty()) {
-                               Either<List<ArtifactDefinition>, ResponseFormat> handleNodeTypeArtifactsRes = handleNodeTypeArtifacts(
-                                               preparedResource, nodeTypesArtifactsToHandle.get(nodeName), createdArtifacts,
-                                               csarInfo.getModifier(), inTransaction, true);
-                               if (handleNodeTypeArtifactsRes.isRight()) {
-                                       return Either.right(handleNodeTypeArtifactsRes.right()
-                                                       .value());
-                               }
-                       }
-               } else {
-                       Either<Resource, ResponseFormat> createdCsarArtifactsEither = handleVfCsarArtifacts(preparedResource,
-                                       csarInfo, createdArtifacts,
-                                       new ArtifactOperationInfo(false, false, operation), shouldLock,
-                                       inTransaction);
-                       log.trace("************* Finished to add artifacts from yaml {}", yamlFileName);
-                       if (createdCsarArtifactsEither.isRight()) {
-                               return createdCsarArtifactsEither;
-
-                       }
-                       resource = createdCsarArtifactsEither.left()
-                                       .value();
-               }
-               return Either.left(resource);
-       }
-
-       private Resource handleResourceGenericType(Resource resource) {
-               Resource genericResource = fetchAndSetDerivedFromGenericType(resource);
-               if (resource.shouldGenerateInputs()) {
-                       generateAndAddInputsFromGenericTypeProperties(resource, genericResource);
-               }
-               return genericResource;
-       }
-
-       private Either<Map<String, EnumMap<ArtifactOperationEnum, List<ArtifactDefinition>>>, ResponseFormat> findNodeTypesArtifactsToHandle(
-               final Map<String, NodeTypeInfo> nodeTypesInfo, final CsarInfo csarInfo, final Resource oldResource) {
-
-               final Map<String, EnumMap<ArtifactOperationEnum, List<ArtifactDefinition>>> nodeTypesArtifactsToHandle = new HashMap<>();
-               Either<Map<String, EnumMap<ArtifactOperationEnum, List<ArtifactDefinition>>>, ResponseFormat>
-                       nodeTypesArtifactsToHandleRes = Either.left(nodeTypesArtifactsToHandle);
-
-               try {
-                       final Map<String, List<ArtifactDefinition>> extractedVfcsArtifacts = CsarUtils
-                               .extractVfcsArtifactsFromCsar(csarInfo.getCsar());
-                       final Map<String, ImmutablePair<String, String>> extractedVfcToscaNames = extractVfcToscaNames(
-                               nodeTypesInfo, oldResource.getName(), csarInfo);
-                       log.debug("Going to fetch node types for resource with name {} during import csar with UUID {}. ",
-                               oldResource.getName(), csarInfo.getCsarUUID());
-                       extractedVfcToscaNames.forEach((namespace, vfcToscaNames) -> findAddNodeTypeArtifactsToHandle(csarInfo,
-                               nodeTypesArtifactsToHandle, oldResource, extractedVfcsArtifacts, namespace, vfcToscaNames));
-               } catch (Exception e) {
-                       final ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR);
-                       nodeTypesArtifactsToHandleRes = Either.right(responseFormat);
-                       log.debug("Exception occurred when findNodeTypesUpdatedArtifacts, error is:{}", e.getMessage(), e);
-               }
-               return nodeTypesArtifactsToHandleRes;
-       }
-
-       private void findAddNodeTypeArtifactsToHandle(CsarInfo csarInfo,
-                                                                                                 Map<String, EnumMap<ArtifactOperationEnum, List<ArtifactDefinition>>> nodeTypesArtifactsToHandle,
-                                                                                                 Resource resource, Map<String, List<ArtifactDefinition>> extractedVfcsArtifacts, String namespace,
-                                                                                                 ImmutablePair<String, String> vfcToscaNames) {
-
-               EnumMap<ArtifactOperationEnum, List<ArtifactDefinition>> curNodeTypeArtifactsToHandle = null;
-               log.debug("Going to fetch node type with tosca name {}. ", vfcToscaNames.getLeft());
-               Resource curNodeType = findVfcResource(csarInfo, resource, vfcToscaNames.getLeft(), vfcToscaNames.getRight(),
-                               null);
-               if (!isEmpty(extractedVfcsArtifacts)) {
-                       List<ArtifactDefinition> currArtifacts = new ArrayList<>();
-                       if (extractedVfcsArtifacts.containsKey(namespace)) {
-                               handleAndAddExtractedVfcsArtifacts(currArtifacts, extractedVfcsArtifacts.get(namespace));
-                       }
-                       curNodeTypeArtifactsToHandle = findNodeTypeArtifactsToHandle(curNodeType, currArtifacts);
-               } else if (curNodeType != null) {
-                       // delete all artifacts if have not received artifacts from
-                       // csar
-                       curNodeTypeArtifactsToHandle = new EnumMap<>(ArtifactOperationEnum.class);
-                       List<ArtifactDefinition> artifactsToDelete = new ArrayList<>();
-                       // delete all informational artifacts
-                       artifactsToDelete.addAll(curNodeType.getArtifacts()
-                                       .values()
-                                       .stream()
-                                       .filter(a -> a.getArtifactGroupType() == ArtifactGroupTypeEnum.INFORMATIONAL)
-                                       .collect(toList()));
-                       // delete all deployment artifacts
-                       artifactsToDelete.addAll(curNodeType.getDeploymentArtifacts()
-                                       .values());
-                       if (!artifactsToDelete.isEmpty()) {
-                               curNodeTypeArtifactsToHandle.put(ArtifactOperationEnum.DELETE, artifactsToDelete);
-                       }
-               }
-               if (isNotEmpty(curNodeTypeArtifactsToHandle)) {
-                       nodeTypesArtifactsToHandle.put(namespace, curNodeTypeArtifactsToHandle);
-               }
-       }
-
-       private Resource findVfcResource(CsarInfo csarInfo, Resource resource, String currVfcToscaName,
-                                                                        String previousVfcToscaName, StorageOperationStatus status) {
-               if (status != null && status != StorageOperationStatus.NOT_FOUND) {
-                       log.debug("Error occurred during fetching node type with tosca name {}, error: {}", currVfcToscaName,
-                                       status);
-                       ResponseFormat responseFormat = componentsUtils
-                                       .getResponseFormat(componentsUtils.convertFromStorageResponse(status), csarInfo.getCsarUUID());
-                       componentsUtils.auditResource(responseFormat, csarInfo.getModifier(), resource,
-                                       AuditingActionEnum.CREATE_RESOURCE);
-                       throw new ByActionStatusComponentException(componentsUtils.convertFromStorageResponse(status), csarInfo.getCsarUUID());
-               } else if (StringUtils.isNotEmpty(currVfcToscaName)) {
-                       return (Resource) toscaOperationFacade.getLatestByToscaResourceName(currVfcToscaName)
-                                       .left()
-                                       .on(st -> findVfcResource(csarInfo, resource, previousVfcToscaName, null, st));
-               }
-               return null;
-       }
-
-       private EnumMap<ArtifactOperationEnum, List<ArtifactDefinition>> findNodeTypeArtifactsToHandle(Resource curNodeType,
-                                                                                                                                                                                                  List<ArtifactDefinition> extractedArtifacts) {
-
-               try {
-                       List<ArtifactDefinition> artifactsToUpload = new ArrayList<>(extractedArtifacts);
-                       List<ArtifactDefinition> artifactsToUpdate = new ArrayList<>();
-                       List<ArtifactDefinition> artifactsToDelete = new ArrayList<>();
-                       processExistingNodeTypeArtifacts(extractedArtifacts, artifactsToUpload, artifactsToUpdate,
-                                       artifactsToDelete, collectExistingArtifacts(curNodeType));
-                       return putFoundArtifacts(artifactsToUpload, artifactsToUpdate, artifactsToDelete);
-               } catch (Exception e) {
-                       log.debug("Exception occurred when findNodeTypeArtifactsToHandle, error is:{}", e.getMessage(), e);
-                       throw new ByActionStatusComponentException(ActionStatus.GENERAL_ERROR);
-               }
-       }
-
-       private EnumMap<ArtifactOperationEnum, List<ArtifactDefinition>> putFoundArtifacts(
-                       List<ArtifactDefinition> artifactsToUpload, List<ArtifactDefinition> artifactsToUpdate,
-                       List<ArtifactDefinition> artifactsToDelete) {
-               EnumMap<ArtifactOperationEnum, List<ArtifactDefinition>> nodeTypeArtifactsToHandle = null;
-               if (!artifactsToUpload.isEmpty() || !artifactsToUpdate.isEmpty() || !artifactsToDelete.isEmpty()) {
-                       nodeTypeArtifactsToHandle = new EnumMap<>(ArtifactOperationEnum.class);
-                       if (!artifactsToUpload.isEmpty()) {
-                               nodeTypeArtifactsToHandle.put(ArtifactOperationEnum.CREATE, artifactsToUpload);
-                       }
-                       if (!artifactsToUpdate.isEmpty()) {
-                               nodeTypeArtifactsToHandle.put(ArtifactOperationEnum.UPDATE, artifactsToUpdate);
-                       }
-                       if (!artifactsToDelete.isEmpty()) {
-                               nodeTypeArtifactsToHandle.put(ArtifactOperationEnum.DELETE, artifactsToDelete);
-                       }
-               }
-               return nodeTypeArtifactsToHandle;
-       }
-
-       private void processExistingNodeTypeArtifacts(List<ArtifactDefinition> extractedArtifacts,
-                                                                                                 List<ArtifactDefinition> artifactsToUpload, List<ArtifactDefinition> artifactsToUpdate,
-                                                                                                 List<ArtifactDefinition> artifactsToDelete, Map<String, ArtifactDefinition> existingArtifacts) {
-               if (!existingArtifacts.isEmpty()) {
-                       extractedArtifacts.stream()
-                                       .forEach(a -> processNodeTypeArtifact(artifactsToUpload, artifactsToUpdate, existingArtifacts, a));
-                       artifactsToDelete.addAll(existingArtifacts.values());
-               }
-       }
-
-       private void processNodeTypeArtifact(List<ArtifactDefinition> artifactsToUpload,
-                                                                                List<ArtifactDefinition> artifactsToUpdate, Map<String, ArtifactDefinition> existingArtifacts,
-                                                                                ArtifactDefinition currNewArtifact) {
-               Optional<ArtifactDefinition> foundArtifact = existingArtifacts.values()
-                               .stream()
-                               .filter(a -> a.getArtifactName()
-                                               .equals(currNewArtifact.getArtifactName()))
-                               .findFirst();
-               if (foundArtifact.isPresent()) {
-                       if (foundArtifact.get()
-                                       .getArtifactType()
-                                       .equals(currNewArtifact.getArtifactType())) {
-                               updateFoundArtifact(artifactsToUpdate, currNewArtifact, foundArtifact.get());
-                               existingArtifacts.remove(foundArtifact.get()
-                                               .getArtifactLabel());
-                               artifactsToUpload.remove(currNewArtifact);
-                       } else {
-                               log.debug("Can't upload two artifact with the same name {}.", currNewArtifact.getArtifactName());
-                               throw new ByActionStatusComponentException(ActionStatus.ARTIFACT_ALREADY_EXIST_IN_DIFFERENT_TYPE_IN_CSAR,
-                                               currNewArtifact.getArtifactName(), currNewArtifact.getArtifactType(), foundArtifact.get()
-                                               .getArtifactType());
-                       }
-               }
-       }
-
-       private void updateFoundArtifact(List<ArtifactDefinition> artifactsToUpdate, ArtifactDefinition currNewArtifact,
-                                                                        ArtifactDefinition foundArtifact) {
-               if (!foundArtifact.getArtifactChecksum()
-                               .equals(currNewArtifact.getArtifactChecksum())) {
-                       foundArtifact.setPayload(currNewArtifact.getPayloadData());
-                       foundArtifact.setPayloadData(Base64.encodeBase64String(currNewArtifact.getPayloadData()));
-                       foundArtifact.setArtifactChecksum(
-                                       GeneralUtility.calculateMD5Base64EncodedByByteArray(currNewArtifact.getPayloadData()));
-                       artifactsToUpdate.add(foundArtifact);
-               }
-       }
-
-       private Map<String, ArtifactDefinition> collectExistingArtifacts(Resource curNodeType) {
-               Map<String, ArtifactDefinition> existingArtifacts = new HashMap<>();
-               if (curNodeType == null) {
-                       return existingArtifacts;
-               }
-               if (MapUtils.isNotEmpty(curNodeType.getDeploymentArtifacts())) {
-                       existingArtifacts.putAll(curNodeType.getDeploymentArtifacts());
-               }
-               if (MapUtils.isNotEmpty(curNodeType.getArtifacts())) {
-                       existingArtifacts.putAll(curNodeType.getArtifacts()
-                                       .entrySet()
-                                       .stream()
-                                       .filter(e -> e.getValue()
-                                                       .getArtifactGroupType() == ArtifactGroupTypeEnum.INFORMATIONAL)
-                                       .collect(toMap(Map.Entry::getKey, Map.Entry::getValue)));
-               }
-               return existingArtifacts;
-       }
-
-       /**
-        * Changes resource life cycle state to checked out
-        *
-        * @param resource
-        * @param user
-        * @param inTransaction
-        * @return
-        */
-       private Either<Resource, ResponseFormat> checkoutResource(Resource resource, User user, boolean inTransaction) {
-               Either<Resource, ResponseFormat> checkoutResourceRes;
-               try {
-                       if (!resource.getComponentMetadataDefinition()
-                                       .getMetadataDataDefinition()
-                                       .getState()
-                                       .equals(LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT.name())) {
-                               log.debug(
-                                               "************* Going to change life cycle state of resource {} to not certified checked out. ",
-                                               resource.getName());
-                               Either<? extends Component, ResponseFormat> checkoutRes = lifecycleBusinessLogic.changeComponentState(
-                                               resource.getComponentType(), resource.getUniqueId(), user, LifeCycleTransitionEnum.CHECKOUT,
-                                               new LifecycleChangeInfoWithAction(CERTIFICATION_ON_IMPORT,
-                                                               LifecycleChanceActionEnum.CREATE_FROM_CSAR),
-                                               inTransaction, true);
-                               if (checkoutRes.isRight()) {
-                                       log.debug("Could not change state of component {} with uid {} to checked out. Status is {}. ",
-                                                       resource.getComponentType()
-                                                                       .getNodeType(),
-                                                       resource.getUniqueId(), checkoutRes.right()
-                                                                       .value()
-                                                                       .getStatus());
-                                       checkoutResourceRes = Either.right(checkoutRes.right()
-                                                       .value());
-                               } else {
-                                       checkoutResourceRes = Either.left((Resource) checkoutRes.left()
-                                                       .value());
-                               }
-                       } else {
-                               checkoutResourceRes = Either.left(resource);
-                       }
-               } catch (Exception e) {
-                       ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR);
-                       checkoutResourceRes = Either.right(responseFormat);
-                       log.debug("Exception occurred when checkoutResource {} , error is:{}", resource.getName(), e.getMessage(),
-                                       e);
-               }
-               return checkoutResourceRes;
-       }
-
-       /**
-        * Handles Artifacts of NodeType
-        *
-        * @param nodeTypeResource
-        * @param nodeTypeArtifactsToHandle
-        * @param user
-        * @param inTransaction
-        * @return
-        */
-       public Either<List<ArtifactDefinition>, ResponseFormat> handleNodeTypeArtifacts(Resource nodeTypeResource,
-                                                                                                                                                                       Map<ArtifactOperationEnum, List<ArtifactDefinition>> nodeTypeArtifactsToHandle,
-                                                                                                                                                                       List<ArtifactDefinition> createdArtifacts, User user, boolean inTransaction, boolean ignoreLifecycleState) {
-               List<ArtifactDefinition> handleNodeTypeArtifactsRequestRes;
-               Either<List<ArtifactDefinition>, ResponseFormat> handleNodeTypeArtifactsRes = null;
-               Either<Resource, ResponseFormat> changeStateResponse;
-               try {
-                       changeStateResponse = checkoutResource(nodeTypeResource, user, inTransaction);
-                       if (changeStateResponse.isRight()) {
-                               return Either.right(changeStateResponse.right()
-                                               .value());
-                       }
-                       nodeTypeResource = changeStateResponse.left()
-                                       .value();
-
-                       List<ArtifactDefinition> handledNodeTypeArtifacts = new ArrayList<>();
-                       log.debug("************* Going to handle artifacts of node type resource {}. ", nodeTypeResource.getName());
-                       for (Entry<ArtifactOperationEnum, List<ArtifactDefinition>> curOperationEntry : nodeTypeArtifactsToHandle
-                                       .entrySet()) {
-                               ArtifactOperationEnum curOperation = curOperationEntry.getKey();
-                               List<ArtifactDefinition> curArtifactsToHandle = curOperationEntry.getValue();
-                               if (curArtifactsToHandle != null && !curArtifactsToHandle.isEmpty()) {
-                                       log.debug("************* Going to {} artifact to vfc {}", curOperation.name(),
-                                                       nodeTypeResource.getName());
-                                       handleNodeTypeArtifactsRequestRes = artifactsBusinessLogic
-                                                       .handleArtifactsRequestForInnerVfcComponent(curArtifactsToHandle, nodeTypeResource, user,
-                                                                       createdArtifacts, new ArtifactOperationInfo(false,
-                                                                                       ignoreLifecycleState, curOperation),
-                                                                       false, inTransaction);
-                                       if (ArtifactOperationEnum.isCreateOrLink(curOperation)) {
-                                               createdArtifacts.addAll(handleNodeTypeArtifactsRequestRes);
-                                       }
-                                       handledNodeTypeArtifacts.addAll(handleNodeTypeArtifactsRequestRes);
-                               }
-                       }
-                       if (handleNodeTypeArtifactsRes == null) {
-                               handleNodeTypeArtifactsRes = Either.left(handledNodeTypeArtifacts);
-                       }
-               } catch (Exception e) {
-                       ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR);
-                       handleNodeTypeArtifactsRes = Either.right(responseFormat);
-                       log.debug("Exception occurred when handleVfcArtifacts, error is:{}", e.getMessage(), e);
-               }
-               return handleNodeTypeArtifactsRes;
-       }
-
-       private Map<String, ImmutablePair<String, String>> extractVfcToscaNames(final Map<String, NodeTypeInfo> nodeTypesInfo,
-                                                                                                                                                       final String vfResourceName,
-                                                                                                                                                       final CsarInfo csarInfo) {
-               final Map<String, ImmutablePair<String, String>> vfcToscaNames = new HashMap<>();
-
-               final Map<String, Object> nodes = extractAllNodes(nodeTypesInfo, csarInfo);
-               if (!nodes.isEmpty()) {
-                       final Iterator<Entry<String, Object>> nodesNameEntry = nodes.entrySet().iterator();
-                       while (nodesNameEntry.hasNext()) {
-                               final Entry<String, Object> nodeType = nodesNameEntry.next();
-                               final ImmutablePair<String, String> toscaResourceName = buildNestedToscaResourceName(
-                                       ResourceTypeEnum.VFC.name(), vfResourceName, nodeType.getKey());
-                               vfcToscaNames.put(nodeType.getKey(), toscaResourceName);
-                       }
-               }
-               for (final NodeTypeInfo cvfc : nodeTypesInfo.values()) {
-                       vfcToscaNames.put(cvfc.getType(), buildNestedToscaResourceName(ResourceTypeEnum.CVFC.name(),
-                               vfResourceName, cvfc.getType()));
-               }
-               return vfcToscaNames;
-       }
-
-       private Map<String, Object> extractAllNodes(Map<String, NodeTypeInfo> nodeTypesInfo, CsarInfo csarInfo) {
-               Map<String, Object> nodes = new HashMap<>();
-               for (NodeTypeInfo nodeTypeInfo : nodeTypesInfo.values()) {
-                       extractNodeTypes(nodes, nodeTypeInfo.getMappedToscaTemplate());
-               }
-               extractNodeTypes(nodes, csarInfo.getMappedToscaMainTemplate());
-               return nodes;
-       }
-
-       private void extractNodeTypes(Map<String, Object> nodes, Map<String, Object> mappedToscaTemplate) {
-               Either<Map<String, Object>, ResultStatusEnum> eitherNodeTypes = ImportUtils
-                               .findFirstToscaMapElement(mappedToscaTemplate, TypeUtils.ToscaTagNamesEnum.NODE_TYPES);
-               if (eitherNodeTypes.isLeft()) {
-                       nodes.putAll(eitherNodeTypes.left()
-                                       .value());
-               }
-       }
-
-       public Resource createResourceFromCsar(Resource resource, User user, Map<String, byte[]> csarUIPayload,
-                                                                                  String csarUUID) {
-               log.trace("************* created successfully from YAML, resource TOSCA ");
-               loggerSupportability.log(LoggerSupportabilityActions.CREATE_RESOURCE_FROM_YAML,StatusCode.STARTED,"Starting to create Resource From Csar by user {}", user.getUserId() );
-               CsarInfo csarInfo = csarBusinessLogic.getCsarInfo(resource, null, user, csarUIPayload, csarUUID);
-               Map<String, NodeTypeInfo> nodeTypesInfo = csarInfo.extractNodeTypesInfo();
-               Either<Map<String, EnumMap<ArtifactOperationEnum, List<ArtifactDefinition>>>, ResponseFormat> findNodeTypesArtifactsToHandleRes = findNodeTypesArtifactsToHandle(
-                               nodeTypesInfo, csarInfo, resource);
-               if (findNodeTypesArtifactsToHandleRes.isRight()) {
-                       log.debug("failed to find node types for update with artifacts during import csar {}. ",
-                                       csarInfo.getCsarUUID());
-                       loggerSupportability.log(LoggerSupportabilityActions.CREATE_RESOURCE_FROM_YAML,resource.getComponentMetadataForSupportLog(),
-                                       StatusCode.ERROR,"error: {}",findNodeTypesArtifactsToHandleRes.right().value());
-                       throw new ByResponseFormatComponentException(findNodeTypesArtifactsToHandleRes.right().value());
-               }
-               Resource vfResource = createResourceFromYaml(resource, csarInfo.getMainTemplateContent(),
-                               csarInfo.getMainTemplateName(), nodeTypesInfo, csarInfo, findNodeTypesArtifactsToHandleRes.left()
-                                               .value(),
-                               true, false, null);
-               log.trace("*************VF Resource created successfully from YAML, resource TOSCA name: {}",
-                               vfResource.getToscaResourceName());
-               loggerSupportability.log(LoggerSupportabilityActions.CREATE_RESOURCE_FROM_YAML,StatusCode.COMPLETE,"Ended create Resource From Csar by user {}", user.getUserId() );
-               return vfResource;
-       }
-
-       private Resource validateResourceBeforeCreate(Resource resource, User user, boolean inTransaction) {
-               log.trace("validating resource before create");
-               user.copyData(validateUser(user, CREATE_RESOURCE, resource, AuditingActionEnum.CREATE_RESOURCE, false));
-               // validate user role
-               validateUserRole(user, resource, new ArrayList<>(), AuditingActionEnum.CREATE_RESOURCE, null);
-               // VF / PNF "derivedFrom" should be null (or ignored)
-               if (ModelConverter.isAtomicComponent(resource)) {
-                       validateDerivedFromNotEmpty(user, resource, AuditingActionEnum.CREATE_RESOURCE);
-               }
-               return validateResourceBeforeCreate(resource, user, AuditingActionEnum.CREATE_RESOURCE, inTransaction, null);
-
-       }
-
-       // resource, yamlFileContents, yamlFileName, nodeTypesInfo,csarInfo,
-       // nodeTypesArtifactsToCreate, true, false, null
-       private Resource createResourceFromYaml(Resource resource, String topologyTemplateYaml, String yamlName,
-                                                                                       Map<String, NodeTypeInfo> nodeTypesInfo, CsarInfo csarInfo,
-                                                                                       Map<String, EnumMap<ArtifactOperationEnum, List<ArtifactDefinition>>> nodeTypesArtifactsToCreate,
-                                                                                       boolean shouldLock, boolean inTransaction, String nodeName) {
-
-               List<ArtifactDefinition> createdArtifacts = new ArrayList<>();
-               Resource createdResource;
-               try {
-            ParsedToscaYamlInfo parsedToscaYamlInfo = csarBusinessLogic.getParsedToscaYamlInfo(topologyTemplateYaml, yamlName, nodeTypesInfo, csarInfo, nodeName, resource);
+            preparedResource = updateExistingResourceByImport(newResource, oldResource, csarInfo.getModifier(), inTransaction, shouldLock,
+                isNested).left;
+            log.trace("YAML topology file found in CSAR, file name: {}, contents: {}", yamlFileName, yamlFileContent);
+            handleResourceGenericType(preparedResource);
+            handleNodeTypes(yamlFileName, preparedResource, yamlFileContent, shouldLock, nodeTypesArtifactsToHandle, createdArtifacts, nodeTypesInfo,
+                csarInfo, nodeName);
+            preparedResource = createInputsOnResource(preparedResource, uploadComponentInstanceInfoMap.getInputs());
+            Map<String, Resource> existingNodeTypesByResourceNames = new HashMap<>();
+            preparedResource = createResourceInstances(yamlFileName, preparedResource, oldResource, instances, csarInfo.getCreatedNodes(),
+                existingNodeTypesByResourceNames);
+            preparedResource = createResourceInstancesRelations(csarInfo.getModifier(), yamlFileName, preparedResource, oldResource, instances,
+                existingNodeTypesByResourceNames);
+        } catch (ComponentException e) {
+            ResponseFormat responseFormat =
+                e.getResponseFormat() == null ? componentsUtils.getResponseFormat(e.getActionStatus(), e.getParams()) : e.getResponseFormat();
+            log.debug("#updateResourceFromYaml - failed to update newResource from yaml {} .The error is {}", yamlFileName, responseFormat);
+            componentsUtils
+                .auditResource(responseFormat, csarInfo.getModifier(), preparedResource == null ? oldResource : preparedResource, actionEnum);
+            throw e;
+        } catch (StorageException e) {
+            ResponseFormat responseFormat = componentsUtils
+                .getResponseFormat(componentsUtils.convertFromStorageResponse(e.getStorageOperationStatus()));
+            log.debug("#updateResourceFromYaml - failed to update newResource from yaml {} .The error is {}", yamlFileName, responseFormat);
+            componentsUtils
+                .auditResource(responseFormat, csarInfo.getModifier(), preparedResource == null ? oldResource : preparedResource, actionEnum);
+            throw e;
+        }
+        Either<Map<String, GroupDefinition>, ResponseFormat> validateUpdateVfGroupNamesRes = groupBusinessLogic
+            .validateUpdateVfGroupNames(uploadComponentInstanceInfoMap.getGroups(), preparedResource.getSystemName());
+        if (validateUpdateVfGroupNamesRes.isRight()) {
+            throw new ByResponseFormatComponentException(validateUpdateVfGroupNamesRes.right().value());
+        }
+        // add groups to newResource
+        Map<String, GroupDefinition> groups;
+        if (!validateUpdateVfGroupNamesRes.left().value().isEmpty()) {
+            groups = validateUpdateVfGroupNamesRes.left().value();
+        } else {
+            groups = uploadComponentInstanceInfoMap.getGroups();
+        }
+        handleGroupsProperties(preparedResource, groups);
+        Either<Boolean, ActionStatus> isTopologyChanged = topologyComparator.isTopologyChanged(oldResource, preparedResource);
+        preparedResource = updateGroupsOnResource(preparedResource, groups);
+        NodeTypeInfoToUpdateArtifacts nodeTypeInfoToUpdateArtifacts = new NodeTypeInfoToUpdateArtifacts(nodeName, nodeTypesArtifactsToHandle);
+        Either<Resource, ResponseFormat> updateArtifactsEither = createOrUpdateArtifacts(ArtifactOperationEnum.UPDATE, createdArtifacts, yamlFileName,
+            csarInfo, preparedResource, nodeTypeInfoToUpdateArtifacts, inTransaction, shouldLock);
+        if (updateArtifactsEither.isRight()) {
+            log.debug("failed to update artifacts {}", updateArtifactsEither.right().value());
+            throw new ByResponseFormatComponentException(updateArtifactsEither.right().value());
+        }
+        preparedResource = getResourceWithGroups(updateArtifactsEither.left().value().getUniqueId());
+        updateGroupsName(oldResource, preparedResource, isTopologyChanged.left().value());
+        updateResourceInstancesNames(oldResource, csarInfo, preparedResource, isTopologyChanged.left().value());
+        final String preparedResourceId = preparedResource != null ? preparedResource.getUniqueId() : "";
+        preparedResource = getResourceWithGroups(preparedResourceId);
+        updateVolumeGroup(preparedResource);
+        ActionStatus mergingPropsAndInputsStatus = resourceDataMergeBusinessLogic.mergeResourceEntities(oldResource, preparedResource);
+        if (mergingPropsAndInputsStatus != ActionStatus.OK) {
+            ResponseFormat responseFormat = componentsUtils.getResponseFormatByResource(mergingPropsAndInputsStatus, preparedResource);
+            throw new ByResponseFormatComponentException(responseFormat);
+        }
+        compositionBusinessLogic.setPositionsForComponentInstances(preparedResource, csarInfo.getModifier().getUserId());
+        return preparedResource;
+    }
+
+    protected void updateVolumeGroup(Resource preparedResource) {
+        List<GroupDefinition> groups = preparedResource.safeGetGroups();
+        for (GroupDefinition group : groups) {
+            Map<String, ArtifactDefinition> createdNewArtifacts = preparedResource.getDeploymentArtifacts();
+            if (DEFAULT_GROUP_VF_MODULE.equals(group.getType())) {
+                List<PropertyDataDefinition> volumePropList = group.getProperties().stream().filter(p -> "volume_group".equals(p.getName()))
+                    .collect(Collectors.toList());
+                if (!volumePropList.isEmpty()) {
+                    PropertyDataDefinition volumeProp = volumePropList.get(0);
+                    if (volumeProp != null) {
+                        boolean isVolumeGroup = isVolumeGroup(group.getArtifacts(), new ArrayList<>(createdNewArtifacts.values()));
+                        if (!volumePropList.get(0).getValue().equals(String.valueOf(isVolumeGroup))) {
+                            volumeProp.setValue(String.valueOf(isVolumeGroup));
+                            volumeProp.setDefaultValue(String.valueOf(isVolumeGroup));
+                        }
+                    }
+                }
+            }
+        }
+    }
+
+    private void updateGroupsName(Resource oldResource, Resource preparedResource, boolean isTopologyChanged) {
+        if (oldResource == null || preparedResource == null) {
+            log.debug("Failed to update groups name : oldResource or preparedResource is null");
+        } else if (CollectionUtils.isNotEmpty(oldResource.getGroups()) && CollectionUtils.isNotEmpty(preparedResource.getGroups())) {
+            Map<String, String> oldGroups = oldResource.getGroups().stream()
+                .collect(toMap(GroupDataDefinition::getInvariantName, GroupDataDefinition::getName));
+            List<GroupDefinition> updatedGroups = preparedResource.getGroups().stream()
+                .filter(group -> oldGroups.containsKey(group.getInvariantName()) && !group.getName().equals(oldGroups.get(group.getInvariantName())))
+                .collect(toList());
+            if (CollectionUtils.isNotEmpty(updatedGroups)) {
+                if (isTopologyChanged) {
+                    updatedGroups.stream().filter(group -> !group.isVspOriginated())
+                        .forEach(group -> group.setName(oldGroups.get(group.getInvariantName())));
+                } else {
+                    updatedGroups.forEach(group -> group.setName(oldGroups.get(group.getInvariantName())));
+                }
+                groupBusinessLogic.updateGroups(preparedResource, updatedGroups, false);
+            }
+        }
+    }
+
+    private void updateResourceInstancesNames(Resource oldResource, CsarInfo csarInfo, Resource preparedResource, boolean isTopologyChanged) {
+        if (oldResource == null || preparedResource == null) {
+            log.debug("Failed to update resource instances names : oldResource or preparedResource is null");
+        } else {
+            if (CollectionUtils.isNotEmpty(oldResource.getComponentInstances())) {
+                Map<String, String> oldInstances = oldResource.getComponentInstances().stream()
+                    .collect(toMap(ComponentInstance::getInvariantName, ComponentInstance::getName));
+                List<ComponentInstance> updatedInstances = preparedResource.getComponentInstances().stream()
+                    .filter(i -> oldInstances.containsKey(i.getInvariantName()) && !i.getName().equals(oldInstances.get(i.getInvariantName())))
+                    .collect(toList());
+                if (CollectionUtils.isNotEmpty(updatedInstances)) {
+                    if (isTopologyChanged) {
+                        updatedInstances.stream().filter(i -> !i.isCreatedFromCsar()).forEach(i -> i.setName(oldInstances.get(i.getInvariantName())));
+                    } else {
+                        updatedInstances.forEach(i -> i.setName(oldInstances.get(i.getInvariantName())));
+                    }
+                }
+            }
+            componentInstanceBusinessLogic.updateComponentInstance(ComponentTypeEnum.RESOURCE_PARAM_NAME, null, preparedResource.getUniqueId(),
+                csarInfo.getModifier().getUserId(), preparedResource.getComponentInstances(), false);
+        }
+    }
+
+    private Either<Resource, ResponseFormat> createOrUpdateArtifacts(ArtifactOperationEnum operation, List<ArtifactDefinition> createdArtifacts,
+                                                                     String yamlFileName, CsarInfo csarInfo, Resource preparedResource,
+                                                                     NodeTypeInfoToUpdateArtifacts nodeTypeInfoToUpdateArtifacts,
+                                                                     boolean inTransaction, boolean shouldLock) {
+        String nodeName = nodeTypeInfoToUpdateArtifacts.getNodeName();
+        Resource resource = preparedResource;
+        Map<String, EnumMap<ArtifactOperationEnum, List<ArtifactDefinition>>> nodeTypesArtifactsToHandle = nodeTypeInfoToUpdateArtifacts
+            .getNodeTypesArtifactsToHandle();
+        if (preparedResource.getResourceType() == ResourceTypeEnum.CVFC) {
+            if (nodeName != null && nodeTypesArtifactsToHandle.get(nodeName) != null && !nodeTypesArtifactsToHandle.get(nodeName).isEmpty()) {
+                Either<List<ArtifactDefinition>, ResponseFormat> handleNodeTypeArtifactsRes = handleNodeTypeArtifacts(preparedResource,
+                    nodeTypesArtifactsToHandle.get(nodeName), createdArtifacts, csarInfo.getModifier(), inTransaction, true);
+                if (handleNodeTypeArtifactsRes.isRight()) {
+                    return Either.right(handleNodeTypeArtifactsRes.right().value());
+                }
+            }
+        } else {
+            Either<Resource, ResponseFormat> createdCsarArtifactsEither = handleVfCsarArtifacts(preparedResource, csarInfo, createdArtifacts,
+                new ArtifactOperationInfo(false, false, operation), shouldLock, inTransaction);
+            log.trace("************* Finished to add artifacts from yaml {}", yamlFileName);
+            if (createdCsarArtifactsEither.isRight()) {
+                return createdCsarArtifactsEither;
+            }
+            resource = createdCsarArtifactsEither.left().value();
+        }
+        return Either.left(resource);
+    }
+
+    private Resource handleResourceGenericType(Resource resource) {
+        Resource genericResource = fetchAndSetDerivedFromGenericType(resource);
+        if (resource.shouldGenerateInputs()) {
+            generateAndAddInputsFromGenericTypeProperties(resource, genericResource);
+        }
+        return genericResource;
+    }
+
+    private Either<Map<String, EnumMap<ArtifactOperationEnum, List<ArtifactDefinition>>>, ResponseFormat> findNodeTypesArtifactsToHandle(
+        final Map<String, NodeTypeInfo> nodeTypesInfo, final CsarInfo csarInfo, final Resource oldResource) {
+        final Map<String, EnumMap<ArtifactOperationEnum, List<ArtifactDefinition>>> nodeTypesArtifactsToHandle = new HashMap<>();
+        Either<Map<String, EnumMap<ArtifactOperationEnum, List<ArtifactDefinition>>>, ResponseFormat> nodeTypesArtifactsToHandleRes = Either
+            .left(nodeTypesArtifactsToHandle);
+        try {
+            final Map<String, List<ArtifactDefinition>> extractedVfcsArtifacts = CsarUtils.extractVfcsArtifactsFromCsar(csarInfo.getCsar());
+            final Map<String, ImmutablePair<String, String>> extractedVfcToscaNames = extractVfcToscaNames(nodeTypesInfo, oldResource.getName(),
+                csarInfo);
+            log.debug("Going to fetch node types for resource with name {} during import csar with UUID {}. ", oldResource.getName(),
+                csarInfo.getCsarUUID());
+            extractedVfcToscaNames.forEach(
+                (namespace, vfcToscaNames) -> findAddNodeTypeArtifactsToHandle(csarInfo, nodeTypesArtifactsToHandle, oldResource,
+                    extractedVfcsArtifacts, namespace, vfcToscaNames));
+        } catch (Exception e) {
+            final ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR);
+            nodeTypesArtifactsToHandleRes = Either.right(responseFormat);
+            log.debug("Exception occurred when findNodeTypesUpdatedArtifacts, error is:{}", e.getMessage(), e);
+        }
+        return nodeTypesArtifactsToHandleRes;
+    }
+
+    private void findAddNodeTypeArtifactsToHandle(CsarInfo csarInfo,
+                                                  Map<String, EnumMap<ArtifactOperationEnum, List<ArtifactDefinition>>> nodeTypesArtifactsToHandle,
+                                                  Resource resource, Map<String, List<ArtifactDefinition>> extractedVfcsArtifacts, String namespace,
+                                                  ImmutablePair<String, String> vfcToscaNames) {
+        EnumMap<ArtifactOperationEnum, List<ArtifactDefinition>> curNodeTypeArtifactsToHandle = null;
+        log.debug("Going to fetch node type with tosca name {}. ", vfcToscaNames.getLeft());
+        Resource curNodeType = findVfcResource(csarInfo, resource, vfcToscaNames.getLeft(), vfcToscaNames.getRight(), null);
+        if (!isEmpty(extractedVfcsArtifacts)) {
+            List<ArtifactDefinition> currArtifacts = new ArrayList<>();
+            if (extractedVfcsArtifacts.containsKey(namespace)) {
+                handleAndAddExtractedVfcsArtifacts(currArtifacts, extractedVfcsArtifacts.get(namespace));
+            }
+            curNodeTypeArtifactsToHandle = findNodeTypeArtifactsToHandle(curNodeType, currArtifacts);
+        } else if (curNodeType != null) {
+            // delete all artifacts if have not received artifacts from
+
+            // csar
+            curNodeTypeArtifactsToHandle = new EnumMap<>(ArtifactOperationEnum.class);
+            List<ArtifactDefinition> artifactsToDelete = new ArrayList<>();
+            // delete all informational artifacts
+            artifactsToDelete.addAll(
+                curNodeType.getArtifacts().values().stream().filter(a -> a.getArtifactGroupType() == ArtifactGroupTypeEnum.INFORMATIONAL)
+                    .collect(toList()));
+            // delete all deployment artifacts
+            artifactsToDelete.addAll(curNodeType.getDeploymentArtifacts().values());
+            if (!artifactsToDelete.isEmpty()) {
+                curNodeTypeArtifactsToHandle.put(ArtifactOperationEnum.DELETE, artifactsToDelete);
+            }
+        }
+        if (isNotEmpty(curNodeTypeArtifactsToHandle)) {
+            nodeTypesArtifactsToHandle.put(namespace, curNodeTypeArtifactsToHandle);
+        }
+    }
+
+    private Resource findVfcResource(CsarInfo csarInfo, Resource resource, String currVfcToscaName, String previousVfcToscaName,
+                                     StorageOperationStatus status) {
+        if (status != null && status != StorageOperationStatus.NOT_FOUND) {
+            log.debug("Error occurred during fetching node type with tosca name {}, error: {}", currVfcToscaName, status);
+            ResponseFormat responseFormat = componentsUtils
+                .getResponseFormat(componentsUtils.convertFromStorageResponse(status), csarInfo.getCsarUUID());
+            componentsUtils.auditResource(responseFormat, csarInfo.getModifier(), resource, AuditingActionEnum.CREATE_RESOURCE);
+            throw new ByActionStatusComponentException(componentsUtils.convertFromStorageResponse(status), csarInfo.getCsarUUID());
+        } else if (StringUtils.isNotEmpty(currVfcToscaName)) {
+            return (Resource) toscaOperationFacade.getLatestByToscaResourceName(currVfcToscaName).left()
+                .on(st -> findVfcResource(csarInfo, resource, previousVfcToscaName, null, st));
+        }
+        return null;
+    }
+
+    private EnumMap<ArtifactOperationEnum, List<ArtifactDefinition>> findNodeTypeArtifactsToHandle(Resource curNodeType,
+                                                                                                   List<ArtifactDefinition> extractedArtifacts) {
+        try {
+            List<ArtifactDefinition> artifactsToUpload = new ArrayList<>(extractedArtifacts);
+            List<ArtifactDefinition> artifactsToUpdate = new ArrayList<>();
+            List<ArtifactDefinition> artifactsToDelete = new ArrayList<>();
+            processExistingNodeTypeArtifacts(extractedArtifacts, artifactsToUpload, artifactsToUpdate, artifactsToDelete,
+                collectExistingArtifacts(curNodeType));
+            return putFoundArtifacts(artifactsToUpload, artifactsToUpdate, artifactsToDelete);
+        } catch (Exception e) {
+            log.debug("Exception occurred when findNodeTypeArtifactsToHandle, error is:{}", e.getMessage(), e);
+            throw new ByActionStatusComponentException(ActionStatus.GENERAL_ERROR);
+        }
+    }
+
+    private EnumMap<ArtifactOperationEnum, List<ArtifactDefinition>> putFoundArtifacts(List<ArtifactDefinition> artifactsToUpload,
+                                                                                       List<ArtifactDefinition> artifactsToUpdate,
+                                                                                       List<ArtifactDefinition> artifactsToDelete) {
+        EnumMap<ArtifactOperationEnum, List<ArtifactDefinition>> nodeTypeArtifactsToHandle = null;
+        if (!artifactsToUpload.isEmpty() || !artifactsToUpdate.isEmpty() || !artifactsToDelete.isEmpty()) {
+            nodeTypeArtifactsToHandle = new EnumMap<>(ArtifactOperationEnum.class);
+            if (!artifactsToUpload.isEmpty()) {
+                nodeTypeArtifactsToHandle.put(ArtifactOperationEnum.CREATE, artifactsToUpload);
+            }
+            if (!artifactsToUpdate.isEmpty()) {
+                nodeTypeArtifactsToHandle.put(ArtifactOperationEnum.UPDATE, artifactsToUpdate);
+            }
+            if (!artifactsToDelete.isEmpty()) {
+                nodeTypeArtifactsToHandle.put(ArtifactOperationEnum.DELETE, artifactsToDelete);
+            }
+        }
+        return nodeTypeArtifactsToHandle;
+    }
+
+    private void processExistingNodeTypeArtifacts(List<ArtifactDefinition> extractedArtifacts, List<ArtifactDefinition> artifactsToUpload,
+                                                  List<ArtifactDefinition> artifactsToUpdate, List<ArtifactDefinition> artifactsToDelete,
+                                                  Map<String, ArtifactDefinition> existingArtifacts) {
+        if (!existingArtifacts.isEmpty()) {
+            extractedArtifacts.stream().forEach(a -> processNodeTypeArtifact(artifactsToUpload, artifactsToUpdate, existingArtifacts, a));
+            artifactsToDelete.addAll(existingArtifacts.values());
+        }
+    }
+
+    private void processNodeTypeArtifact(List<ArtifactDefinition> artifactsToUpload, List<ArtifactDefinition> artifactsToUpdate,
+                                         Map<String, ArtifactDefinition> existingArtifacts, ArtifactDefinition currNewArtifact) {
+        Optional<ArtifactDefinition> foundArtifact = existingArtifacts.values().stream()
+            .filter(a -> a.getArtifactName().equals(currNewArtifact.getArtifactName())).findFirst();
+        if (foundArtifact.isPresent()) {
+            if (foundArtifact.get().getArtifactType().equals(currNewArtifact.getArtifactType())) {
+                updateFoundArtifact(artifactsToUpdate, currNewArtifact, foundArtifact.get());
+                existingArtifacts.remove(foundArtifact.get().getArtifactLabel());
+                artifactsToUpload.remove(currNewArtifact);
+            } else {
+                log.debug("Can't upload two artifact with the same name {}.", currNewArtifact.getArtifactName());
+                throw new ByActionStatusComponentException(ActionStatus.ARTIFACT_ALREADY_EXIST_IN_DIFFERENT_TYPE_IN_CSAR,
+                    currNewArtifact.getArtifactName(), currNewArtifact.getArtifactType(), foundArtifact.get().getArtifactType());
+            }
+        }
+    }
+
+    private void updateFoundArtifact(List<ArtifactDefinition> artifactsToUpdate, ArtifactDefinition currNewArtifact,
+                                     ArtifactDefinition foundArtifact) {
+        if (!foundArtifact.getArtifactChecksum().equals(currNewArtifact.getArtifactChecksum())) {
+            foundArtifact.setPayload(currNewArtifact.getPayloadData());
+            foundArtifact.setPayloadData(Base64.encodeBase64String(currNewArtifact.getPayloadData()));
+            foundArtifact.setArtifactChecksum(GeneralUtility.calculateMD5Base64EncodedByByteArray(currNewArtifact.getPayloadData()));
+            artifactsToUpdate.add(foundArtifact);
+        }
+    }
+
+    private Map<String, ArtifactDefinition> collectExistingArtifacts(Resource curNodeType) {
+        Map<String, ArtifactDefinition> existingArtifacts = new HashMap<>();
+        if (curNodeType == null) {
+            return existingArtifacts;
+        }
+        if (MapUtils.isNotEmpty(curNodeType.getDeploymentArtifacts())) {
+            existingArtifacts.putAll(curNodeType.getDeploymentArtifacts());
+        }
+        if (MapUtils.isNotEmpty(curNodeType.getArtifacts())) {
+            existingArtifacts.putAll(
+                curNodeType.getArtifacts().entrySet().stream().filter(e -> e.getValue().getArtifactGroupType() == ArtifactGroupTypeEnum.INFORMATIONAL)
+                    .collect(toMap(Map.Entry::getKey, Map.Entry::getValue)));
+        }
+        return existingArtifacts;
+    }
+
+    /**
+     * Changes resource life cycle state to checked out
+     *
+     * @param resource
+     * @param user
+     * @param inTransaction
+     * @return
+     */
+    private Either<Resource, ResponseFormat> checkoutResource(Resource resource, User user, boolean inTransaction) {
+        Either<Resource, ResponseFormat> checkoutResourceRes;
+        try {
+            if (!resource.getComponentMetadataDefinition().getMetadataDataDefinition().getState()
+                .equals(LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT.name())) {
+                log.debug("************* Going to change life cycle state of resource {} to not certified checked out. ", resource.getName());
+                Either<? extends Component, ResponseFormat> checkoutRes = lifecycleBusinessLogic
+                    .changeComponentState(resource.getComponentType(), resource.getUniqueId(), user, LifeCycleTransitionEnum.CHECKOUT,
+                        new LifecycleChangeInfoWithAction(CERTIFICATION_ON_IMPORT, LifecycleChanceActionEnum.CREATE_FROM_CSAR), inTransaction, true);
+                if (checkoutRes.isRight()) {
+                    log.debug("Could not change state of component {} with uid {} to checked out. Status is {}. ",
+                        resource.getComponentType().getNodeType(), resource.getUniqueId(), checkoutRes.right().value().getStatus());
+                    checkoutResourceRes = Either.right(checkoutRes.right().value());
+                } else {
+                    checkoutResourceRes = Either.left((Resource) checkoutRes.left().value());
+                }
+            } else {
+                checkoutResourceRes = Either.left(resource);
+            }
+        } catch (Exception e) {
+            ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR);
+            checkoutResourceRes = Either.right(responseFormat);
+            log.debug("Exception occurred when checkoutResource {} , error is:{}", resource.getName(), e.getMessage(), e);
+        }
+        return checkoutResourceRes;
+    }
+
+    /**
+     * Handles Artifacts of NodeType
+     *
+     * @param nodeTypeResource
+     * @param nodeTypeArtifactsToHandle
+     * @param user
+     * @param inTransaction
+     * @return
+     */
+    public Either<List<ArtifactDefinition>, ResponseFormat> handleNodeTypeArtifacts(Resource nodeTypeResource,
+                                                                                    Map<ArtifactOperationEnum, List<ArtifactDefinition>> nodeTypeArtifactsToHandle,
+                                                                                    List<ArtifactDefinition> createdArtifacts, User user,
+                                                                                    boolean inTransaction, boolean ignoreLifecycleState) {
+        List<ArtifactDefinition> handleNodeTypeArtifactsRequestRes;
+        Either<List<ArtifactDefinition>, ResponseFormat> handleNodeTypeArtifactsRes = null;
+        Either<Resource, ResponseFormat> changeStateResponse;
+        try {
+            changeStateResponse = checkoutResource(nodeTypeResource, user, inTransaction);
+            if (changeStateResponse.isRight()) {
+                return Either.right(changeStateResponse.right().value());
+            }
+            nodeTypeResource = changeStateResponse.left().value();
+            List<ArtifactDefinition> handledNodeTypeArtifacts = new ArrayList<>();
+            log.debug("************* Going to handle artifacts of node type resource {}. ", nodeTypeResource.getName());
+            for (Entry<ArtifactOperationEnum, List<ArtifactDefinition>> curOperationEntry : nodeTypeArtifactsToHandle.entrySet()) {
+                ArtifactOperationEnum curOperation = curOperationEntry.getKey();
+                List<ArtifactDefinition> curArtifactsToHandle = curOperationEntry.getValue();
+                if (curArtifactsToHandle != null && !curArtifactsToHandle.isEmpty()) {
+                    log.debug("************* Going to {} artifact to vfc {}", curOperation.name(), nodeTypeResource.getName());
+                    handleNodeTypeArtifactsRequestRes = artifactsBusinessLogic
+                        .handleArtifactsRequestForInnerVfcComponent(curArtifactsToHandle, nodeTypeResource, user, createdArtifacts,
+                            new ArtifactOperationInfo(false, ignoreLifecycleState, curOperation), false, inTransaction);
+                    if (ArtifactOperationEnum.isCreateOrLink(curOperation)) {
+                        createdArtifacts.addAll(handleNodeTypeArtifactsRequestRes);
+                    }
+                    handledNodeTypeArtifacts.addAll(handleNodeTypeArtifactsRequestRes);
+                }
+            }
+            if (handleNodeTypeArtifactsRes == null) {
+                handleNodeTypeArtifactsRes = Either.left(handledNodeTypeArtifacts);
+            }
+        } catch (Exception e) {
+            ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR);
+            handleNodeTypeArtifactsRes = Either.right(responseFormat);
+            log.debug("Exception occurred when handleVfcArtifacts, error is:{}", e.getMessage(), e);
+        }
+        return handleNodeTypeArtifactsRes;
+    }
+
+    private Map<String, ImmutablePair<String, String>> extractVfcToscaNames(final Map<String, NodeTypeInfo> nodeTypesInfo,
+                                                                            final String vfResourceName, final CsarInfo csarInfo) {
+        final Map<String, ImmutablePair<String, String>> vfcToscaNames = new HashMap<>();
+        final Map<String, Object> nodes = extractAllNodes(nodeTypesInfo, csarInfo);
+        if (!nodes.isEmpty()) {
+            final Iterator<Entry<String, Object>> nodesNameEntry = nodes.entrySet().iterator();
+            while (nodesNameEntry.hasNext()) {
+                final Entry<String, Object> nodeType = nodesNameEntry.next();
+                final ImmutablePair<String, String> toscaResourceName = buildNestedToscaResourceName(ResourceTypeEnum.VFC.name(), vfResourceName,
+                    nodeType.getKey());
+                vfcToscaNames.put(nodeType.getKey(), toscaResourceName);
+            }
+        }
+        for (final NodeTypeInfo cvfc : nodeTypesInfo.values()) {
+            vfcToscaNames.put(cvfc.getType(), buildNestedToscaResourceName(ResourceTypeEnum.CVFC.name(), vfResourceName, cvfc.getType()));
+        }
+        return vfcToscaNames;
+    }
+
+    private Map<String, Object> extractAllNodes(Map<String, NodeTypeInfo> nodeTypesInfo, CsarInfo csarInfo) {
+        Map<String, Object> nodes = new HashMap<>();
+        for (NodeTypeInfo nodeTypeInfo : nodeTypesInfo.values()) {
+            extractNodeTypes(nodes, nodeTypeInfo.getMappedToscaTemplate());
+        }
+        extractNodeTypes(nodes, csarInfo.getMappedToscaMainTemplate());
+        return nodes;
+    }
+
+    private void extractNodeTypes(Map<String, Object> nodes, Map<String, Object> mappedToscaTemplate) {
+        Either<Map<String, Object>, ResultStatusEnum> eitherNodeTypes = ImportUtils
+            .findFirstToscaMapElement(mappedToscaTemplate, TypeUtils.ToscaTagNamesEnum.NODE_TYPES);
+        if (eitherNodeTypes.isLeft()) {
+            nodes.putAll(eitherNodeTypes.left().value());
+        }
+    }
+
+    public Resource createResourceFromCsar(Resource resource, User user, Map<String, byte[]> csarUIPayload, String csarUUID) {
+        log.trace("************* created successfully from YAML, resource TOSCA ");
+        loggerSupportability
+            .log(LoggerSupportabilityActions.CREATE_RESOURCE_FROM_YAML, StatusCode.STARTED, "Starting to create Resource From Csar by user {}",
+                user.getUserId());
+        CsarInfo csarInfo = csarBusinessLogic.getCsarInfo(resource, null, user, csarUIPayload, csarUUID);
+        Map<String, NodeTypeInfo> nodeTypesInfo = csarInfo.extractNodeTypesInfo();
+        Either<Map<String, EnumMap<ArtifactOperationEnum, List<ArtifactDefinition>>>, ResponseFormat> findNodeTypesArtifactsToHandleRes = findNodeTypesArtifactsToHandle(
+            nodeTypesInfo, csarInfo, resource);
+        if (findNodeTypesArtifactsToHandleRes.isRight()) {
+            log.debug("failed to find node types for update with artifacts during import csar {}. ", csarInfo.getCsarUUID());
+            loggerSupportability
+                .log(LoggerSupportabilityActions.CREATE_RESOURCE_FROM_YAML, resource.getComponentMetadataForSupportLog(), StatusCode.ERROR,
+                    "error: {}", findNodeTypesArtifactsToHandleRes.right().value());
+            throw new ByResponseFormatComponentException(findNodeTypesArtifactsToHandleRes.right().value());
+        }
+        Resource vfResource = createResourceFromYaml(resource, csarInfo.getMainTemplateContent(), csarInfo.getMainTemplateName(), nodeTypesInfo,
+            csarInfo, findNodeTypesArtifactsToHandleRes.left().value(), true, false, null);
+        log.trace("*************VF Resource created successfully from YAML, resource TOSCA name: {}", vfResource.getToscaResourceName());
+        loggerSupportability
+            .log(LoggerSupportabilityActions.CREATE_RESOURCE_FROM_YAML, StatusCode.COMPLETE, "Ended create Resource From Csar by user {}",
+                user.getUserId());
+        return vfResource;
+    }
+
+    private Resource validateResourceBeforeCreate(Resource resource, User user, boolean inTransaction) {
+        log.trace("validating resource before create");
+        user.copyData(validateUser(user, CREATE_RESOURCE, resource, AuditingActionEnum.CREATE_RESOURCE, false));
+        // validate user role
+        validateUserRole(user, resource, new ArrayList<>(), AuditingActionEnum.CREATE_RESOURCE, null);
+        // VF / PNF "derivedFrom" should be null (or ignored)
+        if (ModelConverter.isAtomicComponent(resource)) {
+            validateDerivedFromNotEmpty(user, resource, AuditingActionEnum.CREATE_RESOURCE);
+        }
+        return validateResourceBeforeCreate(resource, user, AuditingActionEnum.CREATE_RESOURCE, inTransaction, null);
+    }
+
+    private Resource createResourceFromYaml(Resource resource, String topologyTemplateYaml, String yamlName, Map<String, NodeTypeInfo> nodeTypesInfo,
+                                            CsarInfo csarInfo,
+                                            Map<String, EnumMap<ArtifactOperationEnum, List<ArtifactDefinition>>> nodeTypesArtifactsToCreate,
+                                            boolean shouldLock, boolean inTransaction, String nodeName) {
+        List<ArtifactDefinition> createdArtifacts = new ArrayList<>();
+        Resource createdResource;
+        try {
+            ParsedToscaYamlInfo parsedToscaYamlInfo = csarBusinessLogic
+                .getParsedToscaYamlInfo(topologyTemplateYaml, yamlName, nodeTypesInfo, csarInfo, nodeName, resource);
             if (MapUtils.isEmpty(parsedToscaYamlInfo.getInstances()) && resource.getResourceType() != ResourceTypeEnum.PNF) {
                 throw new ByActionStatusComponentException(ActionStatus.NOT_TOPOLOGY_TOSCA_TEMPLATE, yamlName);
             }
-                       log.debug("#createResourceFromYaml - Going to create resource {} and RIs ", resource.getName());
-                       loggerSupportability.log(LoggerSupportabilityActions.CREATE_RESOURCE_FROM_YAML,resource.getComponentMetadataForSupportLog(),
-                                       StatusCode.STARTED,"");
-                       createdResource = createResourceAndRIsFromYaml(yamlName, resource, parsedToscaYamlInfo,
-                                       AuditingActionEnum.IMPORT_RESOURCE, false, createdArtifacts, topologyTemplateYaml, nodeTypesInfo,
-                                       csarInfo, nodeTypesArtifactsToCreate, shouldLock, inTransaction, nodeName);
-                       log.debug("#createResourceFromYaml - The resource {} has been created ", resource.getName());
-                       loggerSupportability.log(LoggerSupportabilityActions.CREATE_RESOURCE_FROM_YAML,resource.getComponentMetadataForSupportLog(),
-                                       StatusCode.COMPLETE,"The resource has been created: {}",resource.getName());
-               } catch (ComponentException e) {
-                       ResponseFormat responseFormat = e.getResponseFormat() == null
-                                       ? componentsUtils.getResponseFormat(e.getActionStatus(), e.getParams()) : e.getResponseFormat();
-                       componentsUtils.auditResource(responseFormat, csarInfo.getModifier(), resource,
-                                       AuditingActionEnum.IMPORT_RESOURCE);
-                       throw e;
-               } catch (StorageException e) {
-                       ResponseFormat responseFormat = componentsUtils
-                                       .getResponseFormat(componentsUtils.convertFromStorageResponse(e.getStorageOperationStatus()));
-                       componentsUtils.auditResource(responseFormat, csarInfo.getModifier(), resource,
-                                       AuditingActionEnum.IMPORT_RESOURCE);
-                       throw e;
-               }
-               return createdResource;
-
-       }
-
-       public Map<String, Resource> createResourcesFromYamlNodeTypesList(String yamlName, Resource resource,
-                                                                                                                                         Map<String, Object> mappedToscaTemplate, boolean needLock,
-                                                                                                                                         Map<String, EnumMap<ArtifactOperationEnum, List<ArtifactDefinition>>> nodeTypesArtifactsToHandle,
-                                                                                                                                         List<ArtifactDefinition> nodeTypesNewCreatedArtifacts, Map<String, NodeTypeInfo> nodeTypesInfo,
-                                                                                                                                         CsarInfo csarInfo) {
-
-               Either<String, ResultStatusEnum> toscaVersion = findFirstToscaStringElement(mappedToscaTemplate,
-                               TypeUtils.ToscaTagNamesEnum.TOSCA_VERSION);
-               if (toscaVersion.isRight()) {
-                       throw new ByActionStatusComponentException(ActionStatus.INVALID_TOSCA_TEMPLATE);
-               }
-               Map<String, Object> mapToConvert = new HashMap<>();
-               mapToConvert.put(TypeUtils.ToscaTagNamesEnum.TOSCA_VERSION.getElementName(), toscaVersion.left()
-                               .value());
-               Map<String, Object> nodeTypes = getNodeTypesFromTemplate(mappedToscaTemplate);
-               createNodeTypes(yamlName, resource, needLock, nodeTypesArtifactsToHandle, nodeTypesNewCreatedArtifacts,
-                               nodeTypesInfo, csarInfo, mapToConvert, nodeTypes);
-               return csarInfo.getCreatedNodes();
-       }
-
-       private Map<String, Object> getNodeTypesFromTemplate(Map<String, Object> mappedToscaTemplate) {
-               return ImportUtils.findFirstToscaMapElement(mappedToscaTemplate, TypeUtils.ToscaTagNamesEnum.NODE_TYPES)
-                               .left()
-                               .orValue(HashMap::new);
-       }
-
-       private void createNodeTypes(String yamlName, Resource resource, boolean needLock,
-                                                                Map<String, EnumMap<ArtifactOperationEnum, List<ArtifactDefinition>>> nodeTypesArtifactsToHandle,
-                                                                List<ArtifactDefinition> nodeTypesNewCreatedArtifacts, Map<String, NodeTypeInfo> nodeTypesInfo,
-                                                                CsarInfo csarInfo, Map<String, Object> mapToConvert, Map<String, Object> nodeTypes) {
-               Iterator<Entry<String, Object>> nodesNameValueIter = nodeTypes.entrySet()
-                               .iterator();
-               Resource vfcCreated = null;
-               while (nodesNameValueIter.hasNext()) {
-                       Entry<String, Object> nodeType = nodesNameValueIter.next();
-                       Map<ArtifactOperationEnum, List<ArtifactDefinition>> nodeTypeArtifactsToHandle = nodeTypesArtifactsToHandle == null
-                                       || nodeTypesArtifactsToHandle.isEmpty() ? null : nodeTypesArtifactsToHandle.get(nodeType.getKey());
-
-                       if (nodeTypesInfo.containsKey(nodeType.getKey())) {
-                               log.trace("************* Going to handle nested vfc {}", nodeType.getKey());
-                               vfcCreated = handleNestedVfc(resource, nodeTypesArtifactsToHandle, nodeTypesNewCreatedArtifacts,
-                                               nodeTypesInfo, csarInfo, nodeType.getKey());
-                               log.trace("************* Finished to handle nested vfc {}", nodeType.getKey());
-                       } else if (csarInfo.getCreatedNodesToscaResourceNames() != null
-                                       && !csarInfo.getCreatedNodesToscaResourceNames()
-                                       .containsKey(nodeType.getKey())) {
-                               log.trace("************* Going to create node {}", nodeType.getKey());
-                               ImmutablePair<Resource, ActionStatus> resourceCreated = createNodeTypeResourceFromYaml(yamlName,
-                                               nodeType, csarInfo.getModifier(), mapToConvert, resource, needLock, nodeTypeArtifactsToHandle,
-                                               nodeTypesNewCreatedArtifacts, true, csarInfo, true);
-                               log.debug("************* Finished to create node {}", nodeType.getKey());
-
-                               vfcCreated = resourceCreated.getLeft();
-                               csarInfo.getCreatedNodesToscaResourceNames()
-                                               .put(nodeType.getKey(), vfcCreated.getToscaResourceName());
-                       }
-                       if (vfcCreated != null) {
-                               csarInfo.getCreatedNodes()
-                                               .put(nodeType.getKey(), vfcCreated);
-                       }
-                       mapToConvert.remove(TypeUtils.ToscaTagNamesEnum.NODE_TYPES.getElementName());
-               }
-       }
-
-       private Resource handleNestedVfc(Resource resource,
-                                                                        Map<String, EnumMap<ArtifactOperationEnum, List<ArtifactDefinition>>> nodesArtifactsToHandle,
-                                                                        List<ArtifactDefinition> createdArtifacts, Map<String, NodeTypeInfo> nodesInfo, CsarInfo csarInfo,
-                                                                        String nodeName) {
-
-               String yamlName = nodesInfo.get(nodeName)
-                               .getTemplateFileName();
-               Map<String, Object> nestedVfcJsonMap = nodesInfo.get(nodeName)
-                               .getMappedToscaTemplate();
-
-               log.debug("************* Going to create node types from yaml {}", yamlName);
-               createResourcesFromYamlNodeTypesList(yamlName, resource, nestedVfcJsonMap, false, nodesArtifactsToHandle,
-                               createdArtifacts, Collections.emptyMap(), csarInfo);
-               log.debug("************* Finished to create node types from yaml {}", yamlName);
-
-               if (nestedVfcJsonMap.containsKey(TypeUtils.ToscaTagNamesEnum.TOPOLOGY_TEMPLATE.getElementName())) {
-                       log.debug("************* Going to handle complex VFC from yaml {}", yamlName);
-                       resource = handleComplexVfc(resource, nodesArtifactsToHandle, createdArtifacts, nodesInfo, csarInfo,
-                                       nodeName, yamlName);
-               }
-               return resource;
-       }
-
-       private Resource handleComplexVfc(final Resource resource,
-                                                                         final Map<String, EnumMap<ArtifactOperationEnum, List<ArtifactDefinition>>>
-                                                                                 nodesArtifactsToHandle,
-                                                                         final List<ArtifactDefinition>
-                                                                                 createdArtifacts, Map<String, NodeTypeInfo> nodesInfo, CsarInfo csarInfo,
-                                                                         final String nodeName, final String yamlName) {
-
-               Resource oldComplexVfc = null;
-               Resource newComplexVfc = buildValidComplexVfc(resource, csarInfo, nodeName, nodesInfo);
-               Either<Resource, StorageOperationStatus> oldComplexVfcRes = toscaOperationFacade
-                       .getFullLatestComponentByToscaResourceName(newComplexVfc.getToscaResourceName());
-               if (oldComplexVfcRes.isRight() && oldComplexVfcRes.right().value() == StorageOperationStatus.NOT_FOUND) {
-                       oldComplexVfcRes = toscaOperationFacade.getFullLatestComponentByToscaResourceName(
-                                       buildNestedToscaResourceName(ResourceTypeEnum.CVFC.name(), csarInfo.getVfResourceName(), nodeName).getRight());
-               }
-               if (oldComplexVfcRes.isRight() && oldComplexVfcRes.right().value() != StorageOperationStatus.NOT_FOUND) {
-                       log.debug("Failed to fetch previous complex VFC by tosca resource name {}. Status is {}. ",
-                               newComplexVfc.getToscaResourceName(), oldComplexVfcRes.right().value());
-                       throw new ByActionStatusComponentException(ActionStatus.GENERAL_ERROR);
-               } else if (oldComplexVfcRes.isLeft()) {
-                       log.debug(VALIDATE_DERIVED_BEFORE_UPDATE);
-                       final Either<Boolean, ResponseFormat> eitherValidation = validateNestedDerivedFromDuringUpdate(
-                                       oldComplexVfcRes.left().value(),
-                                       newComplexVfc, ValidationUtils.hasBeenCertified(oldComplexVfcRes.left().value().getVersion()));
-                       if (eitherValidation.isLeft()) {
-                               oldComplexVfc = oldComplexVfcRes.left().value();
-                       }
-               }
-               newComplexVfc = handleComplexVfc(nodesArtifactsToHandle, createdArtifacts, nodesInfo, csarInfo, nodeName,
-                       yamlName, oldComplexVfc, newComplexVfc);
-               csarInfo.getCreatedNodesToscaResourceNames().put(nodeName, newComplexVfc.getToscaResourceName());
-               final LifecycleChangeInfoWithAction lifecycleChangeInfo = new LifecycleChangeInfoWithAction(CERTIFICATION_ON_IMPORT,
-                       LifecycleChanceActionEnum.CREATE_FROM_CSAR);
-               log.debug("Going to certify cvfc {}. ", newComplexVfc.getName());
-               final Resource result = propagateStateToCertified(csarInfo.getModifier(), newComplexVfc,
-                               lifecycleChangeInfo, true, false, true);
-               csarInfo.getCreatedNodes().put(nodeName, result);
-               csarInfo.removeNodeFromQueue();
-               return result;
-       }
-
-       private Resource handleComplexVfc(
-                       Map<String, EnumMap<ArtifactOperationEnum, List<ArtifactDefinition>>> nodesArtifactsToHandle,
-                       List<ArtifactDefinition> createdArtifacts, Map<String, NodeTypeInfo> nodesInfo, CsarInfo csarInfo,
-                       String nodeName, String yamlName, Resource oldComplexVfc, Resource newComplexVfc) {
-
-               Resource handleComplexVfcRes;
-               Map<String, Object> mappedToscaTemplate = nodesInfo.get(nodeName)
-                               .getMappedToscaTemplate();
-               String yamlContent = new String(csarInfo.getCsar()
-                               .get(yamlName));
-               Map<String, NodeTypeInfo> newNodeTypesInfo = nodesInfo.entrySet()
-                               .stream()
-                               .collect(toMap(Entry::getKey, e -> e.getValue()
-                                               .getUnmarkedCopy()));
-               CsarInfo.markNestedVfc(mappedToscaTemplate, newNodeTypesInfo);
-               if (oldComplexVfc == null) {
-                       handleComplexVfcRes = createResourceFromYaml(newComplexVfc, yamlContent, yamlName, newNodeTypesInfo,
-                                       csarInfo, nodesArtifactsToHandle, false, true, nodeName);
-               } else {
-                       handleComplexVfcRes = updateResourceFromYaml(oldComplexVfc, newComplexVfc,
-                                       AuditingActionEnum.UPDATE_RESOURCE_METADATA, createdArtifacts, yamlContent, yamlName, csarInfo,
-                                       newNodeTypesInfo, nodesArtifactsToHandle, nodeName, true);
-               }
-               return handleComplexVfcRes;
-       }
-
-       private Resource buildValidComplexVfc(Resource resource, CsarInfo csarInfo, String nodeName,
-                                                                                 Map<String, NodeTypeInfo> nodesInfo) {
-
-               Resource complexVfc = buildComplexVfcMetadata(resource, csarInfo, nodeName, nodesInfo);
-               log.debug("************* Going to validate complex VFC from yaml {}", complexVfc.getName());
-               csarInfo.addNodeToQueue(nodeName);
-               return validateResourceBeforeCreate(complexVfc, csarInfo.getModifier(), AuditingActionEnum.IMPORT_RESOURCE,
-                               true, csarInfo);
-       }
-
-       private String getNodeTypeActualName(final String nodeTypefullName, final String nodeTypeNamePrefix) {
-
-               final String nameWithouNamespacePrefix = nodeTypefullName.substring(nodeTypeNamePrefix.length());
-               final String[] findTypes = nameWithouNamespacePrefix.split("\\.");
-
-               if(findTypes.length > 1){
-                       final String resourceType = findTypes[0];
-                       return nameWithouNamespacePrefix.substring(resourceType.length());
-               }
-               return nameWithouNamespacePrefix;
-       }
-
-       private ImmutablePair<Resource, ActionStatus> createNodeTypeResourceFromYaml(final String yamlName,
-                                                                                                                                                                final Entry<String, Object> nodeNameValue,
-                                                                                                                                                                User user,
-                                                                                                                                                                final Map<String, Object> mapToConvert,
-                                                                                                                                                                final Resource resourceVf,
-                                                                                                                                                                final boolean needLock,
-                                                                                                                                                                final Map<ArtifactOperationEnum, List<ArtifactDefinition>> nodeTypeArtifactsToHandle,
-                                                                                                                                                                final List<ArtifactDefinition> nodeTypesNewCreatedArtifacts,
-                                                                                                                                                                final boolean forceCertificationAllowed,
-                                                                                                                                                                final CsarInfo csarInfo,
-                                                                                                                                                                final boolean isNested) {
-
-               final UploadResourceInfo resourceMetaData = fillResourceMetadata(
-                       yamlName, resourceVf, nodeNameValue.getKey(), user);
-
-               final String singleVfcYaml = buildNodeTypeYaml(nodeNameValue, mapToConvert, resourceMetaData.getResourceType(), csarInfo);
-               user = validateUser(user, "CheckIn Resource", resourceVf, AuditingActionEnum.CHECKIN_RESOURCE, true);
-               return createResourceFromNodeType(singleVfcYaml, resourceMetaData, user, true, needLock,
-                               nodeTypeArtifactsToHandle, nodeTypesNewCreatedArtifacts, forceCertificationAllowed, csarInfo,
-                               nodeNameValue.getKey(), isNested);
-       }
-
-       private String buildNodeTypeYaml(final Entry<String, Object> nodeNameValue,
-                                                                        final Map<String, Object> mapToConvert,
-                                                                        final String nodeResourceType,
-                                                                        final CsarInfo csarInfo) {
-               // We need to create a Yaml from each node_types in order to create
-               // resource from each node type using import normative flow.
-               final DumperOptions options = new DumperOptions();
-               options.setDefaultFlowStyle(DumperOptions.FlowStyle.BLOCK);
-               final Yaml yaml = new Yaml(options);
-
-               final Map<String, Object> node = new HashMap<>();
-               node.put(buildNestedToscaResourceName(nodeResourceType, csarInfo.getVfResourceName(), nodeNameValue.getKey())
-                               .getLeft(), nodeNameValue.getValue());
-               mapToConvert.put(TypeUtils.ToscaTagNamesEnum.NODE_TYPES.getElementName(), node);
-
-               return yaml.dumpAsMap(mapToConvert);
-       }
-
-       public Boolean validateResourceCreationFromNodeType(Resource resource, User creator) {
-               validateDerivedFromNotEmpty(creator, resource, AuditingActionEnum.CREATE_RESOURCE);
-               return true;
-       }
-
-       public ImmutablePair<Resource, ActionStatus> createResourceFromNodeType(String nodeTypeYaml,
-                                                                                                                                                       UploadResourceInfo resourceMetaData, User creator, boolean isInTransaction, boolean needLock,
-                                                                                                                                                       Map<ArtifactOperationEnum, List<ArtifactDefinition>> nodeTypeArtifactsToHandle,
-                                                                                                                                                       List<ArtifactDefinition> nodeTypesNewCreatedArtifacts, boolean forceCertificationAllowed, CsarInfo csarInfo,
-                                                                                                                                                       String nodeName, boolean isNested) {
-
-               LifecycleChangeInfoWithAction lifecycleChangeInfo = new LifecycleChangeInfoWithAction(CERTIFICATION_ON_IMPORT,
-                               LifecycleChanceActionEnum.CREATE_FROM_CSAR);
-               Function<Resource, Boolean> validator = resource -> validateResourceCreationFromNodeType(
-                               resource, creator);
-               return resourceImportManager.importCertifiedResource(nodeTypeYaml, resourceMetaData, creator, validator,
-                               lifecycleChangeInfo, isInTransaction, true, needLock, nodeTypeArtifactsToHandle,
-                               nodeTypesNewCreatedArtifacts, forceCertificationAllowed, csarInfo, nodeName, isNested);
-       }
-
-       /**
-        * Validates if a given node type name has a valid prefix.
-        *
-        * @param nodeName node name from definition file
-        * @param definedResourceNamespaceList is a list of all node type name prefix allowed
-        * @return a valid node type name prefix if it`s found
-        */
-       public Optional<String> validateNodeTypeNamePrefix(final String nodeName,
-                                                                                                          final List<String> definedResourceNamespaceList) {
-               for (final String validNamespace : definedResourceNamespaceList) {
-                       if (nodeName.startsWith(validNamespace)) {
-                               return Optional.of(validNamespace);
-                       }
-               }
-               return Optional.empty();
-       }
-
-       private List<String> getDefinedNodeTypeNamespaceList() {
-               return ConfigurationManager.getConfigurationManager().getConfiguration().getDefinedResourceNamespace();
-       }
-
-       private UploadResourceInfo fillResourceMetadata(final String yamlName, final Resource resourceVf,
-                                                                                                       final String nodeName, final User user) {
-
-               final UploadResourceInfo resourceMetaData = new UploadResourceInfo();
-
-               final String nodeTypeNamePrefix = getNodeTypeNamePrefix(nodeName);
-               log.debug("Node type Name prefix {}", nodeTypeNamePrefix);
-
-               if (!nodeName.startsWith(nodeTypeNamePrefix)) {
-                       log.debug("invalid nodeName:{} does not start with {}.", nodeName, getDefinedNodeTypeNamespaceList());
-                       throw new ByActionStatusComponentException(ActionStatus.INVALID_NODE_TEMPLATE, yamlName,
-                               resourceMetaData.getName(), nodeName);
-               }
-
-               final String actualName = this.getNodeTypeActualName(nodeName, nodeTypeNamePrefix);
-               final String namePrefix = nodeName.replace(actualName, "");
-               String resourceType = namePrefix.substring(nodeTypeNamePrefix.length());
-               log.debug("initial  namePrefix:{} resourceType {}. nodeName {} , actualName {} prefix {}", namePrefix,
-                       resourceType, nodeName, actualName, nodeTypeNamePrefix);
-
-               // if we import from csar, the node_type name can be
-               // org.openecomp.resource.abstract.node_name - in this case we always
-               // create a vfc
-               if (resourceType.equals(Constants.ABSTRACT)) {
-                       resourceType = ResourceTypeEnum.VFC.name().toLowerCase();
-               }
-
-               if (!ResourceTypeEnum.containsIgnoreCase(resourceType)) {
-                       resourceType = ResourceTypeEnum.VFC.name().toLowerCase();
-               }
-
-               // validating type
-               if (!ResourceTypeEnum.containsName(resourceType.toUpperCase())) {
-                       log.debug("invalid resourceType:{} the type is not one of the valide types:{}.",
-                               resourceType.toUpperCase(),     ResourceTypeEnum.values());
-                       throw new ByActionStatusComponentException(ActionStatus.INVALID_NODE_TEMPLATE, yamlName,
-                               resourceMetaData.getName(), nodeName);
-               }
-
-               // Setting name
-               resourceMetaData.setName(new StringBuilder(resourceVf.getSystemName()).append(actualName).toString());
-
-               // Setting type from name
-               final String type = resourceType.toUpperCase();
-               resourceMetaData.setResourceType(type);
-
-               resourceMetaData.setDescription(ImportUtils.Constants.INNER_VFC_DESCRIPTION);
-               resourceMetaData.setIcon(ImportUtils.Constants.DEFAULT_ICON);
-               resourceMetaData.setContactId(user.getUserId());
-               resourceMetaData.setVendorName(resourceVf.getVendorName());
-               resourceMetaData.setVendorRelease(resourceVf.getVendorRelease());
-
-               // Setting tag
-               final List<String> tags = new ArrayList<>();
-               tags.add(resourceMetaData.getName());
-               resourceMetaData.setTags(tags);
-
-               // Setting category
-               final CategoryDefinition category = new CategoryDefinition();
-               category.setName(ImportUtils.Constants.ABSTRACT_CATEGORY_NAME);
-               final SubCategoryDefinition subCategory = new SubCategoryDefinition();
-               subCategory.setName(ImportUtils.Constants.ABSTRACT_SUBCATEGORY);
-               category.addSubCategory(subCategory);
-               final List<CategoryDefinition> categories = new ArrayList<>();
-               categories.add(category);
-               resourceMetaData.setCategories(categories);
-
-               return resourceMetaData;
-       }
-
-       private Resource buildComplexVfcMetadata(final Resource resourceVf,
-                                                                                        final CsarInfo csarInfo,
-                                                                                        final String nodeName,
-                                                                                        final Map<String, NodeTypeInfo> nodesInfo) {
-               final Resource cvfc = new Resource();
-               final NodeTypeInfo nodeTypeInfo = nodesInfo.get(nodeName);
-               cvfc.setName(buildCvfcName(csarInfo.getVfResourceName(), nodeName));
-               cvfc.setNormalizedName(ValidationUtils.normaliseComponentName(cvfc.getName()));
-               cvfc.setSystemName(ValidationUtils.convertToSystemName(cvfc.getName()));
-               cvfc.setResourceType(ResourceTypeEnum.CVFC);
-               cvfc.setAbstract(true);
-               cvfc.setDerivedFrom(nodeTypeInfo.getDerivedFrom());
-               cvfc.setDescription(ImportUtils.Constants.CVFC_DESCRIPTION);
-               cvfc.setIcon(ImportUtils.Constants.DEFAULT_ICON);
-               cvfc.setContactId(csarInfo.getModifier()
-                               .getUserId());
-               cvfc.setCreatorUserId(csarInfo.getModifier()
-                               .getUserId());
-               cvfc.setVendorName(resourceVf.getVendorName());
-               cvfc.setVendorRelease(resourceVf.getVendorRelease());
-               cvfc.setResourceVendorModelNumber(resourceVf.getResourceVendorModelNumber());
-               cvfc.setToscaResourceName(buildNestedToscaResourceName(
-                       ResourceTypeEnum.CVFC.name(), csarInfo.getVfResourceName(), nodeName).getLeft());
-               cvfc.setInvariantUUID(UniqueIdBuilder.buildInvariantUUID());
-
-               final List<String> tags = new ArrayList<>();
-               tags.add(cvfc.getName());
-               cvfc.setTags(tags);
-
-               final CategoryDefinition category = new CategoryDefinition();
-               category.setName(ImportUtils.Constants.ABSTRACT_CATEGORY_NAME);
-               SubCategoryDefinition subCategory = new SubCategoryDefinition();
-               subCategory.setName(ImportUtils.Constants.ABSTRACT_SUBCATEGORY);
-               category.addSubCategory(subCategory);
-               final List<CategoryDefinition> categories = new ArrayList<>();
-               categories.add(category);
-               cvfc.setCategories(categories);
-
-               cvfc.setVersion(ImportUtils.Constants.FIRST_NON_CERTIFIED_VERSION);
-               cvfc.setLifecycleState(ImportUtils.Constants.NORMATIVE_TYPE_LIFE_CYCLE_NOT_CERTIFIED_CHECKOUT);
-               cvfc.setHighestVersion(ImportUtils.Constants.NORMATIVE_TYPE_HIGHEST_VERSION);
-
-               return cvfc;
-       }
-
-       private String buildCvfcName(final String resourceVfName, final String nodeName) {
-
-               String nameWithouNamespacePrefix =
-                       nodeName.substring(Constants.USER_DEFINED_RESOURCE_NAMESPACE_PREFIX.length());
-               String[] findTypes = nameWithouNamespacePrefix.split("\\.");
-               String resourceType = findTypes[0];
-               String resourceName = resourceVfName + "-" + nameWithouNamespacePrefix.substring(resourceType.length() + 1);
-               return addCvfcSuffixToResourceName(resourceName);
-       }
-
-       private Resource createResourceAndRIsFromYaml(final String yamlName,
-                                                                                                 Resource resource,
-                                                                                                 final ParsedToscaYamlInfo parsedToscaYamlInfo,
-                                                                                                 final AuditingActionEnum actionEnum,
-                                                                                                 final boolean isNormative,
-                                                                                                 final List<ArtifactDefinition> createdArtifacts,
-                                                                                                 final String topologyTemplateYaml,
-                                                                                                 final Map<String, NodeTypeInfo> nodeTypesInfo,
-                                                                                                 final CsarInfo csarInfo,
-                                                                                                 final Map<String, EnumMap<ArtifactOperationEnum, List<ArtifactDefinition>>> nodeTypesArtifactsToCreate,
-                                                                                                 final boolean shouldLock,
-                                                                                                 final boolean inTransaction,
-                                                                                                 final String nodeName) {
-
-               final List<ArtifactDefinition> nodeTypesNewCreatedArtifacts = new ArrayList<>();
+            log.debug("#createResourceFromYaml - Going to create resource {} and RIs ", resource.getName());
+            loggerSupportability
+                .log(LoggerSupportabilityActions.CREATE_RESOURCE_FROM_YAML, resource.getComponentMetadataForSupportLog(), StatusCode.STARTED, "");
+            createdResource = createResourceAndRIsFromYaml(yamlName, resource, parsedToscaYamlInfo, AuditingActionEnum.IMPORT_RESOURCE, false,
+                createdArtifacts, topologyTemplateYaml, nodeTypesInfo, csarInfo, nodeTypesArtifactsToCreate, shouldLock, inTransaction, nodeName);
+            log.debug("#createResourceFromYaml - The resource {} has been created ", resource.getName());
+            loggerSupportability
+                .log(LoggerSupportabilityActions.CREATE_RESOURCE_FROM_YAML, resource.getComponentMetadataForSupportLog(), StatusCode.COMPLETE,
+                    "The resource has been created: {}", resource.getName());
+        } catch (ComponentException e) {
+            ResponseFormat responseFormat =
+                e.getResponseFormat() == null ? componentsUtils.getResponseFormat(e.getActionStatus(), e.getParams()) : e.getResponseFormat();
+            componentsUtils.auditResource(responseFormat, csarInfo.getModifier(), resource, AuditingActionEnum.IMPORT_RESOURCE);
+            throw e;
+        } catch (StorageException e) {
+            ResponseFormat responseFormat = componentsUtils
+                .getResponseFormat(componentsUtils.convertFromStorageResponse(e.getStorageOperationStatus()));
+            componentsUtils.auditResource(responseFormat, csarInfo.getModifier(), resource, AuditingActionEnum.IMPORT_RESOURCE);
+            throw e;
+        }
+        return createdResource;
+    }
+
+    public Map<String, Resource> createResourcesFromYamlNodeTypesList(String yamlName, Resource resource, Map<String, Object> mappedToscaTemplate,
+                                                                      boolean needLock,
+                                                                      Map<String, EnumMap<ArtifactOperationEnum, List<ArtifactDefinition>>> nodeTypesArtifactsToHandle,
+                                                                      List<ArtifactDefinition> nodeTypesNewCreatedArtifacts,
+                                                                      Map<String, NodeTypeInfo> nodeTypesInfo, CsarInfo csarInfo) {
+        Either<String, ResultStatusEnum> toscaVersion = findFirstToscaStringElement(mappedToscaTemplate, TypeUtils.ToscaTagNamesEnum.TOSCA_VERSION);
+        if (toscaVersion.isRight()) {
+            throw new ByActionStatusComponentException(ActionStatus.INVALID_TOSCA_TEMPLATE);
+        }
+        Map<String, Object> mapToConvert = new HashMap<>();
+        mapToConvert.put(TypeUtils.ToscaTagNamesEnum.TOSCA_VERSION.getElementName(), toscaVersion.left().value());
+        Map<String, Object> nodeTypes = getNodeTypesFromTemplate(mappedToscaTemplate);
+        createNodeTypes(yamlName, resource, needLock, nodeTypesArtifactsToHandle, nodeTypesNewCreatedArtifacts, nodeTypesInfo, csarInfo, mapToConvert,
+            nodeTypes);
+        return csarInfo.getCreatedNodes();
+    }
+
+    private Map<String, Object> getNodeTypesFromTemplate(Map<String, Object> mappedToscaTemplate) {
+        return ImportUtils.findFirstToscaMapElement(mappedToscaTemplate, TypeUtils.ToscaTagNamesEnum.NODE_TYPES).left().orValue(HashMap::new);
+    }
+
+    private void createNodeTypes(String yamlName, Resource resource, boolean needLock,
+                                 Map<String, EnumMap<ArtifactOperationEnum, List<ArtifactDefinition>>> nodeTypesArtifactsToHandle,
+                                 List<ArtifactDefinition> nodeTypesNewCreatedArtifacts, Map<String, NodeTypeInfo> nodeTypesInfo, CsarInfo csarInfo,
+                                 Map<String, Object> mapToConvert, Map<String, Object> nodeTypes) {
+        Iterator<Entry<String, Object>> nodesNameValueIter = nodeTypes.entrySet().iterator();
+        Resource vfcCreated = null;
+        while (nodesNameValueIter.hasNext()) {
+            Entry<String, Object> nodeType = nodesNameValueIter.next();
+            Map<ArtifactOperationEnum, List<ArtifactDefinition>> nodeTypeArtifactsToHandle =
+                nodeTypesArtifactsToHandle == null || nodeTypesArtifactsToHandle.isEmpty() ? null : nodeTypesArtifactsToHandle.get(nodeType.getKey());
+            if (nodeTypesInfo.containsKey(nodeType.getKey())) {
+                log.trace("************* Going to handle nested vfc {}", nodeType.getKey());
+                vfcCreated = handleNestedVfc(resource, nodeTypesArtifactsToHandle, nodeTypesNewCreatedArtifacts, nodeTypesInfo, csarInfo,
+                    nodeType.getKey());
+                log.trace("************* Finished to handle nested vfc {}", nodeType.getKey());
+            } else if (csarInfo.getCreatedNodesToscaResourceNames() != null && !csarInfo.getCreatedNodesToscaResourceNames()
+                .containsKey(nodeType.getKey())) {
+                log.trace("************* Going to create node {}", nodeType.getKey());
+                ImmutablePair<Resource, ActionStatus> resourceCreated = createNodeTypeResourceFromYaml(yamlName, nodeType, csarInfo.getModifier(),
+                    mapToConvert, resource, needLock, nodeTypeArtifactsToHandle, nodeTypesNewCreatedArtifacts, true, csarInfo, true);
+                log.debug("************* Finished to create node {}", nodeType.getKey());
+                vfcCreated = resourceCreated.getLeft();
+                csarInfo.getCreatedNodesToscaResourceNames().put(nodeType.getKey(), vfcCreated.getToscaResourceName());
+            }
+            if (vfcCreated != null) {
+                csarInfo.getCreatedNodes().put(nodeType.getKey(), vfcCreated);
+            }
+            mapToConvert.remove(TypeUtils.ToscaTagNamesEnum.NODE_TYPES.getElementName());
+        }
+    }
+
+    private Resource handleNestedVfc(Resource resource, Map<String, EnumMap<ArtifactOperationEnum, List<ArtifactDefinition>>> nodesArtifactsToHandle,
+                                     List<ArtifactDefinition> createdArtifacts, Map<String, NodeTypeInfo> nodesInfo, CsarInfo csarInfo,
+                                     String nodeName) {
+        String yamlName = nodesInfo.get(nodeName).getTemplateFileName();
+        Map<String, Object> nestedVfcJsonMap = nodesInfo.get(nodeName).getMappedToscaTemplate();
+        log.debug("************* Going to create node types from yaml {}", yamlName);
+        createResourcesFromYamlNodeTypesList(yamlName, resource, nestedVfcJsonMap, false, nodesArtifactsToHandle, createdArtifacts,
+            Collections.emptyMap(), csarInfo);
+        log.debug("************* Finished to create node types from yaml {}", yamlName);
+        if (nestedVfcJsonMap.containsKey(TypeUtils.ToscaTagNamesEnum.TOPOLOGY_TEMPLATE.getElementName())) {
+            log.debug("************* Going to handle complex VFC from yaml {}", yamlName);
+            resource = handleComplexVfc(resource, nodesArtifactsToHandle, createdArtifacts, nodesInfo, csarInfo, nodeName, yamlName);
+        }
+        return resource;
+    }
+
+    private Resource handleComplexVfc(final Resource resource,
+                                      final Map<String, EnumMap<ArtifactOperationEnum, List<ArtifactDefinition>>> nodesArtifactsToHandle,
+                                      final List<ArtifactDefinition> createdArtifacts, Map<String, NodeTypeInfo> nodesInfo, CsarInfo csarInfo,
+                                      final String nodeName, final String yamlName) {
+        Resource oldComplexVfc = null;
+        Resource newComplexVfc = buildValidComplexVfc(resource, csarInfo, nodeName, nodesInfo);
+        Either<Resource, StorageOperationStatus> oldComplexVfcRes = toscaOperationFacade
+            .getFullLatestComponentByToscaResourceName(newComplexVfc.getToscaResourceName());
+        if (oldComplexVfcRes.isRight() && oldComplexVfcRes.right().value() == StorageOperationStatus.NOT_FOUND) {
+            oldComplexVfcRes = toscaOperationFacade.getFullLatestComponentByToscaResourceName(
+                buildNestedToscaResourceName(ResourceTypeEnum.CVFC.name(), csarInfo.getVfResourceName(), nodeName).getRight());
+        }
+        if (oldComplexVfcRes.isRight() && oldComplexVfcRes.right().value() != StorageOperationStatus.NOT_FOUND) {
+            log.debug("Failed to fetch previous complex VFC by tosca resource name {}. Status is {}. ", newComplexVfc.getToscaResourceName(),
+                oldComplexVfcRes.right().value());
+            throw new ByActionStatusComponentException(ActionStatus.GENERAL_ERROR);
+        } else if (oldComplexVfcRes.isLeft()) {
+            log.debug(VALIDATE_DERIVED_BEFORE_UPDATE);
+            final Either<Boolean, ResponseFormat> eitherValidation = validateNestedDerivedFromDuringUpdate(oldComplexVfcRes.left().value(),
+                newComplexVfc, ValidationUtils.hasBeenCertified(oldComplexVfcRes.left().value().getVersion()));
+            if (eitherValidation.isLeft()) {
+                oldComplexVfc = oldComplexVfcRes.left().value();
+            }
+        }
+        newComplexVfc = handleComplexVfc(nodesArtifactsToHandle, createdArtifacts, nodesInfo, csarInfo, nodeName, yamlName, oldComplexVfc,
+            newComplexVfc);
+        csarInfo.getCreatedNodesToscaResourceNames().put(nodeName, newComplexVfc.getToscaResourceName());
+        final LifecycleChangeInfoWithAction lifecycleChangeInfo = new LifecycleChangeInfoWithAction(CERTIFICATION_ON_IMPORT,
+            LifecycleChanceActionEnum.CREATE_FROM_CSAR);
+        log.debug("Going to certify cvfc {}. ", newComplexVfc.getName());
+        final Resource result = propagateStateToCertified(csarInfo.getModifier(), newComplexVfc, lifecycleChangeInfo, true, false, true);
+        csarInfo.getCreatedNodes().put(nodeName, result);
+        csarInfo.removeNodeFromQueue();
+        return result;
+    }
+
+    private Resource handleComplexVfc(Map<String, EnumMap<ArtifactOperationEnum, List<ArtifactDefinition>>> nodesArtifactsToHandle,
+                                      List<ArtifactDefinition> createdArtifacts, Map<String, NodeTypeInfo> nodesInfo, CsarInfo csarInfo,
+                                      String nodeName, String yamlName, Resource oldComplexVfc, Resource newComplexVfc) {
+        Resource handleComplexVfcRes;
+        Map<String, Object> mappedToscaTemplate = nodesInfo.get(nodeName).getMappedToscaTemplate();
+        String yamlContent = new String(csarInfo.getCsar().get(yamlName));
+        Map<String, NodeTypeInfo> newNodeTypesInfo = nodesInfo.entrySet().stream().collect(toMap(Entry::getKey, e -> e.getValue().getUnmarkedCopy()));
+        CsarInfo.markNestedVfc(mappedToscaTemplate, newNodeTypesInfo);
+        if (oldComplexVfc == null) {
+            handleComplexVfcRes = createResourceFromYaml(newComplexVfc, yamlContent, yamlName, newNodeTypesInfo, csarInfo, nodesArtifactsToHandle,
+                false, true, nodeName);
+        } else {
+            handleComplexVfcRes = updateResourceFromYaml(oldComplexVfc, newComplexVfc, AuditingActionEnum.UPDATE_RESOURCE_METADATA, createdArtifacts,
+                yamlContent, yamlName, csarInfo, newNodeTypesInfo, nodesArtifactsToHandle, nodeName, true);
+        }
+        return handleComplexVfcRes;
+    }
+
+    private Resource buildValidComplexVfc(Resource resource, CsarInfo csarInfo, String nodeName, Map<String, NodeTypeInfo> nodesInfo) {
+        Resource complexVfc = buildComplexVfcMetadata(resource, csarInfo, nodeName, nodesInfo);
+        log.debug("************* Going to validate complex VFC from yaml {}", complexVfc.getName());
+        csarInfo.addNodeToQueue(nodeName);
+        return validateResourceBeforeCreate(complexVfc, csarInfo.getModifier(), AuditingActionEnum.IMPORT_RESOURCE, true, csarInfo);
+    }
+
+    private String getNodeTypeActualName(final String nodeTypefullName, final String nodeTypeNamePrefix) {
+        final String nameWithouNamespacePrefix = nodeTypefullName.substring(nodeTypeNamePrefix.length());
+        final String[] findTypes = nameWithouNamespacePrefix.split("\\.");
+        if (findTypes.length > 1) {
+            final String resourceType = findTypes[0];
+            return nameWithouNamespacePrefix.substring(resourceType.length());
+        }
+        return nameWithouNamespacePrefix;
+    }
+
+    private ImmutablePair<Resource, ActionStatus> createNodeTypeResourceFromYaml(final String yamlName, final Entry<String, Object> nodeNameValue,
+                                                                                 User user, final Map<String, Object> mapToConvert,
+                                                                                 final Resource resourceVf, final boolean needLock,
+                                                                                 final Map<ArtifactOperationEnum, List<ArtifactDefinition>> nodeTypeArtifactsToHandle,
+                                                                                 final List<ArtifactDefinition> nodeTypesNewCreatedArtifacts,
+                                                                                 final boolean forceCertificationAllowed, final CsarInfo csarInfo,
+                                                                                 final boolean isNested) {
+        final UploadResourceInfo resourceMetaData = fillResourceMetadata(yamlName, resourceVf, nodeNameValue.getKey(), user);
+        final String singleVfcYaml = buildNodeTypeYaml(nodeNameValue, mapToConvert, resourceMetaData.getResourceType(), csarInfo);
+        user = validateUser(user, "CheckIn Resource", resourceVf, AuditingActionEnum.CHECKIN_RESOURCE, true);
+        return createResourceFromNodeType(singleVfcYaml, resourceMetaData, user, true, needLock, nodeTypeArtifactsToHandle,
+            nodeTypesNewCreatedArtifacts, forceCertificationAllowed, csarInfo, nodeNameValue.getKey(), isNested);
+    }
+
+    private String buildNodeTypeYaml(final Entry<String, Object> nodeNameValue, final Map<String, Object> mapToConvert, final String nodeResourceType,
+                                     final CsarInfo csarInfo) {
+        // We need to create a Yaml from each node_types in order to create
+
+        // resource from each node type using import normative flow.
+        final DumperOptions options = new DumperOptions();
+        options.setDefaultFlowStyle(DumperOptions.FlowStyle.BLOCK);
+        final Yaml yaml = new Yaml(options);
+        final Map<String, Object> node = new HashMap<>();
+        node.put(buildNestedToscaResourceName(nodeResourceType, csarInfo.getVfResourceName(), nodeNameValue.getKey()).getLeft(),
+            nodeNameValue.getValue());
+        mapToConvert.put(TypeUtils.ToscaTagNamesEnum.NODE_TYPES.getElementName(), node);
+        return yaml.dumpAsMap(mapToConvert);
+    }
+
+    public Boolean validateResourceCreationFromNodeType(Resource resource, User creator) {
+        validateDerivedFromNotEmpty(creator, resource, AuditingActionEnum.CREATE_RESOURCE);
+        return true;
+    }
+
+    public ImmutablePair<Resource, ActionStatus> createResourceFromNodeType(String nodeTypeYaml, UploadResourceInfo resourceMetaData, User creator,
+                                                                            boolean isInTransaction, boolean needLock,
+                                                                            Map<ArtifactOperationEnum, List<ArtifactDefinition>> nodeTypeArtifactsToHandle,
+                                                                            List<ArtifactDefinition> nodeTypesNewCreatedArtifacts,
+                                                                            boolean forceCertificationAllowed, CsarInfo csarInfo, String nodeName,
+                                                                            boolean isNested) {
+        LifecycleChangeInfoWithAction lifecycleChangeInfo = new LifecycleChangeInfoWithAction(CERTIFICATION_ON_IMPORT,
+            LifecycleChanceActionEnum.CREATE_FROM_CSAR);
+        Function<Resource, Boolean> validator = resource -> validateResourceCreationFromNodeType(resource, creator);
+        return resourceImportManager
+            .importCertifiedResource(nodeTypeYaml, resourceMetaData, creator, validator, lifecycleChangeInfo, isInTransaction, true, needLock,
+                nodeTypeArtifactsToHandle, nodeTypesNewCreatedArtifacts, forceCertificationAllowed, csarInfo, nodeName, isNested);
+    }
+
+    /**
+     * Validates if a given node type name has a valid prefix.
+     *
+     * @param nodeName                     node name from definition file
+     * @param definedResourceNamespaceList is a list of all node type name prefix allowed
+     * @return a valid node type name prefix if it`s found
+     */
+    public Optional<String> validateNodeTypeNamePrefix(final String nodeName, final List<String> definedResourceNamespaceList) {
+        for (final String validNamespace : definedResourceNamespaceList) {
+            if (nodeName.startsWith(validNamespace)) {
+                return Optional.of(validNamespace);
+            }
+        }
+        return Optional.empty();
+    }
+
+    private List<String> getDefinedNodeTypeNamespaceList() {
+        return ConfigurationManager.getConfigurationManager().getConfiguration().getDefinedResourceNamespace();
+    }
+
+    private UploadResourceInfo fillResourceMetadata(final String yamlName, final Resource resourceVf, final String nodeName, final User user) {
+        final UploadResourceInfo resourceMetaData = new UploadResourceInfo();
+        final String nodeTypeNamePrefix = getNodeTypeNamePrefix(nodeName);
+        log.debug("Node type Name prefix {}", nodeTypeNamePrefix);
+        if (!nodeName.startsWith(nodeTypeNamePrefix)) {
+            log.debug("invalid nodeName:{} does not start with {}.", nodeName, getDefinedNodeTypeNamespaceList());
+            throw new ByActionStatusComponentException(ActionStatus.INVALID_NODE_TEMPLATE, yamlName, resourceMetaData.getName(), nodeName);
+        }
+        final String actualName = this.getNodeTypeActualName(nodeName, nodeTypeNamePrefix);
+        final String namePrefix = nodeName.replace(actualName, "");
+        String resourceType = namePrefix.substring(nodeTypeNamePrefix.length());
+        log.debug("initial  namePrefix:{} resourceType {}. nodeName {} , actualName {} prefix {}", namePrefix, resourceType, nodeName, actualName,
+            nodeTypeNamePrefix);
+        // if we import from csar, the node_type name can be
+
+        // org.openecomp.resource.abstract.node_name - in this case we always
+
+        // create a vfc
+        if (resourceType.equals(Constants.ABSTRACT)) {
+            resourceType = ResourceTypeEnum.VFC.name().toLowerCase();
+        }
+        if (!ResourceTypeEnum.containsIgnoreCase(resourceType)) {
+            resourceType = ResourceTypeEnum.VFC.name().toLowerCase();
+        }
+        // validating type
+        if (!ResourceTypeEnum.containsName(resourceType.toUpperCase())) {
+            log.debug("invalid resourceType:{} the type is not one of the valide types:{}.", resourceType.toUpperCase(), ResourceTypeEnum.values());
+            throw new ByActionStatusComponentException(ActionStatus.INVALID_NODE_TEMPLATE, yamlName, resourceMetaData.getName(), nodeName);
+        }
+        // Setting name
+        resourceMetaData.setName(new StringBuilder(resourceVf.getSystemName()).append(actualName).toString());
+        // Setting type from name
+        final String type = resourceType.toUpperCase();
+        resourceMetaData.setResourceType(type);
+        resourceMetaData.setDescription(ImportUtils.Constants.INNER_VFC_DESCRIPTION);
+        resourceMetaData.setIcon(ImportUtils.Constants.DEFAULT_ICON);
+        resourceMetaData.setContactId(user.getUserId());
+        resourceMetaData.setVendorName(resourceVf.getVendorName());
+        resourceMetaData.setVendorRelease(resourceVf.getVendorRelease());
+        // Setting tag
+        final List<String> tags = new ArrayList<>();
+        tags.add(resourceMetaData.getName());
+        resourceMetaData.setTags(tags);
+        // Setting category
+        final CategoryDefinition category = new CategoryDefinition();
+        category.setName(ImportUtils.Constants.ABSTRACT_CATEGORY_NAME);
+        final SubCategoryDefinition subCategory = new SubCategoryDefinition();
+        subCategory.setName(ImportUtils.Constants.ABSTRACT_SUBCATEGORY);
+        category.addSubCategory(subCategory);
+        final List<CategoryDefinition> categories = new ArrayList<>();
+        categories.add(category);
+        resourceMetaData.setCategories(categories);
+        return resourceMetaData;
+    }
+
+    private Resource buildComplexVfcMetadata(final Resource resourceVf, final CsarInfo csarInfo, final String nodeName,
+                                             final Map<String, NodeTypeInfo> nodesInfo) {
+        final Resource cvfc = new Resource();
+        final NodeTypeInfo nodeTypeInfo = nodesInfo.get(nodeName);
+        cvfc.setName(buildCvfcName(csarInfo.getVfResourceName(), nodeName));
+        cvfc.setNormalizedName(ValidationUtils.normaliseComponentName(cvfc.getName()));
+        cvfc.setSystemName(ValidationUtils.convertToSystemName(cvfc.getName()));
+        cvfc.setResourceType(ResourceTypeEnum.CVFC);
+        cvfc.setAbstract(true);
+        cvfc.setDerivedFrom(nodeTypeInfo.getDerivedFrom());
+        cvfc.setDescription(ImportUtils.Constants.CVFC_DESCRIPTION);
+        cvfc.setIcon(ImportUtils.Constants.DEFAULT_ICON);
+        cvfc.setContactId(csarInfo.getModifier().getUserId());
+        cvfc.setCreatorUserId(csarInfo.getModifier().getUserId());
+        cvfc.setVendorName(resourceVf.getVendorName());
+        cvfc.setVendorRelease(resourceVf.getVendorRelease());
+        cvfc.setResourceVendorModelNumber(resourceVf.getResourceVendorModelNumber());
+        cvfc.setToscaResourceName(buildNestedToscaResourceName(ResourceTypeEnum.CVFC.name(), csarInfo.getVfResourceName(), nodeName).getLeft());
+        cvfc.setInvariantUUID(UniqueIdBuilder.buildInvariantUUID());
+        final List<String> tags = new ArrayList<>();
+        tags.add(cvfc.getName());
+        cvfc.setTags(tags);
+        final CategoryDefinition category = new CategoryDefinition();
+        category.setName(ImportUtils.Constants.ABSTRACT_CATEGORY_NAME);
+        SubCategoryDefinition subCategory = new SubCategoryDefinition();
+        subCategory.setName(ImportUtils.Constants.ABSTRACT_SUBCATEGORY);
+        category.addSubCategory(subCategory);
+        final List<CategoryDefinition> categories = new ArrayList<>();
+        categories.add(category);
+        cvfc.setCategories(categories);
+        cvfc.setVersion(ImportUtils.Constants.FIRST_NON_CERTIFIED_VERSION);
+        cvfc.setLifecycleState(ImportUtils.Constants.NORMATIVE_TYPE_LIFE_CYCLE_NOT_CERTIFIED_CHECKOUT);
+        cvfc.setHighestVersion(ImportUtils.Constants.NORMATIVE_TYPE_HIGHEST_VERSION);
+        return cvfc;
+    }
+
+    private String buildCvfcName(final String resourceVfName, final String nodeName) {
+        String nameWithouNamespacePrefix = nodeName.substring(Constants.USER_DEFINED_RESOURCE_NAMESPACE_PREFIX.length());
+        String[] findTypes = nameWithouNamespacePrefix.split("\\.");
+        String resourceType = findTypes[0];
+        String resourceName = resourceVfName + "-" + nameWithouNamespacePrefix.substring(resourceType.length() + 1);
+        return addCvfcSuffixToResourceName(resourceName);
+    }
 
+    private Resource createResourceAndRIsFromYaml(final String yamlName, Resource resource, final ParsedToscaYamlInfo parsedToscaYamlInfo,
+                                                  final AuditingActionEnum actionEnum, final boolean isNormative,
+                                                  final List<ArtifactDefinition> createdArtifacts, final String topologyTemplateYaml,
+                                                  final Map<String, NodeTypeInfo> nodeTypesInfo, final CsarInfo csarInfo,
+                                                  final Map<String, EnumMap<ArtifactOperationEnum, List<ArtifactDefinition>>> nodeTypesArtifactsToCreate,
+                                                  final boolean shouldLock, final boolean inTransaction, final String nodeName) {
+        final List<ArtifactDefinition> nodeTypesNewCreatedArtifacts = new ArrayList<>();
         if (shouldLock) {
-            final Either<Boolean, ResponseFormat> lockResult = lockComponentByName(resource.getSystemName(), resource,
-                    CREATE_RESOURCE);
+            final Either<Boolean, ResponseFormat> lockResult = lockComponentByName(resource.getSystemName(), resource, CREATE_RESOURCE);
             if (lockResult.isRight()) {
                 rollback(inTransaction, resource, createdArtifacts, nodeTypesNewCreatedArtifacts);
                 throw new ByResponseFormatComponentException(lockResult.right().value());
@@ -1638,48 +1395,44 @@ public class ResourceBusinessLogic extends ComponentBusinessLogic {
         }
         try {
             log.trace("************* createResourceFromYaml before full create resource {}", yamlName);
-            loggerSupportability.log(LoggerSupportabilityActions.CREATE_INPUTS,resource.getComponentMetadataForSupportLog(), StatusCode.STARTED,"Starting to add inputs from yaml: {}",yamlName);
+            loggerSupportability.log(LoggerSupportabilityActions.CREATE_INPUTS, resource.getComponentMetadataForSupportLog(), StatusCode.STARTED,
+                "Starting to add inputs from yaml: {}", yamlName);
             final Resource genericResource = fetchAndSetDerivedFromGenericType(resource);
             resource = createResourceTransaction(resource, csarInfo.getModifier(), isNormative);
             log.trace("************* createResourceFromYaml after full create resource {}", yamlName);
             log.trace("************* Going to add inputs from yaml {}", yamlName);
-            if (resource.shouldGenerateInputs())
+            if (resource.shouldGenerateInputs()) {
                 generateAndAddInputsFromGenericTypeProperties(resource, genericResource);
-
+            }
             final Map<String, InputDefinition> inputs = parsedToscaYamlInfo.getInputs();
             resource = createInputsOnResource(resource, inputs);
             log.trace("************* Finish to add inputs from yaml {}", yamlName);
-            loggerSupportability.log(LoggerSupportabilityActions.CREATE_INPUTS,
-                               resource.getComponentMetadataForSupportLog(),
-                               StatusCode.COMPLETE,"Finish to add inputs from yaml: {}",yamlName);
+            loggerSupportability.log(LoggerSupportabilityActions.CREATE_INPUTS, resource.getComponentMetadataForSupportLog(), StatusCode.COMPLETE,
+                "Finish to add inputs from yaml: {}", yamlName);
             if (resource.getResourceType() == ResourceTypeEnum.PNF) {
                 log.trace("************* Adding generic properties to PNF");
-                resource = (Resource) propertyBusinessLogic.copyPropertyToComponent(resource,
-                                       genericResource.getProperties());
+                resource = (Resource) propertyBusinessLogic.copyPropertyToComponent(resource, genericResource.getProperties());
                 log.trace("************* Adding software information to PNF");
                 softwareInformationBusinessLogic.setSoftwareInformation(resource, csarInfo);
                 log.trace("************* Removing non-mano software information file from PNF");
-                if (csarInfo.getSoftwareInformationPath().isPresent() &&
-                        !softwareInformationBusinessLogic.removeSoftwareInformationFile(csarInfo)) {
-                    log.warn(EcompLoggerErrorCode.BUSINESS_PROCESS_ERROR , ResourceBusinessLogic.class.getName(),
-                            "catalog-be", "Could not remove the software information file.");
+                if (csarInfo.getSoftwareInformationPath().isPresent() && !softwareInformationBusinessLogic.removeSoftwareInformationFile(csarInfo)) {
+                    log.warn(EcompLoggerErrorCode.BUSINESS_PROCESS_ERROR, ResourceBusinessLogic.class.getName(), "catalog-be",
+                        "Could not remove the software information file.");
                 }
             }
-
-            final Map<String, UploadComponentInstanceInfo> uploadComponentInstanceInfoMap = parsedToscaYamlInfo
-                               .getInstances();
+            final Map<String, UploadComponentInstanceInfo> uploadComponentInstanceInfoMap = parsedToscaYamlInfo.getInstances();
             log.trace("************* Going to create nodes, RI's and Relations  from yaml {}", yamlName);
-            loggerSupportability.log(LoggerSupportabilityActions.CREATE_RESOURCE_FROM_YAML,resource.getComponentMetadataForSupportLog(), StatusCode.STARTED,"Start create nodes, RI and Relations  from yaml: {}",yamlName);
-            resource = createRIAndRelationsFromYaml(yamlName, resource, uploadComponentInstanceInfoMap,
-                               topologyTemplateYaml, nodeTypesNewCreatedArtifacts, nodeTypesInfo, csarInfo, nodeTypesArtifactsToCreate,
-                               nodeName);
+            loggerSupportability
+                .log(LoggerSupportabilityActions.CREATE_RESOURCE_FROM_YAML, resource.getComponentMetadataForSupportLog(), StatusCode.STARTED,
+                    "Start create nodes, RI and Relations  from yaml: {}", yamlName);
+            resource = createRIAndRelationsFromYaml(yamlName, resource, uploadComponentInstanceInfoMap, topologyTemplateYaml,
+                nodeTypesNewCreatedArtifacts, nodeTypesInfo, csarInfo, nodeTypesArtifactsToCreate, nodeName);
             log.trace("************* Finished to create nodes, RI and Relation  from yaml {}", yamlName);
-            loggerSupportability.log(LoggerSupportabilityActions.CREATE_RELATIONS,
-                               resource.getComponentMetadataForSupportLog(),
-                               StatusCode.COMPLETE,"Finished to create nodes, RI and Relation  from yaml: {}",yamlName);
+            loggerSupportability.log(LoggerSupportabilityActions.CREATE_RELATIONS, resource.getComponentMetadataForSupportLog(), StatusCode.COMPLETE,
+                "Finished to create nodes, RI and Relation  from yaml: {}", yamlName);
             // validate update vf module group names
             final Either<Map<String, GroupDefinition>, ResponseFormat> validateUpdateVfGroupNamesRes = groupBusinessLogic
-                               .validateUpdateVfGroupNames(parsedToscaYamlInfo.getGroups(), resource.getSystemName());
+                .validateUpdateVfGroupNames(parsedToscaYamlInfo.getGroups(), resource.getSystemName());
             if (validateUpdateVfGroupNamesRes.isRight()) {
                 rollback(inTransaction, resource, createdArtifacts, nodeTypesNewCreatedArtifacts);
                 throw new ByResponseFormatComponentException(validateUpdateVfGroupNamesRes.right().value());
@@ -1687,3781 +1440,3150 @@ public class ResourceBusinessLogic extends ComponentBusinessLogic {
             // add groups to resource
             final Map<String, GroupDefinition> groups;
             log.trace("************* Going to add groups from yaml {}", yamlName);
-            loggerSupportability.log(LoggerSupportabilityActions.CREATE_GROUPS,resource.getComponentMetadataForSupportLog(),
-                               StatusCode.STARTED,"Start to add groups from yaml: {}",yamlName);
+            loggerSupportability.log(LoggerSupportabilityActions.CREATE_GROUPS, resource.getComponentMetadataForSupportLog(), StatusCode.STARTED,
+                "Start to add groups from yaml: {}", yamlName);
             if (!validateUpdateVfGroupNamesRes.left().value().isEmpty()) {
                 groups = validateUpdateVfGroupNamesRes.left().value();
             } else {
                 groups = parsedToscaYamlInfo.getGroups();
             }
-
-                       final Either<Resource, ResponseFormat> createGroupsOnResource = createGroupsOnResource(resource, groups);
-                       if (createGroupsOnResource.isRight()) {
-                               rollback(inTransaction, resource, createdArtifacts, nodeTypesNewCreatedArtifacts);
-                               loggerSupportability.log(LoggerSupportabilityActions.CREATE_GROUPS,
-                                       resource.getComponentMetadataForSupportLog(),
-                                       StatusCode.ERROR,"ERROR while adding groups from yaml: {}",yamlName);
-                               throw new ByResponseFormatComponentException(createGroupsOnResource.right().value());
-                       }
-                       resource = createGroupsOnResource.left().value();
-                       log.trace("************* Finished to add groups from yaml {}", yamlName);
-                       loggerSupportability.log(LoggerSupportabilityActions.CREATE_GROUPS,
-                               resource.getComponentMetadataForSupportLog(),
-                               StatusCode.COMPLETE,"Finished to add groups from yaml: {}", yamlName);
-                       log.trace("************* Going to add artifacts from yaml {}", yamlName);
-                       loggerSupportability.log(LoggerSupportabilityActions.CREATE_ARTIFACTS,
-                               resource.getComponentMetadataForSupportLog(),
-                               StatusCode.STARTED,"Started to add artifacts from yaml: {}",yamlName);
-
-                       log.trace("************* Starting to add policies from yaml {}", yamlName);
-                       Map<String, PolicyDefinition> policies = parsedToscaYamlInfo.getPolicies();
-                       if (MapUtils.isNotEmpty(policies)) {
-                               resource = createPoliciesOnResource(resource, policies);
-                       }
-                       log.trace("************* Finished to add policies from yaml {}", yamlName);
-
-                       final NodeTypeInfoToUpdateArtifacts nodeTypeInfoToUpdateArtifacts =
-                                       new NodeTypeInfoToUpdateArtifacts(nodeName, nodeTypesArtifactsToCreate);
-
-                       final Either<Resource, ResponseFormat> createArtifactsEither = createOrUpdateArtifacts(
-                               ArtifactOperationEnum.CREATE, createdArtifacts, yamlName, csarInfo, resource,
-                               nodeTypeInfoToUpdateArtifacts, inTransaction, shouldLock);
-                       if (createArtifactsEither.isRight()) {
-                               rollback(inTransaction, resource, createdArtifacts, nodeTypesNewCreatedArtifacts);
-                               loggerSupportability.log(LoggerSupportabilityActions.CREATE_ARTIFACTS,
-                                       resource.getComponentMetadataForSupportLog(), StatusCode.ERROR,"error happened {}",
-                                       createArtifactsEither.right().value());
-                               throw new ByResponseFormatComponentException(createArtifactsEither.right().value());
-                       }
-                       loggerSupportability.log(LoggerSupportabilityActions.CREATE_ARTIFACTS,
-                               resource.getComponentMetadataForSupportLog(),
-                               StatusCode.COMPLETE,"Finished to add artifacts from yaml: "+resource.getToscaResourceName());
-                       final ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.CREATED);
-                       componentsUtils.auditResource(responseFormat, csarInfo.getModifier(), resource, actionEnum);
-                       ASDCKpiApi.countCreatedResourcesKPI();
-                       return resource;
-
+            final Either<Resource, ResponseFormat> createGroupsOnResource = createGroupsOnResource(resource, groups);
+            if (createGroupsOnResource.isRight()) {
+                rollback(inTransaction, resource, createdArtifacts, nodeTypesNewCreatedArtifacts);
+                loggerSupportability.log(LoggerSupportabilityActions.CREATE_GROUPS, resource.getComponentMetadataForSupportLog(), StatusCode.ERROR,
+                    "ERROR while adding groups from yaml: {}", yamlName);
+                throw new ByResponseFormatComponentException(createGroupsOnResource.right().value());
+            }
+            resource = createGroupsOnResource.left().value();
+            log.trace("************* Finished to add groups from yaml {}", yamlName);
+            loggerSupportability.log(LoggerSupportabilityActions.CREATE_GROUPS, resource.getComponentMetadataForSupportLog(), StatusCode.COMPLETE,
+                "Finished to add groups from yaml: {}", yamlName);
+            log.trace("************* Going to add artifacts from yaml {}", yamlName);
+            loggerSupportability.log(LoggerSupportabilityActions.CREATE_ARTIFACTS, resource.getComponentMetadataForSupportLog(), StatusCode.STARTED,
+                "Started to add artifacts from yaml: {}", yamlName);
+            log.trace("************* Starting to add policies from yaml {}", yamlName);
+            Map<String, PolicyDefinition> policies = parsedToscaYamlInfo.getPolicies();
+            if (MapUtils.isNotEmpty(policies)) {
+                resource = createPoliciesOnResource(resource, policies);
+            }
+            log.trace("************* Finished to add policies from yaml {}", yamlName);
+            final NodeTypeInfoToUpdateArtifacts nodeTypeInfoToUpdateArtifacts = new NodeTypeInfoToUpdateArtifacts(nodeName,
+                nodeTypesArtifactsToCreate);
+            final Either<Resource, ResponseFormat> createArtifactsEither = createOrUpdateArtifacts(ArtifactOperationEnum.CREATE, createdArtifacts,
+                yamlName, csarInfo, resource, nodeTypeInfoToUpdateArtifacts, inTransaction, shouldLock);
+            if (createArtifactsEither.isRight()) {
+                rollback(inTransaction, resource, createdArtifacts, nodeTypesNewCreatedArtifacts);
+                loggerSupportability.log(LoggerSupportabilityActions.CREATE_ARTIFACTS, resource.getComponentMetadataForSupportLog(), StatusCode.ERROR,
+                    "error happened {}", createArtifactsEither.right().value());
+                throw new ByResponseFormatComponentException(createArtifactsEither.right().value());
+            }
+            loggerSupportability.log(LoggerSupportabilityActions.CREATE_ARTIFACTS, resource.getComponentMetadataForSupportLog(), StatusCode.COMPLETE,
+                "Finished to add artifacts from yaml: " + resource.getToscaResourceName());
+            final ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.CREATED);
+            componentsUtils.auditResource(responseFormat, csarInfo.getModifier(), resource, actionEnum);
+            ASDCKpiApi.countCreatedResourcesKPI();
+            return resource;
         } catch (final BusinessLogicException e) {
-                       log.error(EcompLoggerErrorCode.BUSINESS_PROCESS_ERROR, ResourceBusinessLogic.class.getName(),
-                               "An error has occurred during resource and resource instance creation", e);
+            log.error(EcompLoggerErrorCode.BUSINESS_PROCESS_ERROR, ResourceBusinessLogic.class.getName(),
+                "An error has occurred during resource and resource instance creation", e);
             rollback(inTransaction, resource, createdArtifacts, nodeTypesNewCreatedArtifacts);
             throw new ByResponseFormatComponentException(e.getResponseFormat());
         } catch (final Exception e) {
-                       log.error(EcompLoggerErrorCode.BUSINESS_PROCESS_ERROR, ResourceBusinessLogic.class.getName(),
-                               "An error has occurred during resource and resource instance creation", e);
-                       rollback(inTransaction, resource, createdArtifacts, nodeTypesNewCreatedArtifacts);
-                       throw new ByActionStatusComponentException(ActionStatus.GENERAL_ERROR);
+            log.error(EcompLoggerErrorCode.BUSINESS_PROCESS_ERROR, ResourceBusinessLogic.class.getName(),
+                "An error has occurred during resource and resource instance creation", e);
+            rollback(inTransaction, resource, createdArtifacts, nodeTypesNewCreatedArtifacts);
+            throw new ByActionStatusComponentException(ActionStatus.GENERAL_ERROR);
         } finally {
             if (!inTransaction) {
                 janusGraphDao.commit();
-                       }
-                       if (shouldLock) {
-                               graphLockOperation.unlockComponentByName(resource.getSystemName(), resource.getUniqueId(),
-                                       NodeTypeEnum.Resource);
-                       }
-               }
-       }
-
-       private void rollback(boolean inTransaction, Resource resource, List<ArtifactDefinition> createdArtifacts,
-                                                 List<ArtifactDefinition> nodeTypesNewCreatedArtifacts) {
-               if (!inTransaction) {
+            }
+            if (shouldLock) {
+                graphLockOperation.unlockComponentByName(resource.getSystemName(), resource.getUniqueId(), NodeTypeEnum.Resource);
+            }
+        }
+    }
+
+    private void rollback(boolean inTransaction, Resource resource, List<ArtifactDefinition> createdArtifacts,
+                          List<ArtifactDefinition> nodeTypesNewCreatedArtifacts) {
+        if (!inTransaction) {
             janusGraphDao.rollback();
-               }
-               if (isNotEmpty(createdArtifacts) && isNotEmpty(nodeTypesNewCreatedArtifacts)) {
-                       createdArtifacts.addAll(nodeTypesNewCreatedArtifacts);
-                       log.debug("Found {} newly created artifacts to deleted, the component name: {}", createdArtifacts.size(),
-                                       resource.getName());
-               }
-       }
-
-       private Resource getResourceWithGroups(String resourceId) {
-
-               ComponentParametersView filter = new ComponentParametersView();
-               filter.setIgnoreGroups(false);
-               Either<Resource, StorageOperationStatus> updatedResource = toscaOperationFacade.getToscaElement(resourceId,
-                               filter);
-               if (updatedResource.isRight()) {
-                       rollbackWithException(componentsUtils.convertFromStorageResponse(updatedResource.right()
-                                       .value()), resourceId);
-               }
-               return updatedResource.left()
-                               .value();
-       }
-
-       private Either<Resource, ResponseFormat> createGroupsOnResource(Resource resource,
-                                                                                                                                       Map<String, GroupDefinition> groups) {
-               if (groups != null && !groups.isEmpty()) {
-                       List<GroupDefinition> groupsAsList = updateGroupsMembersUsingResource(groups, resource);
-                       handleGroupsProperties(resource, groups);
-                       fillGroupsFinalFields(groupsAsList);
-                       Either<List<GroupDefinition>, ResponseFormat> createGroups = groupBusinessLogic.createGroups(resource,
-                                       groupsAsList, true);
-                       if (createGroups.isRight()) {
-                               return Either.right(createGroups.right()
-                                               .value());
-                       }
-               }
-               return Either.left(resource);
-       }
-
-       private void handleGroupsProperties(Resource resource, Map<String, GroupDefinition> groups) {
-               List<InputDefinition> inputs = resource.getInputs();
-               if (MapUtils.isNotEmpty(groups)) {
-                       groups.values()
-                                       .stream()
-                                       .filter(g -> isNotEmpty(g.getProperties()))
-                                       .flatMap(g -> g.getProperties()
-                                                       .stream())
-                                       .forEach(p -> handleGetInputs(p, inputs));
-               }
-       }
+        }
+        if (isNotEmpty(createdArtifacts) && isNotEmpty(nodeTypesNewCreatedArtifacts)) {
+            createdArtifacts.addAll(nodeTypesNewCreatedArtifacts);
+            log.debug("Found {} newly created artifacts to deleted, the component name: {}", createdArtifacts.size(), resource.getName());
+        }
+    }
 
-    private Resource createPoliciesOnResource(Resource resource, Map<String, PolicyDefinition> policies) {
-               policyBusinessLogic.createPoliciesFromParsedCsar(resource, policies);
-               return resource;
-    }
-
-       private void handleGetInputs(PropertyDataDefinition property, List<InputDefinition> inputs) {
-               if (isNotEmpty(property.getGetInputValues())) {
-                       if (inputs == null || inputs.isEmpty()) {
-                               log.debug("Failed to add property {} to group. Inputs list is empty ", property);
-                               rollbackWithException(ActionStatus.INPUTS_NOT_FOUND, property.getGetInputValues()
-                                               .stream()
-                                               .map(GetInputValueDataDefinition::getInputName)
-                                               .collect(toList())
-                                               .toString());
-                       }
-                       ListIterator<GetInputValueDataDefinition> getInputValuesIter = property.getGetInputValues()
-                                       .listIterator();
-                       while (getInputValuesIter.hasNext()) {
-                               GetInputValueDataDefinition getInput = getInputValuesIter.next();
-                               Either<InputDefinition, RuntimeException> inputEither = findInputByName(inputs, getInput);
-                               if (inputEither.isRight()) {
-                                       throw inputEither.right().value();
-                               } else {
-                                       InputDefinition input = inputEither.left().value();
-                                       getInput.setInputId(input.getUniqueId());
-                                       if (getInput.getGetInputIndex() != null) {
-                                               GetInputValueDataDefinition getInputIndex = getInput.getGetInputIndex();
-                                               Either<InputDefinition, RuntimeException> newInputEither = findInputByName(inputs,
-                                                       getInputIndex);
-                                               if (newInputEither.isRight()) {
-                                                       throw newInputEither.right().value();
-                                               } else {
-                                                       InputDefinition newInput = newInputEither.left().value();
-                                                       getInputIndex.setInputId(newInput.getUniqueId());
-                                               }
-                                               getInputValuesIter.add(getInputIndex);
-                                       }
-                               }
-                       }
-               }
-       }
-
-       static <T> Either<T, RuntimeException> rollbackWithEither(
-               final JanusGraphDao janusGraphDao,
-               final ActionStatus actionStatus,
-               final String... params) {
-               if (janusGraphDao != null)
-                       janusGraphDao.rollback();
-               return Either.right(new ByActionStatusComponentException(actionStatus, params));
-       }
-
-       <T> Either<T, RuntimeException> rollbackWithEither(
-               final ActionStatus actionStatus,
-               final String... params) {
-               return rollbackWithEither(janusGraphDao, actionStatus, params);
-       }
-
-       private Either<InputDefinition, RuntimeException> findInputByName(List<InputDefinition> inputs, GetInputValueDataDefinition getInput) {
-
-               final String inputName = getInput != null ? getInput.getInputName() : "";
-
-               if(inputs == null || inputs.isEmpty()) {
-                       log.debug("#findInputByName - Inputs list is empty");
-                       return rollbackWithEither(ActionStatus.INPUTS_NOT_FOUND, inputName);
-               } else {
-                       Optional<InputDefinition> inputOpt = inputs.stream()
-                               .filter(p -> p.getName().equals(inputName))
-                               .findFirst();
-                       if (!inputOpt.isPresent()) {
-                               log.debug("#findInputByName - Failed to find the input {} ", inputName);
-                               return rollbackWithEither(ActionStatus.INPUTS_NOT_FOUND, inputName);
-                       } else {
-                               return Either.left(inputOpt.get());
-                       }
-               }
-       }
-
-       private void fillGroupsFinalFields(List<GroupDefinition> groupsAsList) {
-               groupsAsList.forEach(groupDefinition -> {
-                       groupDefinition.setInvariantName(groupDefinition.getName());
-                       groupDefinition.setCreatedFrom(CreatedFrom.CSAR);
-               });
-       }
-
-       private Resource updateGroupsOnResource(Resource resource, Map<String, GroupDefinition> groups) {
-               if (isEmpty(groups)) {
-                       return resource;
-               }
-               return updateOrCreateGroups(resource, groups);
-       }
-
-       private Resource updateOrCreateGroups(Resource resource, Map<String, GroupDefinition> groups) {
-               List<GroupDefinition> groupsFromResource = resource.getGroups();
-               List<GroupDefinition> groupsAsList = updateGroupsMembersUsingResource(groups, resource);
-               List<GroupDefinition> groupsToUpdate = new ArrayList<>();
-               List<GroupDefinition> groupsToDelete = new ArrayList<>();
-               List<GroupDefinition> groupsToCreate = new ArrayList<>();
-               if (isNotEmpty(groupsFromResource)) {
-                       addGroupsToCreateOrUpdate(groupsFromResource, groupsAsList, groupsToUpdate, groupsToCreate);
-                       addGroupsToDelete(groupsFromResource, groupsAsList, groupsToDelete);
-               } else {
-                       groupsToCreate.addAll(groupsAsList);
-               }
-               if (isNotEmpty(groupsToCreate)) {
-                       fillGroupsFinalFields(groupsToCreate);
-                       if (isNotEmpty(groupsFromResource)) {
-                               groupBusinessLogic.addGroups(resource, groupsToCreate, true)
-                                               .left()
-                                               .on(this::throwComponentException);
-                       } else {
-                               groupBusinessLogic.createGroups(resource, groupsToCreate, true)
-                                               .left()
-                                               .on(this::throwComponentException);
-                       }
-               }
-               if (isNotEmpty(groupsToDelete)) {
-                       groupBusinessLogic.deleteGroups(resource, groupsToDelete)
-                                       .left()
-                                       .on(this::throwComponentException);
-               }
-               if (isNotEmpty(groupsToUpdate)) {
-                       groupBusinessLogic.updateGroups(resource, groupsToUpdate, true)
-                                       .left()
-                                       .on(this::throwComponentException);
-               }
-               return resource;
-
-       }
-
-       private void addGroupsToDelete(List<GroupDefinition> groupsFromResource, List<GroupDefinition> groupsAsList,
-                                                                  List<GroupDefinition> groupsToDelete) {
-               for (GroupDefinition group : groupsFromResource) {
-                       Optional<GroupDefinition> op = groupsAsList.stream()
-                                       .filter(p -> p.getInvariantName()
-                                                       .equalsIgnoreCase(group.getInvariantName()))
-                                       .findAny();
-                       if (!op.isPresent() && (group.getArtifacts() == null || group.getArtifacts()
-                                       .isEmpty())) {
-                               groupsToDelete.add(group);
-                       }
-               }
-       }
-
-       private void addGroupsToCreateOrUpdate(List<GroupDefinition> groupsFromResource, List<GroupDefinition> groupsAsList,
-                                                                                  List<GroupDefinition> groupsToUpdate, List<GroupDefinition> groupsToCreate) {
-               for (GroupDefinition group : groupsAsList) {
-                       Optional<GroupDefinition> op = groupsFromResource.stream()
-                                       .filter(p -> p.getInvariantName()
-                                                       .equalsIgnoreCase(group.getInvariantName()))
-                                       .findAny();
-                       if (op.isPresent()) {
-                               GroupDefinition groupToUpdate = op.get();
-                               groupToUpdate.setMembers(group.getMembers());
-                               groupToUpdate.setCapabilities(group.getCapabilities());
-                               groupToUpdate.setProperties(group.getProperties());
-                               groupsToUpdate.add(groupToUpdate);
-                       } else {
-                               groupsToCreate.add(group);
-                       }
-               }
-       }
-
-       private Resource createInputsOnResource(Resource resource, Map<String, InputDefinition> inputs) {
-               List<InputDefinition> resourceProperties = resource.getInputs();
-               if (MapUtils.isNotEmpty(inputs) || isNotEmpty(resourceProperties)) {
-
-                       Either<List<InputDefinition>, ResponseFormat> createInputs = inputsBusinessLogic.createInputsInGraph(inputs,
-                                       resource);
-                       if (createInputs.isRight()) {
-                               loggerSupportability.log(LoggerSupportabilityActions.CREATE_INPUTS,resource.getComponentMetadataForSupportLog(),
-                                               StatusCode.ERROR,"failed to add inputs from yaml: {}",createInputs.right()
-                                                               .value());
-                               throw new ByResponseFormatComponentException(createInputs.right()
-                                               .value());
-                       }
-                       resource.setInputs(createInputs.left().value());
-               }
-               return resource;
-       }
-
-       private List<GroupDefinition> updateGroupsMembersUsingResource(Map<String, GroupDefinition> groups,
-                                                                                                                                  Resource component) {
-
-               List<GroupDefinition> result = new ArrayList<>();
-               List<ComponentInstance> componentInstances = component.getComponentInstances();
-
-               if (groups != null) {
-                       Either<Boolean, ResponseFormat> validateCyclicGroupsDependencies = validateCyclicGroupsDependencies(groups);
-                       if (validateCyclicGroupsDependencies.isRight()) {
-                               throw new ByResponseFormatComponentException(validateCyclicGroupsDependencies.right().value());
-                       }
-                       for (Entry<String, GroupDefinition> entry : groups.entrySet()) {
-                               String groupName = entry.getKey();
-                               GroupDefinition groupDefinition = entry.getValue();
-                               GroupDefinition updatedGroupDefinition = new GroupDefinition(groupDefinition);
-                               updatedGroupDefinition.setMembers(null);
-                               Map<String, String> members = groupDefinition.getMembers();
-                               if (members != null) {
-                                       updateGroupMembers(groups, updatedGroupDefinition, component, componentInstances, groupName,
-                                                       members);
-                               }
-                               result.add(updatedGroupDefinition);
-                       }
-               }
-               return result;
-       }
-
-       private void updateGroupMembers(Map<String, GroupDefinition> groups, GroupDefinition updatedGroupDefinition,
-                                                                       Resource component, List<ComponentInstance> componentInstances, String groupName,
-                                                                       Map<String, String> members) {
-               Set<String> compInstancesNames = members.keySet();
-
-               if (CollectionUtils.isEmpty(componentInstances)) {
-                       String membersAstString = compInstancesNames.stream()
-                                       .collect(joining(","));
-                       log.debug(
-                                       "The members: {}, in group: {}, cannot be found in component {}. There are no component instances.",
-                                       membersAstString, groupName, component.getNormalizedName());
-                       throw new ByActionStatusComponentException(
-                                       ActionStatus.GROUP_INVALID_COMPONENT_INSTANCE, membersAstString,
-                                       groupName, component.getNormalizedName(), getComponentTypeForResponse(component));
-               }
-               // Find all component instances with the member names
-               Map<String, String> memberNames = componentInstances.stream()
-                               .collect(toMap(ComponentInstance::getName, ComponentInstance::getUniqueId));
-               memberNames.putAll(groups.keySet()
-                               .stream()
-                               .collect(toMap(g -> g, g -> "")));
-               Map<String, String> relevantInstances = memberNames.entrySet()
-                               .stream()
-                               .filter(n -> compInstancesNames.contains(n.getKey()))
-                               .collect(toMap(Entry::getKey, Entry::getValue));
-
-               if (relevantInstances == null || relevantInstances.size() != compInstancesNames.size()) {
-
-                       List<String> foundMembers = new ArrayList<>();
-                       if (relevantInstances != null) {
-                               foundMembers = relevantInstances.keySet()
-                                               .stream()
-                                               .collect(toList());
-                       }
-                       compInstancesNames.removeAll(foundMembers);
-                       String membersAstString = compInstancesNames.stream()
-                                       .collect(joining(","));
-                       log.debug("The members: {}, in group: {}, cannot be found in component: {}", membersAstString, groupName,
-                                       component.getNormalizedName());
-                       throw new ByActionStatusComponentException(
-                                       ActionStatus.GROUP_INVALID_COMPONENT_INSTANCE, membersAstString,
-                                       groupName, component.getNormalizedName(), getComponentTypeForResponse(component));
-               }
-               updatedGroupDefinition.setMembers(relevantInstances);
-       }
-
-       /**
-        * This Method validates that there is no cyclic group dependencies. meaning
-        * group A as member in group B which is member in group A
-        *
-        * @param allGroups
-        * @return
-        */
-       private Either<Boolean, ResponseFormat> validateCyclicGroupsDependencies(Map<String, GroupDefinition> allGroups) {
-
-               Either<Boolean, ResponseFormat> result = Either.left(true);
-               try {
-                       Iterator<Entry<String, GroupDefinition>> allGroupsItr = allGroups.entrySet()
-                                       .iterator();
-                       while (allGroupsItr.hasNext() && result.isLeft()) {
-                               Entry<String, GroupDefinition> groupAEntry = allGroupsItr.next();
-                               // Fetches a group member A
-                               String groupAName = groupAEntry.getKey();
-                               // Finds all group members in group A
-                               Set<String> allGroupAMembersNames = new HashSet<>();
-                               fillAllGroupMemebersRecursivly(groupAEntry.getKey(), allGroups, allGroupAMembersNames);
-                               // If A is a group member of itself found cyclic dependency
-                               if (allGroupAMembersNames.contains(groupAName)) {
-                                       ResponseFormat responseFormat = componentsUtils
-                                                       .getResponseFormat(ActionStatus.GROUP_HAS_CYCLIC_DEPENDENCY, groupAName);
-                                       result = Either.right(responseFormat);
-                               }
-                       }
-               } catch (Exception e) {
-                       ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR);
-                       result = Either.right(responseFormat);
-                       log.debug("Exception occurred when validateCyclicGroupsDependencies, error is:{}", e.getMessage(), e);
-               }
-               return result;
-       }
-
-       /**
-        * This Method fills recursively the set groupMembers with all the members
-        * of the given group which are also of type group.
-        *
-        * @param groupName
-        * @param allGroups
-        * @param allGroupMembers
-        * @return
-        */
-       private void fillAllGroupMemebersRecursivly(String groupName, Map<String, GroupDefinition> allGroups,
-                                                                                               Set<String> allGroupMembers) {
-
-               // Found Cyclic dependency
-               if (isfillGroupMemebersRecursivlyStopCondition(groupName, allGroups, allGroupMembers)) {
-                       return;
-               }
-               GroupDefinition groupDefinition = allGroups.get(groupName);
-               // All Members Of Current Group Resource Instances & Other Groups
-               Set<String> currGroupMembers = groupDefinition.getMembers()
-                               .keySet();
-               // Filtered Members Of Current Group containing only members which
-               // are groups
-               List<String> currGroupFilteredMembers = currGroupMembers.stream()
-                               .
-                               // Keep Only Elements of type group and not Resource Instances
-                                               filter(allGroups::containsKey)
-                               .
-                               // Add Filtered Elements to main Set
-                                               peek(allGroupMembers::add)
-                               .
-                               // Collect results
-                                               collect(toList());
-
-               // Recursively call the method for all the filtered group members
-               for (String innerGroupName : currGroupFilteredMembers) {
-                       fillAllGroupMemebersRecursivly(innerGroupName, allGroups, allGroupMembers);
-               }
-
-       }
-
-       private boolean isfillGroupMemebersRecursivlyStopCondition(String groupName, Map<String, GroupDefinition> allGroups,
-                                                                                                                          Set<String> allGroupMembers) {
-
-               boolean stop = false;
-               // In Case Not Group Stop
-               if (!allGroups.containsKey(groupName)) {
-                       stop = true;
-               }
-               // In Case Group Has no members stop
-               if (!stop) {
-                       GroupDefinition groupDefinition = allGroups.get(groupName);
-                       stop = isEmpty(groupDefinition.getMembers());
-
-               }
-               // In Case all group members already contained stop
-               if (!stop) {
-                       final Set<String> allMembers = allGroups.get(groupName)
-                                       .getMembers()
-                                       .keySet();
-                       Set<String> membersOfTypeGroup = allMembers.stream()
-                                       .
-                                       // Filter In Only Group members
-                                                       filter(allGroups::containsKey)
-                                       .
-                                       // Collect
-                                                       collect(toSet());
-                       stop = allGroupMembers.containsAll(membersOfTypeGroup);
-               }
-               return stop;
-       }
-
-       private Resource createRIAndRelationsFromYaml(String yamlName, Resource resource,
-                                                                                                 Map<String, UploadComponentInstanceInfo> uploadComponentInstanceInfoMap, String topologyTemplateYaml,
-                                                                                                 List<ArtifactDefinition> nodeTypesNewCreatedArtifacts, Map<String, NodeTypeInfo> nodeTypesInfo,
-                                                                                                 CsarInfo csarInfo,
-                                                                                                 Map<String, EnumMap<ArtifactOperationEnum, List<ArtifactDefinition>>> nodeTypesArtifactsToCreate,
-                                                                                                 String nodeName) {
-
-               log.debug("************* Going to create all nodes {}", yamlName);
-               handleNodeTypes(yamlName, resource, topologyTemplateYaml, false, nodeTypesArtifactsToCreate,
-                               nodeTypesNewCreatedArtifacts, nodeTypesInfo, csarInfo, nodeName);
-               log.debug("************* Finished to create all nodes {}", yamlName);
-               log.debug("************* Going to create all resource instances {}", yamlName);
-               Map<String, Resource> existingNodeTypesByResourceNames = new HashMap<>();
-               resource = createResourceInstances(yamlName, resource, null, uploadComponentInstanceInfoMap,
-                               csarInfo.getCreatedNodes(), existingNodeTypesByResourceNames);
-               log.debug("************* Finished to create all resource instances {}", yamlName);
-               log.debug("************* Going to create all relations {}", yamlName);
-               resource = createResourceInstancesRelations(csarInfo.getModifier(), yamlName, resource, null, uploadComponentInstanceInfoMap, existingNodeTypesByResourceNames);
-               log.debug("************* Finished to create all relations {}", yamlName);
-               log.debug("************* Going to create positions {}", yamlName);
-               compositionBusinessLogic.setPositionsForComponentInstances(resource, csarInfo.getModifier()
-                               .getUserId());
-               log.debug("************* Finished to set positions {}", yamlName);
-               return resource;
-       }
-
-       private void handleAndAddExtractedVfcsArtifacts(List<ArtifactDefinition> vfcArtifacts,
-                                                                                                       List<ArtifactDefinition> artifactsToAdd) {
-               List<String> vfcArtifactNames = vfcArtifacts.stream()
-                               .map(ArtifactDataDefinition::getArtifactName)
-                               .collect(toList());
-               artifactsToAdd.stream()
-                               .forEach(a -> {
-                                       if (!vfcArtifactNames.contains(a.getArtifactName())) {
-                                               vfcArtifacts.add(a);
-                                       } else {
-                                               log.debug("Can't upload two artifact with the same name {}. ", a.getArtifactName());
-                                       }
-                               });
-
-       }
-
-       @SuppressWarnings("unchecked")
-       private void handleNodeTypes(String yamlName, Resource resource, String topologyTemplateYaml, boolean needLock,
-                                                                Map<String, EnumMap<ArtifactOperationEnum, List<ArtifactDefinition>>> nodeTypesArtifactsToHandle,
-                                                                List<ArtifactDefinition> nodeTypesNewCreatedArtifacts, Map<String, NodeTypeInfo> nodeTypesInfo,
-                                                                CsarInfo csarInfo, String nodeName) {
-               try {
-                       for (Entry<String, NodeTypeInfo> nodeTypeEntry : nodeTypesInfo.entrySet()) {
-                               if (nodeTypeEntry.getValue()
-                                               .isNested()) {
-
-                                       handleNestedVfc(resource, nodeTypesArtifactsToHandle, nodeTypesNewCreatedArtifacts, nodeTypesInfo,
-                                                       csarInfo, nodeTypeEntry.getKey());
-                                       log.trace("************* finished to create node {}", nodeTypeEntry.getKey());
-                               }
-                       }
-                       Map<String, Object> mappedToscaTemplate = null;
-                       if (StringUtils.isNotEmpty(nodeName) && isNotEmpty(nodeTypesInfo) && nodeTypesInfo.containsKey(nodeName)) {
-                               mappedToscaTemplate = nodeTypesInfo.get(nodeName)
-                                               .getMappedToscaTemplate();
-                       }
-                       if (isEmpty(mappedToscaTemplate)) {
-                               mappedToscaTemplate = (Map<String, Object>) new Yaml().load(topologyTemplateYaml);
-                       }
-                       createResourcesFromYamlNodeTypesList(yamlName, resource, mappedToscaTemplate, needLock,
-                                       nodeTypesArtifactsToHandle, nodeTypesNewCreatedArtifacts, nodeTypesInfo, csarInfo);
-               } catch (ComponentException e) {
-                       ResponseFormat responseFormat = e.getResponseFormat() != null ? e.getResponseFormat()
-                                       : componentsUtils.getResponseFormat(e.getActionStatus(), e.getParams());
-                       componentsUtils.auditResource(responseFormat, csarInfo.getModifier(), resource,
-                                       AuditingActionEnum.IMPORT_RESOURCE);
-                       throw e;
-               } catch (StorageException e) {
-                       ResponseFormat responseFormat = componentsUtils
-                                       .getResponseFormat(componentsUtils.convertFromStorageResponse(e.getStorageOperationStatus()));
-                       componentsUtils.auditResource(responseFormat, csarInfo.getModifier(), resource,
-                                       AuditingActionEnum.IMPORT_RESOURCE);
-                       throw e;
-               }
-       }
-
-       private Either<Resource, ResponseFormat> handleVfCsarArtifacts(Resource resource, CsarInfo csarInfo,
-                                                                                                                                  List<ArtifactDefinition> createdArtifacts, ArtifactOperationInfo artifactOperation, boolean shouldLock,
-                                                                                                                                  boolean inTransaction) {
-
-               if (csarInfo.getCsar() != null) {
-                       String vendorLicenseModelId = null;
-                       String vfLicenseModelId = null;
-
-                       if (artifactOperation.isUpdate()) {
-                               Map<String, ArtifactDefinition> deploymentArtifactsMap = resource.getDeploymentArtifacts();
-                               if (deploymentArtifactsMap != null && !deploymentArtifactsMap.isEmpty()) {
-                                       for (Entry<String, ArtifactDefinition> artifactEntry : deploymentArtifactsMap.entrySet()) {
-                                               if (artifactEntry.getValue()
-                                                               .getArtifactName()
-                                                               .equalsIgnoreCase(Constants.VENDOR_LICENSE_MODEL)) {
-                                                       vendorLicenseModelId = artifactEntry.getValue()
-                                                                       .getUniqueId();
-                                               }
-                                               if (artifactEntry.getValue()
-                                                               .getArtifactName()
-                                                               .equalsIgnoreCase(Constants.VF_LICENSE_MODEL)) {
-                                                       vfLicenseModelId = artifactEntry.getValue()
-                                                                       .getUniqueId();
-                                               }
-                                       }
-                               }
-
-                       }
-                       // Specific Behavior for license artifacts
-                       createOrUpdateSingleNonMetaArtifact(resource, csarInfo,
-                                       CsarUtils.ARTIFACTS_PATH + Constants.VENDOR_LICENSE_MODEL, Constants.VENDOR_LICENSE_MODEL,
-                                       ArtifactTypeEnum.VENDOR_LICENSE.getType(), ArtifactGroupTypeEnum.DEPLOYMENT,
-                                       Constants.VENDOR_LICENSE_LABEL, Constants.VENDOR_LICENSE_DISPLAY_NAME,
-                                       Constants.VENDOR_LICENSE_DESCRIPTION, vendorLicenseModelId, artifactOperation, null, true,
-                                       shouldLock, inTransaction);
-                       createOrUpdateSingleNonMetaArtifact(resource, csarInfo,
-                                       CsarUtils.ARTIFACTS_PATH + Constants.VF_LICENSE_MODEL, Constants.VF_LICENSE_MODEL,
-                                       ArtifactTypeEnum.VF_LICENSE.getType(), ArtifactGroupTypeEnum.DEPLOYMENT, Constants.VF_LICENSE_LABEL,
-                                       Constants.VF_LICENSE_DISPLAY_NAME, Constants.VF_LICENSE_DESCRIPTION, vfLicenseModelId,
-                                       artifactOperation, null, true, shouldLock, inTransaction);
-
-                       Either<Resource, ResponseFormat> eitherCreateResult = createOrUpdateNonMetaArtifacts(csarInfo, resource,
-                                       createdArtifacts, shouldLock, inTransaction, artifactOperation);
-                       if (eitherCreateResult.isRight()) {
-                               return Either.right(eitherCreateResult.right()
-                                               .value());
-                       }
-
-                       Either<ImmutablePair<String, String>, ResponseFormat> artifacsMetaCsarStatus = CsarValidationUtils
-                                       .getArtifactsMeta(csarInfo.getCsar(), csarInfo.getCsarUUID(), componentsUtils);
-
-                       if (artifacsMetaCsarStatus.isLeft()) {
-                               String artifactsFileName = artifacsMetaCsarStatus.left()
-                                               .value()
-                                               .getKey();
-                               String artifactsContents = artifacsMetaCsarStatus.left()
-                                               .value()
-                                               .getValue();
-                               Either<Resource, ResponseFormat> createArtifactsFromCsar;
-                               if (artifactOperation.isCreateOrLink()) {
-                                       createArtifactsFromCsar = csarArtifactsAndGroupsBusinessLogic.createResourceArtifactsFromCsar(
-                                                       csarInfo, resource, artifactsContents, artifactsFileName, createdArtifacts);
-                               } else {
-                                       Either<Component, ResponseFormat> result  = csarArtifactsAndGroupsBusinessLogic.updateResourceArtifactsFromCsar(
-                                                       csarInfo, resource, artifactsContents, artifactsFileName, createdArtifacts, shouldLock,
-                                                       inTransaction);
-                                       if ((result.left().value() instanceof Resource) && result.isLeft()) {
-                                               Resource service1 = (Resource) result.left().value();
-                                               createArtifactsFromCsar = Either.left(service1);
-                                       } else {
-                                               createArtifactsFromCsar = Either.right(result.right().value());
-                                       }
-                               }
-
-                               if (createArtifactsFromCsar.isRight()) {
-                                       log.debug("Couldn't create artifacts from artifacts.meta");
-                                       return Either.right(createArtifactsFromCsar.right()
-                                                       .value());
-                               }
-
-                               return Either.left(createArtifactsFromCsar.left()
-                                               .value());
-                       } else {
-
-                               return csarArtifactsAndGroupsBusinessLogic.deleteVFModules(resource, csarInfo, shouldLock,
-                                               inTransaction);
-
-                       }
-               }
-               return Either.left(resource);
-       }
-
-       private Either<Boolean, ResponseFormat> createOrUpdateSingleNonMetaArtifact(Resource resource, CsarInfo csarInfo,
-                                                                                                                                                               String artifactPath, String artifactFileName, String artifactType, ArtifactGroupTypeEnum artifactGroupType,
-                                                                                                                                                               String artifactLabel, String artifactDisplayName, String artifactDescription, String artifactId,
-                                                                                                                                                               ArtifactOperationInfo operation, List<ArtifactDefinition> createdArtifacts, boolean isFromCsar,
-                                                                                                                                                               boolean shouldLock, boolean inTransaction) {
-               byte[] artifactFileBytes = null;
-
-               if (csarInfo.getCsar()
-                               .containsKey(artifactPath)) {
-                       artifactFileBytes = csarInfo.getCsar()
-                                       .get(artifactPath);
-               }
-               Either<Boolean, ResponseFormat> result = Either.left(true);
-               if (operation.isUpdate() || operation.isDelete()) {
-                       if (isArtifactDeletionRequired(artifactId, artifactFileBytes, isFromCsar)) {
-                               Either<ArtifactDefinition, ResponseFormat> handleDelete = artifactsBusinessLogic
-                                               .handleDelete(resource.getUniqueId(), artifactId, csarInfo.getModifier(),
-                                                       resource, shouldLock,
-                                                               inTransaction);
-                               if (handleDelete.isRight()) {
-                                       result = Either.right(handleDelete.right()
-                                                       .value());
-                               } else {
-                                       ArtifactDefinition value = handleDelete.left().value();
-                                       String updatedArtifactId = value.getUniqueId();
-                                       if (artifactGroupType == ArtifactGroupTypeEnum.DEPLOYMENT) {
-                                               resource.getDeploymentArtifacts().remove(updatedArtifactId);
-                                       } else {
-                                               resource.getArtifacts().remove(updatedArtifactId);
-                                       }
-                               }
-                               return result;
-                       }
-
-                       if (StringUtils.isEmpty(artifactId) && artifactFileBytes != null) {
-                               operation = new ArtifactOperationInfo(false, false,
-                                               ArtifactOperationEnum.CREATE);
-                       }
-
-               }
-               if (artifactFileBytes != null) {
-                       Map<String, Object> vendorLicenseModelJson = ArtifactUtils.buildJsonForUpdateArtifact(artifactId,
-                                       artifactFileName, artifactType, artifactGroupType, artifactLabel, artifactDisplayName,
-                                       artifactDescription, artifactFileBytes, null, isFromCsar);
-                       Either<Either<ArtifactDefinition, Operation>, ResponseFormat> eitherNonMetaArtifacts = csarArtifactsAndGroupsBusinessLogic
-                                       .createOrUpdateCsarArtifactFromJson(resource, csarInfo.getModifier(), vendorLicenseModelJson,
-                                                       operation);
-                       addNonMetaCreatedArtifactsToSupportRollback(operation, createdArtifacts, eitherNonMetaArtifacts);
-                       if (eitherNonMetaArtifacts.isRight()) {
-                               BeEcompErrorManager.getInstance()
-                                               .logInternalFlowError("UploadLicenseArtifact", "Failed to upload license artifact: "
-                                                                               + artifactFileName + "With csar uuid: " + csarInfo.getCsarUUID(),
-                                                               ErrorSeverity.WARNING);
-                               return Either.right(eitherNonMetaArtifacts.right()
-                                               .value());
-                       }
-                       ArtifactDefinition artifactDefinition = eitherNonMetaArtifacts.left().value().left().value();
-                       createOrUpdateResourceWithUpdatedArtifact(artifactDefinition,resource, artifactGroupType);
-               }
-
-               return result;
-       }
-
-       private void createOrUpdateResourceWithUpdatedArtifact(ArtifactDefinition artifact, Resource resource, ArtifactGroupTypeEnum groupTypeEnum) {
-               if (groupTypeEnum == ArtifactGroupTypeEnum.DEPLOYMENT) {
-                       resource.getDeploymentArtifacts().put(artifact.getArtifactLabel(), artifact);
-               } else {
-                       resource.getArtifacts().put(artifact.getArtifactLabel(), artifact);
-               }
-       }
-
-       private boolean isArtifactDeletionRequired(String artifactId, byte[] artifactFileBytes, boolean isFromCsar) {
-               return !StringUtils.isEmpty(artifactId) && artifactFileBytes == null && isFromCsar;
-       }
-
-       private void addNonMetaCreatedArtifactsToSupportRollback(ArtifactOperationInfo operation,
-                                                                                                                        List<ArtifactDefinition> createdArtifacts,
-                                                                                                                        Either<Either<ArtifactDefinition, Operation>, ResponseFormat> eitherNonMetaArtifacts) {
-               if (operation.isCreateOrLink() && createdArtifacts != null
-                               && eitherNonMetaArtifacts.isLeft()) {
-                       Either<ArtifactDefinition, Operation> eitherResult = eitherNonMetaArtifacts.left()
-                                       .value();
-                       if (eitherResult.isLeft()) {
-                               createdArtifacts.add(eitherResult.left()
-                                               .value());
-                       }
-               }
-       }
-
-       private Either<Resource, ResponseFormat> createOrUpdateNonMetaArtifacts(CsarInfo csarInfo, Resource resource,
-                                                                                                                                                       List<ArtifactDefinition> createdArtifacts, boolean shouldLock, boolean inTransaction,
-                                                                                                                                                       ArtifactOperationInfo artifactOperation) {
-
-               Either<Resource, ResponseFormat> resStatus = null;
-               Map<String, Set<List<String>>> collectedWarningMessages = new HashMap<>();
-
-               try {
-                       Either<List<NonMetaArtifactInfo>, String> artifactPathAndNameList = getValidArtifactNames(csarInfo,
-                                       collectedWarningMessages);
-                       if (artifactPathAndNameList.isRight()) {
-                               return Either.right(getComponentsUtils().getResponseFormatByArtifactId(
-                                               ActionStatus.ARTIFACT_NAME_INVALID, artifactPathAndNameList.right()
-                                                               .value()));
-                       }
-                       EnumMap<ArtifactOperationEnum, List<NonMetaArtifactInfo>> vfCsarArtifactsToHandle = null;
-
-                       if (artifactOperation.isCreateOrLink()) {
-                               vfCsarArtifactsToHandle = new EnumMap<>(ArtifactOperationEnum.class);
-                               vfCsarArtifactsToHandle.put(artifactOperation.getArtifactOperationEnum(), artifactPathAndNameList.left()
-                                               .value());
-                       } else {
-                               Either<EnumMap<ArtifactOperationEnum, List<NonMetaArtifactInfo>>, ResponseFormat> findVfCsarArtifactsToHandleRes = findVfCsarArtifactsToHandle(
-                                               resource, artifactPathAndNameList.left()
-                                                               .value(),
-                                               csarInfo.getModifier());
-
-                               if (findVfCsarArtifactsToHandleRes.isRight()) {
-                                       resStatus = Either.right(findVfCsarArtifactsToHandleRes.right()
-                                                       .value());
-                               }
-                               if (resStatus == null) {
-                                       vfCsarArtifactsToHandle = findVfCsarArtifactsToHandleRes.left()
-                                                       .value();
-                               }
-                       }
-                       if (resStatus == null && vfCsarArtifactsToHandle != null) {
-                               resStatus = processCsarArtifacts(csarInfo, resource, createdArtifacts, shouldLock, inTransaction,
-                                               resStatus, vfCsarArtifactsToHandle);
-                       }
-                       if (resStatus == null) {
-                               resStatus = Either.left(resource);
-                       }
-               } catch (Exception e) {
-                       resStatus = Either.right(componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR));
-                       log.debug("Exception occurred in createNonMetaArtifacts, message:{}", e.getMessage(), e);
-               } finally {
-                       CsarUtils.handleWarningMessages(collectedWarningMessages);
-               }
-               return resStatus;
-       }
-
-       private Either<Resource, ResponseFormat> processCsarArtifacts(CsarInfo csarInfo, Resource resource,
-                                                                                                                                 List<ArtifactDefinition> createdArtifacts, boolean shouldLock, boolean inTransaction,
-                                                                                                                                 Either<Resource, ResponseFormat> resStatus,
-                                                                                                                                 EnumMap<ArtifactOperationEnum, List<NonMetaArtifactInfo>> vfCsarArtifactsToHandle) {
-               for (Entry<ArtifactOperationEnum, List<NonMetaArtifactInfo>> currArtifactOperationPair : vfCsarArtifactsToHandle
-                               .entrySet()) {
-
-                       Optional<ResponseFormat> optionalCreateInDBError =
-                                       // Stream of artifacts to be created
-                                       currArtifactOperationPair.getValue()
-                                                       .stream()
-                                                       // create each artifact
-                                                       .map(e -> createOrUpdateSingleNonMetaArtifact(resource, csarInfo, e.getPath(),
-                                                                       e.getArtifactName(), e.getArtifactType(),
-                                                                       e.getArtifactGroupType(), e.getArtifactLabel(), e.getDisplayName(),
-                                                                       CsarUtils.ARTIFACT_CREATED_FROM_CSAR, e.getArtifactUniqueId(),
-                                                                       new ArtifactOperationInfo(false, false,
-                                                                                       currArtifactOperationPair.getKey()),
-                                                                       createdArtifacts, e.isFromCsar(), shouldLock, inTransaction))
-                                                       // filter in only error
-                                                       .filter(Either::isRight)
-                                                       .
-                                                       // Convert the error from either to
-                                                       // ResponseFormat
-                                                                       map(e -> e.right()
-                                                                       .value())
-                                                       .
-                                                       // Check if an error occurred
-                                                                       findAny();
-                       // Error found on artifact Creation
-                       if (optionalCreateInDBError.isPresent()) {
-                               resStatus = Either.right(optionalCreateInDBError.get());
-                               break;
-                       }
-               }
-               return resStatus;
-       }
-
-       private Either<List<NonMetaArtifactInfo>, String> getValidArtifactNames(CsarInfo csarInfo,
-                                                                                                                                                       Map<String, Set<List<String>>> collectedWarningMessages) {
-               List<NonMetaArtifactInfo> artifactPathAndNameList =
-                               // Stream of file paths contained in csar
-                               csarInfo.getCsar()
-                                               .entrySet()
-                                               .stream()
-                                               // Filter in only VF artifact path location
-                                               .filter(e -> Pattern.compile(VF_NODE_TYPE_ARTIFACTS_PATH_PATTERN)
-                                                               .matcher(e.getKey())
-                                                               .matches())
-                                               // Validate and add warnings
-                                               .map(e -> CsarUtils.validateNonMetaArtifact(e.getKey(), e.getValue(), collectedWarningMessages))
-                                               // Filter in Non Warnings
-                                               .filter(Either::isLeft)
-                                               // Convert from Either to NonMetaArtifactInfo
-                                               .map(e -> e.left()
-                                                               .value())
-                                               // collect to List
-                                               .collect(toList());
-               Pattern englishNumbersAndUnderScoresOnly = Pattern.compile(CsarUtils.VALID_ENGLISH_ARTIFACT_NAME);
-               for (NonMetaArtifactInfo nonMetaArtifactInfo : artifactPathAndNameList) {
-                       if (!englishNumbersAndUnderScoresOnly.matcher(nonMetaArtifactInfo.getDisplayName())
-                                       .matches()) {
-                               return Either.right(nonMetaArtifactInfo.getArtifactName());
-                       }
-               }
-               return Either.left(artifactPathAndNameList);
-       }
-
-       private Either<EnumMap<ArtifactOperationEnum, List<NonMetaArtifactInfo>>, ResponseFormat> findVfCsarArtifactsToHandle(
-                       Resource resource, List<NonMetaArtifactInfo> artifactPathAndNameList, User user) {
-
-               List<ArtifactDefinition> existingArtifacts = new ArrayList<>();
-               // collect all Deployment and Informational artifacts of VF
-               if (resource.getDeploymentArtifacts() != null && !resource.getDeploymentArtifacts()
-                               .isEmpty()) {
-                       existingArtifacts.addAll(resource.getDeploymentArtifacts()
-                                       .values());
-               }
-               if (resource.getArtifacts() != null && !resource.getArtifacts()
-                               .isEmpty()) {
-                       existingArtifacts.addAll(resource.getArtifacts()
-                                       .values());
-               }
-               existingArtifacts = existingArtifacts.stream()
-                               // filter MANDATORY artifacts, LICENSE artifacts and artifacts
-                               // was created from HEAT.meta
-                               .filter(this::isNonMetaArtifact)
-                               .collect(toList());
-
-               List<String> artifactsToIgnore = new ArrayList<>();
-               // collect IDs of Artifacts of VF which belongs to any group
-               if (resource.getGroups() != null) {
-                       resource.getGroups()
-                                       .stream()
-                                       .forEach(g -> {
-                                               if (g.getArtifacts() != null && !g.getArtifacts()
-                                                               .isEmpty()) {
-                                                       artifactsToIgnore.addAll(g.getArtifacts());
-                                               }
-                                       });
-               }
-               existingArtifacts = existingArtifacts.stream()
-                               // filter artifacts which belongs to any group
-                               .filter(a -> !artifactsToIgnore.contains(a.getUniqueId()))
-                               .collect(toList());
-               return organizeVfCsarArtifactsByArtifactOperation(artifactPathAndNameList, existingArtifacts, resource, user);
-       }
-
-       private boolean isNonMetaArtifact(ArtifactDefinition artifact) {
-               boolean result = true;
-               if (artifact.getMandatory() || artifact.getArtifactName() == null || !isValidArtifactType(artifact)) {
-                       result = false;
-               }
-               return result;
-       }
-
-       private boolean isValidArtifactType(ArtifactDefinition artifact) {
-               boolean result = true;
-               if (artifact.getArtifactType() == null
-                               || ArtifactTypeEnum.parse(artifact.getArtifactType()) == ArtifactTypeEnum.VENDOR_LICENSE
-                               || ArtifactTypeEnum.parse(artifact.getArtifactType()) == ArtifactTypeEnum.VF_LICENSE) {
-                       result = false;
-               }
-               return result;
-       }
-
-       private Resource createResourceInstancesRelations(User user, String yamlName, Resource resource, Resource oldResource,
-                                                                                                         Map<String, UploadComponentInstanceInfo> uploadResInstancesMap, Map<String, Resource> existingNodeTypesByResourceNames) {
-               log.debug("#createResourceInstancesRelations - Going to create relations ");
-               loggerSupportability.log(LoggerSupportabilityActions.CREATE_RELATIONS,resource.getComponentMetadataForSupportLog(),     StatusCode.STARTED,"Start to create relations");
-               List<ComponentInstance> componentInstancesList = resource.getComponentInstances();
-               if (isEmpty(uploadResInstancesMap) || CollectionUtils.isEmpty(componentInstancesList)  &&
-                resource.getResourceType() != ResourceTypeEnum.PNF) { // PNF can have no resource instances {
-                       log.debug(
-                                       "#createResourceInstancesRelations - No instances found in the resource {} is empty, yaml template file name {}, ",
-                                       resource.getUniqueId(), yamlName);
-                       loggerSupportability.log(LoggerSupportabilityActions.CREATE_RELATIONS,resource.getComponentMetadataForSupportLog(),     StatusCode.ERROR,"No instances found in the resource: {}, is empty, yaml template file name: {}",resource.getName(),yamlName);
-                       BeEcompErrorManager.getInstance()
-                               .logInternalDataError("createResourceInstancesRelations",
-                                       "No instances found in a resource or nn yaml template. ", ErrorSeverity.ERROR);
-                       throw new ByActionStatusComponentException(ActionStatus.NOT_TOPOLOGY_TOSCA_TEMPLATE, yamlName);
-               }
-               Map<String, List<ComponentInstanceProperty>> instProperties = new HashMap<>();
-               Map<ComponentInstance, Map<String, List<CapabilityDefinition>>> instCapabilities = new HashMap<>();
-               Map<ComponentInstance, Map<String, List<RequirementDefinition>>> instRequirements = new HashMap<>();
-               Map<String, Map<String, ArtifactDefinition>> instDeploymentArtifacts = new HashMap<>();
-               Map<String, Map<String, ArtifactDefinition>> instArtifacts = new HashMap<>();
-        Map<String, List<AttributeDefinition>> instAttributes = new HashMap<>();
-               List<RequirementCapabilityRelDef> relations = new ArrayList<>();
-               Map<String, List<ComponentInstanceInput>> instInputs = new HashMap<>();
-
-               log.debug("#createResourceInstancesRelations - Before get all datatypes. ");
-               Either<Map<String, DataTypeDefinition>, JanusGraphOperationStatus> allDataTypes = dataTypeCache.getAll();
-               if (allDataTypes.isRight()) {
-                       JanusGraphOperationStatus status = allDataTypes.right()
-                               .value();
-                       BeEcompErrorManager.getInstance()
-                               .logInternalFlowError("UpdatePropertyValueOnComponentInstance",
-                                                       "Failed to update property value on instance. Status is " + status, ErrorSeverity.ERROR);
-                       loggerSupportability.log(LoggerSupportabilityActions.CREATE_RELATIONS,resource.getComponentMetadataForSupportLog(),
-                                       StatusCode.ERROR,"ERROR while update property value on instance. Status is: "+status);
-                       throw new ByActionStatusComponentException(componentsUtils.convertFromStorageResponse(
-                                       DaoStatusConverter.convertJanusGraphStatusToStorageStatus(status)), yamlName);
-
-               }
-               Resource finalResource = resource;
-               uploadResInstancesMap.values()
-                               .forEach(i -> processComponentInstance(yamlName, finalResource, componentInstancesList, allDataTypes,
-                                               instProperties, instCapabilities, instRequirements, instDeploymentArtifacts, instArtifacts,
-                                               instAttributes, existingNodeTypesByResourceNames, instInputs, i));
-               resource.getComponentInstances()
-                               .stream()
-                               .filter(i -> !i.isCreatedFromCsar())
-                       .forEach(i -> processUiComponentInstance(oldResource, i, instCapabilities, instRequirements,
-                               instDeploymentArtifacts, instArtifacts, instProperties, instInputs, instAttributes));
-
-               associateComponentInstancePropertiesToComponent(yamlName, resource, instProperties);
-               associateComponentInstanceInputsToComponent(yamlName, resource, instInputs);
-               associateDeploymentArtifactsToInstances(user, yamlName, resource, instDeploymentArtifacts);
-               associateArtifactsToInstances(yamlName, resource, instArtifacts);
-               associateOrAddCalculatedCapReq(yamlName, resource, instCapabilities, instRequirements);
-               associateInstAttributeToComponentToInstances(yamlName, resource, instAttributes);
-               addRelationsToRI(yamlName, resource, uploadResInstancesMap, componentInstancesList, relations);
-               associateResourceInstances(yamlName, resource, relations);
-               handleSubstitutionMappings(resource, uploadResInstancesMap);
-               log.debug("************* in create relations, getResource start");
-               loggerSupportability.log(LoggerSupportabilityActions.CREATE_RELATIONS,resource.getComponentMetadataForSupportLog(),     StatusCode.COMPLETE,"create relations");
-               Either<Resource, StorageOperationStatus> eitherGetResource = toscaOperationFacade
-                               .getToscaFullElement(resource.getUniqueId());
-               log.debug("************* in create relations, getResource end");
-               if (eitherGetResource.isRight()) {
-                       loggerSupportability.log(LoggerSupportabilityActions.CREATE_RELATIONS,resource.getComponentMetadataForSupportLog(),
-                                       StatusCode.ERROR,"ERROR while create relations");
-                       throw new ByResponseFormatComponentException(componentsUtils
-                                       .getResponseFormatByResource(componentsUtils.convertFromStorageResponse(eitherGetResource.right()
-                                                       .value()), resource));
-               }
-               return eitherGetResource.left()
-                               .value();
-       }
-
-       private void processUiComponentInstance(Resource oldResource, ComponentInstance instance,
-                                                                                       Map<ComponentInstance, Map<String, List<CapabilityDefinition>>> instCapabilities,
-                                                                                       Map<ComponentInstance, Map<String, List<RequirementDefinition>>> instRequirements,
-                                                                                       Map<String, Map<String, ArtifactDefinition>> instDeploymentArtifacts,
-                                                                                       Map<String, Map<String, ArtifactDefinition>> instArtifacts, Map<String,
-                                                                                       List<ComponentInstanceProperty>> instProperties, Map<String,
-                                                                                       List<ComponentInstanceInput>> instInputs,
-                                                                                       Map<String, List<AttributeDefinition>> instAttributes) {
-               Optional<ComponentInstance> foundInstance = findInstance(oldResource, instance);
-               if (foundInstance.isPresent()) {
-                       if (MapUtils.isNotEmpty(foundInstance.get().getCapabilities())) {
-                               instCapabilities.put(instance, foundInstance.get().getCapabilities());
-                       }
-                       if (MapUtils.isNotEmpty(foundInstance.get().getRequirements())) {
-                               instRequirements.put(instance, foundInstance.get().getRequirements());
-                       }
-                       if (MapUtils.isNotEmpty(foundInstance.get().getDeploymentArtifacts())) {
-                               instDeploymentArtifacts.put(instance.getUniqueId(), foundInstance.get().getDeploymentArtifacts());
-                       }
-                       if(MapUtils.isNotEmpty(foundInstance.get().getArtifacts())){
-                               instArtifacts.put(instance.getUniqueId(), foundInstance.get().getArtifacts());
-                       }
-                       if (MapUtils.isNotEmpty(oldResource.getComponentInstancesProperties()) &&
-                               CollectionUtils
-                                       .isNotEmpty(oldResource.getComponentInstancesProperties().get(foundInstance.get().getUniqueId()))) {
-                               instProperties.put(instance.getUniqueId(),
-                                       oldResource.getComponentInstancesProperties().get(foundInstance.get().getUniqueId()));
-                       }
-                       if (MapUtils.isNotEmpty(oldResource.getComponentInstancesInputs()) &&
-                               CollectionUtils
-                                       .isNotEmpty(oldResource.getComponentInstancesInputs().get(foundInstance.get().getUniqueId()))) {
-                               instInputs.put(instance.getUniqueId(),
-                                       oldResource.getComponentInstancesInputs().get(foundInstance.get().getUniqueId()));
-                       }
-                       if(MapUtils.isNotEmpty(oldResource.getComponentInstancesAttributes()) &&
-                                       CollectionUtils.isNotEmpty(oldResource.getComponentInstancesAttributes().get(foundInstance.get().getUniqueId()))){
-                               instAttributes.put(instance.getUniqueId(), oldResource.getComponentInstancesAttributes().get(foundInstance.get().getUniqueId()).stream().map(AttributeDefinition::new).collect(toList()));
-                       }
-               }
-       }
-
-       private Optional<ComponentInstance> findInstance(Resource oldResource, ComponentInstance instance) {
-               if(oldResource != null && CollectionUtils.isNotEmpty(oldResource.getComponentInstances())) {
-                       return oldResource.getComponentInstances().stream().filter(i -> i.getName().equals(instance.getName())).findFirst();
-               }
-               return Optional.empty();
-       }
-
-       private void associateResourceInstances(String yamlName, Resource resource,
-                                                                                       List<RequirementCapabilityRelDef> relations) {
-               Either<List<RequirementCapabilityRelDef>, StorageOperationStatus> relationsEither = toscaOperationFacade.associateResourceInstances(resource, resource.getUniqueId(), relations);
-
-               if (relationsEither.isRight() && relationsEither.right().value() != StorageOperationStatus.NOT_FOUND) {
-                       StorageOperationStatus status = relationsEither.right().value();
-                       log.debug("failed to associate instances of resource {} status is {}", resource.getUniqueId(),
-                                       status);
-                       throw new ByActionStatusComponentException(componentsUtils.convertFromStorageResponse(status), yamlName);
-               } else {
-                       setResourceInstanceRelationsOnComponent(resource, relationsEither.left().value());
-               }
-       }
-
-       private void associateInstAttributeToComponentToInstances(String yamlName, Resource resource,
-                                                                                                                         Map<String, List<AttributeDefinition>> instAttributes) {
-               StorageOperationStatus addArtToInst;
-               addArtToInst = toscaOperationFacade.associateInstAttributeToComponentToInstances(instAttributes,
-                       resource);
-               if (addArtToInst != StorageOperationStatus.OK && addArtToInst != StorageOperationStatus.NOT_FOUND) {
-                       log.debug("failed to associate attributes of resource {} status is {}", resource.getUniqueId(),
-                               addArtToInst);
-                       throw new ByActionStatusComponentException(componentsUtils.convertFromStorageResponse(addArtToInst),
-                               yamlName);
-               }
-       }
-
-       private void associateOrAddCalculatedCapReq(String yamlName, Resource resource,
-                                                                                               Map<ComponentInstance, Map<String, List<CapabilityDefinition>>> instCapabilities,
-                                                                                               Map<ComponentInstance, Map<String, List<RequirementDefinition>>> instRequirements) {
-               StorageOperationStatus addArtToInst;
-               addArtToInst = toscaOperationFacade.associateOrAddCalculatedCapReq(instCapabilities, instRequirements,
-                               resource);
-               if (addArtToInst != StorageOperationStatus.OK && addArtToInst != StorageOperationStatus.NOT_FOUND) {
-                       log.debug("failed to associate cap and req of resource {} status is {}", resource.getUniqueId(),
-                                       addArtToInst);
-                       throw new ByActionStatusComponentException(componentsUtils.convertFromStorageResponse(addArtToInst), yamlName);
-               }
-       }
-
-       private void associateArtifactsToInstances(String yamlName, Resource resource,
-                                                                                          Map<String, Map<String, ArtifactDefinition>> instArtifacts) {
-               StorageOperationStatus addArtToInst;
-
-               addArtToInst = toscaOperationFacade.associateArtifactsToInstances(instArtifacts, resource);
-               if (addArtToInst != StorageOperationStatus.OK && addArtToInst != StorageOperationStatus.NOT_FOUND) {
-                       log.debug("failed to associate artifact of resource {} status is {}", resource.getUniqueId(), addArtToInst);
-                       throw new ByActionStatusComponentException(componentsUtils.convertFromStorageResponse(addArtToInst), yamlName);
-               }
-       }
-
-       private void associateDeploymentArtifactsToInstances(User user, String yamlName, Resource resource,
-                                                                                                                Map<String, Map<String, ArtifactDefinition>> instDeploymentArtifacts) {
-               StorageOperationStatus addArtToInst = toscaOperationFacade
-                               .associateDeploymentArtifactsToInstances(instDeploymentArtifacts, resource, user);
-               if (addArtToInst != StorageOperationStatus.OK && addArtToInst != StorageOperationStatus.NOT_FOUND) {
-                       log.debug("failed to associate artifact of resource {} status is {}", resource.getUniqueId(), addArtToInst);
-                       throw new ByActionStatusComponentException(componentsUtils.convertFromStorageResponse(addArtToInst), yamlName);
-               }
-       }
-
-       private void associateComponentInstanceInputsToComponent(String yamlName, Resource resource,
-                                                                                                                        Map<String, List<ComponentInstanceInput>> instInputs) {
-               if (MapUtils.isNotEmpty(instInputs)) {
-                       Either<Map<String, List<ComponentInstanceInput>>, StorageOperationStatus> addInputToInst = toscaOperationFacade
-                                       .associateComponentInstanceInputsToComponent(instInputs, resource.getUniqueId());
-                       if (addInputToInst.isRight()) {
-
-                               StorageOperationStatus addInputToInstError = addInputToInst.right().value();
-                               log.debug("failed to associate inputs value of resource {} status is {}", resource.getUniqueId(),
-                                               addInputToInstError);
-                               throw new ByActionStatusComponentException(componentsUtils.convertFromStorageResponse(addInputToInstError), yamlName);
-                       }
-                       setComponentInstanceInputsOnComponent(resource, instInputs);
-               }
-       }
-
-       private void setComponentInstanceInputsOnComponent(Resource resource, Map<String, List<ComponentInstanceInput>> instInputs) {
-               Map<String, List<ComponentInstanceInput>> componentInstancesInputs = resource.getComponentInstancesInputs();
-               if (componentInstancesInputs == null)
-                       componentInstancesInputs = new HashMap<>();
-               componentInstancesInputs.putAll(instInputs);
-               resource.setComponentInstancesInputs(componentInstancesInputs);
-       }
-
-       private void associateComponentInstancePropertiesToComponent(String yamlName, Resource resource,
-                                                                                                                                Map<String, List<ComponentInstanceProperty>> instProperties) {
-               Either<Map<String, List<ComponentInstanceProperty>>, StorageOperationStatus> addPropToInst = toscaOperationFacade
-                               .associateComponentInstancePropertiesToComponent(instProperties, resource.getUniqueId());
-               if (addPropToInst.isRight()) {
-                       loggerSupportability.log(LoggerSupportabilityActions.CREATE_RELATIONS,resource.getComponentMetadataForSupportLog(),
-                                       StatusCode.ERROR,"ERROR while  associate compnent insatnce properties of resource: {} status is: {}",resource.getName(),addPropToInst.right().value());
-                       StorageOperationStatus storageOperationStatus = addPropToInst.right().value();
-                       log.debug("failed to associate properties of resource {} status is {}", resource.getUniqueId(),
-                                       storageOperationStatus);
-                       throw new ByActionStatusComponentException(componentsUtils.convertFromStorageResponse(storageOperationStatus), yamlName);
-               }
-               setComponentInstancePropertiesOnComponent(resource, instProperties);
-       }
-
-       private void setComponentInstancePropertiesOnComponent(Resource resource, Map<String, List<ComponentInstanceProperty>> instProperties) {
-               Map<String, List<ComponentInstanceProperty>> componentInstanceProps = resource.getComponentInstancesProperties();
-               if (componentInstanceProps == null )
-                       componentInstanceProps = new HashMap<>();
-               componentInstanceProps.putAll(instProperties);
-               resource.setComponentInstancesProperties(componentInstanceProps);
-       }
-
-       private void handleSubstitutionMappings(Resource resource,
-                                                                                       Map<String, UploadComponentInstanceInfo> uploadResInstancesMap) {
-               if (resource.getResourceType() == ResourceTypeEnum.CVFC) {
-                       Either<Resource, StorageOperationStatus> getResourceRes =
-                                       updateCalculatedCapReqWithSubstitutionMappings(resource, uploadResInstancesMap);
-                       if (getResourceRes.isRight()) {
-                               ResponseFormat responseFormat = componentsUtils
-                                               .getResponseFormatByResource(componentsUtils.convertFromStorageResponse(getResourceRes.right()
-                                                               .value()), resource);
-                               throw new ByResponseFormatComponentException(responseFormat);
-                       }
-               }
-       }
-
-       private void addRelationsToRI(String yamlName, Resource resource,
-                                                                 Map<String, UploadComponentInstanceInfo> uploadResInstancesMap,
-                                                                 List<ComponentInstance> componentInstancesList, List<RequirementCapabilityRelDef> relations) {
-               for (Entry<String, UploadComponentInstanceInfo> entry : uploadResInstancesMap.entrySet()) {
-                       UploadComponentInstanceInfo uploadComponentInstanceInfo = entry.getValue();
-                       ComponentInstance currentCompInstance = null;
-                       for (ComponentInstance compInstance : componentInstancesList) {
-
-                               if (compInstance.getName()
-                                               .equals(uploadComponentInstanceInfo.getName())) {
-                                       currentCompInstance = compInstance;
-                                       break;
-                               }
-
-                       }
-                       if (currentCompInstance == null) {
-                               log.debug(COMPONENT_INSTANCE_WITH_NAME_IN_RESOURCE, uploadComponentInstanceInfo.getName(),
-                                               resource.getUniqueId());
-                               BeEcompErrorManager.getInstance()
-                                               .logInternalDataError(
-                                                               COMPONENT_INSTANCE_WITH_NAME + uploadComponentInstanceInfo.getName() + IN_RESOURCE,
-                                                               resource.getUniqueId(), ErrorSeverity.ERROR);
-                               throw new ByActionStatusComponentException(ActionStatus.NOT_TOPOLOGY_TOSCA_TEMPLATE, yamlName);
-                       }
-
-                       ResponseFormat addRelationToRiRes = addRelationToRI(yamlName, resource, entry.getValue(), relations);
-                       if (addRelationToRiRes.getStatus() != 200) {
-                               throw new ByResponseFormatComponentException(addRelationToRiRes);
-                       }
-               }
-
-       }
-
-       private void setResourceInstanceRelationsOnComponent(Resource resource, List<RequirementCapabilityRelDef> relations) {
-               if (resource.getComponentInstancesRelations() != null) {
-                       resource.getComponentInstancesRelations().addAll(relations);
-               } else {
-                       resource.setComponentInstancesRelations(relations);
-               }
-       }
-
-       private void processComponentInstance(String yamlName, Resource resource,
-                                                                                 List<ComponentInstance> componentInstancesList,
-                                                                                 Either<Map<String, DataTypeDefinition>, JanusGraphOperationStatus> allDataTypes,
-                                                                                 Map<String, List<ComponentInstanceProperty>> instProperties,
-                                                                                 Map<ComponentInstance, Map<String, List<CapabilityDefinition>>> instCapabilties,
-                                                                                 Map<ComponentInstance, Map<String, List<RequirementDefinition>>> instRequirements,
-                                                                                 Map<String, Map<String, ArtifactDefinition>> instDeploymentArtifacts,
-                                                                                 Map<String, Map<String, ArtifactDefinition>> instArtifacts,
-                                                                                 Map<String, List<AttributeDefinition>> instAttributes,
-                                                                                 Map<String, Resource> originCompMap,
-                                                                                 Map<String, List<ComponentInstanceInput>> instInputs,
-                                                                                 UploadComponentInstanceInfo uploadComponentInstanceInfo) {
-               Optional<ComponentInstance> currentCompInstanceOpt = componentInstancesList.stream()
-                               .filter(i -> i.getName()
-                                               .equals(uploadComponentInstanceInfo.getName()))
-                               .findFirst();
-               if (!currentCompInstanceOpt.isPresent()) {
-                       log.debug(COMPONENT_INSTANCE_WITH_NAME_IN_RESOURCE, uploadComponentInstanceInfo.getName(),
-                                       resource.getUniqueId());
-                       BeEcompErrorManager.getInstance()
-                                       .logInternalDataError(
-                                                       COMPONENT_INSTANCE_WITH_NAME + uploadComponentInstanceInfo.getName() + IN_RESOURCE,
-                                                       resource.getUniqueId(), ErrorSeverity.ERROR);
-                       throw new ByActionStatusComponentException(ActionStatus.NOT_TOPOLOGY_TOSCA_TEMPLATE, yamlName);
-               }
-               ComponentInstance currentCompInstance = currentCompInstanceOpt.get();
-               String resourceInstanceId = currentCompInstance.getUniqueId();
-               Resource originResource = getOriginResource(originCompMap, currentCompInstance);
-               if (isNotEmpty(originResource.getRequirements())) {
-                       instRequirements.put(currentCompInstance, originResource.getRequirements());
-               }
-               if (isNotEmpty(originResource.getCapabilities())) {
-                       processComponentInstanceCapabilities(allDataTypes, instCapabilties, uploadComponentInstanceInfo,
-                               currentCompInstance, originResource);
-               }
-               if (originResource.getDeploymentArtifacts() != null && !originResource.getDeploymentArtifacts()
-                       .isEmpty()) {
-                       instDeploymentArtifacts.put(resourceInstanceId, originResource.getDeploymentArtifacts());
-               }
-               if (originResource.getArtifacts() != null && !originResource.getArtifacts().isEmpty()) {
-                       instArtifacts.put(resourceInstanceId, originResource.getArtifacts());
-               }
-               if (originResource.getAttributes() != null && !originResource.getAttributes().isEmpty()) {
-                       instAttributes.put(resourceInstanceId, originResource.getAttributes());
-               }
-               if (originResource.getResourceType() != ResourceTypeEnum.CVFC) {
-                       ResponseFormat addPropertiesValueToRiRes = addPropertyValuesToRi(uploadComponentInstanceInfo, resource,
-                               originResource, currentCompInstance, instProperties, allDataTypes.left()
-                                       .value());
-                       if (addPropertiesValueToRiRes.getStatus() != 200) {
-                               throw new ByResponseFormatComponentException(addPropertiesValueToRiRes);
-                       }
-               } else {
-                       addInputsValuesToRi(uploadComponentInstanceInfo, resource, originResource, currentCompInstance, instInputs,
-                                       allDataTypes.left()
-                                                       .value());
-               }
-       }
-
-       private Resource getOriginResource(Map<String, Resource> originCompMap, ComponentInstance currentCompInstance) {
-               Resource originResource;
-               if (!originCompMap.containsKey(currentCompInstance.getComponentUid())) {
-                       Either<Resource, StorageOperationStatus> getOriginResourceRes = toscaOperationFacade
-                                       .getToscaFullElement(currentCompInstance.getComponentUid());
-                       if (getOriginResourceRes.isRight()) {
-                               log.debug("failed to fetch resource with uniqueId {} and tosca component name {} status is {}",
-                                               currentCompInstance.getComponentUid(), currentCompInstance.getToscaComponentName(),
-                                               getOriginResourceRes);
-                               throw new ByActionStatusComponentException(componentsUtils.convertFromStorageResponse(getOriginResourceRes.right()
-                                               .value()), currentCompInstance.getComponentUid());
-                       }
-                       originResource = getOriginResourceRes.left()
-                                       .value();
-                       originCompMap.put(originResource.getUniqueId(), originResource);
-               } else {
-                       originResource = originCompMap.get(currentCompInstance.getComponentUid());
-               }
-               return originResource;
-       }
-
-       private void processComponentInstanceCapabilities(
-                       Either<Map<String, DataTypeDefinition>, JanusGraphOperationStatus> allDataTypes,
-                       Map<ComponentInstance, Map<String, List<CapabilityDefinition>>> instCapabilties,
-                       UploadComponentInstanceInfo uploadComponentInstanceInfo, ComponentInstance currentCompInstance,
-                       Resource originResource) {
-               Map<String, List<CapabilityDefinition>> originCapabilities;
-               if (isNotEmpty(uploadComponentInstanceInfo.getCapabilities())) {
-                       originCapabilities = new HashMap<>();
-                       Map<String, Map<String, UploadPropInfo>> newPropertiesMap = new HashMap<>();
-                       originResource.getCapabilities()
-                                       .forEach((k, v) -> addCapabilities(originCapabilities, k, v));
-                       uploadComponentInstanceInfo.getCapabilities()
-                                       .values()
-                                       .forEach(l -> addCapabilitiesProperties(newPropertiesMap, l));
-                       updateCapabilityPropertiesValues(allDataTypes, originCapabilities, newPropertiesMap);
-               } else {
-                       originCapabilities = originResource.getCapabilities();
-               }
-               instCapabilties.put(currentCompInstance, originCapabilities);
-       }
-
-       private void updateCapabilityPropertiesValues(
-                       Either<Map<String, DataTypeDefinition>, JanusGraphOperationStatus> allDataTypes,
-                       Map<String, List<CapabilityDefinition>> originCapabilities,
-                       Map<String, Map<String, UploadPropInfo>> newPropertiesMap) {
-               originCapabilities.values()
-                               .stream()
-                               .flatMap(Collection::stream)
-                               .filter(c -> newPropertiesMap.containsKey(c.getName()))
-                               .forEach(c -> updatePropertyValues(c.getProperties(), newPropertiesMap.get(c.getName()),
-                                               allDataTypes.left()
-                                                               .value()));
-       }
-
-       private void addCapabilitiesProperties(Map<String, Map<String, UploadPropInfo>> newPropertiesMap,
-                                                                                  List<UploadCapInfo> capabilities) {
-               for (UploadCapInfo capability : capabilities) {
-                       if (isNotEmpty(capability.getProperties())) {
-                               newPropertiesMap.put(capability.getName(), capability.getProperties()
-                                               .stream()
-                                               .collect(toMap(UploadInfo::getName, p -> p)));
-                       }
-               }
-       }
-
-       private void addCapabilities(Map<String, List<CapabilityDefinition>> originCapabilities, String type,
-                                                                List<CapabilityDefinition> capabilities) {
-               List<CapabilityDefinition> list = capabilities.stream()
-                               .map(CapabilityDefinition::new)
-                               .collect(toList());
-               originCapabilities.put(type, list);
-       }
-
-       private void updatePropertyValues(List<ComponentInstanceProperty> properties,
-                                                                         Map<String, UploadPropInfo> newProperties, Map<String, DataTypeDefinition> allDataTypes) {
-               properties.forEach(p -> updatePropertyValue(p, newProperties.get(p.getName()), allDataTypes));
-       }
-
-       private String updatePropertyValue(ComponentInstanceProperty property, UploadPropInfo propertyInfo,
-                                                                          Map<String, DataTypeDefinition> allDataTypes) {
-               String value = null;
-               List<GetInputValueDataDefinition> getInputs = null;
-               boolean isValidate = true;
-               if (null != propertyInfo && propertyInfo.getValue() != null) {
-                       getInputs = propertyInfo.getGet_input();
-                       isValidate = getInputs == null || getInputs.isEmpty();
-                       if (isValidate) {
-                               value = getPropertyJsonStringValue(propertyInfo.getValue(), property.getType());
-                       } else {
-                               value = getPropertyJsonStringValue(propertyInfo.getValue(),
-                                               TypeUtils.ToscaTagNamesEnum.GET_INPUT.getElementName());
-                       }
-               }
-               property.setValue(value);
-        return validatePropValueBeforeCreate(property, value, isValidate, allDataTypes);
-       }
-
-       private Either<Resource, StorageOperationStatus> updateCalculatedCapReqWithSubstitutionMappings(Resource resource,
-                                                                                                                                                                                                       Map<String, UploadComponentInstanceInfo> uploadResInstancesMap) {
-               Either<Resource, StorageOperationStatus> updateRes = null;
-               Map<ComponentInstance, Map<String, List<CapabilityDefinition>>> updatedInstCapabilities = new HashMap<>();
-               Map<ComponentInstance, Map<String, List<RequirementDefinition>>> updatedInstRequirements = new HashMap<>();
-               StorageOperationStatus status = toscaOperationFacade
-                               .deleteAllCalculatedCapabilitiesRequirements(resource.getUniqueId());
-               if (status != StorageOperationStatus.OK && status != StorageOperationStatus.NOT_FOUND) {
-                       log.debug(
-                                       "Failed to delete all calculated capabilities and requirements of resource {} upon update. Status is {}",
-                                       resource.getUniqueId(), status);
-                       updateRes = Either.right(status);
-               }
-               if (updateRes == null) {
-                       fillUpdatedInstCapabilitiesRequirements(resource.getComponentInstances(), uploadResInstancesMap,
-                                       updatedInstCapabilities, updatedInstRequirements);
-                       status = toscaOperationFacade.associateOrAddCalculatedCapReq(updatedInstCapabilities,
-                                       updatedInstRequirements, resource);
-                       if (status != StorageOperationStatus.OK && status != StorageOperationStatus.NOT_FOUND) {
-                               log.debug(
-                                               "Failed to associate capabilities and requirementss of resource {}, updated according to a substitution mapping. Status is {}",
-                                               resource.getUniqueId(), status);
-                               updateRes = Either.right(status);
-                       }
-               }
-               if (updateRes == null) {
-                       updateRes = Either.left(resource);
-               }
-               return updateRes;
-       }
-
-       private void fillUpdatedInstCapabilitiesRequirements(List<ComponentInstance> componentInstances,
-                                                                                                                Map<String, UploadComponentInstanceInfo> uploadResInstancesMap,
-                                                                                                                Map<ComponentInstance, Map<String, List<CapabilityDefinition>>> updatedInstCapabilities,
-                                                                                                                Map<ComponentInstance, Map<String, List<RequirementDefinition>>> updatedInstRequirements) {
-
-               componentInstances.stream()
-                               .forEach(i -> {
-                                       fillUpdatedInstCapabilities(updatedInstCapabilities, i, uploadResInstancesMap.get(i.getName())
-                                                       .getCapabilitiesNamesToUpdate());
-                                       fillUpdatedInstRequirements(updatedInstRequirements, i, uploadResInstancesMap.get(i.getName())
-                                                       .getRequirementsNamesToUpdate());
-                               });
-       }
-
-       private void fillUpdatedInstRequirements(
-                       Map<ComponentInstance, Map<String, List<RequirementDefinition>>> updatedInstRequirements,
-                       ComponentInstance instance, Map<String, String> requirementsNamesToUpdate) {
-               Map<String, List<RequirementDefinition>> updatedRequirements = new HashMap<>();
-               Set<String> updatedReqNames = new HashSet<>();
-               if (isNotEmpty(requirementsNamesToUpdate)) {
-                       for (Map.Entry<String, List<RequirementDefinition>> requirements : instance.getRequirements()
-                                       .entrySet()) {
-                               updatedRequirements.put(requirements.getKey(), requirements.getValue()
-                                               .stream()
-                                               .filter(r -> requirementsNamesToUpdate.containsKey(r.getName())
-                                                               && !updatedReqNames.contains(requirementsNamesToUpdate.get(r.getName())))
-                                               .map(r -> {
-                                                       r.setParentName(r.getName());
-                                                       r.setName(requirementsNamesToUpdate.get(r.getName()));
-                                                       updatedReqNames.add(r.getName());
-                                                       return r;
-                                               })
-                                               .collect(toList()));
-                       }
-               }
-               if (isNotEmpty(updatedRequirements)) {
-                       updatedInstRequirements.put(instance, updatedRequirements);
-               }
-       }
-
-       private void fillUpdatedInstCapabilities(
-                       Map<ComponentInstance, Map<String, List<CapabilityDefinition>>> updatedInstCapabilties,
-                       ComponentInstance instance, Map<String, String> capabilitiesNamesToUpdate) {
-               Map<String, List<CapabilityDefinition>> updatedCapabilities = new HashMap<>();
-               Set<String> updatedCapNames = new HashSet<>();
-               if (isNotEmpty(capabilitiesNamesToUpdate)) {
-                       for (Map.Entry<String, List<CapabilityDefinition>> requirements : instance.getCapabilities()
-                                       .entrySet()) {
-                               updatedCapabilities.put(requirements.getKey(), requirements.getValue()
-                                               .stream()
-                                               .filter(c -> capabilitiesNamesToUpdate.containsKey(c.getName())
-                                                               && !updatedCapNames.contains(capabilitiesNamesToUpdate.get(c.getName())))
-                                               .map(c -> {
-                                                       c.setParentName(c.getName());
-                                                       c.setName(capabilitiesNamesToUpdate.get(c.getName()));
-                                                       updatedCapNames.add(c.getName());
-                                                       return c;
-                                               })
-                                               .collect(toList()));
-                       }
-               }
-               if (isNotEmpty(updatedCapabilities)) {
-                       updatedInstCapabilties.put(instance, updatedCapabilities);
-               }
-       }
-
-       private ResponseFormat addRelationToRI(String yamlName, Resource resource,
-                                                                                  UploadComponentInstanceInfo nodesInfoValue, List<RequirementCapabilityRelDef> relations) {
-               List<ComponentInstance> componentInstancesList = resource.getComponentInstances();
-
-               ComponentInstance currentCompInstance = null;
-
-               for (ComponentInstance compInstance : componentInstancesList) {
-
-                       if (compInstance.getName()
-                                       .equals(nodesInfoValue.getName())) {
-                               currentCompInstance = compInstance;
-                               break;
-                       }
-
-               }
-
-               if (currentCompInstance == null) {
-                       log.debug(COMPONENT_INSTANCE_WITH_NAME_IN_RESOURCE, nodesInfoValue.getName(), resource.getUniqueId());
-                       BeEcompErrorManager.getInstance()
-                                       .logInternalDataError(COMPONENT_INSTANCE_WITH_NAME + nodesInfoValue.getName() + IN_RESOURCE,
-                                                       resource.getUniqueId(), ErrorSeverity.ERROR);
-                       return componentsUtils.getResponseFormat(ActionStatus.NOT_TOPOLOGY_TOSCA_TEMPLATE, yamlName);
-               }
-               String resourceInstanceId = currentCompInstance.getUniqueId();
-
-               Map<String, List<UploadReqInfo>> regMap = nodesInfoValue.getRequirements();
-
-               if (regMap != null) {
-                       Iterator<Entry<String, List<UploadReqInfo>>> nodesRegValue = regMap.entrySet()
-                                       .iterator();
-
-                       while (nodesRegValue.hasNext()) {
-                               Entry<String, List<UploadReqInfo>> nodesRegInfoEntry = nodesRegValue.next();
-
-                               List<UploadReqInfo> uploadRegInfoList = nodesRegInfoEntry.getValue();
-                               for (UploadReqInfo uploadRegInfo : uploadRegInfoList) {
-                                       log.debug("Going to create  relation {}", uploadRegInfo.getName());
-                                       loggerSupportability.log(LoggerSupportabilityActions.CREATE_RELATIONS,resource.getComponentMetadataForSupportLog(),     StatusCode.STARTED,"Started to create relations on instance: {}",uploadRegInfo.getName());
-                                       String regName = uploadRegInfo.getName();
-                                       RequirementCapabilityRelDef regCapRelDef = new RequirementCapabilityRelDef();
-                                       regCapRelDef.setFromNode(resourceInstanceId);
-                                       log.debug("try to find available requirement {} ", regName);
-                                       Either<RequirementDefinition, ResponseFormat> eitherReqStatus = findAviableRequiremen(regName,
-                                                       yamlName, nodesInfoValue, currentCompInstance, uploadRegInfo.getCapabilityName());
-                                       if (eitherReqStatus.isRight()) {
-                                               log.debug("failed to find available requirement {} status is {}", regName,
-                                                               eitherReqStatus.right()
-                                                                               .value());
-                                               loggerSupportability.log(LoggerSupportabilityActions.CREATE_RELATIONS,resource.getComponentMetadataForSupportLog(),     StatusCode.ERROR,"ERROR while search available requirement {} status is: {}",regName,eitherReqStatus.right().value());
-                                               return eitherReqStatus.right()
-                                                               .value();
-                                       }
-
-                                       RequirementDefinition validReq = eitherReqStatus.left()
-                                                       .value();
-                                       List<CapabilityRequirementRelationship> reqAndRelationshipPairList = regCapRelDef
-                                                       .getRelationships();
-                                       if (reqAndRelationshipPairList == null) {
-                                               reqAndRelationshipPairList = new ArrayList<>();
-                                       }
-                                       RelationshipInfo reqAndRelationshipPair = new RelationshipInfo();
-                                       reqAndRelationshipPair.setRequirement(regName);
-                                       reqAndRelationshipPair.setRequirementOwnerId(validReq.getOwnerId());
-                                       reqAndRelationshipPair.setRequirementUid(validReq.getUniqueId());
-                                       RelationshipImpl relationship = new RelationshipImpl();
-                                       relationship.setType(validReq.getCapability());
-                                       reqAndRelationshipPair.setRelationships(relationship);
-
-                                       ComponentInstance currentCapCompInstance = null;
-                                       for (ComponentInstance compInstance : componentInstancesList) {
-                                               if (compInstance.getName()
-                                                               .equals(uploadRegInfo.getNode())) {
-                                                       currentCapCompInstance = compInstance;
-                                                       break;
-                                               }
-                                       }
-
-                                       if (currentCapCompInstance == null) {
-                                               log.debug("The component instance  with name {} not found on resource {} ",
-                                                               uploadRegInfo.getNode(), resource.getUniqueId());
-                                               loggerSupportability.log(LoggerSupportabilityActions.CREATE_RELATIONS,resource.getComponentMetadataForSupportLog(), StatusCode.ERROR,"ERROR component instance  with name: {} not found on resource: {}",uploadRegInfo.getNode(),resource.getUniqueId());
-                                               BeEcompErrorManager.getInstance()
-                                                               .logInternalDataError(
-                                                                               COMPONENT_INSTANCE_WITH_NAME + uploadRegInfo.getNode() + IN_RESOURCE,
-                                                                               resource.getUniqueId(), ErrorSeverity.ERROR);
-                                               return componentsUtils.getResponseFormat(ActionStatus.NOT_TOPOLOGY_TOSCA_TEMPLATE, yamlName);
-                                       }
-                                       regCapRelDef.setToNode(currentCapCompInstance.getUniqueId());
-                                       log.debug("try to find aviable Capability  req name is {} ", validReq.getName());
-                                       CapabilityDefinition aviableCapForRel = findAvailableCapabilityByTypeOrName(validReq,
-                                                       currentCapCompInstance, uploadRegInfo);
-
-                                       if (aviableCapForRel == null) {
-                                               log.debug("aviable capability was not found. req name is {} component instance is {}",
-                                                               validReq.getName(), currentCapCompInstance.getUniqueId());
-                                               loggerSupportability.log(LoggerSupportabilityActions.CREATE_RELATIONS,resource.getComponentMetadataForSupportLog(),     StatusCode.ERROR,"ERROR available capability was not found. req name is: {} component instance is: {}",validReq.getName(),currentCapCompInstance.getUniqueId());
-                                               BeEcompErrorManager.getInstance()
-                                                               .logInternalDataError(
-                                                                               "aviable capability was not found. req name is " + validReq.getName()
-                                                                                               + " component instance is " + currentCapCompInstance.getUniqueId(),
-                                                                               resource.getUniqueId(), ErrorSeverity.ERROR);
-                                               return componentsUtils.getResponseFormat(ActionStatus.NOT_TOPOLOGY_TOSCA_TEMPLATE, yamlName);
-                                       }
-                                       reqAndRelationshipPair.setCapability(aviableCapForRel.getName());
-                                       reqAndRelationshipPair.setCapabilityUid(aviableCapForRel.getUniqueId());
-                                       reqAndRelationshipPair.setCapabilityOwnerId(aviableCapForRel.getOwnerId());
-
-                                       CapabilityRequirementRelationship capReqRel = new CapabilityRequirementRelationship();
-                                       capReqRel.setRelation(reqAndRelationshipPair);
-                                       reqAndRelationshipPairList.add(capReqRel);
-                                       regCapRelDef.setRelationships(reqAndRelationshipPairList);
-                                       relations.add(regCapRelDef);
-                               }
-                       }
-               } else if (resource.getResourceType() != ResourceTypeEnum.CVFC) {
-                       return componentsUtils.getResponseFormat(ActionStatus.OK, yamlName);
-               }
-               return componentsUtils.getResponseFormat(ActionStatus.OK);
-       }
-
-       private void addInputsValuesToRi(UploadComponentInstanceInfo uploadComponentInstanceInfo, Resource resource,
-                                                                        Resource originResource, ComponentInstance currentCompInstance,
-                                                                        Map<String, List<ComponentInstanceInput>> instInputs, Map<String, DataTypeDefinition> allDataTypes) {
-               Map<String, List<UploadPropInfo>> propMap = uploadComponentInstanceInfo.getProperties();
-               if (MapUtils.isNotEmpty(propMap)) {
-                       Map<String, InputDefinition> currPropertiesMap = new HashMap<>();
-                       List<ComponentInstanceInput> instPropList = new ArrayList<>();
-
-                       if (CollectionUtils.isEmpty(originResource.getInputs())) {
-                               log.debug("failed to find properties ");
-                               loggerSupportability.log(LoggerSupportabilityActions.CREATE_INPUTS,resource.getComponentMetadataForSupportLog(),StatusCode.ERROR,"ERROR while try to find properties");
-                               throw new ByActionStatusComponentException(ActionStatus.PROPERTY_NOT_FOUND);
-                       }
-                       originResource.getInputs()
-                                       .forEach(p -> addInput(currPropertiesMap, p));
-                       for (List<UploadPropInfo> propertyList : propMap.values()) {
-                               processProperty(resource, currentCompInstance, allDataTypes, currPropertiesMap, instPropList,
-                                               propertyList);
-                       }
-                       currPropertiesMap.values()
-                                       .forEach(p -> instPropList.add(new ComponentInstanceInput(p)));
-                       instInputs.put(currentCompInstance.getUniqueId(), instPropList);
-               }
-       }
-
-       private void processProperty(Resource resource, ComponentInstance currentCompInstance,
-                                                                Map<String, DataTypeDefinition> allDataTypes, Map<String, InputDefinition> currPropertiesMap,
-                                                                List<ComponentInstanceInput> instPropList, List<UploadPropInfo> propertyList) {
-               UploadPropInfo propertyInfo = propertyList.get(0);
-               String propName = propertyInfo.getName();
-               if (!currPropertiesMap.containsKey(propName)) {
-                       loggerSupportability.log(LoggerSupportabilityActions.PROPERTY,resource.getComponentMetadataForSupportLog(),
-                                       StatusCode.ERROR,"ERROR failed to find property: {}",propName);
-                       log.debug("failed to find property {} ", propName);
-                       throw new ByActionStatusComponentException(ActionStatus.PROPERTY_NOT_FOUND, propName);
-               }
-               InputDefinition curPropertyDef = currPropertiesMap.get(propName);
-               ComponentInstanceInput property = null;
-
-               String value = null;
-               List<GetInputValueDataDefinition> getInputs = null;
-               boolean isValidate = true;
-               if (propertyInfo.getValue() != null) {
-                       getInputs = propertyInfo.getGet_input();
-                       isValidate = getInputs == null || getInputs.isEmpty();
-                       if (isValidate) {
-                               value = getPropertyJsonStringValue(propertyInfo.getValue(), curPropertyDef.getType());
-                       } else {
-                               value = getPropertyJsonStringValue(propertyInfo.getValue(),
-                                               TypeUtils.ToscaTagNamesEnum.GET_INPUT.getElementName());
-                       }
-               }
-               property = new ComponentInstanceInput(curPropertyDef, value, null);
+    private Resource getResourceWithGroups(String resourceId) {
+        ComponentParametersView filter = new ComponentParametersView();
+        filter.setIgnoreGroups(false);
+        Either<Resource, StorageOperationStatus> updatedResource = toscaOperationFacade.getToscaElement(resourceId, filter);
+        if (updatedResource.isRight()) {
+            rollbackWithException(componentsUtils.convertFromStorageResponse(updatedResource.right().value()), resourceId);
+        }
+        return updatedResource.left().value();
+    }
 
-        String validPropertyVAlue = validatePropValueBeforeCreate(property, value, isValidate, allDataTypes);
+    private Either<Resource, ResponseFormat> createGroupsOnResource(Resource resource, Map<String, GroupDefinition> groups) {
+        if (groups != null && !groups.isEmpty()) {
+            List<GroupDefinition> groupsAsList = updateGroupsMembersUsingResource(groups, resource);
+            handleGroupsProperties(resource, groups);
+            fillGroupsFinalFields(groupsAsList);
+            Either<List<GroupDefinition>, ResponseFormat> createGroups = groupBusinessLogic.createGroups(resource, groupsAsList, true);
+            if (createGroups.isRight()) {
+                return Either.right(createGroups.right().value());
+            }
+        }
+        return Either.left(resource);
+    }
+
+    private void handleGroupsProperties(Resource resource, Map<String, GroupDefinition> groups) {
+        List<InputDefinition> inputs = resource.getInputs();
+        if (MapUtils.isNotEmpty(groups)) {
+            groups.values().stream().filter(g -> isNotEmpty(g.getProperties())).flatMap(g -> g.getProperties().stream())
+                .forEach(p -> handleGetInputs(p, inputs));
+        }
+    }
+
+    private Resource createPoliciesOnResource(Resource resource, Map<String, PolicyDefinition> policies) {
+        policyBusinessLogic.createPoliciesFromParsedCsar(resource, policies);
+        return resource;
+    }
+
+    private void handleGetInputs(PropertyDataDefinition property, List<InputDefinition> inputs) {
+        if (isNotEmpty(property.getGetInputValues())) {
+            if (inputs == null || inputs.isEmpty()) {
+                log.debug("Failed to add property {} to group. Inputs list is empty ", property);
+                rollbackWithException(ActionStatus.INPUTS_NOT_FOUND,
+                    property.getGetInputValues().stream().map(GetInputValueDataDefinition::getInputName).collect(toList()).toString());
+            }
+            ListIterator<GetInputValueDataDefinition> getInputValuesIter = property.getGetInputValues().listIterator();
+            while (getInputValuesIter.hasNext()) {
+                GetInputValueDataDefinition getInput = getInputValuesIter.next();
+                Either<InputDefinition, RuntimeException> inputEither = findInputByName(inputs, getInput);
+                if (inputEither.isRight()) {
+                    throw inputEither.right().value();
+                } else {
+                    InputDefinition input = inputEither.left().value();
+                    getInput.setInputId(input.getUniqueId());
+                    if (getInput.getGetInputIndex() != null) {
+                        GetInputValueDataDefinition getInputIndex = getInput.getGetInputIndex();
+                        Either<InputDefinition, RuntimeException> newInputEither = findInputByName(inputs, getInputIndex);
+                        if (newInputEither.isRight()) {
+                            throw newInputEither.right().value();
+                        } else {
+                            InputDefinition newInput = newInputEither.left().value();
+                            getInputIndex.setInputId(newInput.getUniqueId());
+                        }
+                        getInputValuesIter.add(getInputIndex);
+                    }
+                }
+            }
+        }
+    }
+
+    <T> Either<T, RuntimeException> rollbackWithEither(final ActionStatus actionStatus, final String... params) {
+        return rollbackWithEither(janusGraphDao, actionStatus, params);
+    }
+
+    private Either<InputDefinition, RuntimeException> findInputByName(List<InputDefinition> inputs, GetInputValueDataDefinition getInput) {
+        final String inputName = getInput != null ? getInput.getInputName() : "";
+        if (inputs == null || inputs.isEmpty()) {
+            log.debug("#findInputByName - Inputs list is empty");
+            return rollbackWithEither(ActionStatus.INPUTS_NOT_FOUND, inputName);
+        } else {
+            Optional<InputDefinition> inputOpt = inputs.stream().filter(p -> p.getName().equals(inputName)).findFirst();
+            if (!inputOpt.isPresent()) {
+                log.debug("#findInputByName - Failed to find the input {} ", inputName);
+                return rollbackWithEither(ActionStatus.INPUTS_NOT_FOUND, inputName);
+            } else {
+                return Either.left(inputOpt.get());
+            }
+        }
+    }
+
+    private void fillGroupsFinalFields(List<GroupDefinition> groupsAsList) {
+        groupsAsList.forEach(groupDefinition -> {
+            groupDefinition.setInvariantName(groupDefinition.getName());
+            groupDefinition.setCreatedFrom(CreatedFrom.CSAR);
+        });
+    }
+
+    private Resource updateGroupsOnResource(Resource resource, Map<String, GroupDefinition> groups) {
+        if (isEmpty(groups)) {
+            return resource;
+        }
+        return updateOrCreateGroups(resource, groups);
+    }
+
+    private Resource updateOrCreateGroups(Resource resource, Map<String, GroupDefinition> groups) {
+        List<GroupDefinition> groupsFromResource = resource.getGroups();
+        List<GroupDefinition> groupsAsList = updateGroupsMembersUsingResource(groups, resource);
+        List<GroupDefinition> groupsToUpdate = new ArrayList<>();
+        List<GroupDefinition> groupsToDelete = new ArrayList<>();
+        List<GroupDefinition> groupsToCreate = new ArrayList<>();
+        if (isNotEmpty(groupsFromResource)) {
+            addGroupsToCreateOrUpdate(groupsFromResource, groupsAsList, groupsToUpdate, groupsToCreate);
+            addGroupsToDelete(groupsFromResource, groupsAsList, groupsToDelete);
+        } else {
+            groupsToCreate.addAll(groupsAsList);
+        }
+        if (isNotEmpty(groupsToCreate)) {
+            fillGroupsFinalFields(groupsToCreate);
+            if (isNotEmpty(groupsFromResource)) {
+                groupBusinessLogic.addGroups(resource, groupsToCreate, true).left().on(this::throwComponentException);
+            } else {
+                groupBusinessLogic.createGroups(resource, groupsToCreate, true).left().on(this::throwComponentException);
+            }
+        }
+        if (isNotEmpty(groupsToDelete)) {
+            groupBusinessLogic.deleteGroups(resource, groupsToDelete).left().on(this::throwComponentException);
+        }
+        if (isNotEmpty(groupsToUpdate)) {
+            groupBusinessLogic.updateGroups(resource, groupsToUpdate, true).left().on(this::throwComponentException);
+        }
+        return resource;
+    }
+
+    private void addGroupsToDelete(List<GroupDefinition> groupsFromResource, List<GroupDefinition> groupsAsList,
+                                   List<GroupDefinition> groupsToDelete) {
+        for (GroupDefinition group : groupsFromResource) {
+            Optional<GroupDefinition> op = groupsAsList.stream().filter(p -> p.getInvariantName().equalsIgnoreCase(group.getInvariantName()))
+                .findAny();
+            if (!op.isPresent() && (group.getArtifacts() == null || group.getArtifacts().isEmpty())) {
+                groupsToDelete.add(group);
+            }
+        }
+    }
+
+    private void addGroupsToCreateOrUpdate(List<GroupDefinition> groupsFromResource, List<GroupDefinition> groupsAsList,
+                                           List<GroupDefinition> groupsToUpdate, List<GroupDefinition> groupsToCreate) {
+        for (GroupDefinition group : groupsAsList) {
+            Optional<GroupDefinition> op = groupsFromResource.stream().filter(p -> p.getInvariantName().equalsIgnoreCase(group.getInvariantName()))
+                .findAny();
+            if (op.isPresent()) {
+                GroupDefinition groupToUpdate = op.get();
+                groupToUpdate.setMembers(group.getMembers());
+                groupToUpdate.setCapabilities(group.getCapabilities());
+                groupToUpdate.setProperties(group.getProperties());
+                groupsToUpdate.add(groupToUpdate);
+            } else {
+                groupsToCreate.add(group);
+            }
+        }
+    }
+
+    private Resource createInputsOnResource(Resource resource, Map<String, InputDefinition> inputs) {
+        List<InputDefinition> resourceProperties = resource.getInputs();
+        if (MapUtils.isNotEmpty(inputs) || isNotEmpty(resourceProperties)) {
+            Either<List<InputDefinition>, ResponseFormat> createInputs = inputsBusinessLogic.createInputsInGraph(inputs, resource);
+            if (createInputs.isRight()) {
+                loggerSupportability.log(LoggerSupportabilityActions.CREATE_INPUTS, resource.getComponentMetadataForSupportLog(), StatusCode.ERROR,
+                    "failed to add inputs from yaml: {}", createInputs.right().value());
+                throw new ByResponseFormatComponentException(createInputs.right().value());
+            }
+            resource.setInputs(createInputs.left().value());
+        }
+        return resource;
+    }
+
+    private List<GroupDefinition> updateGroupsMembersUsingResource(Map<String, GroupDefinition> groups, Resource component) {
+        List<GroupDefinition> result = new ArrayList<>();
+        List<ComponentInstance> componentInstances = component.getComponentInstances();
+        if (groups != null) {
+            Either<Boolean, ResponseFormat> validateCyclicGroupsDependencies = validateCyclicGroupsDependencies(groups);
+            if (validateCyclicGroupsDependencies.isRight()) {
+                throw new ByResponseFormatComponentException(validateCyclicGroupsDependencies.right().value());
+            }
+            for (Entry<String, GroupDefinition> entry : groups.entrySet()) {
+                String groupName = entry.getKey();
+                GroupDefinition groupDefinition = entry.getValue();
+                GroupDefinition updatedGroupDefinition = new GroupDefinition(groupDefinition);
+                updatedGroupDefinition.setMembers(null);
+                Map<String, String> members = groupDefinition.getMembers();
+                if (members != null) {
+                    updateGroupMembers(groups, updatedGroupDefinition, component, componentInstances, groupName, members);
+                }
+                result.add(updatedGroupDefinition);
+            }
+        }
+        return result;
+    }
+
+    private void updateGroupMembers(Map<String, GroupDefinition> groups, GroupDefinition updatedGroupDefinition, Resource component,
+                                    List<ComponentInstance> componentInstances, String groupName, Map<String, String> members) {
+        Set<String> compInstancesNames = members.keySet();
+        if (CollectionUtils.isEmpty(componentInstances)) {
+            String membersAstString = compInstancesNames.stream().collect(joining(","));
+            log.debug("The members: {}, in group: {}, cannot be found in component {}. There are no component instances.", membersAstString,
+                groupName, component.getNormalizedName());
+            throw new ByActionStatusComponentException(ActionStatus.GROUP_INVALID_COMPONENT_INSTANCE, membersAstString, groupName,
+                component.getNormalizedName(), getComponentTypeForResponse(component));
+        }
+        // Find all component instances with the member names
+        Map<String, String> memberNames = componentInstances.stream().collect(toMap(ComponentInstance::getName, ComponentInstance::getUniqueId));
+        memberNames.putAll(groups.keySet().stream().collect(toMap(g -> g, g -> "")));
+        Map<String, String> relevantInstances = memberNames.entrySet().stream().filter(n -> compInstancesNames.contains(n.getKey()))
+            .collect(toMap(Entry::getKey, Entry::getValue));
+        if (relevantInstances == null || relevantInstances.size() != compInstancesNames.size()) {
+            List<String> foundMembers = new ArrayList<>();
+            if (relevantInstances != null) {
+                foundMembers = relevantInstances.keySet().stream().collect(toList());
+            }
+            compInstancesNames.removeAll(foundMembers);
+            String membersAstString = compInstancesNames.stream().collect(joining(","));
+            log.debug("The members: {}, in group: {}, cannot be found in component: {}", membersAstString, groupName, component.getNormalizedName());
+            throw new ByActionStatusComponentException(ActionStatus.GROUP_INVALID_COMPONENT_INSTANCE, membersAstString, groupName,
+                component.getNormalizedName(), getComponentTypeForResponse(component));
+        }
+        updatedGroupDefinition.setMembers(relevantInstances);
+    }
+
+    /**
+     * This Method validates that there is no cyclic group dependencies. meaning group A as member in group B which is member in group A
+     *
+     * @param allGroups
+     * @return
+     */
+    private Either<Boolean, ResponseFormat> validateCyclicGroupsDependencies(Map<String, GroupDefinition> allGroups) {
+        Either<Boolean, ResponseFormat> result = Either.left(true);
+        try {
+            Iterator<Entry<String, GroupDefinition>> allGroupsItr = allGroups.entrySet().iterator();
+            while (allGroupsItr.hasNext() && result.isLeft()) {
+                Entry<String, GroupDefinition> groupAEntry = allGroupsItr.next();
+                // Fetches a group member A
+                String groupAName = groupAEntry.getKey();
+                // Finds all group members in group A
+                Set<String> allGroupAMembersNames = new HashSet<>();
+                fillAllGroupMemebersRecursivly(groupAEntry.getKey(), allGroups, allGroupAMembersNames);
+                // If A is a group member of itself found cyclic dependency
+                if (allGroupAMembersNames.contains(groupAName)) {
+                    ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.GROUP_HAS_CYCLIC_DEPENDENCY, groupAName);
+                    result = Either.right(responseFormat);
+                }
+            }
+        } catch (Exception e) {
+            ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR);
+            result = Either.right(responseFormat);
+            log.debug("Exception occurred when validateCyclicGroupsDependencies, error is:{}", e.getMessage(), e);
+        }
+        return result;
+    }
+
+    /**
+     * This Method fills recursively the set groupMembers with all the members of the given group which are also of type group.
+     *
+     * @param groupName
+     * @param allGroups
+     * @param allGroupMembers
+     * @return
+     */
+    private void fillAllGroupMemebersRecursivly(String groupName, Map<String, GroupDefinition> allGroups, Set<String> allGroupMembers) {
+        // Found Cyclic dependency
+        if (isfillGroupMemebersRecursivlyStopCondition(groupName, allGroups, allGroupMembers)) {
+            return;
+        }
+        GroupDefinition groupDefinition = allGroups.get(groupName);
+        // All Members Of Current Group Resource Instances & Other Groups
+        Set<String> currGroupMembers = groupDefinition.getMembers().keySet();
+        // Filtered Members Of Current Group containing only members which
+
+        // are groups
+        List<String> currGroupFilteredMembers = currGroupMembers.stream().
+            // Keep Only Elements of type group and not Resource Instances
+                filter(allGroups::containsKey).
+            // Add Filtered Elements to main Set
+                peek(allGroupMembers::add).
+            // Collect results
+                collect(toList());
+        // Recursively call the method for all the filtered group members
+        for (String innerGroupName : currGroupFilteredMembers) {
+            fillAllGroupMemebersRecursivly(innerGroupName, allGroups, allGroupMembers);
+        }
+    }
+
+    private boolean isfillGroupMemebersRecursivlyStopCondition(String groupName, Map<String, GroupDefinition> allGroups,
+                                                               Set<String> allGroupMembers) {
+        boolean stop = false;
+        // In Case Not Group Stop
+        if (!allGroups.containsKey(groupName)) {
+            stop = true;
+        }
+        // In Case Group Has no members stop
+        if (!stop) {
+            GroupDefinition groupDefinition = allGroups.get(groupName);
+            stop = isEmpty(groupDefinition.getMembers());
+        }
+        // In Case all group members already contained stop
+        if (!stop) {
+            final Set<String> allMembers = allGroups.get(groupName).getMembers().keySet();
+            Set<String> membersOfTypeGroup = allMembers.stream().
+                // Filter In Only Group members
+                    filter(allGroups::containsKey).
+                // Collect
+                    collect(toSet());
+            stop = allGroupMembers.containsAll(membersOfTypeGroup);
+        }
+        return stop;
+    }
+
+    private Resource createRIAndRelationsFromYaml(String yamlName, Resource resource,
+                                                  Map<String, UploadComponentInstanceInfo> uploadComponentInstanceInfoMap,
+                                                  String topologyTemplateYaml, List<ArtifactDefinition> nodeTypesNewCreatedArtifacts,
+                                                  Map<String, NodeTypeInfo> nodeTypesInfo, CsarInfo csarInfo,
+                                                  Map<String, EnumMap<ArtifactOperationEnum, List<ArtifactDefinition>>> nodeTypesArtifactsToCreate,
+                                                  String nodeName) {
+        log.debug("************* Going to create all nodes {}", yamlName);
+        handleNodeTypes(yamlName, resource, topologyTemplateYaml, false, nodeTypesArtifactsToCreate, nodeTypesNewCreatedArtifacts, nodeTypesInfo,
+            csarInfo, nodeName);
+        log.debug("************* Finished to create all nodes {}", yamlName);
+        log.debug("************* Going to create all resource instances {}", yamlName);
+        Map<String, Resource> existingNodeTypesByResourceNames = new HashMap<>();
+        resource = createResourceInstances(yamlName, resource, null, uploadComponentInstanceInfoMap, csarInfo.getCreatedNodes(),
+            existingNodeTypesByResourceNames);
+        log.debug("************* Finished to create all resource instances {}", yamlName);
+        log.debug("************* Going to create all relations {}", yamlName);
+        resource = createResourceInstancesRelations(csarInfo.getModifier(), yamlName, resource, null, uploadComponentInstanceInfoMap,
+            existingNodeTypesByResourceNames);
+        log.debug("************* Finished to create all relations {}", yamlName);
+        log.debug("************* Going to create positions {}", yamlName);
+        compositionBusinessLogic.setPositionsForComponentInstances(resource, csarInfo.getModifier().getUserId());
+        log.debug("************* Finished to set positions {}", yamlName);
+        return resource;
+    }
+
+    private void handleAndAddExtractedVfcsArtifacts(List<ArtifactDefinition> vfcArtifacts, List<ArtifactDefinition> artifactsToAdd) {
+        List<String> vfcArtifactNames = vfcArtifacts.stream().map(ArtifactDataDefinition::getArtifactName).collect(toList());
+        artifactsToAdd.stream().forEach(a -> {
+            if (!vfcArtifactNames.contains(a.getArtifactName())) {
+                vfcArtifacts.add(a);
+            } else {
+                log.debug("Can't upload two artifact with the same name {}. ", a.getArtifactName());
+            }
+        });
+    }
+
+    @SuppressWarnings("unchecked")
+    private void handleNodeTypes(String yamlName, Resource resource, String topologyTemplateYaml, boolean needLock,
+                                 Map<String, EnumMap<ArtifactOperationEnum, List<ArtifactDefinition>>> nodeTypesArtifactsToHandle,
+                                 List<ArtifactDefinition> nodeTypesNewCreatedArtifacts, Map<String, NodeTypeInfo> nodeTypesInfo, CsarInfo csarInfo,
+                                 String nodeName) {
+        try {
+            for (Entry<String, NodeTypeInfo> nodeTypeEntry : nodeTypesInfo.entrySet()) {
+                if (nodeTypeEntry.getValue().isNested()) {
+                    handleNestedVfc(resource, nodeTypesArtifactsToHandle, nodeTypesNewCreatedArtifacts, nodeTypesInfo, csarInfo,
+                        nodeTypeEntry.getKey());
+                    log.trace("************* finished to create node {}", nodeTypeEntry.getKey());
+                }
+            }
+            Map<String, Object> mappedToscaTemplate = null;
+            if (StringUtils.isNotEmpty(nodeName) && isNotEmpty(nodeTypesInfo) && nodeTypesInfo.containsKey(nodeName)) {
+                mappedToscaTemplate = nodeTypesInfo.get(nodeName).getMappedToscaTemplate();
+            }
+            if (isEmpty(mappedToscaTemplate)) {
+                mappedToscaTemplate = (Map<String, Object>) new Yaml().load(topologyTemplateYaml);
+            }
+            createResourcesFromYamlNodeTypesList(yamlName, resource, mappedToscaTemplate, needLock, nodeTypesArtifactsToHandle,
+                nodeTypesNewCreatedArtifacts, nodeTypesInfo, csarInfo);
+        } catch (ComponentException e) {
+            ResponseFormat responseFormat =
+                e.getResponseFormat() != null ? e.getResponseFormat() : componentsUtils.getResponseFormat(e.getActionStatus(), e.getParams());
+            componentsUtils.auditResource(responseFormat, csarInfo.getModifier(), resource, AuditingActionEnum.IMPORT_RESOURCE);
+            throw e;
+        } catch (StorageException e) {
+            ResponseFormat responseFormat = componentsUtils
+                .getResponseFormat(componentsUtils.convertFromStorageResponse(e.getStorageOperationStatus()));
+            componentsUtils.auditResource(responseFormat, csarInfo.getModifier(), resource, AuditingActionEnum.IMPORT_RESOURCE);
+            throw e;
+        }
+    }
+
+    private Either<Resource, ResponseFormat> handleVfCsarArtifacts(Resource resource, CsarInfo csarInfo, List<ArtifactDefinition> createdArtifacts,
+                                                                   ArtifactOperationInfo artifactOperation, boolean shouldLock,
+                                                                   boolean inTransaction) {
+        if (csarInfo.getCsar() != null) {
+            String vendorLicenseModelId = null;
+            String vfLicenseModelId = null;
+            if (artifactOperation.isUpdate()) {
+                Map<String, ArtifactDefinition> deploymentArtifactsMap = resource.getDeploymentArtifacts();
+                if (deploymentArtifactsMap != null && !deploymentArtifactsMap.isEmpty()) {
+                    for (Entry<String, ArtifactDefinition> artifactEntry : deploymentArtifactsMap.entrySet()) {
+                        if (artifactEntry.getValue().getArtifactName().equalsIgnoreCase(Constants.VENDOR_LICENSE_MODEL)) {
+                            vendorLicenseModelId = artifactEntry.getValue().getUniqueId();
+                        }
+                        if (artifactEntry.getValue().getArtifactName().equalsIgnoreCase(Constants.VF_LICENSE_MODEL)) {
+                            vfLicenseModelId = artifactEntry.getValue().getUniqueId();
+                        }
+                    }
+                }
+            }
+            // Specific Behavior for license artifacts
+            createOrUpdateSingleNonMetaArtifact(resource, csarInfo, CsarUtils.ARTIFACTS_PATH + Constants.VENDOR_LICENSE_MODEL,
+                Constants.VENDOR_LICENSE_MODEL, ArtifactTypeEnum.VENDOR_LICENSE.getType(), ArtifactGroupTypeEnum.DEPLOYMENT,
+                Constants.VENDOR_LICENSE_LABEL, Constants.VENDOR_LICENSE_DISPLAY_NAME, Constants.VENDOR_LICENSE_DESCRIPTION, vendorLicenseModelId,
+                artifactOperation, null, true, shouldLock, inTransaction);
+            createOrUpdateSingleNonMetaArtifact(resource, csarInfo, CsarUtils.ARTIFACTS_PATH + Constants.VF_LICENSE_MODEL, Constants.VF_LICENSE_MODEL,
+                ArtifactTypeEnum.VF_LICENSE.getType(), ArtifactGroupTypeEnum.DEPLOYMENT, Constants.VF_LICENSE_LABEL,
+                Constants.VF_LICENSE_DISPLAY_NAME, Constants.VF_LICENSE_DESCRIPTION, vfLicenseModelId, artifactOperation, null, true, shouldLock,
+                inTransaction);
+            Either<Resource, ResponseFormat> eitherCreateResult = createOrUpdateNonMetaArtifacts(csarInfo, resource, createdArtifacts, shouldLock,
+                inTransaction, artifactOperation);
+            if (eitherCreateResult.isRight()) {
+                return Either.right(eitherCreateResult.right().value());
+            }
+            Either<ImmutablePair<String, String>, ResponseFormat> artifacsMetaCsarStatus = CsarValidationUtils
+                .getArtifactsMeta(csarInfo.getCsar(), csarInfo.getCsarUUID(), componentsUtils);
+            if (artifacsMetaCsarStatus.isLeft()) {
+                String artifactsFileName = artifacsMetaCsarStatus.left().value().getKey();
+                String artifactsContents = artifacsMetaCsarStatus.left().value().getValue();
+                Either<Resource, ResponseFormat> createArtifactsFromCsar;
+                if (artifactOperation.isCreateOrLink()) {
+                    createArtifactsFromCsar = csarArtifactsAndGroupsBusinessLogic
+                        .createResourceArtifactsFromCsar(csarInfo, resource, artifactsContents, artifactsFileName, createdArtifacts);
+                } else {
+                    Either<Component, ResponseFormat> result = csarArtifactsAndGroupsBusinessLogic
+                        .updateResourceArtifactsFromCsar(csarInfo, resource, artifactsContents, artifactsFileName, createdArtifacts, shouldLock,
+                            inTransaction);
+                    if ((result.left().value() instanceof Resource) && result.isLeft()) {
+                        Resource service1 = (Resource) result.left().value();
+                        createArtifactsFromCsar = Either.left(service1);
+                    } else {
+                        createArtifactsFromCsar = Either.right(result.right().value());
+                    }
+                }
+                if (createArtifactsFromCsar.isRight()) {
+                    log.debug("Couldn't create artifacts from artifacts.meta");
+                    return Either.right(createArtifactsFromCsar.right().value());
+                }
+                return Either.left(createArtifactsFromCsar.left().value());
+            } else {
+                return csarArtifactsAndGroupsBusinessLogic.deleteVFModules(resource, csarInfo, shouldLock, inTransaction);
+            }
+        }
+        return Either.left(resource);
+    }
+
+    private Either<Boolean, ResponseFormat> createOrUpdateSingleNonMetaArtifact(Resource resource, CsarInfo csarInfo, String artifactPath,
+                                                                                String artifactFileName, String artifactType,
+                                                                                ArtifactGroupTypeEnum artifactGroupType, String artifactLabel,
+                                                                                String artifactDisplayName, String artifactDescription,
+                                                                                String artifactId, ArtifactOperationInfo operation,
+                                                                                List<ArtifactDefinition> createdArtifacts, boolean isFromCsar,
+                                                                                boolean shouldLock, boolean inTransaction) {
+        byte[] artifactFileBytes = null;
+        if (csarInfo.getCsar().containsKey(artifactPath)) {
+            artifactFileBytes = csarInfo.getCsar().get(artifactPath);
+        }
+        Either<Boolean, ResponseFormat> result = Either.left(true);
+        if (operation.isUpdate() || operation.isDelete()) {
+            if (isArtifactDeletionRequired(artifactId, artifactFileBytes, isFromCsar)) {
+                Either<ArtifactDefinition, ResponseFormat> handleDelete = artifactsBusinessLogic
+                    .handleDelete(resource.getUniqueId(), artifactId, csarInfo.getModifier(), resource, shouldLock, inTransaction);
+                if (handleDelete.isRight()) {
+                    result = Either.right(handleDelete.right().value());
+                } else {
+                    ArtifactDefinition value = handleDelete.left().value();
+                    String updatedArtifactId = value.getUniqueId();
+                    if (artifactGroupType == ArtifactGroupTypeEnum.DEPLOYMENT) {
+                        resource.getDeploymentArtifacts().remove(updatedArtifactId);
+                    } else {
+                        resource.getArtifacts().remove(updatedArtifactId);
+                    }
+                }
+                return result;
+            }
+            if (StringUtils.isEmpty(artifactId) && artifactFileBytes != null) {
+                operation = new ArtifactOperationInfo(false, false, ArtifactOperationEnum.CREATE);
+            }
+        }
+        if (artifactFileBytes != null) {
+            Map<String, Object> vendorLicenseModelJson = ArtifactUtils
+                .buildJsonForUpdateArtifact(artifactId, artifactFileName, artifactType, artifactGroupType, artifactLabel, artifactDisplayName,
+                    artifactDescription, artifactFileBytes, null, isFromCsar);
+            Either<Either<ArtifactDefinition, Operation>, ResponseFormat> eitherNonMetaArtifacts = csarArtifactsAndGroupsBusinessLogic
+                .createOrUpdateCsarArtifactFromJson(resource, csarInfo.getModifier(), vendorLicenseModelJson, operation);
+            addNonMetaCreatedArtifactsToSupportRollback(operation, createdArtifacts, eitherNonMetaArtifacts);
+            if (eitherNonMetaArtifacts.isRight()) {
+                BeEcompErrorManager.getInstance().logInternalFlowError("UploadLicenseArtifact",
+                    "Failed to upload license artifact: " + artifactFileName + "With csar uuid: " + csarInfo.getCsarUUID(), ErrorSeverity.WARNING);
+                return Either.right(eitherNonMetaArtifacts.right().value());
+            }
+            ArtifactDefinition artifactDefinition = eitherNonMetaArtifacts.left().value().left().value();
+            createOrUpdateResourceWithUpdatedArtifact(artifactDefinition, resource, artifactGroupType);
+        }
+        return result;
+    }
+
+    private void createOrUpdateResourceWithUpdatedArtifact(ArtifactDefinition artifact, Resource resource, ArtifactGroupTypeEnum groupTypeEnum) {
+        if (groupTypeEnum == ArtifactGroupTypeEnum.DEPLOYMENT) {
+            resource.getDeploymentArtifacts().put(artifact.getArtifactLabel(), artifact);
+        } else {
+            resource.getArtifacts().put(artifact.getArtifactLabel(), artifact);
+        }
+    }
+
+    private boolean isArtifactDeletionRequired(String artifactId, byte[] artifactFileBytes, boolean isFromCsar) {
+        return !StringUtils.isEmpty(artifactId) && artifactFileBytes == null && isFromCsar;
+    }
+
+    private void addNonMetaCreatedArtifactsToSupportRollback(ArtifactOperationInfo operation, List<ArtifactDefinition> createdArtifacts,
+                                                             Either<Either<ArtifactDefinition, Operation>, ResponseFormat> eitherNonMetaArtifacts) {
+        if (operation.isCreateOrLink() && createdArtifacts != null && eitherNonMetaArtifacts.isLeft()) {
+            Either<ArtifactDefinition, Operation> eitherResult = eitherNonMetaArtifacts.left().value();
+            if (eitherResult.isLeft()) {
+                createdArtifacts.add(eitherResult.left().value());
+            }
+        }
+    }
+
+    private Either<Resource, ResponseFormat> createOrUpdateNonMetaArtifacts(CsarInfo csarInfo, Resource resource,
+                                                                            List<ArtifactDefinition> createdArtifacts, boolean shouldLock,
+                                                                            boolean inTransaction, ArtifactOperationInfo artifactOperation) {
+        Either<Resource, ResponseFormat> resStatus = null;
+        Map<String, Set<List<String>>> collectedWarningMessages = new HashMap<>();
+        try {
+            Either<List<NonMetaArtifactInfo>, String> artifactPathAndNameList = getValidArtifactNames(csarInfo, collectedWarningMessages);
+            if (artifactPathAndNameList.isRight()) {
+                return Either.right(
+                    getComponentsUtils().getResponseFormatByArtifactId(ActionStatus.ARTIFACT_NAME_INVALID, artifactPathAndNameList.right().value()));
+            }
+            EnumMap<ArtifactOperationEnum, List<NonMetaArtifactInfo>> vfCsarArtifactsToHandle = null;
+            if (artifactOperation.isCreateOrLink()) {
+                vfCsarArtifactsToHandle = new EnumMap<>(ArtifactOperationEnum.class);
+                vfCsarArtifactsToHandle.put(artifactOperation.getArtifactOperationEnum(), artifactPathAndNameList.left().value());
+            } else {
+                Either<EnumMap<ArtifactOperationEnum, List<NonMetaArtifactInfo>>, ResponseFormat> findVfCsarArtifactsToHandleRes = findVfCsarArtifactsToHandle(
+                    resource, artifactPathAndNameList.left().value(), csarInfo.getModifier());
+                if (findVfCsarArtifactsToHandleRes.isRight()) {
+                    resStatus = Either.right(findVfCsarArtifactsToHandleRes.right().value());
+                }
+                if (resStatus == null) {
+                    vfCsarArtifactsToHandle = findVfCsarArtifactsToHandleRes.left().value();
+                }
+            }
+            if (resStatus == null && vfCsarArtifactsToHandle != null) {
+                resStatus = processCsarArtifacts(csarInfo, resource, createdArtifacts, shouldLock, inTransaction, resStatus, vfCsarArtifactsToHandle);
+            }
+            if (resStatus == null) {
+                resStatus = Either.left(resource);
+            }
+        } catch (Exception e) {
+            resStatus = Either.right(componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR));
+            log.debug("Exception occurred in createNonMetaArtifacts, message:{}", e.getMessage(), e);
+        } finally {
+            CsarUtils.handleWarningMessages(collectedWarningMessages);
+        }
+        return resStatus;
+    }
+
+    private Either<Resource, ResponseFormat> processCsarArtifacts(CsarInfo csarInfo, Resource resource, List<ArtifactDefinition> createdArtifacts,
+                                                                  boolean shouldLock, boolean inTransaction,
+                                                                  Either<Resource, ResponseFormat> resStatus,
+                                                                  EnumMap<ArtifactOperationEnum, List<NonMetaArtifactInfo>> vfCsarArtifactsToHandle) {
+        for (Entry<ArtifactOperationEnum, List<NonMetaArtifactInfo>> currArtifactOperationPair : vfCsarArtifactsToHandle.entrySet()) {
+            Optional<ResponseFormat> optionalCreateInDBError =
+                // Stream of artifacts to be created
+                currArtifactOperationPair.getValue().stream()
+                    // create each artifact
+                    .map(e -> createOrUpdateSingleNonMetaArtifact(resource, csarInfo, e.getPath(), e.getArtifactName(), e.getArtifactType(),
+                        e.getArtifactGroupType(), e.getArtifactLabel(), e.getDisplayName(), CsarUtils.ARTIFACT_CREATED_FROM_CSAR,
+                        e.getArtifactUniqueId(), new ArtifactOperationInfo(false, false, currArtifactOperationPair.getKey()), createdArtifacts,
+                        e.isFromCsar(), shouldLock, inTransaction))
+                    // filter in only error
+                    .filter(Either::isRight).
+                    // Convert the error from either to
+
+                    // ResponseFormat
+                        map(e -> e.right().value()).
+                    // Check if an error occurred
+                        findAny();
+            // Error found on artifact Creation
+            if (optionalCreateInDBError.isPresent()) {
+                resStatus = Either.right(optionalCreateInDBError.get());
+                break;
+            }
+        }
+        return resStatus;
+    }
+
+    private Either<List<NonMetaArtifactInfo>, String> getValidArtifactNames(CsarInfo csarInfo,
+                                                                            Map<String, Set<List<String>>> collectedWarningMessages) {
+        List<NonMetaArtifactInfo> artifactPathAndNameList =
+            // Stream of file paths contained in csar
+            csarInfo.getCsar().entrySet().stream()
+                // Filter in only VF artifact path location
+                .filter(e -> Pattern.compile(VF_NODE_TYPE_ARTIFACTS_PATH_PATTERN).matcher(e.getKey()).matches())
+                // Validate and add warnings
+                .map(e -> CsarUtils.validateNonMetaArtifact(e.getKey(), e.getValue(), collectedWarningMessages))
+                // Filter in Non Warnings
+                .filter(Either::isLeft)
+                // Convert from Either to NonMetaArtifactInfo
+                .map(e -> e.left().value())
+                // collect to List
+                .collect(toList());
+        Pattern englishNumbersAndUnderScoresOnly = Pattern.compile(CsarUtils.VALID_ENGLISH_ARTIFACT_NAME);
+        for (NonMetaArtifactInfo nonMetaArtifactInfo : artifactPathAndNameList) {
+            if (!englishNumbersAndUnderScoresOnly.matcher(nonMetaArtifactInfo.getDisplayName()).matches()) {
+                return Either.right(nonMetaArtifactInfo.getArtifactName());
+            }
+        }
+        return Either.left(artifactPathAndNameList);
+    }
+
+    private Either<EnumMap<ArtifactOperationEnum, List<NonMetaArtifactInfo>>, ResponseFormat> findVfCsarArtifactsToHandle(Resource resource,
+                                                                                                                          List<NonMetaArtifactInfo> artifactPathAndNameList,
+                                                                                                                          User user) {
+        List<ArtifactDefinition> existingArtifacts = new ArrayList<>();
+        // collect all Deployment and Informational artifacts of VF
+        if (resource.getDeploymentArtifacts() != null && !resource.getDeploymentArtifacts().isEmpty()) {
+            existingArtifacts.addAll(resource.getDeploymentArtifacts().values());
+        }
+        if (resource.getArtifacts() != null && !resource.getArtifacts().isEmpty()) {
+            existingArtifacts.addAll(resource.getArtifacts().values());
+        }
+        existingArtifacts = existingArtifacts.stream()
+            // filter MANDATORY artifacts, LICENSE artifacts and artifacts
+
+            // was created from HEAT.meta
+            .filter(this::isNonMetaArtifact).collect(toList());
+        List<String> artifactsToIgnore = new ArrayList<>();
+        // collect IDs of Artifacts of VF which belongs to any group
+        if (resource.getGroups() != null) {
+            resource.getGroups().stream().forEach(g -> {
+                if (g.getArtifacts() != null && !g.getArtifacts().isEmpty()) {
+                    artifactsToIgnore.addAll(g.getArtifacts());
+                }
+            });
+        }
+        existingArtifacts = existingArtifacts.stream()
+            // filter artifacts which belongs to any group
+            .filter(a -> !artifactsToIgnore.contains(a.getUniqueId())).collect(toList());
+        return organizeVfCsarArtifactsByArtifactOperation(artifactPathAndNameList, existingArtifacts, resource, user);
+    }
+
+    private boolean isNonMetaArtifact(ArtifactDefinition artifact) {
+        boolean result = true;
+        if (artifact.getMandatory() || artifact.getArtifactName() == null || !isValidArtifactType(artifact)) {
+            result = false;
+        }
+        return result;
+    }
+
+    private boolean isValidArtifactType(ArtifactDefinition artifact) {
+        boolean result = true;
+        if (artifact.getArtifactType() == null || ArtifactTypeEnum.parse(artifact.getArtifactType()) == ArtifactTypeEnum.VENDOR_LICENSE
+            || ArtifactTypeEnum.parse(artifact.getArtifactType()) == ArtifactTypeEnum.VF_LICENSE) {
+            result = false;
+        }
+        return result;
+    }
+
+    private Resource createResourceInstancesRelations(User user, String yamlName, Resource resource, Resource oldResource,
+                                                      Map<String, UploadComponentInstanceInfo> uploadResInstancesMap,
+                                                      Map<String, Resource> existingNodeTypesByResourceNames) {
+        log.debug("#createResourceInstancesRelations - Going to create relations ");
+        loggerSupportability.log(LoggerSupportabilityActions.CREATE_RELATIONS, resource.getComponentMetadataForSupportLog(), StatusCode.STARTED,
+            "Start to create relations");
+        List<ComponentInstance> componentInstancesList = resource.getComponentInstances();
+        if (isEmpty(uploadResInstancesMap) || CollectionUtils.isEmpty(componentInstancesList) &&
+            resource.getResourceType() != ResourceTypeEnum.PNF) { // PNF can have no resource instances {
+            log.debug("#createResourceInstancesRelations - No instances found in the resource {} is empty, yaml template file name {}, ",
+                resource.getUniqueId(), yamlName);
+            loggerSupportability.log(LoggerSupportabilityActions.CREATE_RELATIONS, resource.getComponentMetadataForSupportLog(), StatusCode.ERROR,
+                "No instances found in the resource: {}, is empty, yaml template file name: {}", resource.getName(), yamlName);
+            BeEcompErrorManager.getInstance()
+                .logInternalDataError("createResourceInstancesRelations", "No instances found in a resource or nn yaml template. ",
+                    ErrorSeverity.ERROR);
+            throw new ByActionStatusComponentException(ActionStatus.NOT_TOPOLOGY_TOSCA_TEMPLATE, yamlName);
+        }
+        Map<String, List<ComponentInstanceProperty>> instProperties = new HashMap<>();
+        Map<ComponentInstance, Map<String, List<CapabilityDefinition>>> instCapabilities = new HashMap<>();
+        Map<ComponentInstance, Map<String, List<RequirementDefinition>>> instRequirements = new HashMap<>();
+        Map<String, Map<String, ArtifactDefinition>> instDeploymentArtifacts = new HashMap<>();
+        Map<String, Map<String, ArtifactDefinition>> instArtifacts = new HashMap<>();
+        Map<String, List<AttributeDefinition>> instAttributes = new HashMap<>();
+        List<RequirementCapabilityRelDef> relations = new ArrayList<>();
+        Map<String, List<ComponentInstanceInput>> instInputs = new HashMap<>();
+        log.debug("#createResourceInstancesRelations - Before get all datatypes. ");
+        Either<Map<String, DataTypeDefinition>, JanusGraphOperationStatus> allDataTypes = dataTypeCache.getAll();
+        if (allDataTypes.isRight()) {
+            JanusGraphOperationStatus status = allDataTypes.right().value();
+            BeEcompErrorManager.getInstance()
+                .logInternalFlowError("UpdatePropertyValueOnComponentInstance", "Failed to update property value on instance. Status is " + status,
+                    ErrorSeverity.ERROR);
+            loggerSupportability.log(LoggerSupportabilityActions.CREATE_RELATIONS, resource.getComponentMetadataForSupportLog(), StatusCode.ERROR,
+                "ERROR while update property value on instance. Status is: " + status);
+            throw new ByActionStatusComponentException(
+                componentsUtils.convertFromStorageResponse(DaoStatusConverter.convertJanusGraphStatusToStorageStatus(status)), yamlName);
+        }
+        Resource finalResource = resource;
+        uploadResInstancesMap.values().forEach(
+            i -> processComponentInstance(yamlName, finalResource, componentInstancesList, allDataTypes, instProperties, instCapabilities,
+                instRequirements, instDeploymentArtifacts, instArtifacts, instAttributes, existingNodeTypesByResourceNames, instInputs, i));
+        resource.getComponentInstances().stream().filter(i -> !i.isCreatedFromCsar()).forEach(
+            i -> processUiComponentInstance(oldResource, i, instCapabilities, instRequirements, instDeploymentArtifacts, instArtifacts,
+                instProperties, instInputs, instAttributes));
+        associateComponentInstancePropertiesToComponent(yamlName, resource, instProperties);
+        associateComponentInstanceInputsToComponent(yamlName, resource, instInputs);
+        associateDeploymentArtifactsToInstances(user, yamlName, resource, instDeploymentArtifacts);
+        associateArtifactsToInstances(yamlName, resource, instArtifacts);
+        associateOrAddCalculatedCapReq(yamlName, resource, instCapabilities, instRequirements);
+        associateInstAttributeToComponentToInstances(yamlName, resource, instAttributes);
+        addRelationsToRI(yamlName, resource, uploadResInstancesMap, componentInstancesList, relations);
+        associateResourceInstances(yamlName, resource, relations);
+        handleSubstitutionMappings(resource, uploadResInstancesMap);
+        log.debug("************* in create relations, getResource start");
+        loggerSupportability
+            .log(LoggerSupportabilityActions.CREATE_RELATIONS, resource.getComponentMetadataForSupportLog(), StatusCode.COMPLETE, "create relations");
+        Either<Resource, StorageOperationStatus> eitherGetResource = toscaOperationFacade.getToscaFullElement(resource.getUniqueId());
+        log.debug("************* in create relations, getResource end");
+        if (eitherGetResource.isRight()) {
+            loggerSupportability.log(LoggerSupportabilityActions.CREATE_RELATIONS, resource.getComponentMetadataForSupportLog(), StatusCode.ERROR,
+                "ERROR while create relations");
+            throw new ByResponseFormatComponentException(
+                componentsUtils.getResponseFormatByResource(componentsUtils.convertFromStorageResponse(eitherGetResource.right().value()), resource));
+        }
+        return eitherGetResource.left().value();
+    }
+
+    private void processUiComponentInstance(Resource oldResource, ComponentInstance instance,
+                                            Map<ComponentInstance, Map<String, List<CapabilityDefinition>>> instCapabilities,
+                                            Map<ComponentInstance, Map<String, List<RequirementDefinition>>> instRequirements,
+                                            Map<String, Map<String, ArtifactDefinition>> instDeploymentArtifacts,
+                                            Map<String, Map<String, ArtifactDefinition>> instArtifacts,
+                                            Map<String, List<ComponentInstanceProperty>> instProperties,
+                                            Map<String, List<ComponentInstanceInput>> instInputs,
+                                            Map<String, List<AttributeDefinition>> instAttributes) {
+        Optional<ComponentInstance> foundInstance = findInstance(oldResource, instance);
+        if (foundInstance.isPresent()) {
+            if (MapUtils.isNotEmpty(foundInstance.get().getCapabilities())) {
+                instCapabilities.put(instance, foundInstance.get().getCapabilities());
+            }
+            if (MapUtils.isNotEmpty(foundInstance.get().getRequirements())) {
+                instRequirements.put(instance, foundInstance.get().getRequirements());
+            }
+            if (MapUtils.isNotEmpty(foundInstance.get().getDeploymentArtifacts())) {
+                instDeploymentArtifacts.put(instance.getUniqueId(), foundInstance.get().getDeploymentArtifacts());
+            }
+            if (MapUtils.isNotEmpty(foundInstance.get().getArtifacts())) {
+                instArtifacts.put(instance.getUniqueId(), foundInstance.get().getArtifacts());
+            }
+            if (MapUtils.isNotEmpty(oldResource.getComponentInstancesProperties()) && CollectionUtils
+                .isNotEmpty(oldResource.getComponentInstancesProperties().get(foundInstance.get().getUniqueId()))) {
+                instProperties.put(instance.getUniqueId(), oldResource.getComponentInstancesProperties().get(foundInstance.get().getUniqueId()));
+            }
+            if (MapUtils.isNotEmpty(oldResource.getComponentInstancesInputs()) && CollectionUtils
+                .isNotEmpty(oldResource.getComponentInstancesInputs().get(foundInstance.get().getUniqueId()))) {
+                instInputs.put(instance.getUniqueId(), oldResource.getComponentInstancesInputs().get(foundInstance.get().getUniqueId()));
+            }
+            if (MapUtils.isNotEmpty(oldResource.getComponentInstancesAttributes()) && CollectionUtils
+                .isNotEmpty(oldResource.getComponentInstancesAttributes().get(foundInstance.get().getUniqueId()))) {
+                instAttributes.put(instance.getUniqueId(),
+                    oldResource.getComponentInstancesAttributes().get(foundInstance.get().getUniqueId()).stream().map(AttributeDefinition::new)
+                        .collect(toList()));
+            }
+        }
+    }
+
+    private Optional<ComponentInstance> findInstance(Resource oldResource, ComponentInstance instance) {
+        if (oldResource != null && CollectionUtils.isNotEmpty(oldResource.getComponentInstances())) {
+            return oldResource.getComponentInstances().stream().filter(i -> i.getName().equals(instance.getName())).findFirst();
+        }
+        return Optional.empty();
+    }
+
+    private void associateResourceInstances(String yamlName, Resource resource, List<RequirementCapabilityRelDef> relations) {
+        Either<List<RequirementCapabilityRelDef>, StorageOperationStatus> relationsEither = toscaOperationFacade
+            .associateResourceInstances(resource, resource.getUniqueId(), relations);
+        if (relationsEither.isRight() && relationsEither.right().value() != StorageOperationStatus.NOT_FOUND) {
+            StorageOperationStatus status = relationsEither.right().value();
+            log.debug("failed to associate instances of resource {} status is {}", resource.getUniqueId(), status);
+            throw new ByActionStatusComponentException(componentsUtils.convertFromStorageResponse(status), yamlName);
+        } else {
+            setResourceInstanceRelationsOnComponent(resource, relationsEither.left().value());
+        }
+    }
+
+    private void associateInstAttributeToComponentToInstances(String yamlName, Resource resource,
+                                                              Map<String, List<AttributeDefinition>> instAttributes) {
+        StorageOperationStatus addArtToInst;
+        addArtToInst = toscaOperationFacade.associateInstAttributeToComponentToInstances(instAttributes, resource);
+        if (addArtToInst != StorageOperationStatus.OK && addArtToInst != StorageOperationStatus.NOT_FOUND) {
+            log.debug("failed to associate attributes of resource {} status is {}", resource.getUniqueId(), addArtToInst);
+            throw new ByActionStatusComponentException(componentsUtils.convertFromStorageResponse(addArtToInst), yamlName);
+        }
+    }
+
+    private void associateOrAddCalculatedCapReq(String yamlName, Resource resource,
+                                                Map<ComponentInstance, Map<String, List<CapabilityDefinition>>> instCapabilities,
+                                                Map<ComponentInstance, Map<String, List<RequirementDefinition>>> instRequirements) {
+        StorageOperationStatus addArtToInst;
+        addArtToInst = toscaOperationFacade.associateOrAddCalculatedCapReq(instCapabilities, instRequirements, resource);
+        if (addArtToInst != StorageOperationStatus.OK && addArtToInst != StorageOperationStatus.NOT_FOUND) {
+            log.debug("failed to associate cap and req of resource {} status is {}", resource.getUniqueId(), addArtToInst);
+            throw new ByActionStatusComponentException(componentsUtils.convertFromStorageResponse(addArtToInst), yamlName);
+        }
+    }
+
+    private void associateArtifactsToInstances(String yamlName, Resource resource, Map<String, Map<String, ArtifactDefinition>> instArtifacts) {
+        StorageOperationStatus addArtToInst;
+        addArtToInst = toscaOperationFacade.associateArtifactsToInstances(instArtifacts, resource);
+        if (addArtToInst != StorageOperationStatus.OK && addArtToInst != StorageOperationStatus.NOT_FOUND) {
+            log.debug("failed to associate artifact of resource {} status is {}", resource.getUniqueId(), addArtToInst);
+            throw new ByActionStatusComponentException(componentsUtils.convertFromStorageResponse(addArtToInst), yamlName);
+        }
+    }
+
+    private void associateDeploymentArtifactsToInstances(User user, String yamlName, Resource resource,
+                                                         Map<String, Map<String, ArtifactDefinition>> instDeploymentArtifacts) {
+        StorageOperationStatus addArtToInst = toscaOperationFacade.associateDeploymentArtifactsToInstances(instDeploymentArtifacts, resource, user);
+        if (addArtToInst != StorageOperationStatus.OK && addArtToInst != StorageOperationStatus.NOT_FOUND) {
+            log.debug("failed to associate artifact of resource {} status is {}", resource.getUniqueId(), addArtToInst);
+            throw new ByActionStatusComponentException(componentsUtils.convertFromStorageResponse(addArtToInst), yamlName);
+        }
+    }
+
+    private void associateComponentInstanceInputsToComponent(String yamlName, Resource resource,
+                                                             Map<String, List<ComponentInstanceInput>> instInputs) {
+        if (MapUtils.isNotEmpty(instInputs)) {
+            Either<Map<String, List<ComponentInstanceInput>>, StorageOperationStatus> addInputToInst = toscaOperationFacade
+                .associateComponentInstanceInputsToComponent(instInputs, resource.getUniqueId());
+            if (addInputToInst.isRight()) {
+                StorageOperationStatus addInputToInstError = addInputToInst.right().value();
+                log.debug("failed to associate inputs value of resource {} status is {}", resource.getUniqueId(), addInputToInstError);
+                throw new ByActionStatusComponentException(componentsUtils.convertFromStorageResponse(addInputToInstError), yamlName);
+            }
+            setComponentInstanceInputsOnComponent(resource, instInputs);
+        }
+    }
+
+    private void setComponentInstanceInputsOnComponent(Resource resource, Map<String, List<ComponentInstanceInput>> instInputs) {
+        Map<String, List<ComponentInstanceInput>> componentInstancesInputs = resource.getComponentInstancesInputs();
+        if (componentInstancesInputs == null) {
+            componentInstancesInputs = new HashMap<>();
+        }
+        componentInstancesInputs.putAll(instInputs);
+        resource.setComponentInstancesInputs(componentInstancesInputs);
+    }
+
+    private void associateComponentInstancePropertiesToComponent(String yamlName, Resource resource,
+                                                                 Map<String, List<ComponentInstanceProperty>> instProperties) {
+        Either<Map<String, List<ComponentInstanceProperty>>, StorageOperationStatus> addPropToInst = toscaOperationFacade
+            .associateComponentInstancePropertiesToComponent(instProperties, resource.getUniqueId());
+        if (addPropToInst.isRight()) {
+            loggerSupportability.log(LoggerSupportabilityActions.CREATE_RELATIONS, resource.getComponentMetadataForSupportLog(), StatusCode.ERROR,
+                "ERROR while  associate compnent insatnce properties of resource: {} status is: {}", resource.getName(),
+                addPropToInst.right().value());
+            StorageOperationStatus storageOperationStatus = addPropToInst.right().value();
+            log.debug("failed to associate properties of resource {} status is {}", resource.getUniqueId(), storageOperationStatus);
+            throw new ByActionStatusComponentException(componentsUtils.convertFromStorageResponse(storageOperationStatus), yamlName);
+        }
+        setComponentInstancePropertiesOnComponent(resource, instProperties);
+    }
+
+    private void setComponentInstancePropertiesOnComponent(Resource resource, Map<String, List<ComponentInstanceProperty>> instProperties) {
+        Map<String, List<ComponentInstanceProperty>> componentInstanceProps = resource.getComponentInstancesProperties();
+        if (componentInstanceProps == null) {
+            componentInstanceProps = new HashMap<>();
+        }
+        componentInstanceProps.putAll(instProperties);
+        resource.setComponentInstancesProperties(componentInstanceProps);
+    }
+
+    private void handleSubstitutionMappings(Resource resource, Map<String, UploadComponentInstanceInfo> uploadResInstancesMap) {
+        if (resource.getResourceType() == ResourceTypeEnum.CVFC) {
+            Either<Resource, StorageOperationStatus> getResourceRes = updateCalculatedCapReqWithSubstitutionMappings(resource, uploadResInstancesMap);
+            if (getResourceRes.isRight()) {
+                ResponseFormat responseFormat = componentsUtils
+                    .getResponseFormatByResource(componentsUtils.convertFromStorageResponse(getResourceRes.right().value()), resource);
+                throw new ByResponseFormatComponentException(responseFormat);
+            }
+        }
+    }
+
+    private void addRelationsToRI(String yamlName, Resource resource, Map<String, UploadComponentInstanceInfo> uploadResInstancesMap,
+                                  List<ComponentInstance> componentInstancesList, List<RequirementCapabilityRelDef> relations) {
+        for (Entry<String, UploadComponentInstanceInfo> entry : uploadResInstancesMap.entrySet()) {
+            UploadComponentInstanceInfo uploadComponentInstanceInfo = entry.getValue();
+            ComponentInstance currentCompInstance = null;
+            for (ComponentInstance compInstance : componentInstancesList) {
+                if (compInstance.getName().equals(uploadComponentInstanceInfo.getName())) {
+                    currentCompInstance = compInstance;
+                    break;
+                }
+            }
+            if (currentCompInstance == null) {
+                log.debug(COMPONENT_INSTANCE_WITH_NAME_IN_RESOURCE, uploadComponentInstanceInfo.getName(), resource.getUniqueId());
+                BeEcompErrorManager.getInstance()
+                    .logInternalDataError(COMPONENT_INSTANCE_WITH_NAME + uploadComponentInstanceInfo.getName() + IN_RESOURCE, resource.getUniqueId(),
+                        ErrorSeverity.ERROR);
+                throw new ByActionStatusComponentException(ActionStatus.NOT_TOPOLOGY_TOSCA_TEMPLATE, yamlName);
+            }
+            ResponseFormat addRelationToRiRes = addRelationToRI(yamlName, resource, entry.getValue(), relations);
+            if (addRelationToRiRes.getStatus() != 200) {
+                throw new ByResponseFormatComponentException(addRelationToRiRes);
+            }
+        }
+    }
+
+    private void setResourceInstanceRelationsOnComponent(Resource resource, List<RequirementCapabilityRelDef> relations) {
+        if (resource.getComponentInstancesRelations() != null) {
+            resource.getComponentInstancesRelations().addAll(relations);
+        } else {
+            resource.setComponentInstancesRelations(relations);
+        }
+    }
+
+    private void processComponentInstance(String yamlName, Resource resource, List<ComponentInstance> componentInstancesList,
+                                          Either<Map<String, DataTypeDefinition>, JanusGraphOperationStatus> allDataTypes,
+                                          Map<String, List<ComponentInstanceProperty>> instProperties,
+                                          Map<ComponentInstance, Map<String, List<CapabilityDefinition>>> instCapabilties,
+                                          Map<ComponentInstance, Map<String, List<RequirementDefinition>>> instRequirements,
+                                          Map<String, Map<String, ArtifactDefinition>> instDeploymentArtifacts,
+                                          Map<String, Map<String, ArtifactDefinition>> instArtifacts,
+                                          Map<String, List<AttributeDefinition>> instAttributes, Map<String, Resource> originCompMap,
+                                          Map<String, List<ComponentInstanceInput>> instInputs,
+                                          UploadComponentInstanceInfo uploadComponentInstanceInfo) {
+        Optional<ComponentInstance> currentCompInstanceOpt = componentInstancesList.stream()
+            .filter(i -> i.getName().equals(uploadComponentInstanceInfo.getName())).findFirst();
+        if (!currentCompInstanceOpt.isPresent()) {
+            log.debug(COMPONENT_INSTANCE_WITH_NAME_IN_RESOURCE, uploadComponentInstanceInfo.getName(), resource.getUniqueId());
+            BeEcompErrorManager.getInstance()
+                .logInternalDataError(COMPONENT_INSTANCE_WITH_NAME + uploadComponentInstanceInfo.getName() + IN_RESOURCE, resource.getUniqueId(),
+                    ErrorSeverity.ERROR);
+            throw new ByActionStatusComponentException(ActionStatus.NOT_TOPOLOGY_TOSCA_TEMPLATE, yamlName);
+        }
+        ComponentInstance currentCompInstance = currentCompInstanceOpt.get();
+        String resourceInstanceId = currentCompInstance.getUniqueId();
+        Resource originResource = getOriginResource(originCompMap, currentCompInstance);
+        if (isNotEmpty(originResource.getRequirements())) {
+            instRequirements.put(currentCompInstance, originResource.getRequirements());
+        }
+        if (isNotEmpty(originResource.getCapabilities())) {
+            processComponentInstanceCapabilities(allDataTypes, instCapabilties, uploadComponentInstanceInfo, currentCompInstance, originResource);
+        }
+        if (originResource.getDeploymentArtifacts() != null && !originResource.getDeploymentArtifacts().isEmpty()) {
+            instDeploymentArtifacts.put(resourceInstanceId, originResource.getDeploymentArtifacts());
+        }
+        if (originResource.getArtifacts() != null && !originResource.getArtifacts().isEmpty()) {
+            instArtifacts.put(resourceInstanceId, originResource.getArtifacts());
+        }
+        if (originResource.getAttributes() != null && !originResource.getAttributes().isEmpty()) {
+            instAttributes.put(resourceInstanceId, originResource.getAttributes());
+        }
+        if (originResource.getResourceType() != ResourceTypeEnum.CVFC) {
+            ResponseFormat addPropertiesValueToRiRes = addPropertyValuesToRi(uploadComponentInstanceInfo, resource, originResource,
+                currentCompInstance, instProperties, allDataTypes.left().value());
+            if (addPropertiesValueToRiRes.getStatus() != 200) {
+                throw new ByResponseFormatComponentException(addPropertiesValueToRiRes);
+            }
+        } else {
+            addInputsValuesToRi(uploadComponentInstanceInfo, resource, originResource, currentCompInstance, instInputs, allDataTypes.left().value());
+        }
+    }
+
+    private Resource getOriginResource(Map<String, Resource> originCompMap, ComponentInstance currentCompInstance) {
+        Resource originResource;
+        if (!originCompMap.containsKey(currentCompInstance.getComponentUid())) {
+            Either<Resource, StorageOperationStatus> getOriginResourceRes = toscaOperationFacade
+                .getToscaFullElement(currentCompInstance.getComponentUid());
+            if (getOriginResourceRes.isRight()) {
+                log.debug("failed to fetch resource with uniqueId {} and tosca component name {} status is {}", currentCompInstance.getComponentUid(),
+                    currentCompInstance.getToscaComponentName(), getOriginResourceRes);
+                throw new ByActionStatusComponentException(componentsUtils.convertFromStorageResponse(getOriginResourceRes.right().value()),
+                    currentCompInstance.getComponentUid());
+            }
+            originResource = getOriginResourceRes.left().value();
+            originCompMap.put(originResource.getUniqueId(), originResource);
+        } else {
+            originResource = originCompMap.get(currentCompInstance.getComponentUid());
+        }
+        return originResource;
+    }
+
+    private void processComponentInstanceCapabilities(Either<Map<String, DataTypeDefinition>, JanusGraphOperationStatus> allDataTypes,
+                                                      Map<ComponentInstance, Map<String, List<CapabilityDefinition>>> instCapabilties,
+                                                      UploadComponentInstanceInfo uploadComponentInstanceInfo, ComponentInstance currentCompInstance,
+                                                      Resource originResource) {
+        Map<String, List<CapabilityDefinition>> originCapabilities;
+        if (isNotEmpty(uploadComponentInstanceInfo.getCapabilities())) {
+            originCapabilities = new HashMap<>();
+            Map<String, Map<String, UploadPropInfo>> newPropertiesMap = new HashMap<>();
+            originResource.getCapabilities().forEach((k, v) -> addCapabilities(originCapabilities, k, v));
+            uploadComponentInstanceInfo.getCapabilities().values().forEach(l -> addCapabilitiesProperties(newPropertiesMap, l));
+            updateCapabilityPropertiesValues(allDataTypes, originCapabilities, newPropertiesMap);
+        } else {
+            originCapabilities = originResource.getCapabilities();
+        }
+        instCapabilties.put(currentCompInstance, originCapabilities);
+    }
+
+    private void updateCapabilityPropertiesValues(Either<Map<String, DataTypeDefinition>, JanusGraphOperationStatus> allDataTypes,
+                                                  Map<String, List<CapabilityDefinition>> originCapabilities,
+                                                  Map<String, Map<String, UploadPropInfo>> newPropertiesMap) {
+        originCapabilities.values().stream().flatMap(Collection::stream).filter(c -> newPropertiesMap.containsKey(c.getName()))
+            .forEach(c -> updatePropertyValues(c.getProperties(), newPropertiesMap.get(c.getName()), allDataTypes.left().value()));
+    }
+
+    private void addCapabilitiesProperties(Map<String, Map<String, UploadPropInfo>> newPropertiesMap, List<UploadCapInfo> capabilities) {
+        for (UploadCapInfo capability : capabilities) {
+            if (isNotEmpty(capability.getProperties())) {
+                newPropertiesMap.put(capability.getName(), capability.getProperties().stream().collect(toMap(UploadInfo::getName, p -> p)));
+            }
+        }
+    }
+
+    private void addCapabilities(Map<String, List<CapabilityDefinition>> originCapabilities, String type, List<CapabilityDefinition> capabilities) {
+        List<CapabilityDefinition> list = capabilities.stream().map(CapabilityDefinition::new).collect(toList());
+        originCapabilities.put(type, list);
+    }
+
+    private void updatePropertyValues(List<ComponentInstanceProperty> properties, Map<String, UploadPropInfo> newProperties,
+                                      Map<String, DataTypeDefinition> allDataTypes) {
+        properties.forEach(p -> updatePropertyValue(p, newProperties.get(p.getName()), allDataTypes));
+    }
+
+    private String updatePropertyValue(ComponentInstanceProperty property, UploadPropInfo propertyInfo,
+                                       Map<String, DataTypeDefinition> allDataTypes) {
+        String value = null;
+        List<GetInputValueDataDefinition> getInputs = null;
+        boolean isValidate = true;
+        if (null != propertyInfo && propertyInfo.getValue() != null) {
+            getInputs = propertyInfo.getGet_input();
+            isValidate = getInputs == null || getInputs.isEmpty();
+            if (isValidate) {
+                value = getPropertyJsonStringValue(propertyInfo.getValue(), property.getType());
+            } else {
+                value = getPropertyJsonStringValue(propertyInfo.getValue(), TypeUtils.ToscaTagNamesEnum.GET_INPUT.getElementName());
+            }
+        }
+        property.setValue(value);
+        return validatePropValueBeforeCreate(property, value, isValidate, allDataTypes);
+    }
+
+    private Either<Resource, StorageOperationStatus> updateCalculatedCapReqWithSubstitutionMappings(Resource resource,
+                                                                                                    Map<String, UploadComponentInstanceInfo> uploadResInstancesMap) {
+        Either<Resource, StorageOperationStatus> updateRes = null;
+        Map<ComponentInstance, Map<String, List<CapabilityDefinition>>> updatedInstCapabilities = new HashMap<>();
+        Map<ComponentInstance, Map<String, List<RequirementDefinition>>> updatedInstRequirements = new HashMap<>();
+        StorageOperationStatus status = toscaOperationFacade.deleteAllCalculatedCapabilitiesRequirements(resource.getUniqueId());
+        if (status != StorageOperationStatus.OK && status != StorageOperationStatus.NOT_FOUND) {
+            log.debug("Failed to delete all calculated capabilities and requirements of resource {} upon update. Status is {}",
+                resource.getUniqueId(), status);
+            updateRes = Either.right(status);
+        }
+        if (updateRes == null) {
+            fillUpdatedInstCapabilitiesRequirements(resource.getComponentInstances(), uploadResInstancesMap, updatedInstCapabilities,
+                updatedInstRequirements);
+            status = toscaOperationFacade.associateOrAddCalculatedCapReq(updatedInstCapabilities, updatedInstRequirements, resource);
+            if (status != StorageOperationStatus.OK && status != StorageOperationStatus.NOT_FOUND) {
+                log.debug(
+                    "Failed to associate capabilities and requirementss of resource {}, updated according to a substitution mapping. Status is {}",
+                    resource.getUniqueId(), status);
+                updateRes = Either.right(status);
+            }
+        }
+        if (updateRes == null) {
+            updateRes = Either.left(resource);
+        }
+        return updateRes;
+    }
+
+    private void fillUpdatedInstCapabilitiesRequirements(List<ComponentInstance> componentInstances,
+                                                         Map<String, UploadComponentInstanceInfo> uploadResInstancesMap,
+                                                         Map<ComponentInstance, Map<String, List<CapabilityDefinition>>> updatedInstCapabilities,
+                                                         Map<ComponentInstance, Map<String, List<RequirementDefinition>>> updatedInstRequirements) {
+        componentInstances.stream().forEach(i -> {
+            fillUpdatedInstCapabilities(updatedInstCapabilities, i, uploadResInstancesMap.get(i.getName()).getCapabilitiesNamesToUpdate());
+            fillUpdatedInstRequirements(updatedInstRequirements, i, uploadResInstancesMap.get(i.getName()).getRequirementsNamesToUpdate());
+        });
+    }
+
+    private void fillUpdatedInstRequirements(Map<ComponentInstance, Map<String, List<RequirementDefinition>>> updatedInstRequirements,
+                                             ComponentInstance instance, Map<String, String> requirementsNamesToUpdate) {
+        Map<String, List<RequirementDefinition>> updatedRequirements = new HashMap<>();
+        Set<String> updatedReqNames = new HashSet<>();
+        if (isNotEmpty(requirementsNamesToUpdate)) {
+            for (Map.Entry<String, List<RequirementDefinition>> requirements : instance.getRequirements().entrySet()) {
+                updatedRequirements.put(requirements.getKey(), requirements.getValue().stream().filter(
+                    r -> requirementsNamesToUpdate.containsKey(r.getName()) && !updatedReqNames.contains(requirementsNamesToUpdate.get(r.getName())))
+                    .map(r -> {
+                        r.setParentName(r.getName());
+                        r.setName(requirementsNamesToUpdate.get(r.getName()));
+                        updatedReqNames.add(r.getName());
+                        return r;
+                    }).collect(toList()));
+            }
+        }
+        if (isNotEmpty(updatedRequirements)) {
+            updatedInstRequirements.put(instance, updatedRequirements);
+        }
+    }
+
+    private void fillUpdatedInstCapabilities(Map<ComponentInstance, Map<String, List<CapabilityDefinition>>> updatedInstCapabilties,
+                                             ComponentInstance instance, Map<String, String> capabilitiesNamesToUpdate) {
+        Map<String, List<CapabilityDefinition>> updatedCapabilities = new HashMap<>();
+        Set<String> updatedCapNames = new HashSet<>();
+        if (isNotEmpty(capabilitiesNamesToUpdate)) {
+            for (Map.Entry<String, List<CapabilityDefinition>> requirements : instance.getCapabilities().entrySet()) {
+                updatedCapabilities.put(requirements.getKey(), requirements.getValue().stream().filter(
+                    c -> capabilitiesNamesToUpdate.containsKey(c.getName()) && !updatedCapNames.contains(capabilitiesNamesToUpdate.get(c.getName())))
+                    .map(c -> {
+                        c.setParentName(c.getName());
+                        c.setName(capabilitiesNamesToUpdate.get(c.getName()));
+                        updatedCapNames.add(c.getName());
+                        return c;
+                    }).collect(toList()));
+            }
+        }
+        if (isNotEmpty(updatedCapabilities)) {
+            updatedInstCapabilties.put(instance, updatedCapabilities);
+        }
+    }
+
+    private ResponseFormat addRelationToRI(String yamlName, Resource resource, UploadComponentInstanceInfo nodesInfoValue,
+                                           List<RequirementCapabilityRelDef> relations) {
+        List<ComponentInstance> componentInstancesList = resource.getComponentInstances();
+        ComponentInstance currentCompInstance = null;
+        for (ComponentInstance compInstance : componentInstancesList) {
+            if (compInstance.getName().equals(nodesInfoValue.getName())) {
+                currentCompInstance = compInstance;
+                break;
+            }
+        }
+        if (currentCompInstance == null) {
+            log.debug(COMPONENT_INSTANCE_WITH_NAME_IN_RESOURCE, nodesInfoValue.getName(), resource.getUniqueId());
+            BeEcompErrorManager.getInstance()
+                .logInternalDataError(COMPONENT_INSTANCE_WITH_NAME + nodesInfoValue.getName() + IN_RESOURCE, resource.getUniqueId(),
+                    ErrorSeverity.ERROR);
+            return componentsUtils.getResponseFormat(ActionStatus.NOT_TOPOLOGY_TOSCA_TEMPLATE, yamlName);
+        }
+        String resourceInstanceId = currentCompInstance.getUniqueId();
+        Map<String, List<UploadReqInfo>> regMap = nodesInfoValue.getRequirements();
+        if (regMap != null) {
+            Iterator<Entry<String, List<UploadReqInfo>>> nodesRegValue = regMap.entrySet().iterator();
+            while (nodesRegValue.hasNext()) {
+                Entry<String, List<UploadReqInfo>> nodesRegInfoEntry = nodesRegValue.next();
+                List<UploadReqInfo> uploadRegInfoList = nodesRegInfoEntry.getValue();
+                for (UploadReqInfo uploadRegInfo : uploadRegInfoList) {
+                    log.debug("Going to create  relation {}", uploadRegInfo.getName());
+                    loggerSupportability
+                        .log(LoggerSupportabilityActions.CREATE_RELATIONS, resource.getComponentMetadataForSupportLog(), StatusCode.STARTED,
+                            "Started to create relations on instance: {}", uploadRegInfo.getName());
+                    String regName = uploadRegInfo.getName();
+                    RequirementCapabilityRelDef regCapRelDef = new RequirementCapabilityRelDef();
+                    regCapRelDef.setFromNode(resourceInstanceId);
+                    log.debug("try to find available requirement {} ", regName);
+                    Either<RequirementDefinition, ResponseFormat> eitherReqStatus = findAviableRequiremen(regName, yamlName, nodesInfoValue,
+                        currentCompInstance, uploadRegInfo.getCapabilityName());
+                    if (eitherReqStatus.isRight()) {
+                        log.debug("failed to find available requirement {} status is {}", regName, eitherReqStatus.right().value());
+                        loggerSupportability
+                            .log(LoggerSupportabilityActions.CREATE_RELATIONS, resource.getComponentMetadataForSupportLog(), StatusCode.ERROR,
+                                "ERROR while search available requirement {} status is: {}", regName, eitherReqStatus.right().value());
+                        return eitherReqStatus.right().value();
+                    }
+                    RequirementDefinition validReq = eitherReqStatus.left().value();
+                    List<CapabilityRequirementRelationship> reqAndRelationshipPairList = regCapRelDef.getRelationships();
+                    if (reqAndRelationshipPairList == null) {
+                        reqAndRelationshipPairList = new ArrayList<>();
+                    }
+                    RelationshipInfo reqAndRelationshipPair = new RelationshipInfo();
+                    reqAndRelationshipPair.setRequirement(regName);
+                    reqAndRelationshipPair.setRequirementOwnerId(validReq.getOwnerId());
+                    reqAndRelationshipPair.setRequirementUid(validReq.getUniqueId());
+                    RelationshipImpl relationship = new RelationshipImpl();
+                    relationship.setType(validReq.getCapability());
+                    reqAndRelationshipPair.setRelationships(relationship);
+                    ComponentInstance currentCapCompInstance = null;
+                    for (ComponentInstance compInstance : componentInstancesList) {
+                        if (compInstance.getName().equals(uploadRegInfo.getNode())) {
+                            currentCapCompInstance = compInstance;
+                            break;
+                        }
+                    }
+                    if (currentCapCompInstance == null) {
+                        log.debug("The component instance  with name {} not found on resource {} ", uploadRegInfo.getNode(), resource.getUniqueId());
+                        loggerSupportability
+                            .log(LoggerSupportabilityActions.CREATE_RELATIONS, resource.getComponentMetadataForSupportLog(), StatusCode.ERROR,
+                                "ERROR component instance  with name: {} not found on resource: {}", uploadRegInfo.getNode(), resource.getUniqueId());
+                        BeEcompErrorManager.getInstance()
+                            .logInternalDataError(COMPONENT_INSTANCE_WITH_NAME + uploadRegInfo.getNode() + IN_RESOURCE, resource.getUniqueId(),
+                                ErrorSeverity.ERROR);
+                        return componentsUtils.getResponseFormat(ActionStatus.NOT_TOPOLOGY_TOSCA_TEMPLATE, yamlName);
+                    }
+                    regCapRelDef.setToNode(currentCapCompInstance.getUniqueId());
+                    log.debug("try to find aviable Capability  req name is {} ", validReq.getName());
+                    CapabilityDefinition aviableCapForRel = findAvailableCapabilityByTypeOrName(validReq, currentCapCompInstance, uploadRegInfo);
+                    if (aviableCapForRel == null) {
+                        log.debug("aviable capability was not found. req name is {} component instance is {}", validReq.getName(),
+                            currentCapCompInstance.getUniqueId());
+                        loggerSupportability
+                            .log(LoggerSupportabilityActions.CREATE_RELATIONS, resource.getComponentMetadataForSupportLog(), StatusCode.ERROR,
+                                "ERROR available capability was not found. req name is: {} component instance is: {}", validReq.getName(),
+                                currentCapCompInstance.getUniqueId());
+                        BeEcompErrorManager.getInstance().logInternalDataError(
+                            "aviable capability was not found. req name is " + validReq.getName() + " component instance is " + currentCapCompInstance
+                                .getUniqueId(), resource.getUniqueId(), ErrorSeverity.ERROR);
+                        return componentsUtils.getResponseFormat(ActionStatus.NOT_TOPOLOGY_TOSCA_TEMPLATE, yamlName);
+                    }
+                    reqAndRelationshipPair.setCapability(aviableCapForRel.getName());
+                    reqAndRelationshipPair.setCapabilityUid(aviableCapForRel.getUniqueId());
+                    reqAndRelationshipPair.setCapabilityOwnerId(aviableCapForRel.getOwnerId());
+                    CapabilityRequirementRelationship capReqRel = new CapabilityRequirementRelationship();
+                    capReqRel.setRelation(reqAndRelationshipPair);
+                    reqAndRelationshipPairList.add(capReqRel);
+                    regCapRelDef.setRelationships(reqAndRelationshipPairList);
+                    relations.add(regCapRelDef);
+                }
+            }
+        } else if (resource.getResourceType() != ResourceTypeEnum.CVFC) {
+            return componentsUtils.getResponseFormat(ActionStatus.OK, yamlName);
+        }
+        return componentsUtils.getResponseFormat(ActionStatus.OK);
+    }
+
+    private void addInputsValuesToRi(UploadComponentInstanceInfo uploadComponentInstanceInfo, Resource resource, Resource originResource,
+                                     ComponentInstance currentCompInstance, Map<String, List<ComponentInstanceInput>> instInputs,
+                                     Map<String, DataTypeDefinition> allDataTypes) {
+        Map<String, List<UploadPropInfo>> propMap = uploadComponentInstanceInfo.getProperties();
+        if (MapUtils.isNotEmpty(propMap)) {
+            Map<String, InputDefinition> currPropertiesMap = new HashMap<>();
+            List<ComponentInstanceInput> instPropList = new ArrayList<>();
+            if (CollectionUtils.isEmpty(originResource.getInputs())) {
+                log.debug("failed to find properties ");
+                loggerSupportability.log(LoggerSupportabilityActions.CREATE_INPUTS, resource.getComponentMetadataForSupportLog(), StatusCode.ERROR,
+                    "ERROR while try to find properties");
+                throw new ByActionStatusComponentException(ActionStatus.PROPERTY_NOT_FOUND);
+            }
+            originResource.getInputs().forEach(p -> addInput(currPropertiesMap, p));
+            for (List<UploadPropInfo> propertyList : propMap.values()) {
+                processProperty(resource, currentCompInstance, allDataTypes, currPropertiesMap, instPropList, propertyList);
+            }
+            currPropertiesMap.values().forEach(p -> instPropList.add(new ComponentInstanceInput(p)));
+            instInputs.put(currentCompInstance.getUniqueId(), instPropList);
+        }
+    }
+
+    private void processProperty(Resource resource, ComponentInstance currentCompInstance, Map<String, DataTypeDefinition> allDataTypes,
+                                 Map<String, InputDefinition> currPropertiesMap, List<ComponentInstanceInput> instPropList,
+                                 List<UploadPropInfo> propertyList) {
+        UploadPropInfo propertyInfo = propertyList.get(0);
+        String propName = propertyInfo.getName();
+        if (!currPropertiesMap.containsKey(propName)) {
+            loggerSupportability.log(LoggerSupportabilityActions.PROPERTY, resource.getComponentMetadataForSupportLog(), StatusCode.ERROR,
+                "ERROR failed to find property: {}", propName);
+            log.debug("failed to find property {} ", propName);
+            throw new ByActionStatusComponentException(ActionStatus.PROPERTY_NOT_FOUND, propName);
+        }
+        InputDefinition curPropertyDef = currPropertiesMap.get(propName);
+        ComponentInstanceInput property = null;
+        String value = null;
+        List<GetInputValueDataDefinition> getInputs = null;
+        boolean isValidate = true;
+        if (propertyInfo.getValue() != null) {
+            getInputs = propertyInfo.getGet_input();
+            isValidate = getInputs == null || getInputs.isEmpty();
+            if (isValidate) {
+                value = getPropertyJsonStringValue(propertyInfo.getValue(), curPropertyDef.getType());
+            } else {
+                value = getPropertyJsonStringValue(propertyInfo.getValue(), TypeUtils.ToscaTagNamesEnum.GET_INPUT.getElementName());
+            }
+        }
+        property = new ComponentInstanceInput(curPropertyDef, value, null);
+        String validPropertyVAlue = validatePropValueBeforeCreate(property, value, isValidate, allDataTypes);
+        property.setValue(validPropertyVAlue);
+        if (isNotEmpty(getInputs)) {
+            List<GetInputValueDataDefinition> getInputValues = new ArrayList<>();
+            for (GetInputValueDataDefinition getInput : getInputs) {
+                List<InputDefinition> inputs = resource.getInputs();
+                if (CollectionUtils.isEmpty(inputs)) {
+                    loggerSupportability.log(LoggerSupportabilityActions.PROPERTY, resource.getComponentMetadataForSupportLog(), StatusCode.ERROR,
+                        "ERROR Failed to add property: " + propName + " to resource instance: {}. Inputs list is empty ",
+                        currentCompInstance.getUniqueId());
+                    log.debug("Failed to add property {} to resource instance {}. Inputs list is empty ", property,
+                        currentCompInstance.getUniqueId());
+                    throw new ByActionStatusComponentException(ActionStatus.INVALID_CONTENT);
+                }
+                Optional<InputDefinition> optional = inputs.stream().filter(p -> p.getName().equals(getInput.getInputName())).findAny();
+                if (!optional.isPresent()) {
+                    loggerSupportability.log(LoggerSupportabilityActions.PROPERTY, resource.getComponentMetadataForSupportLog(), StatusCode.ERROR,
+                        "ERROR Failed to find input: " + getInput.getInputName());
+                    log.debug("Failed to find input {} ", getInput.getInputName());
+                    // @@TODO error message
+                    throw new ByActionStatusComponentException(ActionStatus.INVALID_CONTENT);
+                }
+                InputDefinition input = optional.get();
+                getInput.setInputId(input.getUniqueId());
+                getInputValues.add(getInput);
+                GetInputValueDataDefinition getInputIndex = getInput.getGetInputIndex();
+                processGetInput(getInputValues, inputs, getInputIndex);
+            }
+            property.setGetInputValues(getInputValues);
+        }
+        instPropList.add(property);
+        // delete overriden property
+        currPropertiesMap.remove(property.getName());
+    }
+
+    private void processGetInput(List<GetInputValueDataDefinition> getInputValues, List<InputDefinition> inputs,
+                                 GetInputValueDataDefinition getInputIndex) {
+        Optional<InputDefinition> optional;
+        if (getInputIndex != null) {
+            optional = inputs.stream().filter(p -> p.getName().equals(getInputIndex.getInputName())).findAny();
+            if (!optional.isPresent()) {
+                log.debug("Failed to find input {} ", getInputIndex.getInputName());
+                // @@TODO error message
+                throw new ByActionStatusComponentException(ActionStatus.INVALID_CONTENT);
+            }
+            InputDefinition inputIndex = optional.get();
+            getInputIndex.setInputId(inputIndex.getUniqueId());
+            getInputValues.add(getInputIndex);
+        }
+    }
+
+    private void addInput(Map<String, InputDefinition> currPropertiesMap, InputDefinition prop) {
+        String propName = prop.getName();
+        if (!currPropertiesMap.containsKey(propName)) {
+            currPropertiesMap.put(propName, prop);
+        }
+    }
+
+    private ResponseFormat addPropertyValuesToRi(UploadComponentInstanceInfo uploadComponentInstanceInfo, Resource resource, Resource originResource,
+                                                 ComponentInstance currentCompInstance, Map<String, List<ComponentInstanceProperty>> instProperties,
+                                                 Map<String, DataTypeDefinition> allDataTypes) {
+        Map<String, List<UploadPropInfo>> propMap = uploadComponentInstanceInfo.getProperties();
+        Map<String, PropertyDefinition> currPropertiesMap = new HashMap<>();
+        List<PropertyDefinition> listFromMap = originResource.getProperties();
+        if ((propMap != null && !propMap.isEmpty()) && (listFromMap == null || listFromMap.isEmpty())) {
+            loggerSupportability.log(LoggerSupportabilityActions.PROPERTY, resource.getComponentMetadataForSupportLog(), StatusCode.ERROR,
+                "ERROR Failed to find properties");
+            log.debug("failed to find properties");
+            return componentsUtils.getResponseFormat(ActionStatus.PROPERTY_NOT_FOUND);
+        }
+        if (listFromMap == null || listFromMap.isEmpty()) {
+            return componentsUtils.getResponseFormat(ActionStatus.OK);
+        }
+        for (PropertyDefinition prop : listFromMap) {
+            String propName = prop.getName();
+            if (!currPropertiesMap.containsKey(propName)) {
+                currPropertiesMap.put(propName, prop);
+            }
+        }
+        List<ComponentInstanceProperty> instPropList = new ArrayList<>();
+        if (propMap != null && propMap.size() > 0) {
+            for (List<UploadPropInfo> propertyList : propMap.values()) {
+                UploadPropInfo propertyInfo = propertyList.get(0);
+                String propName = propertyInfo.getName();
+                if (!currPropertiesMap.containsKey(propName)) {
+                    log.debug("failed to find property {} ", propName);
+                    loggerSupportability.log(LoggerSupportabilityActions.PROPERTY, resource.getComponentMetadataForSupportLog(), StatusCode.ERROR,
+                        "ERROR Failed to find property: {}", propName);
+                    return componentsUtils.getResponseFormat(ActionStatus.PROPERTY_NOT_FOUND, propName);
+                }
+                PropertyDefinition curPropertyDef = currPropertiesMap.get(propName);
+                ComponentInstanceProperty property = null;
+                String value = null;
+                List<GetInputValueDataDefinition> getInputs = null;
+                boolean isValidate = true;
+                if (propertyInfo.getValue() != null) {
+                    getInputs = propertyInfo.getGet_input();
+                    isValidate = getInputs == null || getInputs.isEmpty();
+                    if (isValidate) {
+                        value = getPropertyJsonStringValue(propertyInfo.getValue(), curPropertyDef.getType());
+                    } else {
+                        value = getPropertyJsonStringValue(propertyInfo.getValue(), TypeUtils.ToscaTagNamesEnum.GET_INPUT.getElementName());
+                    }
+                }
+                property = new ComponentInstanceProperty(curPropertyDef, value, null);
+                String validatePropValue = validatePropValueBeforeCreate(property, value, isValidate, allDataTypes);
+                property.setValue(validatePropValue);
+                if (getInputs != null && !getInputs.isEmpty()) {
+                    List<GetInputValueDataDefinition> getInputValues = new ArrayList<>();
+                    for (GetInputValueDataDefinition getInput : getInputs) {
+                        List<InputDefinition> inputs = resource.getInputs();
+                        if (inputs == null || inputs.isEmpty()) {
+                            log.debug("Failed to add property {} to instance. Inputs list is empty ", property);
+                            loggerSupportability
+                                .log(LoggerSupportabilityActions.PROPERTY, resource.getComponentMetadataForSupportLog(), StatusCode.ERROR,
+                                    "Failed to add property: {} to instance. Inputs list is empty", propName);
+                            rollbackWithException(ActionStatus.INPUTS_NOT_FOUND,
+                                property.getGetInputValues().stream().map(GetInputValueDataDefinition::getInputName).collect(toList()).toString());
+                        }
+                        Either<InputDefinition, RuntimeException> inputEither = findInputByName(inputs, getInput);
+                        if (inputEither.isRight()) {
+                            throw inputEither.right().value();
+                        } else {
+                            InputDefinition input = inputEither.left().value();
+                            getInput.setInputId(input.getUniqueId());
+                            getInputValues.add(getInput);
+                            GetInputValueDataDefinition getInputIndex = getInput.getGetInputIndex();
+                            if (getInputIndex != null) {
+                                Either<InputDefinition, RuntimeException> newInputEither = findInputByName(inputs, getInputIndex);
+                                if (inputEither.isRight()) {
+                                    throw newInputEither.right().value();
+                                } else {
+                                    InputDefinition newInput = newInputEither.left().value();
+                                    getInputIndex.setInputId(newInput.getUniqueId());
+                                }
+                                getInputValues.add(getInputIndex);
+                            }
+                        }
+                    }
+                    property.setGetInputValues(getInputValues);
+                }
+                instPropList.add(property);
+                // delete overriden property
+                currPropertiesMap.remove(property.getName());
+            }
+        }
+        // add rest of properties
+        if (!currPropertiesMap.isEmpty()) {
+            for (PropertyDefinition value : currPropertiesMap.values()) {
+                instPropList.add(new ComponentInstanceProperty(value));
+            }
+        }
+        instProperties.put(currentCompInstance.getUniqueId(), instPropList);
+        return componentsUtils.getResponseFormat(ActionStatus.OK);
+    }
+
+    // US740820 Relate RIs according to capability name
+    private CapabilityDefinition findAvailableCapabilityByTypeOrName(RequirementDefinition validReq, ComponentInstance currentCapCompInstance,
+                                                                     UploadReqInfo uploadReqInfo) {
+        if (null == uploadReqInfo.getCapabilityName() || validReq.getCapability()
+            .equals(uploadReqInfo.getCapabilityName())) {// get
+
+            // by
+
+            // capability
+
+            // type
+            return findAvailableCapability(validReq, currentCapCompInstance);
+        }
+        return findAvailableCapability(validReq, currentCapCompInstance, uploadReqInfo);
+    }
+
+    private CapabilityDefinition findAvailableCapability(RequirementDefinition validReq, ComponentInstance currentCapCompInstance,
+                                                         UploadReqInfo uploadReqInfo) {
+        CapabilityDefinition cap = null;
+        Map<String, List<CapabilityDefinition>> capMap = currentCapCompInstance.getCapabilities();
+        if (!capMap.containsKey(validReq.getCapability())) {
+            return null;
+        }
+        Optional<CapabilityDefinition> capByName = capMap.get(validReq.getCapability()).stream()
+            .filter(p -> p.getName().equals(uploadReqInfo.getCapabilityName())).findAny();
+        if (!capByName.isPresent()) {
+            return null;
+        }
+        cap = capByName.get();
+        if (isBoundedByOccurrences(cap)) {
+            String leftOccurrences = cap.getLeftOccurrences();
+            int left = Integer.parseInt(leftOccurrences);
+            if (left > 0) {
+                --left;
+                cap.setLeftOccurrences(String.valueOf(left));
+            }
+        }
+        return cap;
+    }
+
+    private CapabilityDefinition findAvailableCapability(RequirementDefinition validReq, ComponentInstance instance) {
+        Map<String, List<CapabilityDefinition>> capMap = instance.getCapabilities();
+        if (capMap.containsKey(validReq.getCapability())) {
+            List<CapabilityDefinition> capList = capMap.get(validReq.getCapability());
+            for (CapabilityDefinition cap : capList) {
+                if (isBoundedByOccurrences(cap)) {
+                    String leftOccurrences = cap.getLeftOccurrences() != null ? cap.getLeftOccurrences() : cap.getMaxOccurrences();
+                    int left = Integer.parseInt(leftOccurrences);
+                    if (left > 0) {
+                        --left;
+                        cap.setLeftOccurrences(String.valueOf(left));
+                        return cap;
+                    }
+                } else {
+                    return cap;
+                }
+            }
+        }
+        return null;
+    }
+
+    private boolean isBoundedByOccurrences(CapabilityDefinition cap) {
+        return cap.getMaxOccurrences() != null && !cap.getMaxOccurrences().equals(CapabilityDataDefinition.MAX_OCCURRENCES);
+    }
+
+    private Either<RequirementDefinition, ResponseFormat> findAviableRequiremen(String regName, String yamlName,
+                                                                                UploadComponentInstanceInfo uploadComponentInstanceInfo,
+                                                                                ComponentInstance currentCompInstance, String capName) {
+        Map<String, List<RequirementDefinition>> comInstRegDefMap = currentCompInstance.getRequirements();
+        List<RequirementDefinition> list = comInstRegDefMap.get(capName);
+        RequirementDefinition validRegDef = null;
+        if (list == null) {
+            for (Entry<String, List<RequirementDefinition>> entry : comInstRegDefMap.entrySet()) {
+                for (RequirementDefinition reqDef : entry.getValue()) {
+                    if (reqDef.getName().equals(regName)) {
+                        if (reqDef.getMaxOccurrences() != null && !reqDef.getMaxOccurrences().equals(RequirementDataDefinition.MAX_OCCURRENCES)) {
+                            String leftOccurrences = reqDef.getLeftOccurrences();
+                            if (leftOccurrences == null) {
+                                leftOccurrences = reqDef.getMaxOccurrences();
+                            }
+                            int left = Integer.parseInt(leftOccurrences);
+                            if (left > 0) {
+                                --left;
+                                reqDef.setLeftOccurrences(String.valueOf(left));
+                                validRegDef = reqDef;
+                                break;
+                            } else {
+                                continue;
+                            }
+                        } else {
+                            validRegDef = reqDef;
+                            break;
+                        }
+                    }
+                }
+                if (validRegDef != null) {
+                    break;
+                }
+            }
+        } else {
+            for (RequirementDefinition reqDef : list) {
+                if (reqDef.getName().equals(regName)) {
+                    if (reqDef.getMaxOccurrences() != null && !reqDef.getMaxOccurrences().equals(RequirementDataDefinition.MAX_OCCURRENCES)) {
+                        String leftOccurrences = reqDef.getLeftOccurrences();
+                        if (leftOccurrences == null) {
+                            leftOccurrences = reqDef.getMaxOccurrences();
+                        }
+                        int left = Integer.parseInt(leftOccurrences);
+                        if (left > 0) {
+                            --left;
+                            reqDef.setLeftOccurrences(String.valueOf(left));
+                            validRegDef = reqDef;
+                            break;
+                        } else {
+                            continue;
+                        }
+                    } else {
+                        validRegDef = reqDef;
+                        break;
+                    }
+                }
+            }
+        }
+        if (validRegDef == null) {
+            ResponseFormat responseFormat = componentsUtils
+                .getResponseFormat(ActionStatus.INVALID_NODE_TEMPLATE, yamlName, uploadComponentInstanceInfo.getName(),
+                    uploadComponentInstanceInfo.getType());
+            return Either.right(responseFormat);
+        }
+        return Either.left(validRegDef);
+    }
+
+    private Resource createResourceInstances(String yamlName, Resource resource, Resource oldResource,
+                                             Map<String, UploadComponentInstanceInfo> uploadResInstancesMap, Map<String, Resource> nodeNamespaceMap,
+                                             Map<String, Resource> existingNodeTypesByResourceNames) {
+        Either<Resource, ResponseFormat> eitherResource;
+        log.debug("createResourceInstances is {} - going to create resource instanse from CSAR", yamlName);
+        if (isEmpty(uploadResInstancesMap) && resource.getResourceType() != ResourceTypeEnum.PNF) { // PNF can have no resource instances
+            ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.NOT_TOPOLOGY_TOSCA_TEMPLATE);
+            throw new ByResponseFormatComponentException(responseFormat);
+        }
+        if (MapUtils.isNotEmpty(nodeNamespaceMap)) {
+            nodeNamespaceMap.forEach((k, v) -> existingNodeTypesByResourceNames.put(v.getToscaResourceName(), v));
+        }
+        Map<ComponentInstance, Resource> resourcesInstancesMap = new HashMap<>();
+        uploadResInstancesMap.values().forEach(
+            i -> createAndAddResourceInstance(i, yamlName, resource, nodeNamespaceMap, existingNodeTypesByResourceNames, resourcesInstancesMap));
+        if (oldResource != null && oldResource.getResourceType() != ResourceTypeEnum.CVFC && oldResource.getComponentInstances() != null) {
+            Map<String, Resource> existingNodeTypesByUids = existingNodeTypesByResourceNames.values().stream()
+                .collect(toMap(Resource::getUniqueId, r -> r));
+            oldResource.getComponentInstances().stream().filter(i -> !i.isCreatedFromCsar())
+                .forEach(uiInst -> resourcesInstancesMap.put(uiInst, getOriginResource(existingNodeTypesByUids, uiInst)));
+        }
+        if (isNotEmpty(resourcesInstancesMap)) {
+            try {
+                toscaOperationFacade.associateComponentInstancesToComponent(resource, resourcesInstancesMap, false, oldResource != null);
+            } catch (StorageException exp) {
+                if (exp.getStorageOperationStatus() != null && exp.getStorageOperationStatus() != StorageOperationStatus.OK) {
+                    log.debug("Failed to add component instances to container component {}", resource.getName());
+                    ResponseFormat responseFormat = componentsUtils
+                        .getResponseFormat(componentsUtils.convertFromStorageResponse(exp.getStorageOperationStatus()));
+                    eitherResource = Either.right(responseFormat);
+                    throw new ByResponseFormatComponentException(eitherResource.right().value());
+                }
+            }
+        }
+        if (CollectionUtils.isEmpty(resource.getComponentInstances()) &&
+            resource.getResourceType() != ResourceTypeEnum.PNF) { // PNF can have no resource instances
+            log.debug("Error when create resource instance from csar. ComponentInstances list empty");
+            BeEcompErrorManager.getInstance().logBeDaoSystemError("Error when create resource instance from csar. ComponentInstances list empty");
+            throw new ByResponseFormatComponentException(componentsUtils.getResponseFormat(ActionStatus.NOT_TOPOLOGY_TOSCA_TEMPLATE));
+        }
+        return resource;
+    }
+
+    private void createAndAddResourceInstance(UploadComponentInstanceInfo uploadComponentInstanceInfo, String yamlName, Resource resource,
+                                              Map<String, Resource> nodeNamespaceMap, Map<String, Resource> existingnodeTypeMap,
+                                              Map<ComponentInstance, Resource> resourcesInstancesMap) {
+        Either<Resource, ResponseFormat> eitherResource;
+        log.debug("*************Going to create  resource instances {}", yamlName);
+        // updating type if the type is node type name - we need to take the
+
+        // updated name
+        log.debug("*************Going to create  resource instances {}", uploadComponentInstanceInfo.getName());
+        if (nodeNamespaceMap.containsKey(uploadComponentInstanceInfo.getType())) {
+            uploadComponentInstanceInfo.setType(nodeNamespaceMap.get(uploadComponentInstanceInfo.getType()).getToscaResourceName());
+        }
+        Resource refResource = validateResourceInstanceBeforeCreate(yamlName, uploadComponentInstanceInfo, existingnodeTypeMap, resource);
+        ComponentInstance componentInstance = new ComponentInstance();
+        componentInstance.setComponentUid(refResource.getUniqueId());
+        Collection<String> directives = uploadComponentInstanceInfo.getDirectives();
+        if (directives != null && !directives.isEmpty()) {
+            componentInstance.setDirectives(new ArrayList<>(directives));
+        }
+        UploadNodeFilterInfo uploadNodeFilterInfo = uploadComponentInstanceInfo.getUploadNodeFilterInfo();
+        if (uploadNodeFilterInfo != null) {
+            componentInstance
+                .setNodeFilter(new CINodeFilterUtils().getNodeFilterDataDefinition(uploadNodeFilterInfo, componentInstance.getUniqueId()));
+        }
+        ComponentTypeEnum containerComponentType = resource.getComponentType();
+        NodeTypeEnum containerNodeType = containerComponentType.getNodeType();
+        if (containerNodeType == NodeTypeEnum.Resource && isNotEmpty(uploadComponentInstanceInfo.getCapabilities()) && isNotEmpty(
+            refResource.getCapabilities())) {
+            setCapabilityNamesTypes(refResource.getCapabilities(), uploadComponentInstanceInfo.getCapabilities());
+            Map<String, List<CapabilityDefinition>> validComponentInstanceCapabilities = getValidComponentInstanceCapabilities(
+                refResource.getUniqueId(), refResource.getCapabilities(), uploadComponentInstanceInfo.getCapabilities());
+            componentInstance.setCapabilities(validComponentInstanceCapabilities);
+        }
+        if (isNotEmpty(uploadComponentInstanceInfo.getArtifacts())) {
+            Map<String, Map<String, UploadArtifactInfo>> artifacts = uploadComponentInstanceInfo.getArtifacts();
+            Map<String, ToscaArtifactDataDefinition> toscaArtifacts = new HashMap<>();
+            Map<String, Map<String, UploadArtifactInfo>> arts = artifacts.entrySet().stream()
+                .filter(e -> e.getKey().contains(TypeUtils.ToscaTagNamesEnum.ARTIFACTS.getElementName()))
+                .collect(Collectors.toMap(e -> e.getKey(), e -> e.getValue()));
+            Map<String, UploadArtifactInfo> artifact = arts.get(TypeUtils.ToscaTagNamesEnum.ARTIFACTS.getElementName());
+            for (Map.Entry<String, UploadArtifactInfo> entry : artifact.entrySet()) {
+                ToscaArtifactDataDefinition to = new ToscaArtifactDataDefinition();
+                to.setFile(entry.getValue().getFile());
+                to.setType(entry.getValue().getType());
+                toscaArtifacts.put(entry.getKey(), to);
+            }
+            componentInstance.setToscaArtifacts(toscaArtifacts);
+        }
+        if (!existingnodeTypeMap.containsKey(uploadComponentInstanceInfo.getType())) {
+            log.debug("createResourceInstances - not found lates version for resource instance with name {} and type ",
+                uploadComponentInstanceInfo.getName(), uploadComponentInstanceInfo.getType());
+            throw new ByActionStatusComponentException(ActionStatus.INVALID_NODE_TEMPLATE, yamlName, uploadComponentInstanceInfo.getName(),
+                uploadComponentInstanceInfo.getType());
+        }
+        Resource origResource = existingnodeTypeMap.get(uploadComponentInstanceInfo.getType());
+        componentInstance.setName(uploadComponentInstanceInfo.getName());
+        componentInstance.setIcon(origResource.getIcon());
+        componentInstance.setCreatedFrom(CreatedFrom.CSAR);
+        resourcesInstancesMap.put(componentInstance, origResource);
+    }
+
+    private void setCapabilityNamesTypes(Map<String, List<CapabilityDefinition>> originCapabilities,
+                                         Map<String, List<UploadCapInfo>> uploadedCapabilities) {
+        for (Entry<String, List<UploadCapInfo>> currEntry : uploadedCapabilities.entrySet()) {
+            if (originCapabilities.containsKey(currEntry.getKey())) {
+                currEntry.getValue().stream().forEach(cap -> cap.setType(currEntry.getKey()));
+            }
+        }
+        for (Map.Entry<String, List<CapabilityDefinition>> capabilities : originCapabilities.entrySet()) {
+            capabilities.getValue().stream().forEach(cap -> {
+                if (uploadedCapabilities.containsKey(cap.getName())) {
+                    uploadedCapabilities.get(cap.getName()).stream().forEach(c -> {
+                        c.setName(cap.getName());
+                        c.setType(cap.getType());
+                    });
+                }
+            });
+        }
+    }
+
+    private Resource validateResourceInstanceBeforeCreate(String yamlName, UploadComponentInstanceInfo uploadComponentInstanceInfo,
+                                                          Map<String, Resource> nodeNamespaceMap, Resource resource) {
+        log.debug("validateResourceInstanceBeforeCreate - going to validate resource instance with name {} and type {} before create",
+            uploadComponentInstanceInfo.getName(), uploadComponentInstanceInfo.getType());
+        Resource refResource;
+        if (nodeNamespaceMap.containsKey(uploadComponentInstanceInfo.getType())) {
+            refResource = nodeNamespaceMap.get(uploadComponentInstanceInfo.getType());
+        } else {
+            Either<Resource, StorageOperationStatus> findResourceEither = toscaOperationFacade
+                .getByToscaResourceNameMatchingVendorRelease(uploadComponentInstanceInfo.getType(),
+                    ((ResourceMetadataDataDefinition) resource.getComponentMetadataDefinition().getMetadataDataDefinition()).getVendorRelease());
+            if (findResourceEither.isRight()) {
+                log.debug("validateResourceInstanceBeforeCreate - not found latest version for resource instance with name {} and type {}",
+                    uploadComponentInstanceInfo.getName(), uploadComponentInstanceInfo.getType());
+                throw new ByActionStatusComponentException(componentsUtils.convertFromStorageResponse(findResourceEither.right().value()));
+            }
+            refResource = findResourceEither.left().value();
+            nodeNamespaceMap.put(refResource.getToscaResourceName(), refResource);
+        }
+        String componentState = refResource.getComponentMetadataDefinition().getMetadataDataDefinition().getState();
+        if (componentState.equals(LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT.name())) {
+            log.debug(
+                "validateResourceInstanceBeforeCreate - component instance of component {} can not be created because the component is in an illegal state {}.",
+                refResource.getName(), componentState);
+            throw new ByActionStatusComponentException(ActionStatus.ILLEGAL_COMPONENT_STATE, refResource.getComponentType().getValue(),
+                refResource.getName(), componentState);
+        }
+        if (!ModelConverter.isAtomicComponent(refResource) && refResource.getResourceType() != ResourceTypeEnum.CVFC) {
+            log.debug("validateResourceInstanceBeforeCreate -  ref resource type is  ", refResource.getResourceType());
+            throw new ByActionStatusComponentException(ActionStatus.INVALID_NODE_TEMPLATE, yamlName, uploadComponentInstanceInfo.getName(),
+                uploadComponentInstanceInfo.getType());
+        }
+        return refResource;
+    }
+
+    public Resource propagateStateToCertified(User user, Resource resource, LifecycleChangeInfoWithAction lifecycleChangeInfo, boolean inTransaction,
+                                              boolean needLock, boolean forceCertificationAllowed) {
+        boolean failed = false;
+        try {
+            if (resource.getLifecycleState() != LifecycleStateEnum.CERTIFIED && forceCertificationAllowed && lifecycleBusinessLogic
+                .isFirstCertification(resource.getVersion())) {
+                nodeForceCertification(resource, user, lifecycleChangeInfo, inTransaction, needLock);
+            }
+            if (resource.getLifecycleState() == LifecycleStateEnum.CERTIFIED) {
+                Either<ArtifactDefinition, Operation> eitherPopulated = populateToscaArtifacts(resource, user, false, inTransaction, needLock, false);
+                return resource;
+            }
+            return nodeFullCertification(resource.getUniqueId(), user, lifecycleChangeInfo, inTransaction, needLock);
+        } catch (ComponentException e) {
+            failed = true;
+            log.debug("The exception has occurred upon certification of resource {}. ", resource.getName(), e);
+            throw e;
+        } finally {
+            if (failed) {
+                BeEcompErrorManager.getInstance().logBeSystemError("Change LifecycleState - Certify");
+                if (!inTransaction) {
+                    janusGraphDao.rollback();
+                }
+            } else if (!inTransaction) {
+                janusGraphDao.commit();
+            }
+        }
+    }
+
+    private Resource nodeFullCertification(String uniqueId, User user, LifecycleChangeInfoWithAction lifecycleChangeInfo, boolean inTransaction,
+                                           boolean needLock) {
+        Either<Resource, ResponseFormat> resourceResponse = lifecycleBusinessLogic
+            .changeState(uniqueId, user, LifeCycleTransitionEnum.CERTIFY, lifecycleChangeInfo, inTransaction, needLock);
+        if (resourceResponse.isRight()) {
+            throw new ByResponseFormatComponentException(resourceResponse.right().value());
+        }
+        return resourceResponse.left().value();
+    }
+
+    private Resource nodeForceCertification(Resource resource, User user, LifecycleChangeInfoWithAction lifecycleChangeInfo, boolean inTransaction,
+                                            boolean needLock) {
+        return lifecycleBusinessLogic.forceResourceCertification(resource, user, lifecycleChangeInfo, inTransaction, needLock);
+    }
+
+    public ImmutablePair<Resource, ActionStatus> createOrUpdateResourceByImport(final Resource resource, final User user, final boolean isNormative,
+                                                                                final boolean isInTransaction, final boolean needLock,
+                                                                                final CsarInfo csarInfo, final String nodeName,
+                                                                                final boolean isNested) {
+        ImmutablePair<Resource, ActionStatus> result = null;
+        // check if resource already exists (search by tosca name = type)
+        final boolean isNestedResource = isNestedResourceUpdate(csarInfo, nodeName);
+        final Either<Resource, StorageOperationStatus> latestByToscaName = toscaOperationFacade
+            .getLatestByToscaResourceName(resource.getToscaResourceName());
+        if (latestByToscaName.isLeft()) {
+            Resource foundResource = latestByToscaName.left().value();
+            // we don't allow updating names of top level types
+            if (!isNestedResource && !StringUtils.equals(resource.getName(), foundResource.getName())) {
+                BeEcompErrorManager.getInstance()
+                    .logBeComponentMissingError("Create / Update resource by import", ComponentTypeEnum.RESOURCE.getValue(), resource.getName());
+                log.debug("resource already exist new name={} old name={} same type={}", resource.getName(), foundResource.getName(),
+                    resource.getToscaResourceName());
+                final ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.RESOURCE_ALREADY_EXISTS);
+                componentsUtils.auditResource(responseFormat, user, resource, AuditingActionEnum.IMPORT_RESOURCE);
+                throwComponentException(responseFormat);
+            }
+            result = updateExistingResourceByImport(resource, foundResource, user, isNormative, needLock, isNested);
+        } else if (isNotFound(latestByToscaName)) {
+            if (isNestedResource) {
+                result = createOrUpdateNestedResource(resource, user, isNormative, isInTransaction, needLock, csarInfo, isNested, nodeName);
+            } else {
+                result = createResourceByImport(resource, user, isNormative, isInTransaction, csarInfo);
+            }
+        } else {
+            StorageOperationStatus status = latestByToscaName.right().value();
+            log.debug("failed to get latest version of resource {}. status={}", resource.getName(), status);
+            ResponseFormat responseFormat = componentsUtils
+                .getResponseFormatByResource(componentsUtils.convertFromStorageResponse(latestByToscaName.right().value()), resource);
+            componentsUtils.auditResource(responseFormat, user, resource, AuditingActionEnum.IMPORT_RESOURCE);
+            throwComponentException(responseFormat);
+        }
+        return result;
+    }
+
+    private boolean isNestedResourceUpdate(CsarInfo csarInfo, String nodeName) {
+        return csarInfo != null && csarInfo.isUpdate() && nodeName != null;
+    }
+
+    private ImmutablePair<Resource, ActionStatus> createOrUpdateNestedResource(final Resource resource, final User user, final boolean isNormative,
+                                                                               final boolean isInTransaction, final boolean needLock,
+                                                                               final CsarInfo csarInfo, final boolean isNested,
+                                                                               final String nodeName) {
+        final Either<Component, StorageOperationStatus> latestByToscaName = toscaOperationFacade.getLatestByToscaResourceName(
+            buildNestedToscaResourceName(resource.getResourceType().name(), csarInfo.getVfResourceName(), nodeName).getRight());
+        if (latestByToscaName.isLeft()) {
+            final Resource nestedResource = (Resource) latestByToscaName.left().value();
+            log.debug(VALIDATE_DERIVED_BEFORE_UPDATE);
+            final Either<Boolean, ResponseFormat> eitherValidation = validateNestedDerivedFromDuringUpdate(nestedResource, resource,
+                ValidationUtils.hasBeenCertified(nestedResource.getVersion()));
+            if (eitherValidation.isRight()) {
+                return createResourceByImport(resource, user, isNormative, isInTransaction, csarInfo);
+            }
+            return updateExistingResourceByImport(resource, nestedResource, user, isNormative, needLock, isNested);
+        } else {
+            return createResourceByImport(resource, user, isNormative, isInTransaction, csarInfo);
+        }
+    }
+
+    private boolean isNotFound(Either<Resource, StorageOperationStatus> getResourceEither) {
+        return getResourceEither.isRight() && getResourceEither.right().value() == StorageOperationStatus.NOT_FOUND;
+    }
+
+    private ImmutablePair<Resource, ActionStatus> createResourceByImport(Resource resource, User user, boolean isNormative, boolean isInTransaction,
+                                                                         CsarInfo csarInfo) {
+        log.debug("resource with name {} does not exist. create new resource", resource.getName());
+        validateResourceBeforeCreate(resource, user, AuditingActionEnum.IMPORT_RESOURCE, isInTransaction, csarInfo);
+        final Resource createResourceByDao = createResourceByDao(resource, user, AuditingActionEnum.IMPORT_RESOURCE, isNormative, isInTransaction);
+        Resource createdResource = updateCatalog(createResourceByDao, ChangeTypeEnum.LIFECYCLE).left().map(r -> (Resource) r).left().value();
+        ImmutablePair<Resource, ActionStatus> resourcePair = new ImmutablePair<>(createdResource, ActionStatus.CREATED);
+        ASDCKpiApi.countImportResourcesKPI();
+        return resourcePair;
+    }
+
+    public boolean isResourceExist(String resourceName) {
+        Either<Resource, StorageOperationStatus> latestByName = toscaOperationFacade.getLatestByName(resourceName);
+        return latestByName.isLeft();
+    }
+
+    private ImmutablePair<Resource, ActionStatus> updateExistingResourceByImport(Resource newResource, Resource oldResource, User user,
+                                                                                 boolean inTransaction, boolean needLock, boolean isNested) {
+        String lockedResourceId = oldResource.getUniqueId();
+        log.debug("found resource: name={}, id={}, version={}, state={}", oldResource.getName(), lockedResourceId, oldResource.getVersion(),
+            oldResource.getLifecycleState());
+        ImmutablePair<Resource, ActionStatus> resourcePair = null;
+        try {
+            lockComponent(lockedResourceId, oldResource, needLock, "Update Resource by Import");
+            oldResource = prepareResourceForUpdate(oldResource, newResource, user, inTransaction, false);
+            mergeOldResourceMetadataWithNew(oldResource, newResource);
+            validateResourceFieldsBeforeUpdate(oldResource, newResource, inTransaction, isNested);
+            validateCapabilityTypesCreate(user, getCapabilityTypeOperation(), newResource, AuditingActionEnum.IMPORT_RESOURCE, inTransaction);
+            // contact info normalization
+            newResource.setContactId(newResource.getContactId().toLowerCase());
+            PropertyConstraintsUtils.validatePropertiesConstraints(newResource, oldResource);
+            // non-updatable fields
+            newResource.setCreatorUserId(user.getUserId());
+            newResource.setCreatorFullName(user.getFullName());
+            newResource.setLastUpdaterUserId(user.getUserId());
+            newResource.setLastUpdaterFullName(user.getFullName());
+            newResource.setUniqueId(oldResource.getUniqueId());
+            newResource.setVersion(oldResource.getVersion());
+            newResource.setInvariantUUID(oldResource.getInvariantUUID());
+            newResource.setLifecycleState(oldResource.getLifecycleState());
+            newResource.setUUID(oldResource.getUUID());
+            newResource.setNormalizedName(oldResource.getNormalizedName());
+            newResource.setSystemName(oldResource.getSystemName());
+            if (oldResource.getCsarUUID() != null) {
+                newResource.setCsarUUID(oldResource.getCsarUUID());
+            }
+            if (oldResource.getImportedToscaChecksum() != null) {
+                newResource.setImportedToscaChecksum(oldResource.getImportedToscaChecksum());
+            }
+            newResource.setAbstract(oldResource.isAbstract());
+            if (CollectionUtils.isEmpty(newResource.getDerivedFrom())) {
+                newResource.setDerivedFrom(oldResource.getDerivedFrom());
+            }
+            if (CollectionUtils.isEmpty(newResource.getDataTypes())) {
+                newResource.setDataTypes(oldResource.getDataTypes());
+            }
+            if (StringUtils.isEmpty(newResource.getDerivedFromGenericType())) {
+                newResource.setDerivedFromGenericType(oldResource.getDerivedFromGenericType());
+            }
+            if (StringUtils.isEmpty(newResource.getDerivedFromGenericVersion())) {
+                newResource.setDerivedFromGenericVersion(oldResource.getDerivedFromGenericVersion());
+            }
+            // add for new)
+
+            // created without tosca artifacts - add the placeholders
+            if (MapUtils.isEmpty(newResource.getToscaArtifacts())) {
+                setToscaArtifactsPlaceHolders(newResource, user);
+            }
+            if (MapUtils.isEmpty(newResource.getInterfaces())) {
+                newResource.setInterfaces(oldResource.getInterfaces());
+            }
+            if (CollectionUtils.isEmpty(newResource.getAttributes())) {
+                newResource.setAttributes(oldResource.getAttributes());
+            }
+            if (CollectionUtils.isEmpty(newResource.getProperties())) {
+                newResource.setProperties(oldResource.getProperties());
+            }
+            Either<Resource, StorageOperationStatus> overrideResource = toscaOperationFacade.overrideComponent(newResource, oldResource);
+            if (overrideResource.isRight()) {
+                ResponseFormat responseFormat = componentsUtils
+                    .getResponseFormatByResource(componentsUtils.convertFromStorageResponse(overrideResource.right().value()), newResource);
+                componentsUtils.auditResource(responseFormat, user, newResource, AuditingActionEnum.IMPORT_RESOURCE);
+                throwComponentException(responseFormat);
+            }
+            updateCatalog(overrideResource.left().value(), ChangeTypeEnum.LIFECYCLE);
+            log.debug("Resource updated successfully!!!");
+            ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.OK);
+            componentsUtils.auditResource(responseFormat, user, newResource, AuditingActionEnum.IMPORT_RESOURCE,
+                ResourceVersionInfo.newBuilder().state(oldResource.getLifecycleState().name()).version(oldResource.getVersion()).build());
+            resourcePair = new ImmutablePair<>(overrideResource.left().value(), ActionStatus.OK);
+            return resourcePair;
+        } finally {
+            if (resourcePair == null) {
+                BeEcompErrorManager.getInstance().logBeSystemError("Change LifecycleState - Certify");
+                janusGraphDao.rollback();
+            } else if (!inTransaction) {
+                janusGraphDao.commit();
+            }
+            if (needLock) {
+                log.debug("unlock resource {}", lockedResourceId);
+                graphLockOperation.unlockComponent(lockedResourceId, NodeTypeEnum.Resource);
+            }
+        }
+    }
+
+    /**
+     * Merge old resource with new. Keep old category and vendor name without change
+     *
+     * @param oldResource
+     * @param newResource
+     */
+    private void mergeOldResourceMetadataWithNew(Resource oldResource, Resource newResource) {
+        // keep old category and vendor name without change
+
+        // merge the rest of the resource metadata
+        if (newResource.getTags() == null || newResource.getTags().isEmpty()) {
+            newResource.setTags(oldResource.getTags());
+        }
+        if (newResource.getDescription() == null) {
+            newResource.setDescription(oldResource.getDescription());
+        }
+        if (newResource.getVendorRelease() == null) {
+            newResource.setVendorRelease(oldResource.getVendorRelease());
+        }
+        if (newResource.getResourceVendorModelNumber() == null) {
+            newResource.setResourceVendorModelNumber(oldResource.getResourceVendorModelNumber());
+        }
+        if (newResource.getContactId() == null) {
+            newResource.setContactId(oldResource.getContactId());
+        }
+        newResource.setCategories(oldResource.getCategories());
+        if (newResource.getVendorName() == null) {
+            newResource.setVendorName(oldResource.getVendorName());
+        }
+        List<GroupDefinition> oldForUpdate = oldResource.getGroups();
+        if (CollectionUtils.isNotEmpty(oldForUpdate)) {
+            List<GroupDefinition> groupForUpdate = oldForUpdate.stream().map(group -> new GroupDefinition(group)).collect(Collectors.toList());
+            groupForUpdate.stream().filter(group -> group.isVspOriginated()).forEach(group -> group.setName(group.getInvariantName()));
+            newResource.setGroups(groupForUpdate);
+        }
+        if (newResource.getResourceType().isAtomicType() && !newResource.getName().equals("Root")
+            && newResource.getResourceType() != ResourceTypeEnum.CVFC) {
+            ResourceTypeEnum updatedResourceType = newResource.getResourceType();
+            Component derivedFromResource = getParentComponent(newResource);
+            if (derivedFromResource.getComponentType() == ComponentTypeEnum.RESOURCE) {
+                Resource parentResource = (Resource) derivedFromResource;
+                if (!(parentResource.isAbstract() && (ResourceTypeEnum.VFC == parentResource.getResourceType()
+                    || ResourceTypeEnum.ABSTRACT == parentResource.getResourceType())) && parentResource.getResourceType() != updatedResourceType
+                    && oldResource.getResourceType() != updatedResourceType) {
+                    BeEcompErrorManager.getInstance().logInternalDataError("mergeOldResourceMetadataWithNew",
+                        "resource type of the resource does not match to derived from resource type", ErrorSeverity.ERROR);
+                    log.debug(
+                        "#mergeOldResourceMetadataWithNew - resource type {} of the resource {} does not match to derived from resource type {}",
+                        newResource.getResourceType(), newResource.getToscaResourceName(), parentResource.getResourceType());
+                    throw new ByActionStatusComponentException(ActionStatus.INVALID_RESOURCE_TYPE);
+                }
+            }
+        }
+    }
+
+    private Component getParentComponent(Resource newResource) {
+        String toscaResourceNameDerivedFrom = newResource.getDerivedFrom().get(0);
+        Either<Component, StorageOperationStatus> latestByToscaResourceName = toscaOperationFacade
+            .getLatestByToscaResourceName(toscaResourceNameDerivedFrom);
+        if (latestByToscaResourceName.isRight()) {
+            BeEcompErrorManager.getInstance()
+                .logInternalDataError("mergeOldResourceMetadataWithNew", "derived from resource not found", ErrorSeverity.ERROR);
+            log.debug("#mergeOldResourceMetadataWithNew - derived from resource {} not found", toscaResourceNameDerivedFrom);
+            throw new ByActionStatusComponentException(ActionStatus.RESOURCE_NOT_FOUND, toscaResourceNameDerivedFrom);
+        }
+        return latestByToscaResourceName.left().value();
+    }
+
+    private Resource prepareResourceForUpdate(Resource oldResource, Resource newResource, User user, boolean inTransaction, boolean needLock) {
+        if (!ComponentValidationUtils.canWorkOnResource(oldResource, user.getUserId())) {
+            // checkout
+            return lifecycleBusinessLogic
+                .changeState(oldResource.getUniqueId(), user, LifeCycleTransitionEnum.CHECKOUT, new LifecycleChangeInfoWithAction("update by import"),
+                    inTransaction, needLock).left().on(response -> failOnChangeState(response, user, oldResource, newResource));
+        }
+        return oldResource;
+    }
+
+    private Resource failOnChangeState(ResponseFormat response, User user, Resource oldResource, Resource newResource) {
+        log.info("resource {} cannot be updated. reason={}", oldResource.getUniqueId(), response.getFormattedMessage());
+        componentsUtils.auditResource(response, user, newResource, AuditingActionEnum.IMPORT_RESOURCE,
+            ResourceVersionInfo.newBuilder().state(oldResource.getLifecycleState().name()).version(oldResource.getVersion()).build());
+        throw new ByResponseFormatComponentException(response);
+    }
+
+    public Resource validateResourceBeforeCreate(Resource resource, User user, AuditingActionEnum actionEnum, boolean inTransaction,
+                                                 CsarInfo csarInfo) {
+        validateResourceFieldsBeforeCreate(user, resource, actionEnum, inTransaction);
+        validateCapabilityTypesCreate(user, getCapabilityTypeOperation(), resource, actionEnum, inTransaction);
+        validateLifecycleTypesCreate(user, resource, actionEnum);
+        validateResourceType(user, resource, actionEnum);
+        resource.setCreatorUserId(user.getUserId());
+        resource.setCreatorFullName(user.getFirstName() + " " + user.getLastName());
+        resource.setContactId(resource.getContactId().toLowerCase());
+        if (StringUtils.isEmpty(resource.getToscaResourceName()) && !ModelConverter.isAtomicComponent(resource)) {
+            String resourceSystemName;
+            if (csarInfo != null && StringUtils.isNotEmpty(csarInfo.getVfResourceName())) {
+                resourceSystemName = ValidationUtils.convertToSystemName(csarInfo.getVfResourceName());
+            } else {
+                resourceSystemName = resource.getSystemName();
+            }
+            resource
+                .setToscaResourceName(CommonBeUtils.generateToscaResourceName(resource.getResourceType().name().toLowerCase(), resourceSystemName));
+        }
+        // Generate invariant UUID - must be here and not in operation since it
+
+        // should stay constant during clone
+
+        // TODO
+        String invariantUUID = UniqueIdBuilder.buildInvariantUUID();
+        resource.setInvariantUUID(invariantUUID);
+        return resource;
+    }
+
+    private Either<Boolean, ResponseFormat> validateResourceType(User user, Resource resource, AuditingActionEnum actionEnum) {
+        Either<Boolean, ResponseFormat> eitherResult = Either.left(true);
+        if (resource.getResourceType() == null) {
+            log.debug("Invalid resource type for resource");
+            ResponseFormat errorResponse = componentsUtils.getResponseFormat(ActionStatus.INVALID_CONTENT);
+            eitherResult = Either.right(errorResponse);
+            componentsUtils.auditResource(errorResponse, user, resource, actionEnum);
+        }
+        return eitherResult;
+    }
+
+    private Either<Boolean, ResponseFormat> validateLifecycleTypesCreate(User user, Resource resource, AuditingActionEnum actionEnum) {
+        Either<Boolean, ResponseFormat> eitherResult = Either.left(true);
+        if (resource.getInterfaces() != null && resource.getInterfaces().size() > 0) {
+            log.debug("validate interface lifecycle Types Exist");
+            Iterator<InterfaceDefinition> intItr = resource.getInterfaces().values().iterator();
+            while (intItr.hasNext() && eitherResult.isLeft()) {
+                InterfaceDefinition interfaceDefinition = intItr.next();
+                String intType = interfaceDefinition.getUniqueId();
+                Either<InterfaceDefinition, StorageOperationStatus> eitherCapTypeFound = interfaceTypeOperation.getInterface(intType);
+                if (eitherCapTypeFound.isRight()) {
+                    if (eitherCapTypeFound.right().value() == StorageOperationStatus.NOT_FOUND) {
+                        BeEcompErrorManager.getInstance()
+                            .logBeGraphObjectMissingError("Create Resource - validateLifecycleTypesCreate", "Interface", intType);
+                        log.debug("Lifecycle Type: {} is required by resource: {} but does not exist in the DB", intType, resource.getName());
+                        BeEcompErrorManager.getInstance().logBeDaoSystemError("Create Resource - validateLifecycleTypesCreate");
+                        log.debug("request to data model failed with error: {}", eitherCapTypeFound.right().value().name());
+                    }
+                    ResponseFormat errorResponse = componentsUtils.getResponseFormat(ActionStatus.MISSING_LIFECYCLE_TYPE, intType);
+                    eitherResult = Either.right(errorResponse);
+                    componentsUtils.auditResource(errorResponse, user, resource, actionEnum);
+                }
+            }
+        }
+        return eitherResult;
+    }
+
+    private Either<Boolean, ResponseFormat> validateCapabilityTypesCreate(User user, ICapabilityTypeOperation capabilityTypeOperation,
+                                                                          Resource resource, AuditingActionEnum actionEnum, boolean inTransaction) {
+        Either<Boolean, ResponseFormat> eitherResult = Either.left(true);
+        if (resource.getCapabilities() != null && resource.getCapabilities().size() > 0) {
+            log.debug("validate capability Types Exist - capabilities section");
+            for (Entry<String, List<CapabilityDefinition>> typeEntry : resource.getCapabilities().entrySet()) {
+                eitherResult = validateCapabilityTypeExists(user, capabilityTypeOperation, resource, actionEnum, eitherResult, typeEntry,
+                    inTransaction);
+                if (eitherResult.isRight()) {
+                    return Either.right(eitherResult.right().value());
+                }
+            }
+        }
+        if (resource.getRequirements() != null && resource.getRequirements().size() > 0) {
+            log.debug("validate capability Types Exist - requirements section");
+            for (String type : resource.getRequirements().keySet()) {
+                eitherResult = validateCapabilityTypeExists(user, capabilityTypeOperation, resource, resource.getRequirements().get(type), actionEnum,
+                    eitherResult, type, inTransaction);
+                if (eitherResult.isRight()) {
+                    return Either.right(eitherResult.right().value());
+                }
+            }
+        }
+        return eitherResult;
+    }
+
+    // @param typeObject- the object to which the validation is done
+    private Either<Boolean, ResponseFormat> validateCapabilityTypeExists(User user, ICapabilityTypeOperation capabilityTypeOperation,
+                                                                         Resource resource, List<?> validationObjects, AuditingActionEnum actionEnum,
+                                                                         Either<Boolean, ResponseFormat> eitherResult, String type,
+                                                                         boolean inTransaction) {
+        Either<CapabilityTypeDefinition, StorageOperationStatus> eitherCapTypeFound = capabilityTypeOperation.getCapabilityType(type, inTransaction);
+        if (eitherCapTypeFound.isRight()) {
+            if (eitherCapTypeFound.right().value() == StorageOperationStatus.NOT_FOUND) {
+                BeEcompErrorManager.getInstance().logBeGraphObjectMissingError(CREATE_RESOURCE_VALIDATE_CAPABILITY_TYPES, "Capability Type", type);
+                log.debug("Capability Type: {} is required by resource: {} but does not exist in the DB", type, resource.getName());
+                BeEcompErrorManager.getInstance().logBeDaoSystemError(CREATE_RESOURCE_VALIDATE_CAPABILITY_TYPES);
+            }
+            log.debug("Trying to get capability type {} failed with error: {}", type, eitherCapTypeFound.right().value().name());
+            ResponseFormat errorResponse = null;
+            if (type != null) {
+                errorResponse = componentsUtils.getResponseFormat(ActionStatus.MISSING_CAPABILITY_TYPE, type);
+            } else {
+                errorResponse = componentsUtils.getResponseFormatByElement(ActionStatus.MISSING_CAPABILITY_TYPE, validationObjects);
+            }
+            eitherResult = Either.right(errorResponse);
+            componentsUtils.auditResource(errorResponse, user, resource, actionEnum);
+        }
+        return eitherResult;
+    }
+
+    private Either<Boolean, ResponseFormat> validateCapabilityTypeExists(User user, ICapabilityTypeOperation capabilityTypeOperation,
+                                                                         Resource resource, AuditingActionEnum actionEnum,
+                                                                         Either<Boolean, ResponseFormat> eitherResult,
+                                                                         Entry<String, List<CapabilityDefinition>> typeEntry, boolean inTransaction) {
+        Either<CapabilityTypeDefinition, StorageOperationStatus> eitherCapTypeFound = capabilityTypeOperation
+            .getCapabilityType(typeEntry.getKey(), inTransaction);
+        if (eitherCapTypeFound.isRight()) {
+            if (eitherCapTypeFound.right().value() == StorageOperationStatus.NOT_FOUND) {
+                BeEcompErrorManager.getInstance()
+                    .logBeGraphObjectMissingError(CREATE_RESOURCE_VALIDATE_CAPABILITY_TYPES, "Capability Type", typeEntry.getKey());
+                log.debug("Capability Type: {} is required by resource: {} but does not exist in the DB", typeEntry.getKey(), resource.getName());
+                BeEcompErrorManager.getInstance().logBeDaoSystemError(CREATE_RESOURCE_VALIDATE_CAPABILITY_TYPES);
+            }
+            log.debug("Trying to get capability type {} failed with error: {}", typeEntry.getKey(), eitherCapTypeFound.right().value().name());
+            ResponseFormat errorResponse = componentsUtils.getResponseFormat(ActionStatus.MISSING_CAPABILITY_TYPE, typeEntry.getKey());
+            componentsUtils.auditResource(errorResponse, user, resource, actionEnum);
+            return Either.right(errorResponse);
+        }
+        CapabilityTypeDefinition capabilityTypeDefinition = eitherCapTypeFound.left().value();
+        if (capabilityTypeDefinition.getProperties() != null) {
+            for (CapabilityDefinition capDef : typeEntry.getValue()) {
+                List<ComponentInstanceProperty> properties = capDef.getProperties();
+                List<ComponentInstanceProperty> changedProperties = new ArrayList<>();
+                if (properties == null || properties.isEmpty()) {
+                    for (Entry<String, PropertyDefinition> prop : capabilityTypeDefinition.getProperties().entrySet()) {
+                        ComponentInstanceProperty newProp = new ComponentInstanceProperty(prop.getValue());
+                        changedProperties.add(newProp);
+                    }
+                } else {
+                    List<ComponentInstanceProperty> propsToAdd = new ArrayList<>();
+                    for (Entry<String, PropertyDefinition> prop : capabilityTypeDefinition.getProperties().entrySet()) {
+                        PropertyDefinition propFromDef = prop.getValue();
+                        boolean propFound = false;
+                        for (ComponentInstanceProperty cip : properties) {
+                            if (propFromDef.getName().equals(cip.getName())) {
+                                //merge property value and property description only, ignore other fields
+                                if (cip.getDescription() != null && !cip.getDescription().equals(propFromDef.getDescription())) {
+                                    propFromDef.setDescription(cip.getDescription());
+                                }
+                                propertyDataValueMergeBusinessLogic.mergePropertyValue(propFromDef, cip, new ArrayList<>());
+                                if (cip.getValue() != null) {
+                                    propFromDef.setValue(cip.getValue());
+                                }
+                                propsToAdd.add(new ComponentInstanceProperty(propFromDef));
+                                propFound = true;
+                                properties.remove(cip);
+                                break;
+                            }
+                        }
+                        if (!propFound) {
+                            propsToAdd.add(new ComponentInstanceProperty(propFromDef));
+                        }
+                    }
+                    if (!propsToAdd.isEmpty()) {
+                        changedProperties.addAll(propsToAdd);
+                    }
+                }
+                capDef.setProperties(changedProperties);
+            }
+        }
+        return eitherResult;
+    }
+
+    public Resource createResourceByDao(Resource resource, User user, AuditingActionEnum actionEnum, boolean isNormative, boolean inTransaction) {
+        // create resource
+
+        // lock new resource name in order to avoid creation resource with same
+
+        // name
+        Resource createdResource = null;
+        if (!inTransaction) {
+            Either<Boolean, ResponseFormat> lockResult = lockComponentByName(resource.getSystemName(), resource, CREATE_RESOURCE);
+            if (lockResult.isRight()) {
+                ResponseFormat responseFormat = lockResult.right().value();
+                componentsUtils.auditResource(responseFormat, user, resource, actionEnum);
+                throw new ByResponseFormatComponentException(responseFormat);
+            }
+            log.debug("name is locked {} status = {}", resource.getSystemName(), lockResult);
+        }
+        try {
+            if (resource.deriveFromGeneric()) {
+                handleResourceGenericType(resource);
+            }
+            createdResource = createResourceTransaction(resource, user, isNormative);
+            componentsUtils.auditResource(componentsUtils.getResponseFormat(ActionStatus.CREATED), user, createdResource, actionEnum);
+            ASDCKpiApi.countCreatedResourcesKPI();
+        } catch (ComponentException e) {
+            ResponseFormat responseFormat =
+                e.getResponseFormat() == null ? componentsUtils.getResponseFormat(e.getActionStatus(), e.getParams()) : e.getResponseFormat();
+            componentsUtils.auditResource(responseFormat, user, resource, actionEnum);
+            throw e;
+        } catch (StorageException e) {
+            ResponseFormat responseFormat = componentsUtils
+                .getResponseFormat(componentsUtils.convertFromStorageResponse(e.getStorageOperationStatus()));
+            componentsUtils.auditResource(responseFormat, user, resource, actionEnum);
+            throw e;
+        } finally {
+            if (!inTransaction) {
+                graphLockOperation.unlockComponentByName(resource.getSystemName(), resource.getUniqueId(), NodeTypeEnum.Resource);
+            }
+        }
+        return createdResource;
+    }
+
+    private Resource createResourceTransaction(Resource resource, User user, boolean isNormative) {
+        // validate resource name uniqueness
+        log.debug("validate resource name");
+        Either<Boolean, StorageOperationStatus> eitherValidation = toscaOperationFacade
+            .validateComponentNameExists(resource.getName(), resource.getResourceType(), resource.getComponentType());
+        if (eitherValidation.isRight()) {
+            loggerSupportability.log(LoggerSupportabilityActions.VALIDATE_NAME, resource.getComponentMetadataForSupportLog(), StatusCode.ERROR,
+                "ERROR while validate component name {} Status is: {}", resource.getName(), eitherValidation.right().value());
+            log.debug("Failed to validate component name {}. Status is {}. ", resource.getName(), eitherValidation.right().value());
+            throw new ByActionStatusComponentException(componentsUtils.convertFromStorageResponse(eitherValidation.right().value()));
+        }
+        if (eitherValidation.left().value()) {
+            log.debug("resource with name: {}, already exists", resource.getName());
+            loggerSupportability
+                .log(LoggerSupportabilityActions.CREATE_RESOURCE_FROM_YAML, resource.getComponentMetadataForSupportLog(), StatusCode.ERROR,
+                    "resource with name: {} already exists", resource.getName());
+            throw new ByActionStatusComponentException(ActionStatus.COMPONENT_NAME_ALREADY_EXIST, ComponentTypeEnum.RESOURCE.getValue(),
+                resource.getName());
+        }
+        log.debug("send resource {} to dao for create", resource.getName());
+        createArtifactsPlaceHolderData(resource, user);
+        // enrich object
+        if (!isNormative) {
+            log.debug("enrich resource with creator, version and state");
+            resource.setLifecycleState(LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT);
+            resource.setVersion(INITIAL_VERSION);
+            resource.setHighestVersion(true);
+            if (resource.getResourceType() != null && resource.getResourceType() != ResourceTypeEnum.CVFC) {
+                resource.setAbstract(false);
+            }
+        }
+        return toscaOperationFacade.createToscaComponent(resource).left().on(r -> throwComponentExceptionByResource(r, resource));
+    }
+
+    private Resource throwComponentExceptionByResource(StorageOperationStatus status, Resource resource) {
+        ResponseFormat responseFormat = componentsUtils.getResponseFormatByResource(componentsUtils.convertFromStorageResponse(status), resource);
+        throw new ByResponseFormatComponentException(responseFormat);
+    }
+
+    private void createArtifactsPlaceHolderData(Resource resource, User user) {
+        // create mandatory artifacts
+
+        // TODO it must be removed after that artifact uniqueId creation will be
+
+        // moved to ArtifactOperation
+        setInformationalArtifactsPlaceHolder(resource, user);
+        setDeploymentArtifactsPlaceHolder(resource, user);
+        setToscaArtifactsPlaceHolders(resource, user);
+    }
+
+    @SuppressWarnings("unchecked")
+    @Override
+    public void setDeploymentArtifactsPlaceHolder(Component component, User user) {
+        Resource resource = (Resource) component;
+        Map<String, ArtifactDefinition> artifactMap = resource.getDeploymentArtifacts();
+        if (artifactMap == null) {
+            artifactMap = new HashMap<>();
+        }
+        Map<String, Object> deploymentResourceArtifacts = ConfigurationManager.getConfigurationManager().getConfiguration()
+            .getDeploymentResourceArtifacts();
+        if (deploymentResourceArtifacts != null) {
+            Map<String, ArtifactDefinition> finalArtifactMap = artifactMap;
+            deploymentResourceArtifacts.forEach((k, v) -> processDeploymentResourceArtifacts(user, resource, finalArtifactMap, k, v));
+        }
+        resource.setDeploymentArtifacts(artifactMap);
+    }
+
+    private void processDeploymentResourceArtifacts(User user, Resource resource, Map<String, ArtifactDefinition> artifactMap, String k, Object v) {
+        Map<String, Object> artifactDetails = (Map<String, Object>) v;
+        Object object = artifactDetails.get(PLACE_HOLDER_RESOURCE_TYPES);
+        if (object != null) {
+            List<String> artifactTypes = (List<String>) object;
+            if (!artifactTypes.contains(resource.getResourceType().name())) {
+                return;
+            }
+        } else {
+            log.info("resource types for artifact placeholder {} were not defined. default is all resources", k);
+        }
+        if (artifactsBusinessLogic != null) {
+            ArtifactDefinition artifactDefinition = artifactsBusinessLogic
+                .createArtifactPlaceHolderInfo(resource.getUniqueId(), k, (Map<String, Object>) v, user, ArtifactGroupTypeEnum.DEPLOYMENT);
+            if (artifactDefinition != null && !artifactMap.containsKey(artifactDefinition.getArtifactLabel())) {
+                artifactMap.put(artifactDefinition.getArtifactLabel(), artifactDefinition);
+            }
+        }
+    }
+
+    @SuppressWarnings("unchecked")
+    private void setInformationalArtifactsPlaceHolder(Resource resource, User user) {
+        Map<String, ArtifactDefinition> artifactMap = resource.getArtifacts();
+        if (artifactMap == null) {
+            artifactMap = new HashMap<>();
+        }
+        String resourceUniqueId = resource.getUniqueId();
+        List<String> exludeResourceCategory = ConfigurationManager.getConfigurationManager().getConfiguration().getExcludeResourceCategory();
+        List<String> exludeResourceType = ConfigurationManager.getConfigurationManager().getConfiguration().getExcludeResourceType();
+        Map<String, Object> informationalResourceArtifacts = ConfigurationManager.getConfigurationManager().getConfiguration()
+            .getInformationalResourceArtifacts();
+        List<CategoryDefinition> categories = resource.getCategories();
+        boolean isCreateArtifact = true;
+        if (exludeResourceCategory != null) {
+            String category = categories.get(0).getName();
+            isCreateArtifact = exludeResourceCategory.stream().noneMatch(e -> e.equalsIgnoreCase(category));
+        }
+        if (isCreateArtifact && exludeResourceType != null) {
+            String resourceType = resource.getResourceType().name();
+            isCreateArtifact = exludeResourceType.stream().noneMatch(e -> e.equalsIgnoreCase(resourceType));
+        }
+        if (informationalResourceArtifacts != null && isCreateArtifact) {
+            Set<String> keys = informationalResourceArtifacts.keySet();
+            for (String informationalResourceArtifactName : keys) {
+                Map<String, Object> artifactInfoMap = (Map<String, Object>) informationalResourceArtifacts.get(informationalResourceArtifactName);
+                ArtifactDefinition artifactDefinition = artifactsBusinessLogic
+                    .createArtifactPlaceHolderInfo(resourceUniqueId, informationalResourceArtifactName, artifactInfoMap, user,
+                        ArtifactGroupTypeEnum.INFORMATIONAL);
+                artifactMap.put(artifactDefinition.getArtifactLabel(), artifactDefinition);
+            }
+        }
+        resource.setArtifacts(artifactMap);
+    }
+
+    /**
+     * deleteResource
+     *
+     * @param resourceId
+     * @param user
+     * @return
+     */
+    public ResponseFormat deleteResource(String resourceId, User user) {
+        ResponseFormat responseFormat;
+        validateUserExists(user);
+        Either<Resource, StorageOperationStatus> resourceStatus = toscaOperationFacade.getToscaElement(resourceId);
+        if (resourceStatus.isRight()) {
+            log.debug("failed to get resource {}", resourceId);
+            return componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(resourceStatus.right().value()), "");
+        }
+        Resource resource = resourceStatus.left().value();
+        StorageOperationStatus result = StorageOperationStatus.OK;
+        lockComponent(resourceId, resource, "Mark resource to delete");
+        try {
+            result = markComponentToDelete(resource);
+            if (result == StorageOperationStatus.OK) {
+                responseFormat = componentsUtils.getResponseFormat(ActionStatus.NO_CONTENT);
+            } else {
+                ActionStatus actionStatus = componentsUtils.convertFromStorageResponse(result);
+                responseFormat = componentsUtils.getResponseFormatByResource(actionStatus, resource.getName());
+            }
+            return responseFormat;
+        } finally {
+            if (result == null || result != StorageOperationStatus.OK) {
+                janusGraphDao.rollback();
+            } else {
+                janusGraphDao.commit();
+            }
+            graphLockOperation.unlockComponent(resourceId, NodeTypeEnum.Resource);
+        }
+    }
+
+    public ResponseFormat deleteResourceByNameAndVersion(String resourceName, String version, User user) {
+        ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.NO_CONTENT);
+        validateUserExists(user);
+        Resource resource = null;
+        StorageOperationStatus result = StorageOperationStatus.OK;
+        boolean failed = false;
+        try {
+            Either<Resource, StorageOperationStatus> resourceStatus = toscaOperationFacade
+                .getComponentByNameAndVersion(ComponentTypeEnum.RESOURCE, resourceName, version);
+            if (resourceStatus.isRight()) {
+                log.debug("failed to get resource {} version {}", resourceName, version);
+                return componentsUtils
+                    .getResponseFormatByResource(componentsUtils.convertFromStorageResponse(resourceStatus.right().value()), resourceName);
+            }
+            resource = resourceStatus.left().value();
+        } finally {
+            janusGraphDao.commit();
+        }
+        if (resource != null) {
+            lockComponent(resource.getUniqueId(), resource, DELETE_RESOURCE);
+            try {
+                result = markComponentToDelete(resource);
+                if (result != StorageOperationStatus.OK) {
+                    ActionStatus actionStatus = componentsUtils.convertFromStorageResponse(result);
+                    responseFormat = componentsUtils.getResponseFormatByResource(actionStatus, resource.getName());
+                    return responseFormat;
+                }
+            } catch (ComponentException e) {
+                failed = true;
+                throw e;
+            } finally {
+                if (failed || result == null || result != StorageOperationStatus.OK) {
+                    janusGraphDao.rollback();
+                } else {
+                    janusGraphDao.commit();
+                }
+                graphLockOperation.unlockComponent(resource.getUniqueId(), NodeTypeEnum.Resource);
+            }
+        }
+        return responseFormat;
+    }
+
+    public Either<Resource, ResponseFormat> getResource(String resourceId, User user) {
+        if (user != null) {
+            validateUserExists(user);
+        }
+        Either<Resource, StorageOperationStatus> storageStatus = toscaOperationFacade.getToscaElement(resourceId);
+        if (storageStatus.isRight()) {
+            log.debug("failed to get resource by id {}", resourceId);
+            return Either.right(
+                componentsUtils.getResponseFormatByResource(componentsUtils.convertFromStorageResponse(storageStatus.right().value()), resourceId));
+        }
+        if (!(storageStatus.left().value() instanceof Resource)) {
+            return Either.right(componentsUtils
+                .getResponseFormatByResource(componentsUtils.convertFromStorageResponse(StorageOperationStatus.NOT_FOUND), resourceId));
+        }
+        return Either.left(storageStatus.left().value());
+    }
+
+    public Either<Resource, ResponseFormat> getResourceByNameAndVersion(String resourceName, String resourceVersion, String userId) {
+        validateUserExists(userId);
+        Either<Resource, StorageOperationStatus> getResource = toscaOperationFacade
+            .getComponentByNameAndVersion(ComponentTypeEnum.RESOURCE, resourceName, resourceVersion);
+        if (getResource.isRight()) {
+            log.debug("failed to get resource by name {} and version {}", resourceName, resourceVersion);
+            return Either.right(
+                componentsUtils.getResponseFormatByResource(componentsUtils.convertFromStorageResponse(getResource.right().value()), resourceName));
+        }
+        return Either.left(getResource.left().value());
+    }
+
+    /**
+     * updateResourceMetadata
+     *
+     * @param user               - modifier data (userId)
+     * @param inTransaction      TODO
+     * @param resourceIdToUpdate - the resource identifier
+     * @param newResource
+     * @return Either<Resource, responseFormat>
+     */
+    public Resource updateResourceMetadata(String resourceIdToUpdate, Resource newResource, Resource currentResource, User user,
+                                           boolean inTransaction) {
+        validateUserExists(user.getUserId());
+        log.debug("Get resource with id {}", resourceIdToUpdate);
+        boolean needToUnlock = false;
+        try {
+            if (currentResource == null) {
+                Either<Resource, StorageOperationStatus> storageStatus = toscaOperationFacade.getToscaElement(resourceIdToUpdate);
+                if (storageStatus.isRight()) {
+                    throw new ByResponseFormatComponentException(
+                        componentsUtils.getResponseFormatByResource(componentsUtils.convertFromStorageResponse(storageStatus.right().value()), ""));
+                }
+                currentResource = storageStatus.left().value();
+            }
+            // verify that resource is checked-out and the user is the last
+
+            // updater
+            if (!ComponentValidationUtils.canWorkOnResource(currentResource, user.getUserId())) {
+                throw new ByResponseFormatComponentException(componentsUtils.getResponseFormat(ActionStatus.RESTRICTED_OPERATION));
+            }
+            // lock resource
+            StorageOperationStatus lockResult = graphLockOperation.lockComponent(resourceIdToUpdate, NodeTypeEnum.Resource);
+            if (lockResult != StorageOperationStatus.OK) {
+                BeEcompErrorManager.getInstance()
+                    .logBeFailedLockObjectError("Upload Artifact - lock ", NodeTypeEnum.Resource.getName(), resourceIdToUpdate);
+                log.debug("Failed to lock resource: {}, error - {}", resourceIdToUpdate, lockResult);
+                ResponseFormat responseFormat = componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(lockResult));
+                throw new ByResponseFormatComponentException(responseFormat);
+            }
+            needToUnlock = true;
+            // critical section starts here
+
+            // convert json to object
+
+            // Update and updated resource must have a non-empty "derivedFrom"
+
+            // list
+
+            // This code is not called from import resources, because of root
 
-               property.setValue(validPropertyVAlue);
-
-               if (isNotEmpty(getInputs)) {
-                       List<GetInputValueDataDefinition> getInputValues = new ArrayList<>();
-                       for (GetInputValueDataDefinition getInput : getInputs) {
-                               List<InputDefinition> inputs = resource.getInputs();
-                               if (CollectionUtils.isEmpty(inputs)) {
-                                       loggerSupportability.log(LoggerSupportabilityActions.PROPERTY,resource.getComponentMetadataForSupportLog(),
-                                                       StatusCode.ERROR,"ERROR Failed to add property: "+propName+" to resource instance: {}. Inputs list is empty ",currentCompInstance.getUniqueId());
-                                       log.debug("Failed to add property {} to resource instance {}. Inputs list is empty ", property,
-                                                       currentCompInstance.getUniqueId());
-                                       throw new ByActionStatusComponentException(ActionStatus.INVALID_CONTENT);
-                               }
-
-                               Optional<InputDefinition> optional = inputs.stream()
-                                               .filter(p -> p.getName()
-                                                               .equals(getInput.getInputName()))
-                                               .findAny();
-                               if (!optional.isPresent()) {
-                                       loggerSupportability.log(LoggerSupportabilityActions.PROPERTY,resource.getComponentMetadataForSupportLog(),
-                                                       StatusCode.ERROR,"ERROR Failed to find input: "+getInput.getInputName());
-                                       log.debug("Failed to find input {} ", getInput.getInputName());
-                                       // @@TODO error message
-                                       throw new ByActionStatusComponentException(ActionStatus.INVALID_CONTENT);
-                               }
-                               InputDefinition input = optional.get();
-                               getInput.setInputId(input.getUniqueId());
-                               getInputValues.add(getInput);
-
-                               GetInputValueDataDefinition getInputIndex = getInput.getGetInputIndex();
-                               processGetInput(getInputValues, inputs, getInputIndex);
-                       }
-                       property.setGetInputValues(getInputValues);
-               }
-               instPropList.add(property);
-               // delete overriden property
-               currPropertiesMap.remove(property.getName());
-       }
-
-       private void processGetInput(List<GetInputValueDataDefinition> getInputValues, List<InputDefinition> inputs,
-                                                                GetInputValueDataDefinition getInputIndex) {
-               Optional<InputDefinition> optional;
-               if (getInputIndex != null) {
-                       optional = inputs.stream()
-                                       .filter(p -> p.getName()
-                                                       .equals(getInputIndex.getInputName()))
-                                       .findAny();
-                       if (!optional.isPresent()) {
-                               log.debug("Failed to find input {} ", getInputIndex.getInputName());
-                               // @@TODO error message
-                               throw new ByActionStatusComponentException(ActionStatus.INVALID_CONTENT);
-                       }
-                       InputDefinition inputIndex = optional.get();
-                       getInputIndex.setInputId(inputIndex.getUniqueId());
-                       getInputValues.add(getInputIndex);
-               }
-       }
-
-       private void addInput(Map<String, InputDefinition> currPropertiesMap, InputDefinition prop) {
-               String propName = prop.getName();
-               if (!currPropertiesMap.containsKey(propName)) {
-                       currPropertiesMap.put(propName, prop);
-               }
-       }
-
-       private ResponseFormat addPropertyValuesToRi(UploadComponentInstanceInfo uploadComponentInstanceInfo,
-                                                                                                Resource resource, Resource originResource, ComponentInstance currentCompInstance,
-                                                                                                Map<String, List<ComponentInstanceProperty>> instProperties, Map<String, DataTypeDefinition> allDataTypes) {
-
-               Map<String, List<UploadPropInfo>> propMap = uploadComponentInstanceInfo.getProperties();
-               Map<String, PropertyDefinition> currPropertiesMap = new HashMap<>();
-
-               List<PropertyDefinition> listFromMap = originResource.getProperties();
-               if ((propMap != null && !propMap.isEmpty()) && (listFromMap == null || listFromMap.isEmpty())) {
-                       loggerSupportability.log(LoggerSupportabilityActions.PROPERTY,resource.getComponentMetadataForSupportLog(),
-                                       StatusCode.ERROR,"ERROR Failed to find properties");
-                       log.debug("failed to find properties");
-                       return componentsUtils.getResponseFormat(ActionStatus.PROPERTY_NOT_FOUND);
-               }
-               if (listFromMap == null || listFromMap.isEmpty()) {
-                       return componentsUtils.getResponseFormat(ActionStatus.OK);
-               }
-               for (PropertyDefinition prop : listFromMap) {
-                       String propName = prop.getName();
-                       if (!currPropertiesMap.containsKey(propName)) {
-                               currPropertiesMap.put(propName, prop);
-                       }
-               }
-               List<ComponentInstanceProperty> instPropList = new ArrayList<>();
-               if (propMap != null && propMap.size() > 0) {
-                       for (List<UploadPropInfo> propertyList : propMap.values()) {
-
-                               UploadPropInfo propertyInfo = propertyList.get(0);
-                               String propName = propertyInfo.getName();
-                               if (!currPropertiesMap.containsKey(propName)) {
-                                       log.debug("failed to find property {} ", propName);
-                                       loggerSupportability.log(LoggerSupportabilityActions.PROPERTY,resource.getComponentMetadataForSupportLog(), StatusCode.ERROR,"ERROR Failed to find property: {}",propName);
-                                       return componentsUtils.getResponseFormat(ActionStatus.PROPERTY_NOT_FOUND, propName);
-                               }
-                               PropertyDefinition curPropertyDef = currPropertiesMap.get(propName);
-                               ComponentInstanceProperty property = null;
-                               
-                               String value = null;
-                               List<GetInputValueDataDefinition> getInputs = null;
-                               boolean isValidate = true;
-                               if (propertyInfo.getValue() != null) {
-                                   getInputs = propertyInfo.getGet_input();
-                                   isValidate = getInputs == null || getInputs.isEmpty();
-                                   if (isValidate) {
-                                       value = getPropertyJsonStringValue(propertyInfo.getValue(), curPropertyDef.getType());
-                                       } else {
-                                           value = getPropertyJsonStringValue(propertyInfo.getValue(),
-                                                           TypeUtils.ToscaTagNamesEnum.GET_INPUT.getElementName());
-                                       }
-                                   }
-                               property = new ComponentInstanceProperty(curPropertyDef, value, null);
+            // VF "derivedFrom" should be null (or ignored)
+            if (ModelConverter.isAtomicComponent(currentResource)) {
+                validateDerivedFromNotEmpty(null, newResource, null);
+                validateDerivedFromNotEmpty(null, currentResource, null);
+            } else {
+                newResource.setDerivedFrom(null);
+            }
+            Either<Resource, ResponseFormat> dataModelResponse = updateResourceMetadata(resourceIdToUpdate, newResource, user, currentResource, false,
+                true);
+            if (dataModelResponse.isRight()) {
+                log.debug("failed to update resource metadata!!!");
+                throw new ByResponseFormatComponentException(dataModelResponse.right().value());
+            }
+            log.debug("Resource metadata updated successfully!!!");
+            return dataModelResponse.left().value();
+        } catch (ComponentException | StorageException e) {
+            rollback(inTransaction, newResource, null, null);
+            throw e;
+        } finally {
+            if (!inTransaction) {
+                janusGraphDao.commit();
+            }
+            if (needToUnlock) {
+                graphLockOperation.unlockComponent(resourceIdToUpdate, NodeTypeEnum.Resource);
+            }
+        }
+    }
 
-                String validatePropValue = validatePropValueBeforeCreate(property, value, isValidate, allDataTypes);
-                property.setValue(validatePropValue);
+    private Either<Resource, ResponseFormat> updateResourceMetadata(String resourceIdToUpdate, Resource newResource, User user,
+                                                                    Resource currentResource, boolean shouldLock, boolean inTransaction) {
+        updateVfModuleGroupsNames(currentResource, newResource);
+        validateResourceFieldsBeforeUpdate(currentResource, newResource, inTransaction, false);
+        // Setting last updater and uniqueId
+        newResource.setContactId(newResource.getContactId().toLowerCase());
+        newResource.setLastUpdaterUserId(user.getUserId());
+        newResource.setUniqueId(resourceIdToUpdate);
+        // Cannot set highest version through UI
+        newResource.setHighestVersion(currentResource.isHighestVersion());
+        newResource.setCreationDate(currentResource.getCreationDate());
+        Either<Boolean, ResponseFormat> processUpdateOfDerivedFrom = processUpdateOfDerivedFrom(currentResource, newResource, user.getUserId(),
+            inTransaction);
+        if (processUpdateOfDerivedFrom.isRight()) {
+            log.debug("Couldn't update derived from for resource {}", resourceIdToUpdate);
+            return Either.right(processUpdateOfDerivedFrom.right().value());
+        }
+        log.debug("send resource {} to dao for update", newResource.getUniqueId());
+        if (isNotEmpty(newResource.getGroups())) {
+            for (GroupDefinition group : newResource.getGroups()) {
+                if (DEFAULT_GROUP_VF_MODULE.equals(group.getType())) {
+                    groupBusinessLogic
+                        .validateAndUpdateGroupMetadata(newResource.getComponentMetadataDefinition().getMetadataDataDefinition().getUniqueId(), user,
+                            newResource.getComponentType(), group, true, false);
+                }
+            }
+        }
+        Either<Resource, StorageOperationStatus> dataModelResponse = toscaOperationFacade.updateToscaElement(newResource);
+        if (dataModelResponse.isRight()) {
+            ResponseFormat responseFormat = componentsUtils
+                .getResponseFormatByResource(componentsUtils.convertFromStorageResponse(dataModelResponse.right().value()), newResource);
+            return Either.right(responseFormat);
+        } else if (dataModelResponse.left().value() == null) {
+            log.debug("No response from updateResource");
+            return Either.right(componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR));
+        }
+        return Either.left(dataModelResponse.left().value());
+    }
 
-                               if (getInputs != null && !getInputs.isEmpty()) {
-                                       List<GetInputValueDataDefinition> getInputValues = new ArrayList<>();
-                                       for (GetInputValueDataDefinition getInput : getInputs) {
-                                               List<InputDefinition> inputs = resource.getInputs();
-                                               if (inputs == null || inputs.isEmpty()) {
-                                                       log.debug("Failed to add property {} to instance. Inputs list is empty ", property);
-                                                       loggerSupportability.log(LoggerSupportabilityActions.PROPERTY,resource.getComponentMetadataForSupportLog(), StatusCode.ERROR,"Failed to add property: {} to instance. Inputs list is empty",propName);
-                                                       rollbackWithException(ActionStatus.INPUTS_NOT_FOUND, property.getGetInputValues()
-                                                                       .stream()
-                                                                       .map(GetInputValueDataDefinition::getInputName)
-                                                                       .collect(toList())
-                                                                       .toString());
-                                               }
-                                               Either<InputDefinition, RuntimeException> inputEither = findInputByName(inputs, getInput);
-                                               if (inputEither.isRight()) {
-                                                       throw inputEither.right().value();
-                                               } else {
-                                                       InputDefinition input = inputEither.left().value();
-                                                       getInput.setInputId(input.getUniqueId());
-                                                       getInputValues.add(getInput);
-
-                                                       GetInputValueDataDefinition getInputIndex = getInput.getGetInputIndex();
-                                                       if (getInputIndex != null) {
-                                                               Either<InputDefinition, RuntimeException> newInputEither = findInputByName(inputs,
-                                                                       getInputIndex);
-                                                               if (inputEither.isRight()) {
-                                                                       throw newInputEither.right().value();
-                                                               } else {
-                                                                       InputDefinition newInput = newInputEither.left().value();
-                                                                       getInputIndex.setInputId(newInput.getUniqueId());
-                                                               }
-                                                               getInputValues.add(getInputIndex);
-
-                                                       }
-                                               }
-                                       }
-                                       property.setGetInputValues(getInputValues);
-                               }
-                               instPropList.add(property);
-                               // delete overriden property
-                               currPropertiesMap.remove(property.getName());
-                       }
-               }
-               // add rest of properties
-               if (!currPropertiesMap.isEmpty()) {
-                       for (PropertyDefinition value : currPropertiesMap.values()) {
-                               instPropList.add(new ComponentInstanceProperty(value));
-                       }
-               }
-               instProperties.put(currentCompInstance.getUniqueId(), instPropList);
-               return componentsUtils.getResponseFormat(ActionStatus.OK);
-       }
-
-       // US740820 Relate RIs according to capability name
-       private CapabilityDefinition findAvailableCapabilityByTypeOrName(RequirementDefinition validReq,
-                                                                                                                                        ComponentInstance currentCapCompInstance, UploadReqInfo uploadReqInfo) {
-               if (null == uploadReqInfo.getCapabilityName() || validReq.getCapability()
-                               .equals(uploadReqInfo.getCapabilityName())) {// get
-                       // by
-                       // capability
-                       // type
-                       return findAvailableCapability(validReq, currentCapCompInstance);
-               }
-               return findAvailableCapability(validReq, currentCapCompInstance, uploadReqInfo);
-       }
-
-       private CapabilityDefinition findAvailableCapability(RequirementDefinition validReq,
-                                                                                                                ComponentInstance currentCapCompInstance, UploadReqInfo uploadReqInfo) {
-               CapabilityDefinition cap = null;
-               Map<String, List<CapabilityDefinition>> capMap = currentCapCompInstance.getCapabilities();
-               if (!capMap.containsKey(validReq.getCapability())) {
-                       return null;
-               }
-               Optional<CapabilityDefinition> capByName = capMap.get(validReq.getCapability())
-                               .stream()
-                               .filter(p -> p.getName()
-                                               .equals(uploadReqInfo.getCapabilityName()))
-                               .findAny();
-               if (!capByName.isPresent()) {
-                       return null;
-               }
-               cap = capByName.get();
-
-               if (isBoundedByOccurrences(cap)) {
-                       String leftOccurrences = cap.getLeftOccurrences();
-                       int left = Integer.parseInt(leftOccurrences);
-                       if (left > 0) {
-                               --left;
-                               cap.setLeftOccurrences(String.valueOf(left));
-
-                       }
-
-               }
-               return cap;
-       }
-
-       private CapabilityDefinition findAvailableCapability(RequirementDefinition validReq, ComponentInstance instance) {
-               Map<String, List<CapabilityDefinition>> capMap = instance.getCapabilities();
-               if (capMap.containsKey(validReq.getCapability())) {
-                       List<CapabilityDefinition> capList = capMap.get(validReq.getCapability());
-
-                       for (CapabilityDefinition cap : capList) {
-                               if (isBoundedByOccurrences(cap)) {
-                                       String leftOccurrences = cap.getLeftOccurrences() != null ? cap.getLeftOccurrences()
-                                                       : cap.getMaxOccurrences();
-                                       int left = Integer.parseInt(leftOccurrences);
-                                       if (left > 0) {
-                                               --left;
-                                               cap.setLeftOccurrences(String.valueOf(left));
-                                               return cap;
-                                       }
-                               } else {
-                                       return cap;
-                               }
-                       }
-               }
-               return null;
-       }
-
-       private boolean isBoundedByOccurrences(CapabilityDefinition cap) {
-               return cap.getMaxOccurrences() != null && !cap.getMaxOccurrences()
-                               .equals(CapabilityDataDefinition.MAX_OCCURRENCES);
-       }
-
-       private Either<RequirementDefinition, ResponseFormat> findAviableRequiremen(String regName, String yamlName,
-                                                                                                                                                               UploadComponentInstanceInfo uploadComponentInstanceInfo, ComponentInstance currentCompInstance,
-                                                                                                                                                               String capName) {
-               Map<String, List<RequirementDefinition>> comInstRegDefMap = currentCompInstance.getRequirements();
-               List<RequirementDefinition> list = comInstRegDefMap.get(capName);
-               RequirementDefinition validRegDef = null;
-               if (list == null) {
-                       for (Entry<String, List<RequirementDefinition>> entry : comInstRegDefMap.entrySet()) {
-                               for (RequirementDefinition reqDef : entry.getValue()) {
-                                       if (reqDef.getName()
-                                                       .equals(regName)) {
-                                               if (reqDef.getMaxOccurrences() != null && !reqDef.getMaxOccurrences()
-                                                               .equals(RequirementDataDefinition.MAX_OCCURRENCES)) {
-                                                       String leftOccurrences = reqDef.getLeftOccurrences();
-                                                       if (leftOccurrences == null) {
-                                                               leftOccurrences = reqDef.getMaxOccurrences();
-                                                       }
-                                                       int left = Integer.parseInt(leftOccurrences);
-                                                       if (left > 0) {
-                                                               --left;
-                                                               reqDef.setLeftOccurrences(String.valueOf(left));
-                                                               validRegDef = reqDef;
-                                                               break;
-                                                       } else {
-                                                               continue;
-                                                       }
-                                               } else {
-                                                       validRegDef = reqDef;
-                                                       break;
-                                               }
-
-                                       }
-                               }
-                               if (validRegDef != null) {
-                                       break;
-                               }
-                       }
-               } else {
-                       for (RequirementDefinition reqDef : list) {
-                               if (reqDef.getName()
-                                               .equals(regName)) {
-                                       if (reqDef.getMaxOccurrences() != null && !reqDef.getMaxOccurrences()
-                                                       .equals(RequirementDataDefinition.MAX_OCCURRENCES)) {
-                                               String leftOccurrences = reqDef.getLeftOccurrences();
-                                               if (leftOccurrences == null) {
-                                                       leftOccurrences = reqDef.getMaxOccurrences();
-                                               }
-                                               int left = Integer.parseInt(leftOccurrences);
-                                               if (left > 0) {
-                                                       --left;
-                                                       reqDef.setLeftOccurrences(String.valueOf(left));
-                                                       validRegDef = reqDef;
-                                                       break;
-                                               } else {
-                                                       continue;
-                                               }
-                                       } else {
-                                               validRegDef = reqDef;
-                                               break;
-                                       }
-                               }
-                       }
-               }
-               if (validRegDef == null) {
-                       ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.INVALID_NODE_TEMPLATE,
-                                       yamlName, uploadComponentInstanceInfo.getName(), uploadComponentInstanceInfo.getType());
-                       return Either.right(responseFormat);
-               }
-               return Either.left(validRegDef);
-       }
-
-       private Resource createResourceInstances(String yamlName, Resource resource, Resource oldResource,
-                                                                                        Map<String, UploadComponentInstanceInfo> uploadResInstancesMap, Map<String, Resource> nodeNamespaceMap, Map<String, Resource> existingNodeTypesByResourceNames) {
-
-               Either<Resource, ResponseFormat> eitherResource;
-               log.debug("createResourceInstances is {} - going to create resource instanse from CSAR", yamlName);
-        if (isEmpty(uploadResInstancesMap) && resource.getResourceType() != ResourceTypeEnum.PNF) { // PNF can have no resource instances
-            ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.NOT_TOPOLOGY_TOSCA_TEMPLATE);
-            throw new ByResponseFormatComponentException(responseFormat);
-               }
-               if (MapUtils.isNotEmpty(nodeNamespaceMap)) {
-                       nodeNamespaceMap.forEach((k, v) -> existingNodeTypesByResourceNames.put(v.getToscaResourceName(), v));
-               }
-               Map<ComponentInstance, Resource> resourcesInstancesMap = new HashMap<>();
-               uploadResInstancesMap.values()
-                               .forEach(i -> createAndAddResourceInstance(i, yamlName, resource, nodeNamespaceMap,
-                                               existingNodeTypesByResourceNames, resourcesInstancesMap));
-               if (oldResource != null && oldResource.getResourceType() != ResourceTypeEnum.CVFC && oldResource.getComponentInstances() != null) {
-                       Map<String, Resource> existingNodeTypesByUids = existingNodeTypesByResourceNames.values()
-                                       .stream()
-                                       .collect(toMap(Resource::getUniqueId, r -> r));
-                       oldResource.getComponentInstances()
-                                       .stream()
-                                       .filter(i -> !i.isCreatedFromCsar())
-                                       .forEach(uiInst -> resourcesInstancesMap.put(uiInst,
-                                                       getOriginResource(existingNodeTypesByUids, uiInst)));
-               }
-
-               if (isNotEmpty(resourcesInstancesMap)) {
-                       try {
-                               toscaOperationFacade.associateComponentInstancesToComponent(resource,
-                                               resourcesInstancesMap, false, oldResource != null);
-                       } catch (StorageException exp) {
-                               if (exp.getStorageOperationStatus() != null && exp.getStorageOperationStatus() != StorageOperationStatus.OK) {
-                                       log.debug("Failed to add component instances to container component {}", resource.getName());
-                                       ResponseFormat responseFormat = componentsUtils
-                                                       .getResponseFormat(componentsUtils.convertFromStorageResponse(exp.getStorageOperationStatus()));
-                                       eitherResource = Either.right(responseFormat);
-                                       throw new ByResponseFormatComponentException(eitherResource.right().value());
-                               }
-                       }
-               }
-        if (CollectionUtils.isEmpty(resource.getComponentInstances()) &&
-                resource.getResourceType() != ResourceTypeEnum.PNF) { // PNF can have no resource instances
-                       log.debug("Error when create resource instance from csar. ComponentInstances list empty");
-                       BeEcompErrorManager.getInstance()
-                                       .logBeDaoSystemError(
-                                                       "Error when create resource instance from csar. ComponentInstances list empty");
-                       throw new ByResponseFormatComponentException(componentsUtils.getResponseFormat(ActionStatus.NOT_TOPOLOGY_TOSCA_TEMPLATE));
-               }
-               return resource;
-       }
-
-       private void createAndAddResourceInstance(UploadComponentInstanceInfo uploadComponentInstanceInfo, String yamlName,
-                                                                                         Resource resource, Map<String, Resource> nodeNamespaceMap, Map<String, Resource> existingnodeTypeMap,
-                                                                                         Map<ComponentInstance, Resource> resourcesInstancesMap) {
-               Either<Resource, ResponseFormat> eitherResource;
-               log.debug("*************Going to create  resource instances {}", yamlName);
-               // updating type if the type is node type name - we need to take the
-               // updated name
-               log.debug("*************Going to create  resource instances {}", uploadComponentInstanceInfo.getName());
-               if (nodeNamespaceMap.containsKey(uploadComponentInstanceInfo.getType())) {
-                       uploadComponentInstanceInfo.setType(nodeNamespaceMap.get(uploadComponentInstanceInfo.getType())
-                                       .getToscaResourceName());
-               }
-               Resource refResource = validateResourceInstanceBeforeCreate(yamlName, uploadComponentInstanceInfo,
-                               existingnodeTypeMap, resource);
-
-               ComponentInstance componentInstance = new ComponentInstance();
-               componentInstance.setComponentUid(refResource.getUniqueId());
-        Collection<String> directives = uploadComponentInstanceInfo.getDirectives();
-        if(directives != null && !directives.isEmpty()) {
-            componentInstance.setDirectives(new ArrayList<>(directives));
+    private void updateVfModuleGroupsNames(Resource currentResource, Resource newResource) {
+        if (currentResource.getGroups() != null && !currentResource.getName().equals(newResource.getName())) {
+            List<GroupDefinition> updatedGroups = currentResource.getGroups().stream()
+                .map(group -> getUpdatedGroup(group, currentResource.getName(), newResource.getName())).collect(toList());
+            newResource.setGroups(updatedGroups);
         }
-        UploadNodeFilterInfo uploadNodeFilterInfo = uploadComponentInstanceInfo.getUploadNodeFilterInfo();
-        if (uploadNodeFilterInfo != null){
-            componentInstance.setNodeFilter(new CINodeFilterUtils().getNodeFilterDataDefinition(uploadNodeFilterInfo,
-                    componentInstance.getUniqueId()));
+    }
+
+    private GroupDefinition getUpdatedGroup(GroupDefinition currGroup, String replacePattern, String with) {
+        GroupDefinition updatedGroup = new GroupDefinition(currGroup);
+        if (updatedGroup.isSamePrefix(replacePattern) && updatedGroup.getType().equals(DEFAULT_GROUP_VF_MODULE)) {
+            String prefix = updatedGroup.getName().substring(0, replacePattern.length());
+            String newGroupName = updatedGroup.getName().replaceFirst(prefix, with);
+            updatedGroup.setName(newGroupName);
         }
-        ComponentTypeEnum containerComponentType = resource.getComponentType();
-               NodeTypeEnum containerNodeType = containerComponentType.getNodeType();
-               if (containerNodeType == NodeTypeEnum.Resource && isNotEmpty(uploadComponentInstanceInfo.getCapabilities())
-                               && isNotEmpty(refResource.getCapabilities())) {
-                       setCapabilityNamesTypes(refResource.getCapabilities(), uploadComponentInstanceInfo.getCapabilities());
-                       Map<String, List<CapabilityDefinition>> validComponentInstanceCapabilities = getValidComponentInstanceCapabilities(
-                                       refResource.getUniqueId(), refResource.getCapabilities(),
-                                       uploadComponentInstanceInfo.getCapabilities());
-                       componentInstance.setCapabilities(validComponentInstanceCapabilities);
-               }
+        return updatedGroup;
+    }
 
-        if (isNotEmpty(uploadComponentInstanceInfo.getArtifacts())) {
-            Map<String, Map<String, UploadArtifactInfo>> artifacts = uploadComponentInstanceInfo.getArtifacts();
-            Map<String, ToscaArtifactDataDefinition> toscaArtifacts = new HashMap<>();
-            Map<String, Map<String, UploadArtifactInfo>> arts = artifacts.entrySet().stream()
-                                       .filter(e -> e.getKey().contains(TypeUtils.ToscaTagNamesEnum.ARTIFACTS.getElementName()))
-                                        .collect(Collectors.toMap(e -> e.getKey(), e -> e.getValue()));
-            Map<String, UploadArtifactInfo> artifact = arts.get(TypeUtils.ToscaTagNamesEnum.ARTIFACTS.getElementName());
-            for (Map.Entry<String, UploadArtifactInfo> entry : artifact.entrySet()) {
-                ToscaArtifactDataDefinition to = new ToscaArtifactDataDefinition();
-                to.setFile(entry.getValue().getFile());
-                to.setType(entry.getValue().getType());
-                toscaArtifacts.put(entry.getKey(), to);
+    /**
+     * validateResourceFieldsBeforeCreate
+     *
+     * @param user - modifier data (userId)
+     */
+    private void validateResourceFieldsBeforeCreate(User user, Resource resource, AuditingActionEnum actionEnum, boolean inTransaction) {
+        componentValidator.validate(user, resource, actionEnum);
+        // validate category
+        log.debug("validate category");
+        validateCategory(user, resource, actionEnum, inTransaction);
+        // validate vendor name & release & model number
+        log.debug("validate vendor name");
+        validateVendorName(user, resource, actionEnum);
+        log.debug("validate vendor release");
+        validateVendorReleaseName(user, resource, actionEnum);
+        log.debug("validate resource vendor model number");
+        validateResourceVendorModelNumber(user, resource, actionEnum);
+        // validate cost
+        log.debug("validate cost");
+        validateCost(resource);
+        // validate licenseType
+        log.debug("validate licenseType");
+        validateLicenseType(user, resource, actionEnum);
+        // validate template (derived from)
+        log.debug("validate derived from");
+        if (!ModelConverter.isAtomicComponent(resource) && resource.getResourceType() != ResourceTypeEnum.CVFC) {
+            resource.setDerivedFrom(null);
+        }
+        validateDerivedFromExist(user, resource, actionEnum);
+        // warn about non-updatable fields
+        checkComponentFieldsForOverrideAttempt(resource);
+        String currentCreatorFullName = resource.getCreatorFullName();
+        if (currentCreatorFullName != null) {
+            log.debug("Resource Creator fullname is automatically set and cannot be updated");
+        }
+        String currentLastUpdaterFullName = resource.getLastUpdaterFullName();
+        if (currentLastUpdaterFullName != null) {
+            log.debug("Resource LastUpdater fullname is automatically set and cannot be updated");
+        }
+        Long currentLastUpdateDate = resource.getLastUpdateDate();
+        if (currentLastUpdateDate != null) {
+            log.debug("Resource last update date is automatically set and cannot be updated");
+        }
+        Boolean currentAbstract = resource.isAbstract();
+        if (currentAbstract != null) {
+            log.debug("Resource abstract is automatically set and cannot be updated");
+        }
+    }
+
+    /**
+     * validateResourceFieldsBeforeUpdate
+     *
+     * @param currentResource - Resource object to validate
+     * @param isNested
+     */
+    private void validateResourceFieldsBeforeUpdate(Resource currentResource, Resource updateInfoResource, boolean inTransaction, boolean isNested) {
+        validateFields(currentResource, updateInfoResource, inTransaction, isNested);
+        warnNonEditableFields(currentResource, updateInfoResource);
+    }
+
+    private void warnNonEditableFields(Resource currentResource, Resource updateInfoResource) {
+        String currentResourceVersion = currentResource.getVersion();
+        String updatedResourceVersion = updateInfoResource.getVersion();
+        if ((updatedResourceVersion != null) && (!updatedResourceVersion.equals(currentResourceVersion))) {
+            log.debug("Resource version is automatically set and cannot be updated");
+        }
+        String currentCreatorUserId = currentResource.getCreatorUserId();
+        String updatedCreatorUserId = updateInfoResource.getCreatorUserId();
+        if ((updatedCreatorUserId != null) && (!updatedCreatorUserId.equals(currentCreatorUserId))) {
+            log.debug("Resource Creator UserId is automatically set and cannot be updated");
+        }
+        String currentCreatorFullName = currentResource.getCreatorFullName();
+        String updatedCreatorFullName = updateInfoResource.getCreatorFullName();
+        if ((updatedCreatorFullName != null) && (!updatedCreatorFullName.equals(currentCreatorFullName))) {
+            log.debug("Resource Creator fullname is automatically set and cannot be updated");
+        }
+        String currentLastUpdaterUserId = currentResource.getLastUpdaterUserId();
+        String updatedLastUpdaterUserId = updateInfoResource.getLastUpdaterUserId();
+        if ((updatedLastUpdaterUserId != null) && (!updatedLastUpdaterUserId.equals(currentLastUpdaterUserId))) {
+            log.debug("Resource LastUpdater userId is automatically set and cannot be updated");
+        }
+        String currentLastUpdaterFullName = currentResource.getLastUpdaterFullName();
+        String updatedLastUpdaterFullName = updateInfoResource.getLastUpdaterFullName();
+        if ((updatedLastUpdaterFullName != null) && (!updatedLastUpdaterFullName.equals(currentLastUpdaterFullName))) {
+            log.debug("Resource LastUpdater fullname is automatically set and cannot be updated");
+        }
+        Long currentCreationDate = currentResource.getCreationDate();
+        Long updatedCreationDate = updateInfoResource.getCreationDate();
+        if ((updatedCreationDate != null) && (!updatedCreationDate.equals(currentCreationDate))) {
+            log.debug("Resource Creation date is automatically set and cannot be updated");
+        }
+        Long currentLastUpdateDate = currentResource.getLastUpdateDate();
+        Long updatedLastUpdateDate = updateInfoResource.getLastUpdateDate();
+        if ((updatedLastUpdateDate != null) && (!updatedLastUpdateDate.equals(currentLastUpdateDate))) {
+            log.debug("Resource last update date is automatically set and cannot be updated");
+        }
+        LifecycleStateEnum currentLifecycleState = currentResource.getLifecycleState();
+        LifecycleStateEnum updatedLifecycleState = updateInfoResource.getLifecycleState();
+        if ((updatedLifecycleState != null) && (!updatedLifecycleState.equals(currentLifecycleState))) {
+            log.debug("Resource lifecycle state date is automatically set and cannot be updated");
+        }
+        Boolean currentAbstract = currentResource.isAbstract();
+        Boolean updatedAbstract = updateInfoResource.isAbstract();
+        if ((updatedAbstract != null) && (!updatedAbstract.equals(currentAbstract))) {
+            log.debug("Resource abstract is automatically set and cannot be updated");
+        }
+        Boolean currentHighestVersion = currentResource.isHighestVersion();
+        Boolean updatedHighestVersion = updateInfoResource.isHighestVersion();
+        if ((updatedHighestVersion != null) && (!updatedHighestVersion.equals(currentHighestVersion))) {
+            log.debug("Resource highest version is automatically set and cannot be updated");
+        }
+        String currentUuid = currentResource.getUUID();
+        String updatedUuid = updateInfoResource.getUUID();
+        if ((updatedUuid != null) && (!updatedUuid.equals(currentUuid))) {
+            log.debug("Resource UUID is automatically set and cannot be updated");
+        }
+        log.debug("Resource Type  cannot be updated");
+        String currentInvariantUuid = currentResource.getInvariantUUID();
+        String updatedInvariantUuid = updateInfoResource.getInvariantUUID();
+        if ((updatedInvariantUuid != null) && (!updatedInvariantUuid.equals(currentInvariantUuid))) {
+            log.debug("Resource invariant UUID is automatically set and cannot be updated");
+            updateInfoResource.setInvariantUUID(currentInvariantUuid);
+        }
+    }
+
+    private void validateFields(Resource currentResource, Resource updateInfoResource, boolean inTransaction, boolean isNested) {
+        boolean hasBeenCertified = ValidationUtils.hasBeenCertified(currentResource.getVersion());
+        log.debug("validate resource name before update");
+        validateResourceName(currentResource, updateInfoResource, hasBeenCertified, isNested);
+        log.debug("validate description before update");
+        componentDescriptionValidator.validateAndCorrectField(null, updateInfoResource, null);
+        log.debug("validate icon before update");
+        validateIcon(currentResource, updateInfoResource, hasBeenCertified);
+        log.debug("validate tags before update");
+        componentTagsValidator.validateAndCorrectField(null, updateInfoResource, null);
+        log.debug("validate vendor name before update");
+        validateVendorName(null, updateInfoResource, null);
+        log.debug("validate resource vendor model number before update");
+        validateResourceVendorModelNumber(currentResource, updateInfoResource);
+        log.debug("validate vendor release before update");
+        validateVendorReleaseName(null, updateInfoResource, null);
+        log.debug("validate contact info before update");
+        componentContactIdValidator.validateAndCorrectField(null, updateInfoResource, null);
+        log.debug(VALIDATE_DERIVED_BEFORE_UPDATE);
+        validateDerivedFromDuringUpdate(currentResource, updateInfoResource, hasBeenCertified);
+        log.debug("validate category before update");
+        validateCategory(currentResource, updateInfoResource, hasBeenCertified, inTransaction);
+    }
+
+    private boolean isResourceNameEquals(Resource currentResource, Resource updateInfoResource) {
+        String resourceNameUpdated = updateInfoResource.getName();
+        String resourceNameCurrent = currentResource.getName();
+        if (resourceNameCurrent.equals(resourceNameUpdated)) {
+            return true;
+        }
+        // In case of CVFC type we should support the case of old VF with CVFC
+
+        // instances that were created without the "Cvfc" suffix
+        return currentResource.getResourceType() == ResourceTypeEnum.CVFC && resourceNameUpdated
+            .equals(addCvfcSuffixToResourceName(resourceNameCurrent));
+    }
+
+    private String addCvfcSuffixToResourceName(String resourceName) {
+        return resourceName + "Cvfc";
+    }
+
+    private void validateResourceName(Resource currentResource, Resource updateInfoResource, boolean hasBeenCertified, boolean isNested) {
+        String resourceNameUpdated = updateInfoResource.getName();
+        if (!isResourceNameEquals(currentResource, updateInfoResource)) {
+            if (isNested || !hasBeenCertified) {
+                componentNameValidator.validateAndCorrectField(null, updateInfoResource, null);
+                validateResourceNameUniqueness(updateInfoResource);
+                currentResource.setName(resourceNameUpdated);
+                currentResource.setNormalizedName(ValidationUtils.normaliseComponentName(resourceNameUpdated));
+                currentResource.setSystemName(ValidationUtils.convertToSystemName(resourceNameUpdated));
+            } else {
+                log.info("Resource name: {}, cannot be updated once the resource has been certified once.", resourceNameUpdated);
+                throw new ByActionStatusComponentException(ActionStatus.RESOURCE_NAME_CANNOT_BE_CHANGED);
             }
-            componentInstance.setToscaArtifacts(toscaArtifacts);
         }
+    }
 
-               if (!existingnodeTypeMap.containsKey(uploadComponentInstanceInfo.getType())) {
-                       log.debug("createResourceInstances - not found lates version for resource instance with name {} and type ",
-                                       uploadComponentInstanceInfo.getName(), uploadComponentInstanceInfo.getType());
-                       throw new ByActionStatusComponentException(ActionStatus.INVALID_NODE_TEMPLATE,
-                                       yamlName, uploadComponentInstanceInfo.getName(), uploadComponentInstanceInfo.getType());
-               }
-               Resource origResource = existingnodeTypeMap.get(uploadComponentInstanceInfo.getType());
-               componentInstance.setName(uploadComponentInstanceInfo.getName());
-               componentInstance.setIcon(origResource.getIcon());
-               componentInstance.setCreatedFrom(CreatedFrom.CSAR);
-               resourcesInstancesMap.put(componentInstance, origResource);
-       }
-
-       private void setCapabilityNamesTypes(Map<String, List<CapabilityDefinition>> originCapabilities,
-                                                                                Map<String, List<UploadCapInfo>> uploadedCapabilities) {
-               for (Entry<String, List<UploadCapInfo>> currEntry : uploadedCapabilities.entrySet()) {
-                       if (originCapabilities.containsKey(currEntry.getKey())) {
-                               currEntry.getValue()
-                                               .stream()
-                                               .forEach(cap -> cap.setType(currEntry.getKey()));
-                       }
-               }
-               for (Map.Entry<String, List<CapabilityDefinition>> capabilities : originCapabilities.entrySet()) {
-                       capabilities.getValue()
-                                       .stream()
-                                       .forEach(cap -> {
-                                               if (uploadedCapabilities.containsKey(cap.getName())) {
-                                                       uploadedCapabilities.get(cap.getName())
-                                                                       .stream()
-                                                                       .forEach(c -> {
-                                                                               c.setName(cap.getName());
-                                                                               c.setType(cap.getType());
-                                                                       });
-                                               }
-                                       });
-               }
-       }
-
-       private Resource validateResourceInstanceBeforeCreate(String yamlName,
-                       UploadComponentInstanceInfo uploadComponentInstanceInfo, Map<String, Resource> nodeNamespaceMap, Resource resource) {
-
-               log.debug(
-                               "validateResourceInstanceBeforeCreate - going to validate resource instance with name {} and type {} before create",
-                               uploadComponentInstanceInfo.getName(), uploadComponentInstanceInfo.getType());
-               Resource refResource;
-               if (nodeNamespaceMap.containsKey(uploadComponentInstanceInfo.getType())) {
-                       refResource = nodeNamespaceMap.get(uploadComponentInstanceInfo.getType());
-               } else {
-                       Either<Resource, StorageOperationStatus> findResourceEither = toscaOperationFacade
-                                       .getByToscaResourceNameMatchingVendorRelease(uploadComponentInstanceInfo.getType(), 
-                                               ((ResourceMetadataDataDefinition)resource.getComponentMetadataDefinition().getMetadataDataDefinition()).getVendorRelease());
-                       if (findResourceEither.isRight()) {
-                               log.debug(
-                                               "validateResourceInstanceBeforeCreate - not found latest version for resource instance with name {} and type {}",
-                                               uploadComponentInstanceInfo.getName(), uploadComponentInstanceInfo.getType());
-                               throw new ByActionStatusComponentException(componentsUtils.convertFromStorageResponse(findResourceEither.right().value()));
-                       }
-                       refResource = findResourceEither.left().value();
-                       nodeNamespaceMap.put(refResource.getToscaResourceName(), refResource);
-               }
-               String componentState = refResource.getComponentMetadataDefinition()
-                               .getMetadataDataDefinition()
-                               .getState();
-               if (componentState.equals(LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT.name())) {
-                       log.debug(
-                                       "validateResourceInstanceBeforeCreate - component instance of component {} can not be created because the component is in an illegal state {}.",
-                                       refResource.getName(), componentState);
-                       throw new ByActionStatusComponentException(ActionStatus.ILLEGAL_COMPONENT_STATE,
-                                       refResource.getComponentType().getValue(),refResource.getName(), componentState);
-               }
-
-               if (!ModelConverter.isAtomicComponent(refResource) && refResource.getResourceType() != ResourceTypeEnum.CVFC) {
-                       log.debug("validateResourceInstanceBeforeCreate -  ref resource type is  ", refResource.getResourceType());
-                       throw new ByActionStatusComponentException(ActionStatus.INVALID_NODE_TEMPLATE,
-                                       yamlName, uploadComponentInstanceInfo.getName(), uploadComponentInstanceInfo.getType());
-               }
-               return refResource;
-       }
-
-       public Resource propagateStateToCertified(User user, Resource resource,
-                                                                                         LifecycleChangeInfoWithAction lifecycleChangeInfo, boolean inTransaction, boolean needLock,
-                                                                                         boolean forceCertificationAllowed) {
-
-               boolean failed = false;
-               try {
-                       if (resource.getLifecycleState() != LifecycleStateEnum.CERTIFIED && forceCertificationAllowed
-                                       && lifecycleBusinessLogic.isFirstCertification(resource.getVersion())) {
-                               nodeForceCertification(resource, user, lifecycleChangeInfo, inTransaction, needLock);
-                       }
-                       if (resource.getLifecycleState() == LifecycleStateEnum.CERTIFIED) {
-                               Either<ArtifactDefinition, Operation> eitherPopulated = populateToscaArtifacts(
-                                               resource, user, false, inTransaction, needLock, false);
-                               return resource;
-                       }
-                       return nodeFullCertification(resource.getUniqueId(), user, lifecycleChangeInfo, inTransaction, needLock);
-               } catch (ComponentException e) {
-                       failed = true;
-                       log.debug("The exception has occurred upon certification of resource {}. ", resource.getName(), e);
-                       throw e;
-               } finally {
-                       if (failed) {
-                               BeEcompErrorManager.getInstance()
-                                               .logBeSystemError("Change LifecycleState - Certify");
-                               if (!inTransaction) {
-                    janusGraphDao.rollback();
-                               }
-                       } else if (!inTransaction) {
-                janusGraphDao.commit();
-                       }
-               }
-       }
-
-       private Resource nodeFullCertification(String uniqueId, User user,
-                                                                                  LifecycleChangeInfoWithAction lifecycleChangeInfo, boolean inTransaction, boolean needLock) {
-               Either<Resource, ResponseFormat> resourceResponse = lifecycleBusinessLogic.changeState(uniqueId, user, LifeCycleTransitionEnum.CERTIFY, lifecycleChangeInfo,
-                               inTransaction, needLock);
-               if(resourceResponse.isRight()){
-                       throw new ByResponseFormatComponentException(resourceResponse.right().value());
-               }
-               return resourceResponse.left().value();
-       }
-
-       private Resource nodeForceCertification(Resource resource, User user,
-                                                                                       LifecycleChangeInfoWithAction lifecycleChangeInfo, boolean inTransaction, boolean needLock) {
-               return lifecycleBusinessLogic.forceResourceCertification(resource, user, lifecycleChangeInfo, inTransaction,
-                               needLock);
-       }
-
-       public ImmutablePair<Resource, ActionStatus> createOrUpdateResourceByImport(final Resource resource,
-                                                                                                                                                               final User user,
-                                                                                                                                                               final boolean isNormative,
-                                                                                                                                                               final boolean isInTransaction,
-                                                                                                                                                               final boolean needLock,
-                                                                                                                                                               final CsarInfo csarInfo,
-                                                                                                                                                               final String nodeName,
-                                                                                                                                                               final boolean isNested) {
-
-               ImmutablePair<Resource, ActionStatus> result = null;
-               // check if resource already exists (search by tosca name = type)
-               final boolean isNestedResource = isNestedResourceUpdate(csarInfo, nodeName);
-               final Either<Resource, StorageOperationStatus> latestByToscaName = toscaOperationFacade
-                       .getLatestByToscaResourceName(resource.getToscaResourceName());
-
-               if (latestByToscaName.isLeft()) {
-                       Resource foundResource = latestByToscaName.left().value();
-                       // we don't allow updating names of top level types
-                       if (!isNestedResource && !StringUtils.equals(resource.getName(), foundResource.getName())) {
-                               BeEcompErrorManager.getInstance().logBeComponentMissingError("Create / Update resource by import",
-                                       ComponentTypeEnum.RESOURCE.getValue(), resource.getName());
-                               log.debug("resource already exist new name={} old name={} same type={}", resource.getName(),
-                                       foundResource.getName(), resource.getToscaResourceName());
-                               final ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.RESOURCE_ALREADY_EXISTS);
-                               componentsUtils.auditResource(responseFormat, user, resource, AuditingActionEnum.IMPORT_RESOURCE);
-                               throwComponentException(responseFormat);
-                       }
-                       result = updateExistingResourceByImport(resource, foundResource, user, isNormative, needLock, isNested);
-               } else if (isNotFound(latestByToscaName)) {
-                       if (isNestedResource) {
-                               result = createOrUpdateNestedResource(resource, user, isNormative, isInTransaction, needLock, csarInfo,
-                                       isNested, nodeName);
-                       } else {
-                               result = createResourceByImport(resource, user, isNormative, isInTransaction, csarInfo);
-                       }
-               } else {
-                       StorageOperationStatus status = latestByToscaName.right().value();
-                       log.debug("failed to get latest version of resource {}. status={}", resource.getName(), status);
-                       ResponseFormat responseFormat = componentsUtils.getResponseFormatByResource(componentsUtils
-                               .convertFromStorageResponse(latestByToscaName.right().value()), resource);
-                       componentsUtils.auditResource(responseFormat, user, resource, AuditingActionEnum.IMPORT_RESOURCE);
-                       throwComponentException(responseFormat);
-               }
-               return result;
-       }
-
-       private boolean isNestedResourceUpdate(CsarInfo csarInfo, String nodeName) {
-               return csarInfo != null && csarInfo.isUpdate() && nodeName != null;
-       }
-
-       private ImmutablePair<Resource, ActionStatus> createOrUpdateNestedResource(final Resource resource,
-                                                                                                                                                          final User user,
-                                                                                                                                                          final boolean isNormative,
-                                                                                                                                                          final boolean isInTransaction,
-                                                                                                                                                          final boolean needLock,
-                                                                                                                                                          final CsarInfo csarInfo,
-                                                                                                                                                          final boolean isNested,
-                                                                                                                                                          final String nodeName) {
-               final Either<Component, StorageOperationStatus> latestByToscaName = toscaOperationFacade
-                       .getLatestByToscaResourceName(buildNestedToscaResourceName(resource.getResourceType()
-                               .name(), csarInfo.getVfResourceName(), nodeName).getRight());
-               if (latestByToscaName.isLeft()) {
-                       final Resource nestedResource = (Resource) latestByToscaName.left().value();
-                       log.debug(VALIDATE_DERIVED_BEFORE_UPDATE);
-                       final Either<Boolean, ResponseFormat> eitherValidation = validateNestedDerivedFromDuringUpdate(nestedResource,
-                               resource, ValidationUtils.hasBeenCertified(nestedResource.getVersion()));
-                       if (eitherValidation.isRight()) {
-                               return createResourceByImport(resource, user, isNormative, isInTransaction, csarInfo);
-                       }
-                       return updateExistingResourceByImport(resource, nestedResource, user, isNormative, needLock, isNested);
-               } else {
-                       return createResourceByImport(resource, user, isNormative, isInTransaction, csarInfo);
-               }
-       }
-
-       private boolean isNotFound(Either<Resource, StorageOperationStatus> getResourceEither) {
-               return getResourceEither.isRight() && getResourceEither.right()
-                               .value() == StorageOperationStatus.NOT_FOUND;
-       }
-
-       private ImmutablePair<Resource, ActionStatus> createResourceByImport(Resource resource, User user,
-                                                                                                                                                boolean isNormative, boolean isInTransaction, CsarInfo csarInfo) {
-               log.debug("resource with name {} does not exist. create new resource", resource.getName());
-               validateResourceBeforeCreate(resource, user, AuditingActionEnum.IMPORT_RESOURCE, isInTransaction, csarInfo);
-               final Resource createResourceByDao = createResourceByDao(resource, user, AuditingActionEnum.IMPORT_RESOURCE, isNormative,
-                               isInTransaction);
-               Resource createdResource  = updateCatalog(createResourceByDao, ChangeTypeEnum.LIFECYCLE).left().map(r -> (Resource)r).left().value();
-               ImmutablePair<Resource, ActionStatus> resourcePair = new ImmutablePair<>(createdResource, ActionStatus.CREATED);
-               ASDCKpiApi.countImportResourcesKPI();
-               return resourcePair;
-       }
-
-       public boolean isResourceExist(String resourceName) {
-               Either<Resource, StorageOperationStatus> latestByName = toscaOperationFacade.getLatestByName(resourceName);
-               return latestByName.isLeft();
-       }
-
-       private ImmutablePair<Resource, ActionStatus> updateExistingResourceByImport(Resource newResource,
-                                                                                                                                                                Resource oldResource, User user, boolean inTransaction, boolean needLock, boolean isNested) {
-               String lockedResourceId = oldResource.getUniqueId();
-               log.debug("found resource: name={}, id={}, version={}, state={}", oldResource.getName(), lockedResourceId,
-                               oldResource.getVersion(), oldResource.getLifecycleState());
-               ImmutablePair<Resource, ActionStatus> resourcePair = null;
-               try {
-                       lockComponent(lockedResourceId, oldResource, needLock, "Update Resource by Import");
-                       oldResource = prepareResourceForUpdate(oldResource, newResource, user, inTransaction, false);
-                       mergeOldResourceMetadataWithNew(oldResource, newResource);
-
-                       validateResourceFieldsBeforeUpdate(oldResource, newResource, inTransaction, isNested);
-                       validateCapabilityTypesCreate(user, getCapabilityTypeOperation(), newResource, AuditingActionEnum.IMPORT_RESOURCE, inTransaction);
-                       // contact info normalization
-                       newResource.setContactId(newResource.getContactId().toLowerCase());
-                       PropertyConstraintsUtils.validatePropertiesConstraints(newResource, oldResource);
-                       // non-updatable fields
-                       newResource.setCreatorUserId(user.getUserId());
-                       newResource.setCreatorFullName(user.getFullName());
-                       newResource.setLastUpdaterUserId(user.getUserId());
-                       newResource.setLastUpdaterFullName(user.getFullName());
-                       newResource.setUniqueId(oldResource.getUniqueId());
-                       newResource.setVersion(oldResource.getVersion());
-                       newResource.setInvariantUUID(oldResource.getInvariantUUID());
-                       newResource.setLifecycleState(oldResource.getLifecycleState());
-                       newResource.setUUID(oldResource.getUUID());
-                       newResource.setNormalizedName(oldResource.getNormalizedName());
-                       newResource.setSystemName(oldResource.getSystemName());
-                       if (oldResource.getCsarUUID() != null) {
-                               newResource.setCsarUUID(oldResource.getCsarUUID());
-                       }
-                       if (oldResource.getImportedToscaChecksum() != null) {
-                               newResource.setImportedToscaChecksum(oldResource.getImportedToscaChecksum());
-                       }
-                       newResource.setAbstract(oldResource.isAbstract());
-
-                       if (CollectionUtils.isEmpty(newResource.getDerivedFrom())){
-                               newResource.setDerivedFrom(oldResource.getDerivedFrom());
-                       }
-                       if (CollectionUtils.isEmpty(newResource.getDataTypes())){
-                               newResource.setDataTypes(oldResource.getDataTypes());
-                       }
-                       if (StringUtils.isEmpty(newResource.getDerivedFromGenericType())){
-                               newResource.setDerivedFromGenericType(oldResource.getDerivedFromGenericType());
-                       }
-                       if (StringUtils.isEmpty(newResource.getDerivedFromGenericVersion())){
-                               newResource.setDerivedFromGenericVersion(oldResource.getDerivedFromGenericVersion());
-                       }
-                       // add for new)
-                       // created without tosca artifacts - add the placeholders
-                       if (MapUtils.isEmpty(newResource.getToscaArtifacts())){
-                               setToscaArtifactsPlaceHolders(newResource, user);
-                       }
-
-                       if (MapUtils.isEmpty(newResource.getInterfaces())){
-                               newResource.setInterfaces(oldResource.getInterfaces());
-                       }
-                       if (CollectionUtils.isEmpty(newResource.getAttributes())) {
-                               newResource.setAttributes(oldResource.getAttributes());
-                       }
-
-                       if (CollectionUtils.isEmpty(newResource.getProperties())) {
-                               newResource.setProperties(oldResource.getProperties());
-                       }
-
-                       Either<Resource, StorageOperationStatus> overrideResource = toscaOperationFacade.overrideComponent(newResource, oldResource);
-
-                       if (overrideResource.isRight()) {
-                               ResponseFormat responseFormat = componentsUtils
-                                       .getResponseFormatByResource(componentsUtils.convertFromStorageResponse(overrideResource.right()
-                                               .value()), newResource);
-                               componentsUtils.auditResource(responseFormat, user, newResource, AuditingActionEnum.IMPORT_RESOURCE);
-
-                               throwComponentException(responseFormat);
-                       }
-                       updateCatalog(overrideResource.left()
-                               .value(), ChangeTypeEnum.LIFECYCLE);
-
-                       log.debug("Resource updated successfully!!!");
-                       ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.OK);
-                       componentsUtils.auditResource(responseFormat, user, newResource, AuditingActionEnum.IMPORT_RESOURCE,
-                               ResourceVersionInfo.newBuilder()
-                                       .state(oldResource.getLifecycleState()
-                                               .name())
-                                       .version(oldResource.getVersion())
-                                       .build());
-
-                       resourcePair = new ImmutablePair<>(overrideResource.left()
-                               .value(), ActionStatus.OK);
-                       return resourcePair;
-               } finally {
-                       if (resourcePair == null) {
-                               BeEcompErrorManager.getInstance()
-                                               .logBeSystemError("Change LifecycleState - Certify");
-                               janusGraphDao.rollback();
-                       } else if (!inTransaction) {
-                janusGraphDao.commit();
-                       }
-                       if (needLock) {
-                               log.debug("unlock resource {}", lockedResourceId);
-                               graphLockOperation.unlockComponent(lockedResourceId, NodeTypeEnum.Resource);
-                       }
-               }
-
-       }
-
-       /**
-        * Merge old resource with new. Keep old category and vendor name without
-        * change
-        *
-        * @param oldResource
-        * @param newResource
-        */
-       private void mergeOldResourceMetadataWithNew(Resource oldResource, Resource newResource) {
-
-               // keep old category and vendor name without change
-               // merge the rest of the resource metadata
-               if (newResource.getTags() == null || newResource.getTags().isEmpty()) {
-                       newResource.setTags(oldResource.getTags());
-               }
-
-               if (newResource.getDescription() == null) {
-                       newResource.setDescription(oldResource.getDescription());
-               }
-
-               if (newResource.getVendorRelease() == null) {
-                       newResource.setVendorRelease(oldResource.getVendorRelease());
-               }
-
-               if (newResource.getResourceVendorModelNumber() == null) {
-                       newResource.setResourceVendorModelNumber(oldResource.getResourceVendorModelNumber());
-               }
-
-               if (newResource.getContactId() == null) {
-                       newResource.setContactId(oldResource.getContactId());
-               }
-
-               newResource.setCategories(oldResource.getCategories());
-               if (newResource.getVendorName() == null) {
-                       newResource.setVendorName(oldResource.getVendorName());
-               }
-               List<GroupDefinition>oldForUpdate = oldResource.getGroups();
-               if(CollectionUtils.isNotEmpty(oldForUpdate)){
-                       List<GroupDefinition>groupForUpdate = oldForUpdate.stream().map(group -> new GroupDefinition(group)).collect(Collectors.toList());
-
-                       groupForUpdate.stream().filter(group -> group.isVspOriginated())
-                                       .forEach(group -> group.setName(group.getInvariantName()));
-
-                       newResource.setGroups(groupForUpdate);
-               }
-
-
-               if(newResource.getResourceType().isAtomicType() && !newResource.getName().equals("Root")&& newResource.getResourceType() != ResourceTypeEnum.CVFC) {
-                       ResourceTypeEnum updatedResourceType = newResource.getResourceType();
-                       Component derivedFromResource = getParentComponent(newResource);
-                       if (derivedFromResource.getComponentType() == ComponentTypeEnum.RESOURCE) {
-                               Resource parentResource = (Resource) derivedFromResource;
-                               if (!(parentResource.isAbstract() && (ResourceTypeEnum.VFC == parentResource.getResourceType() || ResourceTypeEnum.ABSTRACT == parentResource.getResourceType())) &&
-                                               parentResource.getResourceType() != updatedResourceType && oldResource.getResourceType() != updatedResourceType) {
-                                       BeEcompErrorManager.getInstance()
-                                                       .logInternalDataError("mergeOldResourceMetadataWithNew", "resource type of the resource does not match to derived from resource type",
-                                                                       ErrorSeverity.ERROR);
-                                       log.debug("#mergeOldResourceMetadataWithNew - resource type {} of the resource {} does not match to derived from resource type {}",
-                                                       newResource.getResourceType(), newResource.getToscaResourceName(), parentResource.getResourceType());
-                                       throw new ByActionStatusComponentException(ActionStatus.INVALID_RESOURCE_TYPE);
-                               }
-                       }
-               }
-
-       }
-
-       private Component getParentComponent(Resource newResource) {
-               String toscaResourceNameDerivedFrom = newResource.getDerivedFrom().get(0);
-               Either<Component, StorageOperationStatus> latestByToscaResourceName = toscaOperationFacade.getLatestByToscaResourceName(toscaResourceNameDerivedFrom);
-               if(latestByToscaResourceName.isRight()){
-                       BeEcompErrorManager.getInstance()
-                                       .logInternalDataError("mergeOldResourceMetadataWithNew", "derived from resource not found", ErrorSeverity.ERROR);
-                       log.debug("#mergeOldResourceMetadataWithNew - derived from resource {} not found", toscaResourceNameDerivedFrom);
-                       throw new ByActionStatusComponentException(ActionStatus.RESOURCE_NOT_FOUND, toscaResourceNameDerivedFrom);
-               }
-               return latestByToscaResourceName.left().value();
-       }
-
-       private Resource prepareResourceForUpdate(Resource oldResource, Resource newResource, User user,
-                                                                                         boolean inTransaction, boolean needLock) {
-
-               if (!ComponentValidationUtils.canWorkOnResource(oldResource, user.getUserId())) {
-                       // checkout
-                       return lifecycleBusinessLogic.changeState(oldResource.getUniqueId(), user, LifeCycleTransitionEnum.CHECKOUT,
-                                       new LifecycleChangeInfoWithAction("update by import"), inTransaction, needLock)
-                                       .left()
-                                       .on(response -> failOnChangeState(response, user, oldResource, newResource));
-               }
-               return oldResource;
-       }
-
-       private Resource failOnChangeState(ResponseFormat response, User user, Resource oldResource, Resource newResource) {
-               log.info("resource {} cannot be updated. reason={}", oldResource.getUniqueId(), response.getFormattedMessage());
-               componentsUtils.auditResource(response, user, newResource, AuditingActionEnum.IMPORT_RESOURCE,
-                               ResourceVersionInfo.newBuilder()
-                                               .state(oldResource.getLifecycleState()
-                                                               .name())
-                                               .version(oldResource.getVersion())
-                                               .build());
-               throw new ByResponseFormatComponentException(response);
-       }
-
-       public Resource validateResourceBeforeCreate(Resource resource, User user, AuditingActionEnum actionEnum,
-                                                                                                boolean inTransaction, CsarInfo csarInfo) {
-
-               validateResourceFieldsBeforeCreate(user, resource, actionEnum, inTransaction);
-               validateCapabilityTypesCreate(user, getCapabilityTypeOperation(), resource, actionEnum, inTransaction);
-               validateLifecycleTypesCreate(user, resource, actionEnum);
-               validateResourceType(user, resource, actionEnum);
-               resource.setCreatorUserId(user.getUserId());
-               resource.setCreatorFullName(user.getFirstName() + " " + user.getLastName());
-               resource.setContactId(resource.getContactId()
-                               .toLowerCase());
-               if (StringUtils.isEmpty(resource.getToscaResourceName()) && !ModelConverter.isAtomicComponent(resource)) {
-                       String resourceSystemName;
-                       if (csarInfo != null && StringUtils.isNotEmpty(csarInfo.getVfResourceName())) {
-                               resourceSystemName = ValidationUtils.convertToSystemName(csarInfo.getVfResourceName());
-                       } else {
-                               resourceSystemName = resource.getSystemName();
-                       }
-                       resource.setToscaResourceName(CommonBeUtils
-                               .generateToscaResourceName(resource.getResourceType().name().toLowerCase(), resourceSystemName));
-               }
-
-               // Generate invariant UUID - must be here and not in operation since it
-               // should stay constant during clone
-               // TODO
-               String invariantUUID = UniqueIdBuilder.buildInvariantUUID();
-               resource.setInvariantUUID(invariantUUID);
-
-               return resource;
-       }
-
-       private Either<Boolean, ResponseFormat> validateResourceType(User user, Resource resource,
-                                                                                                                                AuditingActionEnum actionEnum) {
-               Either<Boolean, ResponseFormat> eitherResult = Either.left(true);
-               if (resource.getResourceType() == null) {
-                       log.debug("Invalid resource type for resource");
-                       ResponseFormat errorResponse = componentsUtils.getResponseFormat(ActionStatus.INVALID_CONTENT);
-                       eitherResult = Either.right(errorResponse);
-                       componentsUtils.auditResource(errorResponse, user, resource, actionEnum);
-               }
-               return eitherResult;
-       }
-
-       private Either<Boolean, ResponseFormat> validateLifecycleTypesCreate(User user, Resource resource,
-                                                                                                                                                AuditingActionEnum actionEnum) {
-               Either<Boolean, ResponseFormat> eitherResult = Either.left(true);
-               if (resource.getInterfaces() != null && resource.getInterfaces()
-                               .size() > 0) {
-                       log.debug("validate interface lifecycle Types Exist");
-                       Iterator<InterfaceDefinition> intItr = resource.getInterfaces()
-                                       .values()
-                                       .iterator();
-                       while (intItr.hasNext() && eitherResult.isLeft()) {
-                               InterfaceDefinition interfaceDefinition = intItr.next();
-                               String intType = interfaceDefinition.getUniqueId();
-                               Either<InterfaceDefinition, StorageOperationStatus> eitherCapTypeFound = interfaceTypeOperation
-                                               .getInterface(intType);
-                               if (eitherCapTypeFound.isRight()) {
-                                       if (eitherCapTypeFound.right()
-                                                       .value() == StorageOperationStatus.NOT_FOUND) {
-                                               BeEcompErrorManager.getInstance()
-                                                               .logBeGraphObjectMissingError("Create Resource - validateLifecycleTypesCreate",
-                                                                               "Interface", intType);
-                                               log.debug("Lifecycle Type: {} is required by resource: {} but does not exist in the DB",
-                                                               intType, resource.getName());
-                                               BeEcompErrorManager.getInstance()
-                                                               .logBeDaoSystemError("Create Resource - validateLifecycleTypesCreate");
-                                               log.debug("request to data model failed with error: {}", eitherCapTypeFound.right()
-                                                               .value()
-                                                               .name());
-                                       }
-
-                                       ResponseFormat errorResponse = componentsUtils
-                                                       .getResponseFormat(ActionStatus.MISSING_LIFECYCLE_TYPE, intType);
-                                       eitherResult = Either.right(errorResponse);
-                                       componentsUtils.auditResource(errorResponse, user, resource, actionEnum);
-                               }
-
-                       }
-               }
-               return eitherResult;
-       }
-
-       private Either<Boolean, ResponseFormat> validateCapabilityTypesCreate(User user,
-                                                                                                                                                 ICapabilityTypeOperation capabilityTypeOperation, Resource resource, AuditingActionEnum actionEnum,
-                                                                                                                                                 boolean inTransaction) {
-
-               Either<Boolean, ResponseFormat> eitherResult = Either.left(true);
-               if (resource.getCapabilities() != null && resource.getCapabilities()
-                               .size() > 0) {
-                       log.debug("validate capability Types Exist - capabilities section");
-
-                       for (Entry<String, List<CapabilityDefinition>> typeEntry : resource.getCapabilities()
-                                       .entrySet()) {
-
-                               eitherResult = validateCapabilityTypeExists(user, capabilityTypeOperation, resource, actionEnum,
-                                               eitherResult, typeEntry, inTransaction);
-                               if (eitherResult.isRight()) {
-                                       return Either.right(eitherResult.right()
-                                                       .value());
-                               }
-                       }
-               }
-
-               if (resource.getRequirements() != null && resource.getRequirements()
-                               .size() > 0) {
-                       log.debug("validate capability Types Exist - requirements section");
-                       for (String type : resource.getRequirements()
-                                       .keySet()) {
-                               eitherResult = validateCapabilityTypeExists(user, capabilityTypeOperation, resource,
-                                               resource.getRequirements()
-                                                               .get(type),
-                                               actionEnum, eitherResult, type, inTransaction);
-                               if (eitherResult.isRight()) {
-                                       return Either.right(eitherResult.right()
-                                                       .value());
-                               }
-                       }
-               }
-
-               return eitherResult;
-       }
-
-       // @param typeObject- the object to which the validation is done
-       private Either<Boolean, ResponseFormat> validateCapabilityTypeExists(User user,
-                                                                                                                                                ICapabilityTypeOperation capabilityTypeOperation, Resource resource, List<?> validationObjects,
-                                                                                                                                                AuditingActionEnum actionEnum, Either<Boolean, ResponseFormat> eitherResult, String type,
-                                                                                                                                                boolean inTransaction) {
-               Either<CapabilityTypeDefinition, StorageOperationStatus> eitherCapTypeFound = capabilityTypeOperation
-                               .getCapabilityType(type, inTransaction);
-               if (eitherCapTypeFound.isRight()) {
-                       if (eitherCapTypeFound.right()
-                                       .value() == StorageOperationStatus.NOT_FOUND) {
-                               BeEcompErrorManager.getInstance()
-                                               .logBeGraphObjectMissingError(CREATE_RESOURCE_VALIDATE_CAPABILITY_TYPES, "Capability Type",
-                                                               type);
-                               log.debug("Capability Type: {} is required by resource: {} but does not exist in the DB", type,
-                                               resource.getName());
-                               BeEcompErrorManager.getInstance()
-                                               .logBeDaoSystemError(CREATE_RESOURCE_VALIDATE_CAPABILITY_TYPES);
-                       }
-                       log.debug("Trying to get capability type {} failed with error: {}", type, eitherCapTypeFound.right()
-                                       .value()
-                                       .name());
-                       ResponseFormat errorResponse = null;
-                       if (type != null) {
-                               errorResponse = componentsUtils.getResponseFormat(ActionStatus.MISSING_CAPABILITY_TYPE, type);
-                       } else {
-                               errorResponse = componentsUtils.getResponseFormatByElement(ActionStatus.MISSING_CAPABILITY_TYPE,
-                                               validationObjects);
-                       }
-                       eitherResult = Either.right(errorResponse);
-                       componentsUtils.auditResource(errorResponse, user, resource, actionEnum);
-               }
-               return eitherResult;
-       }
-
-       private Either<Boolean, ResponseFormat> validateCapabilityTypeExists(User user,
-                                                                                                                                                ICapabilityTypeOperation capabilityTypeOperation, Resource resource, AuditingActionEnum actionEnum,
-                                                                                                                                                Either<Boolean, ResponseFormat> eitherResult, Entry<String, List<CapabilityDefinition>> typeEntry,
-                                                                                                                                                boolean inTransaction) {
-               Either<CapabilityTypeDefinition, StorageOperationStatus> eitherCapTypeFound = capabilityTypeOperation
-                               .getCapabilityType(typeEntry.getKey(), inTransaction);
-               if (eitherCapTypeFound.isRight()) {
-                       if (eitherCapTypeFound.right().value() == StorageOperationStatus.NOT_FOUND) {
-                               BeEcompErrorManager.getInstance()
-                                               .logBeGraphObjectMissingError(CREATE_RESOURCE_VALIDATE_CAPABILITY_TYPES, "Capability Type",
-                                                               typeEntry.getKey());
-                               log.debug("Capability Type: {} is required by resource: {} but does not exist in the DB",
-                                               typeEntry.getKey(), resource.getName());
-                               BeEcompErrorManager.getInstance().logBeDaoSystemError(CREATE_RESOURCE_VALIDATE_CAPABILITY_TYPES);
-                       }
-                       log.debug("Trying to get capability type {} failed with error: {}", typeEntry.getKey(),
-                                       eitherCapTypeFound.right().value().name());
-                       ResponseFormat errorResponse = componentsUtils.getResponseFormat(ActionStatus.MISSING_CAPABILITY_TYPE,
-                                       typeEntry.getKey());
-                       componentsUtils.auditResource(errorResponse, user, resource, actionEnum);
-                       return Either.right(errorResponse);
-               }
-               CapabilityTypeDefinition capabilityTypeDefinition = eitherCapTypeFound.left().value();
-               if (capabilityTypeDefinition.getProperties() != null) {
-                       for (CapabilityDefinition capDef : typeEntry.getValue()) {
-                               List<ComponentInstanceProperty> properties = capDef.getProperties();
-                               List<ComponentInstanceProperty> changedProperties = new ArrayList<>();
-                               if (properties == null || properties.isEmpty()) {
-                                       for (Entry<String, PropertyDefinition> prop : capabilityTypeDefinition.getProperties().entrySet()) {
-                                               ComponentInstanceProperty newProp = new ComponentInstanceProperty(prop.getValue());
-                                               changedProperties.add(newProp);
-                                       }
-                               } else {
-                                       List<ComponentInstanceProperty> propsToAdd = new ArrayList<>();
-                                       for (Entry<String, PropertyDefinition> prop : capabilityTypeDefinition.getProperties().entrySet()) {
-                                               PropertyDefinition propFromDef = prop.getValue();
-                                               boolean propFound = false;
-                                               for (ComponentInstanceProperty cip : properties) {
-                                                       if (propFromDef.getName().equals(cip.getName())) {
-                                                               //merge property value and property description only, ignore other fields
-                                                               if(cip.getDescription() != null && !cip.getDescription().equals(propFromDef.getDescription())){
-                                                                       propFromDef.setDescription(cip.getDescription());
-                                                               }
-                                                               propertyDataValueMergeBusinessLogic.mergePropertyValue(propFromDef, cip, new ArrayList<>());
-                                                               if(cip.getValue() != null){
-                                                                       propFromDef.setValue(cip.getValue());
-                                                               }
-                                                               propsToAdd.add(new ComponentInstanceProperty(propFromDef));
-                                                               propFound = true;
-                                                               properties.remove(cip);
-                                                               break;
-                                                       }
-                                               }
-                                               if(!propFound) {
-                                                       propsToAdd.add(new ComponentInstanceProperty(propFromDef));
-                                               }
-                                       }
-                                       if (!propsToAdd.isEmpty()) {
-                                               changedProperties.addAll(propsToAdd);
-                                       }
-                               }
-                               capDef.setProperties(changedProperties);
-                       }
-               }
-               return eitherResult;
-       }
-
-       public Resource createResourceByDao(Resource resource, User user, AuditingActionEnum actionEnum,
-                                                                               boolean isNormative, boolean inTransaction) {
-               // create resource
-
-               // lock new resource name in order to avoid creation resource with same
-               // name
-               Resource createdResource = null;
-               if (!inTransaction) {
-                       Either<Boolean, ResponseFormat> lockResult = lockComponentByName(resource.getSystemName(), resource,
-                                       CREATE_RESOURCE);
-                       if (lockResult.isRight()) {
-                               ResponseFormat responseFormat = lockResult.right().value();
-                               componentsUtils.auditResource(responseFormat, user, resource, actionEnum);
-                               throw new ByResponseFormatComponentException(responseFormat);
-                       }
-
-                       log.debug("name is locked {} status = {}", resource.getSystemName(), lockResult);
-               }
-               try {
-                       if (resource.deriveFromGeneric()) {
-                               handleResourceGenericType(resource);
-                       }
-                       createdResource = createResourceTransaction(resource, user, isNormative);
-                       componentsUtils.auditResource(componentsUtils.getResponseFormat(ActionStatus.CREATED), user,
-                                       createdResource, actionEnum);
-                       ASDCKpiApi.countCreatedResourcesKPI();
-               } catch (ComponentException e) {
-                       ResponseFormat responseFormat = e.getResponseFormat() == null
-                                       ? componentsUtils.getResponseFormat(e.getActionStatus(), e.getParams()) : e.getResponseFormat();
-                       componentsUtils.auditResource(responseFormat, user, resource, actionEnum);
-                       throw e;
-               } catch (StorageException e) {
-                       ResponseFormat responseFormat = componentsUtils
-                                       .getResponseFormat(componentsUtils.convertFromStorageResponse(e.getStorageOperationStatus()));
-                       componentsUtils.auditResource(responseFormat, user, resource, actionEnum);
-                       throw e;
-               } finally {
-            if (!inTransaction) {
-                               graphLockOperation.unlockComponentByName(resource.getSystemName(), resource.getUniqueId(),
-                                               NodeTypeEnum.Resource);
-                       }
-               }
-               return createdResource;
-       }
-
-       private Resource createResourceTransaction(Resource resource, User user, boolean isNormative) {
-               // validate resource name uniqueness
-               log.debug("validate resource name");
-               Either<Boolean, StorageOperationStatus> eitherValidation = toscaOperationFacade.validateComponentNameExists(
-                               resource.getName(), resource.getResourceType(), resource.getComponentType());
-               if (eitherValidation.isRight()) {
-                       loggerSupportability.log(LoggerSupportabilityActions.VALIDATE_NAME,resource.getComponentMetadataForSupportLog(),
-                                       StatusCode.ERROR,"ERROR while validate component name {} Status is: {}",resource.getName(),eitherValidation.right().value());
-                       log.debug("Failed to validate component name {}. Status is {}. ", resource.getName(),
-                                       eitherValidation.right()
-                                                       .value());
-                       throw new ByActionStatusComponentException(componentsUtils.convertFromStorageResponse(eitherValidation.right()
-                                       .value()));
-               }
-               if (eitherValidation.left()
-                               .value()) {
-                       log.debug("resource with name: {}, already exists", resource.getName());
-                       loggerSupportability.log(LoggerSupportabilityActions.CREATE_RESOURCE_FROM_YAML,resource.getComponentMetadataForSupportLog(),
-                                       StatusCode.ERROR,"resource with name: {} already exists",resource.getName());
-                       throw new ByActionStatusComponentException(ActionStatus.COMPONENT_NAME_ALREADY_EXIST,
-                                       ComponentTypeEnum.RESOURCE.getValue(), resource.getName());
-               }
-
-               log.debug("send resource {} to dao for create", resource.getName());
-
-               createArtifactsPlaceHolderData(resource, user);
-               // enrich object
-               if (!isNormative) {
-                       log.debug("enrich resource with creator, version and state");
-                       resource.setLifecycleState(LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT);
-                       resource.setVersion(INITIAL_VERSION);
-                       resource.setHighestVersion(true);
-                       if (resource.getResourceType() != null && resource.getResourceType() != ResourceTypeEnum.CVFC) {
-                               resource.setAbstract(false);
-                       }
-               }
-               return toscaOperationFacade.createToscaComponent(resource)
-                               .left()
-                               .on(r -> throwComponentExceptionByResource(r, resource));
-       }
-
-       private Resource throwComponentExceptionByResource(StorageOperationStatus status, Resource resource) {
-               ResponseFormat responseFormat = componentsUtils
-                               .getResponseFormatByResource(componentsUtils.convertFromStorageResponse(status), resource);
-               throw new ByResponseFormatComponentException(responseFormat);
-       }
-
-       private void createArtifactsPlaceHolderData(Resource resource, User user) {
-               // create mandatory artifacts
-
-               // TODO it must be removed after that artifact uniqueId creation will be
-               // moved to ArtifactOperation
-
-               setInformationalArtifactsPlaceHolder(resource, user);
-               setDeploymentArtifactsPlaceHolder(resource, user);
-               setToscaArtifactsPlaceHolders(resource, user);
-       }
-
-       @SuppressWarnings("unchecked")
-       @Override
-       public void setDeploymentArtifactsPlaceHolder(Component component, User user) {
-               Resource resource = (Resource) component;
-               Map<String, ArtifactDefinition> artifactMap = resource.getDeploymentArtifacts();
-               if (artifactMap == null) {
-                       artifactMap = new HashMap<>();
-               }
-               Map<String, Object> deploymentResourceArtifacts = ConfigurationManager.getConfigurationManager()
-                               .getConfiguration()
-                               .getDeploymentResourceArtifacts();
-               if (deploymentResourceArtifacts != null) {
-                       Map<String, ArtifactDefinition> finalArtifactMap = artifactMap;
-                       deploymentResourceArtifacts
-                                       .forEach((k, v) -> processDeploymentResourceArtifacts(user, resource, finalArtifactMap, k, v));
-               }
-               resource.setDeploymentArtifacts(artifactMap);
-       }
-
-       private void processDeploymentResourceArtifacts(User user, Resource resource,
-                                                                                                       Map<String, ArtifactDefinition> artifactMap, String k, Object v) {
-               Map<String, Object> artifactDetails = (Map<String, Object>) v;
-               Object object = artifactDetails.get(PLACE_HOLDER_RESOURCE_TYPES);
-               if (object != null) {
-                       List<String> artifactTypes = (List<String>) object;
-                       if (!artifactTypes.contains(resource.getResourceType()
-                                       .name())) {
-                               return;
-                       }
-               } else {
-                       log.info("resource types for artifact placeholder {} were not defined. default is all resources", k);
-               }
-               if (artifactsBusinessLogic != null) {
-                       ArtifactDefinition artifactDefinition = artifactsBusinessLogic.createArtifactPlaceHolderInfo(
-                                       resource.getUniqueId(), k, (Map<String, Object>) v, user, ArtifactGroupTypeEnum.DEPLOYMENT);
-                       if (artifactDefinition != null && !artifactMap.containsKey(artifactDefinition.getArtifactLabel())) {
-                               artifactMap.put(artifactDefinition.getArtifactLabel(), artifactDefinition);
-                       }
-               }
-       }
-
-       @SuppressWarnings("unchecked")
-       private void setInformationalArtifactsPlaceHolder(Resource resource, User user) {
-               Map<String, ArtifactDefinition> artifactMap = resource.getArtifacts();
-               if (artifactMap == null) {
-                       artifactMap = new HashMap<>();
-               }
-               String resourceUniqueId = resource.getUniqueId();
-               List<String> exludeResourceCategory = ConfigurationManager.getConfigurationManager()
-                               .getConfiguration()
-                               .getExcludeResourceCategory();
-               List<String> exludeResourceType = ConfigurationManager.getConfigurationManager()
-                               .getConfiguration()
-                               .getExcludeResourceType();
-               Map<String, Object> informationalResourceArtifacts = ConfigurationManager.getConfigurationManager()
-                               .getConfiguration()
-                               .getInformationalResourceArtifacts();
-               List<CategoryDefinition> categories = resource.getCategories();
-               boolean isCreateArtifact = true;
-               if (exludeResourceCategory != null) {
-                       String category = categories.get(0)
-                                       .getName();
-                       isCreateArtifact = exludeResourceCategory.stream()
-                                       .noneMatch(e -> e.equalsIgnoreCase(category));
-               }
-               if (isCreateArtifact && exludeResourceType != null) {
-                       String resourceType = resource.getResourceType()
-                                       .name();
-                       isCreateArtifact = exludeResourceType.stream()
-                                       .noneMatch(e -> e.equalsIgnoreCase(resourceType));
-               }
-               if (informationalResourceArtifacts != null && isCreateArtifact) {
-                       Set<String> keys = informationalResourceArtifacts.keySet();
-                       for (String informationalResourceArtifactName : keys) {
-                               Map<String, Object> artifactInfoMap = (Map<String, Object>) informationalResourceArtifacts
-                                               .get(informationalResourceArtifactName);
-                               ArtifactDefinition artifactDefinition = artifactsBusinessLogic.createArtifactPlaceHolderInfo(
-                                               resourceUniqueId, informationalResourceArtifactName, artifactInfoMap, user,
-                                               ArtifactGroupTypeEnum.INFORMATIONAL);
-                               artifactMap.put(artifactDefinition.getArtifactLabel(), artifactDefinition);
-
-                       }
-               }
-               resource.setArtifacts(artifactMap);
-       }
-
-       /**
-        * deleteResource
-        *
-        * @param resourceId
-        * @param user
-        * @return
-        */
-       public ResponseFormat deleteResource(String resourceId, User user) {
-               ResponseFormat responseFormat;
-               validateUserExists(user);
-
-               Either<Resource, StorageOperationStatus> resourceStatus = toscaOperationFacade.getToscaElement(resourceId);
-               if (resourceStatus.isRight()) {
-                       log.debug("failed to get resource {}", resourceId);
-                       return componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(resourceStatus.right()
-                                       .value()), "");
-               }
-
-               Resource resource = resourceStatus.left()
-                               .value();
-
-               StorageOperationStatus result = StorageOperationStatus.OK;
-               lockComponent(resourceId, resource, "Mark resource to delete");
-               try {
-
-                       result = markComponentToDelete(resource);
-                       if (result == StorageOperationStatus.OK) {
-                               responseFormat = componentsUtils.getResponseFormat(ActionStatus.NO_CONTENT);
-                       } else {
-                               ActionStatus actionStatus = componentsUtils.convertFromStorageResponse(result);
-                               responseFormat = componentsUtils.getResponseFormatByResource(actionStatus, resource.getName());
-                       }
-                       return responseFormat;
-
-               } finally {
-                       if (result == null || result != StorageOperationStatus.OK) {
-                               janusGraphDao.rollback();
-                       } else {
-                janusGraphDao.commit();
-                       }
-                       graphLockOperation.unlockComponent(resourceId, NodeTypeEnum.Resource);
-               }
-
-       }
-
-       public ResponseFormat deleteResourceByNameAndVersion(String resourceName, String version, User user) {
-               ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.NO_CONTENT);
-               validateUserExists(user);
-               Resource resource = null;
-               StorageOperationStatus result = StorageOperationStatus.OK;
-               boolean failed = false;
-               try {
-
-                       Either<Resource, StorageOperationStatus> resourceStatus = toscaOperationFacade
-                                       .getComponentByNameAndVersion(ComponentTypeEnum.RESOURCE, resourceName, version);
-                       if (resourceStatus.isRight()) {
-                               log.debug("failed to get resource {} version {}", resourceName, version);
-                               return componentsUtils
-                                               .getResponseFormatByResource(componentsUtils.convertFromStorageResponse(resourceStatus.right()
-                                                               .value()), resourceName);
-                       }
-
-                       resource = resourceStatus.left()
-                                       .value();
-
-               } finally {
-                       janusGraphDao.commit();
-               }
-               if (resource != null) {
-                       lockComponent(resource.getUniqueId(), resource, DELETE_RESOURCE);
-                       try {
-                               result = markComponentToDelete(resource);
-                               if (result != StorageOperationStatus.OK) {
-                                       ActionStatus actionStatus = componentsUtils.convertFromStorageResponse(result);
-                                       responseFormat = componentsUtils.getResponseFormatByResource(actionStatus, resource.getName());
-                                       return responseFormat;
-                               }
-                       }catch (ComponentException e){
-                               failed = true;
-                               throw e;
-                       }finally {
-                               if (failed || result == null || result != StorageOperationStatus.OK) {
-                                       janusGraphDao.rollback();
-                               } else {
-                    janusGraphDao.commit();
-                               }
-                               graphLockOperation.unlockComponent(resource.getUniqueId(), NodeTypeEnum.Resource);
-                       }
-               }
-               return responseFormat;
-       }
-
-       public Either<Resource, ResponseFormat> getResource(String resourceId, User user) {
-
-               if (user != null) {
-                       validateUserExists(user);
-               }
-
-               Either<Resource, StorageOperationStatus> storageStatus = toscaOperationFacade.getToscaElement(resourceId);
-               if (storageStatus.isRight()) {
-                       log.debug("failed to get resource by id {}", resourceId);
-                       return Either.right(componentsUtils
-                                       .getResponseFormatByResource(componentsUtils.convertFromStorageResponse(storageStatus.right()
-                                                       .value()), resourceId));
-               }
-               if (!(storageStatus.left()
-                               .value() instanceof Resource)) {
-                       return Either.right(componentsUtils.getResponseFormatByResource(
-                                       componentsUtils.convertFromStorageResponse(StorageOperationStatus.NOT_FOUND), resourceId));
-               }
-               return Either.left(storageStatus.left()
-                               .value());
-
-       }
-
-       public Either<Resource, ResponseFormat> getResourceByNameAndVersion(String resourceName, String resourceVersion,
-                                                                                                                                               String userId) {
-
-               validateUserExists(userId);
-
-               Either<Resource, StorageOperationStatus> getResource = toscaOperationFacade
-                               .getComponentByNameAndVersion(ComponentTypeEnum.RESOURCE, resourceName, resourceVersion);
-               if (getResource.isRight()) {
-                       log.debug("failed to get resource by name {} and version {}", resourceName, resourceVersion);
-                       return Either.right(componentsUtils
-                                       .getResponseFormatByResource(componentsUtils.convertFromStorageResponse(getResource.right()
-                                                       .value()), resourceName));
-               }
-               return Either.left(getResource.left()
-                               .value());
-       }
-
-       /**
-        * updateResourceMetadata
-        *
-        * @param user
-        *            - modifier data (userId)
-        * @param inTransaction
-        *            TODO
-        * @param resourceIdToUpdate
-        *            - the resource identifier
-        * @param newResource
-        * @return Either<Resource , responseFormat>
-        */
-       public Resource updateResourceMetadata(String resourceIdToUpdate, Resource newResource, Resource currentResource,
-                                                                                  User user, boolean inTransaction) {
-
-               validateUserExists(user.getUserId());
-
-               log.debug("Get resource with id {}", resourceIdToUpdate);
-               boolean needToUnlock = false;
-
-               try {
-                       if (currentResource == null) {
-                               Either<Resource, StorageOperationStatus> storageStatus = toscaOperationFacade
-                                               .getToscaElement(resourceIdToUpdate);
-                               if (storageStatus.isRight()) {
-                                       throw new ByResponseFormatComponentException(componentsUtils.getResponseFormatByResource(
-                                                       componentsUtils.convertFromStorageResponse(storageStatus.right()
-                                                                       .value()),
-                                                       ""));
-                               }
-
-                               currentResource = storageStatus.left()
-                                               .value();
-                       }
-                       // verify that resource is checked-out and the user is the last
-                       // updater
-                       if (!ComponentValidationUtils.canWorkOnResource(currentResource, user.getUserId())) {
-                               throw new ByResponseFormatComponentException(componentsUtils.getResponseFormat(ActionStatus.RESTRICTED_OPERATION));
-                       }
-
-                       // lock resource
-                       StorageOperationStatus lockResult = graphLockOperation.lockComponent(resourceIdToUpdate,
-                                       NodeTypeEnum.Resource);
-                       if (lockResult != StorageOperationStatus.OK) {
-                               BeEcompErrorManager.getInstance()
-                                               .logBeFailedLockObjectError("Upload Artifact - lock ", NodeTypeEnum.Resource.getName(),
-                                                               resourceIdToUpdate);
-                               log.debug("Failed to lock resource: {}, error - {}", resourceIdToUpdate, lockResult);
-                               ResponseFormat responseFormat = componentsUtils
-                                               .getResponseFormat(componentsUtils.convertFromStorageResponse(lockResult));
-                               throw new ByResponseFormatComponentException(responseFormat);
-                       }
-
-                       needToUnlock = true;
-
-                       // critical section starts here
-                       // convert json to object
-
-                       // Update and updated resource must have a non-empty "derivedFrom"
-                       // list
-                       // This code is not called from import resources, because of root
-                       // VF "derivedFrom" should be null (or ignored)
-                       if (ModelConverter.isAtomicComponent(currentResource)) {
-                               validateDerivedFromNotEmpty(null, newResource, null);
-                               validateDerivedFromNotEmpty(null, currentResource, null);
-                       } else {
-                               newResource.setDerivedFrom(null);
-                       }
-
-            Either<Resource, ResponseFormat> dataModelResponse = updateResourceMetadata(resourceIdToUpdate, newResource,
-                    user, currentResource, false, true);
-            if (dataModelResponse.isRight()) {
-                log.debug("failed to update resource metadata!!!");
-                throw new ByResponseFormatComponentException(dataModelResponse.right().value());
+    private void validateIcon(Resource currentResource, Resource updateInfoResource, boolean hasBeenCertified) {
+        String iconUpdated = updateInfoResource.getIcon();
+        String iconCurrent = currentResource.getIcon();
+        if (!iconCurrent.equals(iconUpdated)) {
+            if (!hasBeenCertified) {
+                componentIconValidator.validateAndCorrectField(null, updateInfoResource, null);
+            } else {
+                log.info("Icon {} cannot be updated once the resource has been certified once.", iconUpdated);
+                throw new ByActionStatusComponentException(ActionStatus.RESOURCE_ICON_CANNOT_BE_CHANGED);
             }
+        }
+    }
 
-                       log.debug("Resource metadata updated successfully!!!");
-                       return dataModelResponse.left()
-                                       .value();
+    private void validateResourceVendorModelNumber(Resource currentResource, Resource updateInfoResource) {
+        String updatedResourceVendorModelNumber = updateInfoResource.getResourceVendorModelNumber();
+        String currentResourceVendorModelNumber = currentResource.getResourceVendorModelNumber();
+        if (!currentResourceVendorModelNumber.equals(updatedResourceVendorModelNumber)) {
+            validateResourceVendorModelNumber(null, updateInfoResource, null);
+        }
+    }
 
-               } catch (ComponentException | StorageException e) {
-                       rollback(inTransaction, newResource, null, null);
-                       throw e;
-               } finally {
-                       if (!inTransaction) {
-                janusGraphDao.commit();
-                       }
-                       if (needToUnlock) {
-                               graphLockOperation.unlockComponent(resourceIdToUpdate, NodeTypeEnum.Resource);
-                       }
-               }
-       }
-
-       private Either<Resource, ResponseFormat> updateResourceMetadata(String resourceIdToUpdate, Resource newResource,
-                                                                                                                                       User user, Resource currentResource, boolean shouldLock, boolean inTransaction) {
-               updateVfModuleGroupsNames(currentResource, newResource);
-               validateResourceFieldsBeforeUpdate(currentResource, newResource, inTransaction, false);
-               // Setting last updater and uniqueId
-               newResource.setContactId(newResource.getContactId()
-                               .toLowerCase());
-               newResource.setLastUpdaterUserId(user.getUserId());
-               newResource.setUniqueId(resourceIdToUpdate);
-               // Cannot set highest version through UI
-               newResource.setHighestVersion(currentResource.isHighestVersion());
-               newResource.setCreationDate(currentResource.getCreationDate());
-
-               Either<Boolean, ResponseFormat> processUpdateOfDerivedFrom = processUpdateOfDerivedFrom(currentResource,
-                               newResource, user.getUserId(), inTransaction);
-
-               if (processUpdateOfDerivedFrom.isRight()) {
-                       log.debug("Couldn't update derived from for resource {}", resourceIdToUpdate);
-                       return Either.right(processUpdateOfDerivedFrom.right()
-                                       .value());
-               }
-
-               log.debug("send resource {} to dao for update", newResource.getUniqueId());
-               if (isNotEmpty(newResource.getGroups())) {
-                       for (GroupDefinition group : newResource.getGroups()) {
-                               if (DEFAULT_GROUP_VF_MODULE.equals(group.getType())) {
-                                       groupBusinessLogic.validateAndUpdateGroupMetadata(newResource.getComponentMetadataDefinition()
-                                                       .getMetadataDataDefinition()
-                                                       .getUniqueId(), user, newResource.getComponentType(), group, true, false);
-                               }
-                       }
-               }
-               Either<Resource, StorageOperationStatus> dataModelResponse = toscaOperationFacade
-                               .updateToscaElement(newResource);
-
-               if (dataModelResponse.isRight()) {
-                       ResponseFormat responseFormat = componentsUtils
-                                       .getResponseFormatByResource(componentsUtils.convertFromStorageResponse(dataModelResponse.right()
-                                                       .value()), newResource);
-                       return Either.right(responseFormat);
-               } else if (dataModelResponse.left()
-                               .value() == null) {
-                       log.debug("No response from updateResource");
-                       return Either.right(componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR));
-               }
-               return Either.left(dataModelResponse.left()
-                               .value());
-       }
-
-       private void updateVfModuleGroupsNames(Resource currentResource, Resource newResource) {
-               if (currentResource.getGroups() != null && !currentResource.getName()
-                               .equals(newResource.getName())) {
-                       List<GroupDefinition> updatedGroups = currentResource.getGroups()
-                                       .stream()
-                                       .map(group -> getUpdatedGroup(group, currentResource.getName(), newResource.getName()))
-                                       .collect(toList());
-                       newResource.setGroups(updatedGroups);
-               }
-       }
-
-       private GroupDefinition getUpdatedGroup(GroupDefinition currGroup, String replacePattern, String with) {
-               GroupDefinition updatedGroup = new GroupDefinition(currGroup);
-               if (updatedGroup.isSamePrefix(replacePattern) && updatedGroup.getType()
-                               .equals(DEFAULT_GROUP_VF_MODULE)) {
-                       String prefix = updatedGroup.getName()
-                                       .substring(0, replacePattern.length());
-                       String newGroupName = updatedGroup.getName()
-                                       .replaceFirst(prefix, with);
-                       updatedGroup.setName(newGroupName);
-               }
-               return updatedGroup;
-       }
-
-       /**
-        * validateResourceFieldsBeforeCreate
-        *
-        * @param user
-        *            - modifier data (userId)
-        */
-       private void validateResourceFieldsBeforeCreate(User user, Resource resource,
-                                                                                                       AuditingActionEnum actionEnum, boolean inTransaction) {
-               componentValidator.validate(user, resource, actionEnum);
-               // validate category
-               log.debug("validate category");
-               validateCategory(user, resource, actionEnum, inTransaction);
-               // validate vendor name & release & model number
-               log.debug("validate vendor name");
-               validateVendorName(user, resource, actionEnum);
-               log.debug("validate vendor release");
-               validateVendorReleaseName(user, resource, actionEnum);
-               log.debug("validate resource vendor model number");
-               validateResourceVendorModelNumber(user, resource, actionEnum);
-               // validate cost
-               log.debug("validate cost");
-               validateCost(resource);
-               // validate licenseType
-               log.debug("validate licenseType");
-               validateLicenseType(user, resource, actionEnum);
-               // validate template (derived from)
-               log.debug("validate derived from");
-               if (!ModelConverter.isAtomicComponent(resource) && resource.getResourceType() != ResourceTypeEnum.CVFC) {
-                       resource.setDerivedFrom(null);
-               }
-               validateDerivedFromExist(user, resource, actionEnum);
-               // warn about non-updatable fields
-               checkComponentFieldsForOverrideAttempt(resource);
-               String currentCreatorFullName = resource.getCreatorFullName();
-               if (currentCreatorFullName != null) {
-                       log.debug("Resource Creator fullname is automatically set and cannot be updated");
-               }
-
-               String currentLastUpdaterFullName = resource.getLastUpdaterFullName();
-               if (currentLastUpdaterFullName != null) {
-                       log.debug("Resource LastUpdater fullname is automatically set and cannot be updated");
-               }
-
-               Long currentLastUpdateDate = resource.getLastUpdateDate();
-               if (currentLastUpdateDate != null) {
-                       log.debug("Resource last update date is automatically set and cannot be updated");
-               }
-
-               Boolean currentAbstract = resource.isAbstract();
-               if (currentAbstract != null) {
-                       log.debug("Resource abstract is automatically set and cannot be updated");
-               }
-       }
-
-       /**
-        * validateResourceFieldsBeforeUpdate
-        *
-        * @param currentResource
-        *            - Resource object to validate
-        * @param isNested
-        */
-       private void validateResourceFieldsBeforeUpdate(Resource currentResource, Resource updateInfoResource,
-                                                                                                       boolean inTransaction, boolean isNested) {
-               validateFields(currentResource, updateInfoResource, inTransaction, isNested);
-               warnNonEditableFields(currentResource, updateInfoResource);
-       }
-
-       private void warnNonEditableFields(Resource currentResource, Resource updateInfoResource) {
-               String currentResourceVersion = currentResource.getVersion();
-               String updatedResourceVersion = updateInfoResource.getVersion();
-
-               if ((updatedResourceVersion != null) && (!updatedResourceVersion.equals(currentResourceVersion))) {
-                       log.debug("Resource version is automatically set and cannot be updated");
-               }
-
-               String currentCreatorUserId = currentResource.getCreatorUserId();
-               String updatedCreatorUserId = updateInfoResource.getCreatorUserId();
-
-               if ((updatedCreatorUserId != null) && (!updatedCreatorUserId.equals(currentCreatorUserId))) {
-                       log.debug("Resource Creator UserId is automatically set and cannot be updated");
-               }
-
-               String currentCreatorFullName = currentResource.getCreatorFullName();
-               String updatedCreatorFullName = updateInfoResource.getCreatorFullName();
-
-               if ((updatedCreatorFullName != null) && (!updatedCreatorFullName.equals(currentCreatorFullName))) {
-                       log.debug("Resource Creator fullname is automatically set and cannot be updated");
-               }
-
-               String currentLastUpdaterUserId = currentResource.getLastUpdaterUserId();
-               String updatedLastUpdaterUserId = updateInfoResource.getLastUpdaterUserId();
-
-               if ((updatedLastUpdaterUserId != null) && (!updatedLastUpdaterUserId.equals(currentLastUpdaterUserId))) {
-                       log.debug("Resource LastUpdater userId is automatically set and cannot be updated");
-               }
-
-               String currentLastUpdaterFullName = currentResource.getLastUpdaterFullName();
-               String updatedLastUpdaterFullName = updateInfoResource.getLastUpdaterFullName();
-
-               if ((updatedLastUpdaterFullName != null) && (!updatedLastUpdaterFullName.equals(currentLastUpdaterFullName))) {
-                       log.debug("Resource LastUpdater fullname is automatically set and cannot be updated");
-               }
-               Long currentCreationDate = currentResource.getCreationDate();
-               Long updatedCreationDate = updateInfoResource.getCreationDate();
-
-               if ((updatedCreationDate != null) && (!updatedCreationDate.equals(currentCreationDate))) {
-                       log.debug("Resource Creation date is automatically set and cannot be updated");
-               }
-
-               Long currentLastUpdateDate = currentResource.getLastUpdateDate();
-               Long updatedLastUpdateDate = updateInfoResource.getLastUpdateDate();
-
-               if ((updatedLastUpdateDate != null) && (!updatedLastUpdateDate.equals(currentLastUpdateDate))) {
-                       log.debug("Resource last update date is automatically set and cannot be updated");
-               }
-
-               LifecycleStateEnum currentLifecycleState = currentResource.getLifecycleState();
-               LifecycleStateEnum updatedLifecycleState = updateInfoResource.getLifecycleState();
-
-               if ((updatedLifecycleState != null) && (!updatedLifecycleState.equals(currentLifecycleState))) {
-                       log.debug("Resource lifecycle state date is automatically set and cannot be updated");
-               }
-
-               Boolean currentAbstract = currentResource.isAbstract();
-               Boolean updatedAbstract = updateInfoResource.isAbstract();
-
-               if ((updatedAbstract != null) && (!updatedAbstract.equals(currentAbstract))) {
-                       log.debug("Resource abstract is automatically set and cannot be updated");
-               }
-
-               Boolean currentHighestVersion = currentResource.isHighestVersion();
-               Boolean updatedHighestVersion = updateInfoResource.isHighestVersion();
-
-               if ((updatedHighestVersion != null) && (!updatedHighestVersion.equals(currentHighestVersion))) {
-                       log.debug("Resource highest version is automatically set and cannot be updated");
-               }
-
-               String currentUuid = currentResource.getUUID();
-               String updatedUuid = updateInfoResource.getUUID();
-
-               if ((updatedUuid != null) && (!updatedUuid.equals(currentUuid))) {
-                       log.debug("Resource UUID is automatically set and cannot be updated");
-               }
-
-               log.debug("Resource Type  cannot be updated");
-               String currentInvariantUuid = currentResource.getInvariantUUID();
-               String updatedInvariantUuid = updateInfoResource.getInvariantUUID();
-
-               if ((updatedInvariantUuid != null) && (!updatedInvariantUuid.equals(currentInvariantUuid))) {
-                       log.debug("Resource invariant UUID is automatically set and cannot be updated");
-                       updateInfoResource.setInvariantUUID(currentInvariantUuid);
-               }
-       }
-
-       private void validateFields(Resource currentResource, Resource updateInfoResource, boolean inTransaction,
-                                                               boolean isNested) {
-               boolean hasBeenCertified = ValidationUtils.hasBeenCertified(currentResource.getVersion());
-               log.debug("validate resource name before update");
-               validateResourceName(currentResource, updateInfoResource, hasBeenCertified, isNested);
-               log.debug("validate description before update");
-               componentDescriptionValidator.validateAndCorrectField(null, updateInfoResource, null);
-               log.debug("validate icon before update");
-               validateIcon(currentResource, updateInfoResource, hasBeenCertified);
-               log.debug("validate tags before update");
-               componentTagsValidator.validateAndCorrectField(null, updateInfoResource, null);
-               log.debug("validate vendor name before update");
-               validateVendorName(null, updateInfoResource, null);
-               log.debug("validate resource vendor model number before update");
-               validateResourceVendorModelNumber(currentResource, updateInfoResource);
-               log.debug("validate vendor release before update");
-               validateVendorReleaseName(null, updateInfoResource, null);
-               log.debug("validate contact info before update");
-               componentContactIdValidator.validateAndCorrectField(null, updateInfoResource, null);
-               log.debug(VALIDATE_DERIVED_BEFORE_UPDATE);
-               validateDerivedFromDuringUpdate(currentResource, updateInfoResource, hasBeenCertified);
-               log.debug("validate category before update");
-               validateCategory(currentResource, updateInfoResource, hasBeenCertified, inTransaction);
-       }
-
-       private boolean isResourceNameEquals(Resource currentResource, Resource updateInfoResource) {
-               String resourceNameUpdated = updateInfoResource.getName();
-               String resourceNameCurrent = currentResource.getName();
-               if (resourceNameCurrent.equals(resourceNameUpdated)) {
-                       return true;
-               }
-               // In case of CVFC type we should support the case of old VF with CVFC
-               // instances that were created without the "Cvfc" suffix
-               return currentResource.getResourceType() == ResourceTypeEnum.CVFC
-                               && resourceNameUpdated.equals(addCvfcSuffixToResourceName(resourceNameCurrent));
-       }
-
-       private String addCvfcSuffixToResourceName(String resourceName) {
-               return resourceName + "Cvfc";
-       }
-
-       private void validateResourceName(Resource currentResource, Resource updateInfoResource, boolean hasBeenCertified,
-                                                                         boolean isNested) {
-               String resourceNameUpdated = updateInfoResource.getName();
-               if (!isResourceNameEquals(currentResource, updateInfoResource)) {
-                       if (isNested || !hasBeenCertified) {
-                               componentNameValidator.validateAndCorrectField(null, updateInfoResource, null);
-                               validateResourceNameUniqueness(updateInfoResource);
-                               currentResource.setName(resourceNameUpdated);
-                               currentResource.setNormalizedName(ValidationUtils.normaliseComponentName(resourceNameUpdated));
-                               currentResource.setSystemName(ValidationUtils.convertToSystemName(resourceNameUpdated));
-
-                       } else {
-                               log.info("Resource name: {}, cannot be updated once the resource has been certified once.",
-                                               resourceNameUpdated);
-                               throw new ByActionStatusComponentException(ActionStatus.RESOURCE_NAME_CANNOT_BE_CHANGED);
-                       }
-               }
-       }
-
-       private void validateIcon(Resource currentResource, Resource updateInfoResource, boolean hasBeenCertified) {
-               String iconUpdated = updateInfoResource.getIcon();
-               String iconCurrent = currentResource.getIcon();
-               if (!iconCurrent.equals(iconUpdated)) {
-                       if (!hasBeenCertified) {
-                               componentIconValidator.validateAndCorrectField(null, updateInfoResource, null);
-                       } else {
-                               log.info("Icon {} cannot be updated once the resource has been certified once.", iconUpdated);
-                               throw new ByActionStatusComponentException(ActionStatus.RESOURCE_ICON_CANNOT_BE_CHANGED);
-                       }
-               }
-       }
-
-       private void validateResourceVendorModelNumber(Resource currentResource, Resource updateInfoResource) {
-               String updatedResourceVendorModelNumber = updateInfoResource.getResourceVendorModelNumber();
-               String currentResourceVendorModelNumber = currentResource.getResourceVendorModelNumber();
-               if (!currentResourceVendorModelNumber.equals(updatedResourceVendorModelNumber)) {
-                       validateResourceVendorModelNumber(null, updateInfoResource, null);
-               }
-       }
-
-       private Either<Boolean, ResponseFormat> validateCategory(Resource currentResource, Resource updateInfoResource,
-                                                                                                                        boolean hasBeenCertified, boolean inTransaction) {
-               validateCategory(null, updateInfoResource, null, inTransaction);
-               if (hasBeenCertified) {
-                       CategoryDefinition currentCategory = currentResource.getCategories()
-                                       .get(0);
-                       SubCategoryDefinition currentSubCategory = currentCategory.getSubcategories()
-                                       .get(0);
-                       CategoryDefinition updateCategory = updateInfoResource.getCategories()
-                                       .get(0);
-                       SubCategoryDefinition updtaeSubCategory = updateCategory.getSubcategories()
-                                       .get(0);
-                       if (!currentCategory.getName()
-                                       .equals(updateCategory.getName())
-                                       || !currentSubCategory.getName()
-                                       .equals(updtaeSubCategory.getName())) {
-                               log.info("Category {} cannot be updated once the resource has been certified once.",
-                                               currentResource.getCategories());
-                               ResponseFormat errorResponse = componentsUtils
-                                               .getResponseFormat(ActionStatus.RESOURCE_CATEGORY_CANNOT_BE_CHANGED);
-                               return Either.right(errorResponse);
-                       }
-               }
-               return Either.left(true);
-       }
-
-       private Either<Boolean, ResponseFormat> validateDerivedFromDuringUpdate(Resource currentResource,
-                                                                                                                                                       Resource updateInfoResource, boolean hasBeenCertified) {
-
-               List<String> currentDerivedFrom = currentResource.getDerivedFrom();
-               List<String> updatedDerivedFrom = updateInfoResource.getDerivedFrom();
-               if (currentDerivedFrom == null || currentDerivedFrom.isEmpty() || updatedDerivedFrom == null
-                               || updatedDerivedFrom.isEmpty()) {
-                       log.trace("Update normative types");
-                       return Either.left(true);
-               }
-
-               String derivedFromCurrent = currentDerivedFrom.get(0);
-               String derivedFromUpdated = updatedDerivedFrom.get(0);
-
-               if (!derivedFromCurrent.equals(derivedFromUpdated)) {
-                       if (!hasBeenCertified) {
-                               validateDerivedFromExist(null, updateInfoResource, null);
-                       } else {
-                               Either<Boolean, ResponseFormat> validateDerivedFromExtending = validateDerivedFromExtending(null,
-                                               currentResource, updateInfoResource, null);
-
-                               if (validateDerivedFromExtending.isRight() || !validateDerivedFromExtending.left()
-                                               .value()) {
-                                       log.debug("Derived from cannot be updated if it doesnt inherits directly or extends inheritance");
-                                       return validateDerivedFromExtending;
-                               }
-                       }
-               } else {
-                       // For derived from, we must know whether it was actually changed,
-                       // otherwise we must do no action.
-                       // Due to changes it inflicts on data model (remove artifacts,
-                       // properties...), it's not like a flat field which can be
-                       // overwritten if not changed.
-                       // So we must indicate that derived from is not changed
-                       updateInfoResource.setDerivedFrom(null);
-               }
-               return Either.left(true);
-       }
-
-       private Either<Boolean, ResponseFormat> validateNestedDerivedFromDuringUpdate(Resource currentResource,
-                                                                                                                                                                 Resource updateInfoResource, boolean hasBeenCertified) {
-
-               List<String> currentDerivedFrom = currentResource.getDerivedFrom();
-               List<String> updatedDerivedFrom = updateInfoResource.getDerivedFrom();
-               if (currentDerivedFrom == null || currentDerivedFrom.isEmpty() || updatedDerivedFrom == null
-                               || updatedDerivedFrom.isEmpty()) {
-                       log.trace("Update normative types");
-                       return Either.left(true);
-               }
-
-               String derivedFromCurrent = currentDerivedFrom.get(0);
-               String derivedFromUpdated = updatedDerivedFrom.get(0);
-
-               if (!derivedFromCurrent.equals(derivedFromUpdated)) {
-                       if (!hasBeenCertified) {
-                               validateDerivedFromExist(null, updateInfoResource, null);
-                       } else {
-                               Either<Boolean, ResponseFormat> validateDerivedFromExtending = validateDerivedFromExtending(null,
-                                               currentResource, updateInfoResource, null);
-
-                               if (validateDerivedFromExtending.isRight() || !validateDerivedFromExtending.left()
-                                               .value()) {
-                                       log.debug("Derived from cannot be updated if it doesnt inherits directly or extends inheritance");
-                                       return validateDerivedFromExtending;
-                               }
-                       }
-               }
-               return Either.left(true);
-       }
-
-       private void validateDerivedFromExist(User user, Resource resource, AuditingActionEnum actionEnum) {
-               if (resource.getDerivedFrom() == null || resource.getDerivedFrom()
-                               .isEmpty()) {
-                       return;
-               }
-               String templateName = resource.getDerivedFrom()
-                               .get(0);
-               Either<Boolean, StorageOperationStatus> dataModelResponse = toscaOperationFacade
-                               .validateToscaResourceNameExists(templateName);
-               if (dataModelResponse.isRight()) {
-                       StorageOperationStatus storageStatus = dataModelResponse.right()
-                                       .value();
-                       BeEcompErrorManager.getInstance()
-                                       .logBeDaoSystemError("Create Resource - validateDerivedFromExist");
-                       log.debug("request to data model failed with error: {}", storageStatus);
-                       ResponseFormat responseFormat = componentsUtils
-                                       .getResponseFormatByResource(componentsUtils.convertFromStorageResponse(storageStatus), resource);
-                       log.trace("audit before sending response");
-                       componentsUtils.auditResource(responseFormat, user, resource, actionEnum);
-                       throw new ByActionStatusComponentException(componentsUtils.convertFromStorageResponse(storageStatus));
-               } else if (!dataModelResponse.left()
-                               .value()) {
-                       log.info("resource template with name: {}, does not exists", templateName);
-                       ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.PARENT_RESOURCE_NOT_FOUND);
-                       componentsUtils.auditResource(responseFormat, user, resource, actionEnum);
-                       throw new ByActionStatusComponentException(ActionStatus.PARENT_RESOURCE_NOT_FOUND);
-               }
-       }
-
-       // Tal G for extending inheritance US815447
-       private Either<Boolean, ResponseFormat> validateDerivedFromExtending(User user, Resource currentResource,
-                                                                                                                                                Resource updateInfoResource, AuditingActionEnum actionEnum) {
-               String currentTemplateName = currentResource.getDerivedFrom()
-                               .get(0);
-               String updatedTemplateName = updateInfoResource.getDerivedFrom()
-                               .get(0);
-
-               Either<Boolean, StorageOperationStatus> dataModelResponse = toscaOperationFacade
-                               .validateToscaResourceNameExtends(currentTemplateName, updatedTemplateName);
-               if (dataModelResponse.isRight()) {
-                       StorageOperationStatus storageStatus = dataModelResponse.right()
-                                       .value();
-                       BeEcompErrorManager.getInstance()
-                                       .logBeDaoSystemError("Create/Update Resource - validateDerivingFromExtendingType");
-                       ResponseFormat responseFormat = componentsUtils.getResponseFormatByResource(
-                                       componentsUtils.convertFromStorageResponse(storageStatus), currentResource);
-                       log.trace("audit before sending response");
-                       componentsUtils.auditResource(responseFormat, user, currentResource, actionEnum);
-                       return Either.right(responseFormat);
-               }
-
-               if (!dataModelResponse.left()
-                               .value()) {
-                       log.info("resource template with name {} does not inherit as original {}", updatedTemplateName,
-                                       currentTemplateName);
-                       ResponseFormat responseFormat = componentsUtils
-                                       .getResponseFormat(ActionStatus.PARENT_RESOURCE_DOES_NOT_EXTEND);
-                       componentsUtils.auditResource(responseFormat, user, currentResource, actionEnum);
-
-                       return Either.right(responseFormat);
-
-               }
-               return Either.left(true);
-       }
-
-       public void validateDerivedFromNotEmpty(User user, Resource resource, AuditingActionEnum actionEnum) {
-               log.debug("validate resource derivedFrom field");
-               if ((resource.getDerivedFrom() == null) || (resource.getDerivedFrom()
-                               .isEmpty())
-                               || (resource.getDerivedFrom()
-                               .get(0)) == null
-                               || (resource.getDerivedFrom()
-                               .get(0)
-                               .trim()
-                               .isEmpty())) {
-                       log.info("derived from (template) field is missing for the resource");
-                       ResponseFormat responseFormat = componentsUtils
-                                       .getResponseFormat(ActionStatus.MISSING_DERIVED_FROM_TEMPLATE);
-                       componentsUtils.auditResource(responseFormat, user, resource, actionEnum);
-
-                       throw new ByActionStatusComponentException(ActionStatus.MISSING_DERIVED_FROM_TEMPLATE);
-               }
-       }
-
-       private void validateResourceNameUniqueness(Resource resource) {
-
-               Either<Boolean, StorageOperationStatus> resourceOperationResponse = toscaOperationFacade
-                               .validateComponentNameExists(resource.getName(), resource.getResourceType(),
-                                               resource.getComponentType());
-               if (resourceOperationResponse.isLeft() && resourceOperationResponse.left()
-                               .value()) {
-                       log.debug("resource with name: {}, already exists", resource.getName());
-                       throw new ByActionStatusComponentException(ActionStatus.COMPONENT_NAME_ALREADY_EXIST,
-                                       ComponentTypeEnum.RESOURCE.getValue(), resource.getName());
-               } else if (resourceOperationResponse.isRight()) {
-                       log.debug("error while validateResourceNameExists for resource: {}", resource.getName());
-                       throw new StorageException(resourceOperationResponse.right()
-                                       .value());
-               }
-       }
-
-       private void validateCategory(User user, Resource resource, AuditingActionEnum actionEnum, boolean inTransaction) {
-
-               List<CategoryDefinition> categories = resource.getCategories();
-               if (CollectionUtils.isEmpty(categories)) {
-                       log.debug(CATEGORY_IS_EMPTY);
-                       ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.COMPONENT_MISSING_CATEGORY,
-                                       ComponentTypeEnum.RESOURCE.getValue());
-                       componentsUtils.auditResource(responseFormat, user, resource, actionEnum);
-                       throw new ByActionStatusComponentException(ActionStatus.COMPONENT_MISSING_CATEGORY,
-                                       ComponentTypeEnum.RESOURCE.getValue());
-               }
-               if (categories.size() > 1) {
-                       log.debug("Must be only one category for resource");
-                       throw new ByActionStatusComponentException(ActionStatus.COMPONENT_TOO_MUCH_CATEGORIES,
-                                       ComponentTypeEnum.RESOURCE.getValue());
-               }
-               CategoryDefinition category = categories.get(0);
-               List<SubCategoryDefinition> subcategories = category.getSubcategories();
-               if (CollectionUtils.isEmpty(subcategories)) {
-                       log.debug("Missinig subcategory for resource");
-                       throw new ByActionStatusComponentException(ActionStatus.COMPONENT_MISSING_SUBCATEGORY);
-               }
-               if (subcategories.size() > 1) {
-                       log.debug("Must be only one sub category for resource");
-                       throw new ByActionStatusComponentException(ActionStatus.RESOURCE_TOO_MUCH_SUBCATEGORIES);
-               }
-
-               SubCategoryDefinition subcategory = subcategories.get(0);
-
-               if (!ValidationUtils.validateStringNotEmpty(category.getName())) {
-                       log.debug(CATEGORY_IS_EMPTY);
-                       ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.COMPONENT_MISSING_CATEGORY,
-                                       ComponentTypeEnum.RESOURCE.getValue());
-                       componentsUtils.auditResource(responseFormat, user, resource, actionEnum);
-                       throw new ByActionStatusComponentException(ActionStatus.COMPONENT_MISSING_CATEGORY,
-                                       ComponentTypeEnum.RESOURCE.getValue());
-               }
-               if (!ValidationUtils.validateStringNotEmpty(subcategory.getName())) {
-                       log.debug(CATEGORY_IS_EMPTY);
-                       ResponseFormat responseFormat = componentsUtils.getResponseFormat(
-                                       ActionStatus.COMPONENT_MISSING_SUBCATEGORY, ComponentTypeEnum.RESOURCE.getValue());
-                       componentsUtils.auditResource(responseFormat, user, resource, actionEnum);
-                       throw new ByActionStatusComponentException(ActionStatus.COMPONENT_MISSING_SUBCATEGORY,
-                                       ComponentTypeEnum.RESOURCE.getValue());
-               }
-
-               validateCategoryListed(category, subcategory, user, resource, actionEnum, inTransaction);
-       }
-
-       private void validateCategoryListed(CategoryDefinition category, SubCategoryDefinition subcategory, User user,
-                                                                               Resource resource, AuditingActionEnum actionEnum, boolean inTransaction) {
-               ResponseFormat responseFormat;
-               if (category != null && subcategory != null) {
-                       log.debug("validating resource category {} against valid categories list", category);
-                       Either<List<CategoryDefinition>, ActionStatus> categories = elementDao
-                                       .getAllCategories(NodeTypeEnum.ResourceNewCategory, inTransaction);
-                       if (categories.isRight()) {
-                               log.debug("failed to retrieve resource categories from JanusGraph");
-                               responseFormat = componentsUtils.getResponseFormat(categories.right()
-                                               .value());
-                               componentsUtils.auditResource(responseFormat, user, resource, actionEnum);
-                               throw new ByActionStatusComponentException(categories.right()
-                                               .value());
-                       }
-                       List<CategoryDefinition> categoryList = categories.left()
-                                       .value();
-                       Optional<CategoryDefinition> foundCategory = categoryList.stream()
-                                       .filter(cat -> cat.getName()
-                                                       .equals(category.getName()))
-                                       .findFirst();
-                       if (!foundCategory.isPresent()) {
-                               log.debug("Category {} is not part of resource category group. Resource category valid values are {}",
-                                               category, categoryList);
-                               failOnInvalidCategory(user, resource, actionEnum);
-                       }
-                       Optional<SubCategoryDefinition> foundSubcategory = foundCategory.get()
-                                       .getSubcategories()
-                                       .stream()
-                                       .filter(subcat -> subcat.getName()
-                                                       .equals(subcategory.getName()))
-                                       .findFirst();
-                       if (!foundSubcategory.isPresent()) {
-                               log.debug(
-                                               "SubCategory {} is not part of resource category group. Resource subcategory valid values are {}",
-                                               subcategory, foundCategory.get()
-                                                               .getSubcategories());
-                               failOnInvalidCategory(user, resource, actionEnum);
-                       }
-               }
-       }
-
-       private void failOnInvalidCategory(User user, Resource resource, AuditingActionEnum actionEnum) {
-               ResponseFormat responseFormat;
-               responseFormat = componentsUtils.getResponseFormat(ActionStatus.COMPONENT_INVALID_CATEGORY,
-                               ComponentTypeEnum.RESOURCE.getValue());
-               componentsUtils.auditResource(responseFormat, user, resource, actionEnum);
-               throw new ByActionStatusComponentException(ActionStatus.COMPONENT_INVALID_CATEGORY, ComponentTypeEnum.RESOURCE.getValue());
-       }
-
-       public void validateVendorReleaseName(User user, Resource resource, AuditingActionEnum actionEnum) {
-               String vendorRelease = resource.getVendorRelease();
-               log.debug("validate vendor relese name");
-               if (!ValidationUtils.validateStringNotEmpty(vendorRelease)) {
-                       log.info("vendor relese name is missing.");
-                       ResponseFormat errorResponse = componentsUtils.getResponseFormat(ActionStatus.MISSING_VENDOR_RELEASE);
-                       componentsUtils.auditResource(errorResponse, user, resource, actionEnum);
-                       throw new ByActionStatusComponentException(ActionStatus.MISSING_VENDOR_RELEASE);
-               }
-
-               validateVendorReleaseName(vendorRelease, user, resource, actionEnum);
-       }
-
-       public void validateVendorReleaseName(String vendorRelease, User user, Resource resource,
-                                                                                 AuditingActionEnum actionEnum) {
-               if (vendorRelease != null) {
-                       if (!ValidationUtils.validateVendorReleaseLength(vendorRelease)) {
-                               log.info("vendor release exceds limit.");
-                               ResponseFormat errorResponse = componentsUtils.getResponseFormat(
-                                               ActionStatus.VENDOR_RELEASE_EXCEEDS_LIMIT, "" + ValidationUtils.VENDOR_RELEASE_MAX_LENGTH);
-                               componentsUtils.auditResource(errorResponse, user, resource, actionEnum);
-                               throw new ByActionStatusComponentException(ActionStatus.VENDOR_RELEASE_EXCEEDS_LIMIT,
-                                               "" + ValidationUtils.VENDOR_RELEASE_MAX_LENGTH);
-                       }
-
-                       if (!ValidationUtils.validateVendorRelease(vendorRelease)) {
-                               log.info("vendor release  is not valid.");
-                               ResponseFormat errorResponse = componentsUtils.getResponseFormat(ActionStatus.INVALID_VENDOR_RELEASE);
-                               componentsUtils.auditResource(errorResponse, user, resource, actionEnum);
+    private Either<Boolean, ResponseFormat> validateCategory(Resource currentResource, Resource updateInfoResource, boolean hasBeenCertified,
+                                                             boolean inTransaction) {
+        validateCategory(null, updateInfoResource, null, inTransaction);
+        if (hasBeenCertified) {
+            CategoryDefinition currentCategory = currentResource.getCategories().get(0);
+            SubCategoryDefinition currentSubCategory = currentCategory.getSubcategories().get(0);
+            CategoryDefinition updateCategory = updateInfoResource.getCategories().get(0);
+            SubCategoryDefinition updtaeSubCategory = updateCategory.getSubcategories().get(0);
+            if (!currentCategory.getName().equals(updateCategory.getName()) || !currentSubCategory.getName().equals(updtaeSubCategory.getName())) {
+                log.info("Category {} cannot be updated once the resource has been certified once.", currentResource.getCategories());
+                ResponseFormat errorResponse = componentsUtils.getResponseFormat(ActionStatus.RESOURCE_CATEGORY_CANNOT_BE_CHANGED);
+                return Either.right(errorResponse);
+            }
+        }
+        return Either.left(true);
+    }
+
+    private Either<Boolean, ResponseFormat> validateDerivedFromDuringUpdate(Resource currentResource, Resource updateInfoResource,
+                                                                            boolean hasBeenCertified) {
+        List<String> currentDerivedFrom = currentResource.getDerivedFrom();
+        List<String> updatedDerivedFrom = updateInfoResource.getDerivedFrom();
+        if (currentDerivedFrom == null || currentDerivedFrom.isEmpty() || updatedDerivedFrom == null || updatedDerivedFrom.isEmpty()) {
+            log.trace("Update normative types");
+            return Either.left(true);
+        }
+        String derivedFromCurrent = currentDerivedFrom.get(0);
+        String derivedFromUpdated = updatedDerivedFrom.get(0);
+        if (!derivedFromCurrent.equals(derivedFromUpdated)) {
+            if (!hasBeenCertified) {
+                validateDerivedFromExist(null, updateInfoResource, null);
+            } else {
+                Either<Boolean, ResponseFormat> validateDerivedFromExtending = validateDerivedFromExtending(null, currentResource, updateInfoResource,
+                    null);
+                if (validateDerivedFromExtending.isRight() || !validateDerivedFromExtending.left().value()) {
+                    log.debug("Derived from cannot be updated if it doesnt inherits directly or extends inheritance");
+                    return validateDerivedFromExtending;
+                }
+            }
+        } else {
+            // For derived from, we must know whether it was actually changed,
+
+            // otherwise we must do no action.
+
+            // Due to changes it inflicts on data model (remove artifacts,
+
+            // properties...), it's not like a flat field which can be
+
+            // overwritten if not changed.
+
+            // So we must indicate that derived from is not changed
+            updateInfoResource.setDerivedFrom(null);
+        }
+        return Either.left(true);
+    }
+
+    private Either<Boolean, ResponseFormat> validateNestedDerivedFromDuringUpdate(Resource currentResource, Resource updateInfoResource,
+                                                                                  boolean hasBeenCertified) {
+        List<String> currentDerivedFrom = currentResource.getDerivedFrom();
+        List<String> updatedDerivedFrom = updateInfoResource.getDerivedFrom();
+        if (currentDerivedFrom == null || currentDerivedFrom.isEmpty() || updatedDerivedFrom == null || updatedDerivedFrom.isEmpty()) {
+            log.trace("Update normative types");
+            return Either.left(true);
+        }
+        String derivedFromCurrent = currentDerivedFrom.get(0);
+        String derivedFromUpdated = updatedDerivedFrom.get(0);
+        if (!derivedFromCurrent.equals(derivedFromUpdated)) {
+            if (!hasBeenCertified) {
+                validateDerivedFromExist(null, updateInfoResource, null);
+            } else {
+                Either<Boolean, ResponseFormat> validateDerivedFromExtending = validateDerivedFromExtending(null, currentResource, updateInfoResource,
+                    null);
+                if (validateDerivedFromExtending.isRight() || !validateDerivedFromExtending.left().value()) {
+                    log.debug("Derived from cannot be updated if it doesnt inherits directly or extends inheritance");
+                    return validateDerivedFromExtending;
+                }
+            }
+        }
+        return Either.left(true);
+    }
+
+    private void validateDerivedFromExist(User user, Resource resource, AuditingActionEnum actionEnum) {
+        if (resource.getDerivedFrom() == null || resource.getDerivedFrom().isEmpty()) {
+            return;
+        }
+        String templateName = resource.getDerivedFrom().get(0);
+        Either<Boolean, StorageOperationStatus> dataModelResponse = toscaOperationFacade.validateToscaResourceNameExists(templateName);
+        if (dataModelResponse.isRight()) {
+            StorageOperationStatus storageStatus = dataModelResponse.right().value();
+            BeEcompErrorManager.getInstance().logBeDaoSystemError("Create Resource - validateDerivedFromExist");
+            log.debug("request to data model failed with error: {}", storageStatus);
+            ResponseFormat responseFormat = componentsUtils
+                .getResponseFormatByResource(componentsUtils.convertFromStorageResponse(storageStatus), resource);
+            log.trace("audit before sending response");
+            componentsUtils.auditResource(responseFormat, user, resource, actionEnum);
+            throw new ByActionStatusComponentException(componentsUtils.convertFromStorageResponse(storageStatus));
+        } else if (!dataModelResponse.left().value()) {
+            log.info("resource template with name: {}, does not exists", templateName);
+            ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.PARENT_RESOURCE_NOT_FOUND);
+            componentsUtils.auditResource(responseFormat, user, resource, actionEnum);
+            throw new ByActionStatusComponentException(ActionStatus.PARENT_RESOURCE_NOT_FOUND);
+        }
+    }
+
+    // Tal G for extending inheritance US815447
+    private Either<Boolean, ResponseFormat> validateDerivedFromExtending(User user, Resource currentResource, Resource updateInfoResource,
+                                                                         AuditingActionEnum actionEnum) {
+        String currentTemplateName = currentResource.getDerivedFrom().get(0);
+        String updatedTemplateName = updateInfoResource.getDerivedFrom().get(0);
+        Either<Boolean, StorageOperationStatus> dataModelResponse = toscaOperationFacade
+            .validateToscaResourceNameExtends(currentTemplateName, updatedTemplateName);
+        if (dataModelResponse.isRight()) {
+            StorageOperationStatus storageStatus = dataModelResponse.right().value();
+            BeEcompErrorManager.getInstance().logBeDaoSystemError("Create/Update Resource - validateDerivingFromExtendingType");
+            ResponseFormat responseFormat = componentsUtils
+                .getResponseFormatByResource(componentsUtils.convertFromStorageResponse(storageStatus), currentResource);
+            log.trace("audit before sending response");
+            componentsUtils.auditResource(responseFormat, user, currentResource, actionEnum);
+            return Either.right(responseFormat);
+        }
+        if (!dataModelResponse.left().value()) {
+            log.info("resource template with name {} does not inherit as original {}", updatedTemplateName, currentTemplateName);
+            ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.PARENT_RESOURCE_DOES_NOT_EXTEND);
+            componentsUtils.auditResource(responseFormat, user, currentResource, actionEnum);
+            return Either.right(responseFormat);
+        }
+        return Either.left(true);
+    }
+
+    public void validateDerivedFromNotEmpty(User user, Resource resource, AuditingActionEnum actionEnum) {
+        log.debug("validate resource derivedFrom field");
+        if ((resource.getDerivedFrom() == null) || (resource.getDerivedFrom().isEmpty()) || (resource.getDerivedFrom().get(0)) == null || (resource
+            .getDerivedFrom().get(0).trim().isEmpty())) {
+            log.info("derived from (template) field is missing for the resource");
+            ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.MISSING_DERIVED_FROM_TEMPLATE);
+            componentsUtils.auditResource(responseFormat, user, resource, actionEnum);
+            throw new ByActionStatusComponentException(ActionStatus.MISSING_DERIVED_FROM_TEMPLATE);
+        }
+    }
+
+    private void validateResourceNameUniqueness(Resource resource) {
+        Either<Boolean, StorageOperationStatus> resourceOperationResponse = toscaOperationFacade
+            .validateComponentNameExists(resource.getName(), resource.getResourceType(), resource.getComponentType());
+        if (resourceOperationResponse.isLeft() && resourceOperationResponse.left().value()) {
+            log.debug("resource with name: {}, already exists", resource.getName());
+            throw new ByActionStatusComponentException(ActionStatus.COMPONENT_NAME_ALREADY_EXIST, ComponentTypeEnum.RESOURCE.getValue(),
+                resource.getName());
+        } else if (resourceOperationResponse.isRight()) {
+            log.debug("error while validateResourceNameExists for resource: {}", resource.getName());
+            throw new StorageException(resourceOperationResponse.right().value());
+        }
+    }
+
+    private void validateCategory(User user, Resource resource, AuditingActionEnum actionEnum, boolean inTransaction) {
+        List<CategoryDefinition> categories = resource.getCategories();
+        if (CollectionUtils.isEmpty(categories)) {
+            log.debug(CATEGORY_IS_EMPTY);
+            ResponseFormat responseFormat = componentsUtils
+                .getResponseFormat(ActionStatus.COMPONENT_MISSING_CATEGORY, ComponentTypeEnum.RESOURCE.getValue());
+            componentsUtils.auditResource(responseFormat, user, resource, actionEnum);
+            throw new ByActionStatusComponentException(ActionStatus.COMPONENT_MISSING_CATEGORY, ComponentTypeEnum.RESOURCE.getValue());
+        }
+        if (categories.size() > 1) {
+            log.debug("Must be only one category for resource");
+            throw new ByActionStatusComponentException(ActionStatus.COMPONENT_TOO_MUCH_CATEGORIES, ComponentTypeEnum.RESOURCE.getValue());
+        }
+        CategoryDefinition category = categories.get(0);
+        List<SubCategoryDefinition> subcategories = category.getSubcategories();
+        if (CollectionUtils.isEmpty(subcategories)) {
+            log.debug("Missinig subcategory for resource");
+            throw new ByActionStatusComponentException(ActionStatus.COMPONENT_MISSING_SUBCATEGORY);
+        }
+        if (subcategories.size() > 1) {
+            log.debug("Must be only one sub category for resource");
+            throw new ByActionStatusComponentException(ActionStatus.RESOURCE_TOO_MUCH_SUBCATEGORIES);
+        }
+        SubCategoryDefinition subcategory = subcategories.get(0);
+        if (!ValidationUtils.validateStringNotEmpty(category.getName())) {
+            log.debug(CATEGORY_IS_EMPTY);
+            ResponseFormat responseFormat = componentsUtils
+                .getResponseFormat(ActionStatus.COMPONENT_MISSING_CATEGORY, ComponentTypeEnum.RESOURCE.getValue());
+            componentsUtils.auditResource(responseFormat, user, resource, actionEnum);
+            throw new ByActionStatusComponentException(ActionStatus.COMPONENT_MISSING_CATEGORY, ComponentTypeEnum.RESOURCE.getValue());
+        }
+        if (!ValidationUtils.validateStringNotEmpty(subcategory.getName())) {
+            log.debug(CATEGORY_IS_EMPTY);
+            ResponseFormat responseFormat = componentsUtils
+                .getResponseFormat(ActionStatus.COMPONENT_MISSING_SUBCATEGORY, ComponentTypeEnum.RESOURCE.getValue());
+            componentsUtils.auditResource(responseFormat, user, resource, actionEnum);
+            throw new ByActionStatusComponentException(ActionStatus.COMPONENT_MISSING_SUBCATEGORY, ComponentTypeEnum.RESOURCE.getValue());
+        }
+        validateCategoryListed(category, subcategory, user, resource, actionEnum, inTransaction);
+    }
+
+    private void validateCategoryListed(CategoryDefinition category, SubCategoryDefinition subcategory, User user, Resource resource,
+                                        AuditingActionEnum actionEnum, boolean inTransaction) {
+        ResponseFormat responseFormat;
+        if (category != null && subcategory != null) {
+            log.debug("validating resource category {} against valid categories list", category);
+            Either<List<CategoryDefinition>, ActionStatus> categories = elementDao.getAllCategories(NodeTypeEnum.ResourceNewCategory, inTransaction);
+            if (categories.isRight()) {
+                log.debug("failed to retrieve resource categories from JanusGraph");
+                responseFormat = componentsUtils.getResponseFormat(categories.right().value());
+                componentsUtils.auditResource(responseFormat, user, resource, actionEnum);
+                throw new ByActionStatusComponentException(categories.right().value());
+            }
+            List<CategoryDefinition> categoryList = categories.left().value();
+            Optional<CategoryDefinition> foundCategory = categoryList.stream().filter(cat -> cat.getName().equals(category.getName())).findFirst();
+            if (!foundCategory.isPresent()) {
+                log.debug("Category {} is not part of resource category group. Resource category valid values are {}", category, categoryList);
+                failOnInvalidCategory(user, resource, actionEnum);
+            }
+            Optional<SubCategoryDefinition> foundSubcategory = foundCategory.get().getSubcategories().stream()
+                .filter(subcat -> subcat.getName().equals(subcategory.getName())).findFirst();
+            if (!foundSubcategory.isPresent()) {
+                log.debug("SubCategory {} is not part of resource category group. Resource subcategory valid values are {}", subcategory,
+                    foundCategory.get().getSubcategories());
+                failOnInvalidCategory(user, resource, actionEnum);
+            }
+        }
+    }
+
+    private void failOnInvalidCategory(User user, Resource resource, AuditingActionEnum actionEnum) {
+        ResponseFormat responseFormat;
+        responseFormat = componentsUtils.getResponseFormat(ActionStatus.COMPONENT_INVALID_CATEGORY, ComponentTypeEnum.RESOURCE.getValue());
+        componentsUtils.auditResource(responseFormat, user, resource, actionEnum);
+        throw new ByActionStatusComponentException(ActionStatus.COMPONENT_INVALID_CATEGORY, ComponentTypeEnum.RESOURCE.getValue());
+    }
+
+    public void validateVendorReleaseName(User user, Resource resource, AuditingActionEnum actionEnum) {
+        String vendorRelease = resource.getVendorRelease();
+        log.debug("validate vendor relese name");
+        if (!ValidationUtils.validateStringNotEmpty(vendorRelease)) {
+            log.info("vendor relese name is missing.");
+            ResponseFormat errorResponse = componentsUtils.getResponseFormat(ActionStatus.MISSING_VENDOR_RELEASE);
+            componentsUtils.auditResource(errorResponse, user, resource, actionEnum);
+            throw new ByActionStatusComponentException(ActionStatus.MISSING_VENDOR_RELEASE);
+        }
+        validateVendorReleaseName(vendorRelease, user, resource, actionEnum);
+    }
+
+    public void validateVendorReleaseName(String vendorRelease, User user, Resource resource, AuditingActionEnum actionEnum) {
+        if (vendorRelease != null) {
+            if (!ValidationUtils.validateVendorReleaseLength(vendorRelease)) {
+                log.info("vendor release exceds limit.");
+                ResponseFormat errorResponse = componentsUtils
+                    .getResponseFormat(ActionStatus.VENDOR_RELEASE_EXCEEDS_LIMIT, "" + ValidationUtils.VENDOR_RELEASE_MAX_LENGTH);
+                componentsUtils.auditResource(errorResponse, user, resource, actionEnum);
+                throw new ByActionStatusComponentException(ActionStatus.VENDOR_RELEASE_EXCEEDS_LIMIT, "" + ValidationUtils.VENDOR_RELEASE_MAX_LENGTH);
+            }
+            if (!ValidationUtils.validateVendorRelease(vendorRelease)) {
+                log.info("vendor release  is not valid.");
+                ResponseFormat errorResponse = componentsUtils.getResponseFormat(ActionStatus.INVALID_VENDOR_RELEASE);
+                componentsUtils.auditResource(errorResponse, user, resource, actionEnum);
                 throw new ByActionStatusComponentException(ActionStatus.INVALID_VENDOR_RELEASE, vendorRelease);
             }
         }
     }
 
-    private void validateVendorName(User user, Resource resource,
-                                    AuditingActionEnum actionEnum) {
+    private void validateVendorName(User user, Resource resource, AuditingActionEnum actionEnum) {
         String vendorName = resource.getVendorName();
         if (!ValidationUtils.validateStringNotEmpty(vendorName)) {
             log.info("vendor name is missing.");
@@ -5472,18 +4594,15 @@ public class ResourceBusinessLogic extends ComponentBusinessLogic {
         validateVendorName(vendorName, user, resource, actionEnum);
     }
 
-    private void validateVendorName(String vendorName, User user, Resource resource,
-                                    AuditingActionEnum actionEnum) {
+    private void validateVendorName(String vendorName, User user, Resource resource, AuditingActionEnum actionEnum) {
         if (vendorName != null) {
             if (!ValidationUtils.validateVendorNameLength(vendorName)) {
                 log.info("vendor name exceds limit.");
-                ResponseFormat errorResponse = componentsUtils.getResponseFormat(ActionStatus.VENDOR_NAME_EXCEEDS_LIMIT,
-                        "" + ValidationUtils.VENDOR_NAME_MAX_LENGTH);
+                ResponseFormat errorResponse = componentsUtils
+                    .getResponseFormat(ActionStatus.VENDOR_NAME_EXCEEDS_LIMIT, "" + ValidationUtils.VENDOR_NAME_MAX_LENGTH);
                 componentsUtils.auditResource(errorResponse, user, resource, actionEnum);
-                throw new ByActionStatusComponentException(ActionStatus.VENDOR_NAME_EXCEEDS_LIMIT,
-                        "" + ValidationUtils.VENDOR_NAME_MAX_LENGTH);
+                throw new ByActionStatusComponentException(ActionStatus.VENDOR_NAME_EXCEEDS_LIMIT, "" + ValidationUtils.VENDOR_NAME_MAX_LENGTH);
             }
-
             if (!ValidationUtils.validateVendorName(vendorName)) {
                 log.info("vendor name  is not valid.");
                 ResponseFormat errorResponse = componentsUtils.getResponseFormat(ActionStatus.INVALID_VENDOR_NAME);
@@ -5498,26 +4617,24 @@ public class ResourceBusinessLogic extends ComponentBusinessLogic {
         if (StringUtils.isNotEmpty(resourceVendorModelNumber)) {
             if (!ValidationUtils.validateResourceVendorModelNumberLength(resourceVendorModelNumber)) {
                 log.info("resource vendor model number exceeds limit.");
-                ResponseFormat errorResponse = componentsUtils.getResponseFormat(
-                        ActionStatus.RESOURCE_VENDOR_MODEL_NUMBER_EXCEEDS_LIMIT,
-                        "" + ValidationUtils.RESOURCE_VENDOR_MODEL_NUMBER_MAX_LENGTH);
+                ResponseFormat errorResponse = componentsUtils.getResponseFormat(ActionStatus.RESOURCE_VENDOR_MODEL_NUMBER_EXCEEDS_LIMIT,
+                    "" + ValidationUtils.RESOURCE_VENDOR_MODEL_NUMBER_MAX_LENGTH);
                 componentsUtils.auditResource(errorResponse, user, resource, actionEnum);
                 throw new ByActionStatusComponentException(ActionStatus.RESOURCE_VENDOR_MODEL_NUMBER_EXCEEDS_LIMIT,
-                        "" + ValidationUtils.RESOURCE_VENDOR_MODEL_NUMBER_MAX_LENGTH);
+                    "" + ValidationUtils.RESOURCE_VENDOR_MODEL_NUMBER_MAX_LENGTH);
             }
             // resource vendor model number is currently validated as vendor
+
             // name
             if (!ValidationUtils.validateVendorName(resourceVendorModelNumber)) {
                 log.info("resource vendor model number  is not valid.");
-                ResponseFormat errorResponse = componentsUtils
-                        .getResponseFormat(ActionStatus.INVALID_RESOURCE_VENDOR_MODEL_NUMBER);
+                ResponseFormat errorResponse = componentsUtils.getResponseFormat(ActionStatus.INVALID_RESOURCE_VENDOR_MODEL_NUMBER);
                 componentsUtils.auditResource(errorResponse, user, resource, actionEnum);
                 throw new ByActionStatusComponentException(ActionStatus.INVALID_RESOURCE_VENDOR_MODEL_NUMBER);
             }
         }
     }
 
-
     private void validateCost(Resource resource) {
         String cost = resource.getCost();
         if (cost != null) {
@@ -5528,13 +4645,11 @@ public class ResourceBusinessLogic extends ComponentBusinessLogic {
         }
     }
 
-    private void validateLicenseType(User user, Resource resource,
-                                     AuditingActionEnum actionEnum) {
+    private void validateLicenseType(User user, Resource resource, AuditingActionEnum actionEnum) {
         log.debug("validate licenseType");
         String licenseType = resource.getLicenseType();
         if (licenseType != null) {
-            List<String> licenseTypes = ConfigurationManager.getConfigurationManager().getConfiguration()
-                    .getLicenseTypes();
+            List<String> licenseTypes = ConfigurationManager.getConfigurationManager().getConfiguration().getLicenseTypes();
             if (!licenseTypes.contains(licenseType)) {
                 log.debug("License type {} isn't configured", licenseType);
                 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.INVALID_CONTENT);
@@ -5547,509 +4662,437 @@ public class ResourceBusinessLogic extends ComponentBusinessLogic {
         }
     }
 
-       private Either<Boolean, ResponseFormat> processUpdateOfDerivedFrom(Resource currentResource,
-                                                                                                                                          Resource updatedResource, String userId, boolean inTransaction) {
-               if (updatedResource.getDerivedFrom() != null) {
-                       log.debug("Starting derived from update for resource {}", updatedResource.getUniqueId());
-                       log.debug("1. Removing interface artifacts from graph");
-                       // Remove all interface artifacts of resource
-                       String resourceId = updatedResource.getUniqueId();
-                       Map<String, InterfaceDefinition> interfaces = currentResource.getInterfaces();
-
-                       if (interfaces != null) {
-                               Collection<InterfaceDefinition> values = interfaces.values();
-                               for (InterfaceDefinition interfaceDefinition : values) {
-                                       String interfaceType = interfaceTypeOperation.getShortInterfaceName(interfaceDefinition);
-
-                                       log.trace("Starting interface artifacts removal for interface type {}", interfaceType);
-                                       Map<String, Operation> operations = interfaceDefinition.getOperationsMap();
-                                       if (operations != null) {
-                                               for (Entry<String, Operation> operationEntry : operations.entrySet()) {
-                                                       Operation operation = operationEntry.getValue();
-                                                       ArtifactDefinition implementation = operation.getImplementationArtifact();
-                                                       if (implementation != null) {
-                                                               String uniqueId = implementation.getUniqueId();
-                                                               log.debug("Removing interface artifact definition {}, operation {}, interfaceType {}",
-                                                                               uniqueId, operationEntry.getKey(), interfaceType);
-                                                               // only thing that transacts and locks here
-                                                               Either<ArtifactDefinition, ResponseFormat> deleteArtifactByInterface =
-                                                                       artifactsBusinessLogic.deleteArtifactByInterface(resourceId, userId, uniqueId, true);
-                                                               if (deleteArtifactByInterface.isRight()) {
-                                                                       log.debug("Couldn't remove artifact definition with id {}", uniqueId);
-                                                                       if (!inTransaction) {
-                                                                               janusGraphDao.rollback();
-                                                                       }
-                                                                       return Either.right(deleteArtifactByInterface.right()
-                                                                                       .value());
-                                                               }
-                                                       } else {
-                                                               log.trace("No implementation found for operation {} - nothing to delete",
-                                                                               operationEntry.getKey());
-                                                       }
-                                               }
-                                       } else {
-                                               log.trace("No operations found for interface type {}", interfaceType);
-                                       }
-                               }
-                       }
-                       log.debug("2. Removing properties");
-                       Either<Map<String, PropertyDefinition>, StorageOperationStatus> findPropertiesOfNode = propertyOperation
-                                       .deleteAllPropertiesAssociatedToNode(NodeTypeEnum.Resource, resourceId);
-
-                       if (findPropertiesOfNode.isRight() && findPropertiesOfNode.right().value() != StorageOperationStatus.OK) {
-                               log.debug("Failed to remove all properties of resource");
-                               if (!inTransaction) {
+    private Either<Boolean, ResponseFormat> processUpdateOfDerivedFrom(Resource currentResource, Resource updatedResource, String userId,
+                                                                       boolean inTransaction) {
+        if (updatedResource.getDerivedFrom() != null) {
+            log.debug("Starting derived from update for resource {}", updatedResource.getUniqueId());
+            log.debug("1. Removing interface artifacts from graph");
+            // Remove all interface artifacts of resource
+            String resourceId = updatedResource.getUniqueId();
+            Map<String, InterfaceDefinition> interfaces = currentResource.getInterfaces();
+            if (interfaces != null) {
+                Collection<InterfaceDefinition> values = interfaces.values();
+                for (InterfaceDefinition interfaceDefinition : values) {
+                    String interfaceType = interfaceTypeOperation.getShortInterfaceName(interfaceDefinition);
+                    log.trace("Starting interface artifacts removal for interface type {}", interfaceType);
+                    Map<String, Operation> operations = interfaceDefinition.getOperationsMap();
+                    if (operations != null) {
+                        for (Entry<String, Operation> operationEntry : operations.entrySet()) {
+                            Operation operation = operationEntry.getValue();
+                            ArtifactDefinition implementation = operation.getImplementationArtifact();
+                            if (implementation != null) {
+                                String uniqueId = implementation.getUniqueId();
+                                log.debug("Removing interface artifact definition {}, operation {}, interfaceType {}", uniqueId,
+                                    operationEntry.getKey(), interfaceType);
+                                // only thing that transacts and locks here
+                                Either<ArtifactDefinition, ResponseFormat> deleteArtifactByInterface = artifactsBusinessLogic
+                                    .deleteArtifactByInterface(resourceId, userId, uniqueId, true);
+                                if (deleteArtifactByInterface.isRight()) {
+                                    log.debug("Couldn't remove artifact definition with id {}", uniqueId);
+                                    if (!inTransaction) {
+                                        janusGraphDao.rollback();
+                                    }
+                                    return Either.right(deleteArtifactByInterface.right().value());
+                                }
+                            } else {
+                                log.trace("No implementation found for operation {} - nothing to delete", operationEntry.getKey());
+                            }
+                        }
+                    } else {
+                        log.trace("No operations found for interface type {}", interfaceType);
+                    }
+                }
+            }
+            log.debug("2. Removing properties");
+            Either<Map<String, PropertyDefinition>, StorageOperationStatus> findPropertiesOfNode = propertyOperation
+                .deleteAllPropertiesAssociatedToNode(NodeTypeEnum.Resource, resourceId);
+            if (findPropertiesOfNode.isRight() && findPropertiesOfNode.right().value() != StorageOperationStatus.OK) {
+                log.debug("Failed to remove all properties of resource");
+                if (!inTransaction) {
                     janusGraphDao.rollback();
-                               }
-                               return Either.right(componentsUtils
-                                               .getResponseFormat(componentsUtils.convertFromStorageResponse(findPropertiesOfNode.right()
-                                                               .value())));
-                       }
-
-               } else {
-                       log.debug("Derived from wasn't changed during update");
-               }
-
-               if (inTransaction) {
-                       return Either.left(true);
-               }
+                }
+                return Either
+                    .right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(findPropertiesOfNode.right().value())));
+            }
+        } else {
+            log.debug("Derived from wasn't changed during update");
+        }
+        if (inTransaction) {
+            return Either.left(true);
+        }
         janusGraphDao.commit();
-               return Either.left(true);
-
-       }
-
-       public ICapabilityTypeOperation getCapabilityTypeOperation() {
-               return capabilityTypeOperation;
-       }
-
-       @Autowired
-       public void setCapabilityTypeOperation(ICapabilityTypeOperation capabilityTypeOperation) {
-               this.capabilityTypeOperation = capabilityTypeOperation;
-       }
-
-       public Boolean validatePropertiesDefaultValues(Resource resource) {
-               log.debug("validate resource properties default values");
-               List<PropertyDefinition> properties = resource.getProperties();
-               if (properties != null) {
-                       iterateOverProperties(properties);
-               }
-               return true;
-       }
-
-       public void iterateOverProperties(List<PropertyDefinition> properties) {
-               String type = null;
-               String innerType = null;
-               for (PropertyDefinition property : properties) {
-                       if (!propertyOperation.isPropertyTypeValid(property)) {
-                               log.info("Invalid type for property {}", property);
-                               throw new ByActionStatusComponentException(ActionStatus.INVALID_PROPERTY_TYPE,
-                                               property.getType(), property.getName());
-                       }
-
-                       Map<String, DataTypeDefinition> allDataTypes = getAllDataTypes(applicationDataTypeCache);
-                       type = property.getType();
-
-                       if (type.equals(ToscaPropertyType.LIST.getType()) || type.equals(ToscaPropertyType.MAP.getType())) {
-                               ResponseFormat responseFormat = validateMapOrListPropertyType(property, innerType, allDataTypes);
-                               if (responseFormat != null) {
-                                       break;
-                               }
-                       }
-                       validateDefaultPropertyValue(property, allDataTypes, type, innerType);
-               }
-       }
-
-       private void validateDefaultPropertyValue(PropertyDefinition property,
-                                                                                         Map<String, DataTypeDefinition> allDataTypes, String type, String innerType) {
-               if (!propertyOperation.isPropertyDefaultValueValid(property, allDataTypes)) {
-                       log.info("Invalid default value for property {}", property);
-                       ResponseFormat responseFormat;
-                       if (type.equals(ToscaPropertyType.LIST.getType()) || type.equals(ToscaPropertyType.MAP.getType())) {
-                               throw new ByActionStatusComponentException(ActionStatus.INVALID_COMPLEX_DEFAULT_VALUE,
-                                               property.getName(), type, innerType, property.getDefaultValue());
-                       }
-                       throw new ByActionStatusComponentException(ActionStatus.INVALID_DEFAULT_VALUE,
-                                       property.getName(), type, property.getDefaultValue());
-               }
-       }
-
-       private ResponseFormat validateMapOrListPropertyType(PropertyDefinition property, String innerType,
-                                                                                                                Map<String, DataTypeDefinition> allDataTypes) {
-               ResponseFormat responseFormat = null;
-               ImmutablePair<String, Boolean> propertyInnerTypeValid = propertyOperation.isPropertyInnerTypeValid(property,
-                               allDataTypes);
-               innerType = propertyInnerTypeValid.getLeft();
-               if (!propertyInnerTypeValid.getRight()
-                               .booleanValue()) {
-                       log.info("Invalid inner type for property {}", property);
-                       responseFormat = componentsUtils.getResponseFormat(ActionStatus.INVALID_PROPERTY_INNER_TYPE, innerType,
-                                       property.getName());
-               }
-               return responseFormat;
-       }
-
-       @Override
-       public Either<List<String>, ResponseFormat> deleteMarkedComponents() {
-               return deleteMarkedComponents(ComponentTypeEnum.RESOURCE);
-       }
-
-       @Override
-       public ComponentInstanceBusinessLogic getComponentInstanceBL() {
-               return componentInstanceBusinessLogic;
-       }
-
-       private String getComponentTypeForResponse(Component component) {
-               String componentTypeForResponse = "SERVICE";
-               if (component instanceof Resource) {
-                       componentTypeForResponse = ((Resource) component).getResourceType()
-                                       .name();
-               }
-               return componentTypeForResponse;
-       }
-
-       public Either<Resource, ResponseFormat> getLatestResourceFromCsarUuid(String csarUuid, User user) {
-               // validate user
-               if (user != null) {
-                       validateUserExists(user);
-               }
-               // get resource from csar uuid
-               Either<Resource, StorageOperationStatus> either = toscaOperationFacade
-                               .getLatestComponentByCsarOrName(ComponentTypeEnum.RESOURCE, csarUuid, "");
-               if (either.isRight()) {
-                       ResponseFormat resp = componentsUtils.getResponseFormat(ActionStatus.RESOURCE_FROM_CSAR_NOT_FOUND,
-                                       csarUuid);
-                       return Either.right(resp);
-               }
-
-               return Either.left(either.left()
-                               .value());
-       }
-
-       @Override
-       public Either<List<ComponentInstance>, ResponseFormat> getComponentInstancesFilteredByPropertiesAndInputs(
-                       String componentId, String userId) {
-               return null;
-       }
-
-       private Map<String, List<CapabilityDefinition>> getValidComponentInstanceCapabilities(String resourceId,
-                                                                                                                                                                                 Map<String, List<CapabilityDefinition>> defaultCapabilities,
-                                                                                                                                                                                 Map<String, List<UploadCapInfo>> uploadedCapabilities) {
-
-               Map<String, List<CapabilityDefinition>> validCapabilitiesMap = new HashMap<>();
-               uploadedCapabilities.forEach((k, v) -> addValidComponentInstanceCapabilities(k, v, resourceId,
-                               defaultCapabilities, validCapabilitiesMap));
-               return validCapabilitiesMap;
-       }
-
-       private void addValidComponentInstanceCapabilities(String key, List<UploadCapInfo> capabilities, String resourceId,
-                                                                                                          Map<String, List<CapabilityDefinition>> defaultCapabilities,
-                                                                                                          Map<String, List<CapabilityDefinition>> validCapabilitiesMap) {
-               String capabilityType = capabilities.get(0)
-                               .getType();
-               if (defaultCapabilities.containsKey(capabilityType)) {
-                       CapabilityDefinition defaultCapability = getCapability(resourceId, defaultCapabilities, capabilityType);
-                       validateCapabilityProperties(capabilities, resourceId, defaultCapability);
-                       List<CapabilityDefinition> validCapabilityList = new ArrayList<>();
-                       validCapabilityList.add(defaultCapability);
-                       validCapabilitiesMap.put(key, validCapabilityList);
-               } else {
-                       throw new ByActionStatusComponentException(ActionStatus.MISSING_CAPABILITY_TYPE, capabilityType);
-               }
-       }
-
-       private void validateCapabilityProperties(List<UploadCapInfo> capabilities, String resourceId,
-                                                                                         CapabilityDefinition defaultCapability) {
-               if (CollectionUtils.isEmpty(defaultCapability.getProperties()) && isNotEmpty(capabilities.get(0)
-                               .getProperties())) {
-                       log.debug("Failed to validate capability {} of component {}. Property list is empty. ",
-                                       defaultCapability.getName(), resourceId);
-                       log.debug("Failed to update capability property values. Property list of fetched capability {} is empty. ",
-                                       defaultCapability.getName());
-                       throw new ByActionStatusComponentException(ActionStatus.PROPERTY_NOT_FOUND, resourceId);
-               } else if (isNotEmpty(capabilities.get(0)
-                               .getProperties())) {
-                       validateUniquenessUpdateUploadedComponentInstanceCapability(defaultCapability, capabilities.get(0));
-               }
-       }
-
-       private CapabilityDefinition getCapability(String resourceId,
-                                                                                          Map<String, List<CapabilityDefinition>> defaultCapabilities, String capabilityType) {
-               CapabilityDefinition defaultCapability;
-               if (isNotEmpty(defaultCapabilities.get(capabilityType)
-                               .get(0)
-                               .getProperties())) {
-                       defaultCapability = defaultCapabilities.get(capabilityType)
-                                       .get(0);
-               } else {
-                       Either<Component, StorageOperationStatus> getFullComponentRes = toscaOperationFacade
-                                       .getToscaFullElement(resourceId);
-                       if (getFullComponentRes.isRight()) {
-                               log.debug("Failed to get full component {}. Status is {}. ", resourceId, getFullComponentRes.right()
-                                               .value());
-                               throw new ByActionStatusComponentException(ActionStatus.COMPONENT_NOT_FOUND, resourceId);
-                       }
-                       defaultCapability = getFullComponentRes.left()
-                                       .value()
-                                       .getCapabilities()
-                                       .get(capabilityType)
-                                       .get(0);
-               }
-               return defaultCapability;
-       }
-
-       private void validateUniquenessUpdateUploadedComponentInstanceCapability(CapabilityDefinition defaultCapability,
-                                                                                                                                                        UploadCapInfo uploadedCapability) {
-               List<ComponentInstanceProperty> validProperties = new ArrayList<>();
-               Map<String, PropertyDefinition> defaultProperties = defaultCapability.getProperties()
-                               .stream()
-                               .collect(toMap(PropertyDefinition::getName, Function.identity()));
-               List<UploadPropInfo> uploadedProperties = uploadedCapability.getProperties();
-               for (UploadPropInfo property : uploadedProperties) {
-                       String propertyName = property.getName()
-                                       .toLowerCase();
-                       String propertyType = property.getType();
-                       ComponentInstanceProperty validProperty;
-                       if (defaultProperties.containsKey(propertyName)
-                                       && propertTypeEqualsTo(defaultProperties, propertyName, propertyType)) {
-                               throw new ByActionStatusComponentException(ActionStatus.PROPERTY_NAME_ALREADY_EXISTS, propertyName);
-                       }
-                       validProperty = new ComponentInstanceProperty();
-                       validProperty.setName(propertyName);
-                       if (property.getValue() != null) {
-                               validProperty.setValue(property.getValue()
-                                               .toString());
-                       }
-                       validProperty.setDescription(property.getDescription());
-                       validProperty.setPassword(property.isPassword());
-                       validProperties.add(validProperty);
-               }
-               defaultCapability.setProperties(validProperties);
-       }
-
-       private boolean propertTypeEqualsTo(Map<String, PropertyDefinition> defaultProperties, String propertyName,
-                                                                               String propertyType) {
-               return propertyType != null && !defaultProperties.get(propertyName)
-                               .getType()
-                               .equals(propertyType);
-       }
-
-       private Either<EnumMap<ArtifactOperationEnum, List<NonMetaArtifactInfo>>, ResponseFormat> organizeVfCsarArtifactsByArtifactOperation(
-                       List<NonMetaArtifactInfo> artifactPathAndNameList, List<ArtifactDefinition> existingArtifactsToHandle,
-                       Resource resource, User user) {
-
-               EnumMap<ArtifactOperationEnum, List<NonMetaArtifactInfo>> nodeTypeArtifactsToHandle = new EnumMap<>(
-                               ArtifactOperationEnum.class);
-               Wrapper<ResponseFormat> responseWrapper = new Wrapper<>();
-               Either<EnumMap<ArtifactOperationEnum, List<NonMetaArtifactInfo>>, ResponseFormat> nodeTypeArtifactsToHandleRes = Either
-                               .left(nodeTypeArtifactsToHandle);
-               try {
-                       // add all found Csar artifacts to list to upload
-                       List<NonMetaArtifactInfo> artifactsToUpload = new ArrayList<>(artifactPathAndNameList);
-                       List<NonMetaArtifactInfo> artifactsToUpdate = new ArrayList<>();
-                       List<NonMetaArtifactInfo> artifactsToDelete = new ArrayList<>();
-                       for (NonMetaArtifactInfo currNewArtifact : artifactPathAndNameList) {
-                               ArtifactDefinition foundArtifact;
-
-                               if (!existingArtifactsToHandle.isEmpty()) {
-                                       foundArtifact = existingArtifactsToHandle.stream()
-                                                       .filter(a -> a.getArtifactName()
-                                                                       .equals(currNewArtifact.getArtifactName()))
-                                                       .findFirst()
-                                                       .orElse(null);
-                                       if (foundArtifact != null) {
-                                               if (foundArtifact.getArtifactType().equals(currNewArtifact.getArtifactType())) {
-                                                       if (!foundArtifact.getArtifactChecksum()
-                                                                       .equals(currNewArtifact.getArtifactChecksum())) {
-                                                               currNewArtifact.setArtifactUniqueId(foundArtifact.getUniqueId());
-                                                               // if current artifact already exists, but has
-                                                               // different content, add him to the list to
-                                                               // update
-                                                               artifactsToUpdate.add(currNewArtifact);
-                                                       }
-                                                       // remove found artifact from the list of existing
-                                                       // artifacts to handle, because it was already
-                                                       // handled
-                                                       existingArtifactsToHandle.remove(foundArtifact);
-                                                       // and remove found artifact from the list to
-                                                       // upload, because it should either be updated or be
-                                                       // ignored
-                                                       artifactsToUpload.remove(currNewArtifact);
-                                               } else {
-                                                       log.debug("Can't upload two artifact with the same name {}.",
-                                                                       currNewArtifact.getArtifactName());
-                                                       ResponseFormat responseFormat = ResponseFormatManager.getInstance()
-                                                                       .getResponseFormat(ActionStatus.ARTIFACT_ALREADY_EXIST_IN_DIFFERENT_TYPE_IN_CSAR,
-                                                                                       currNewArtifact.getArtifactName(), currNewArtifact.getArtifactType(),
-                                                                                       foundArtifact.getArtifactType());
-                                                       AuditingActionEnum auditingAction = artifactsBusinessLogic
-                                                                       .detectAuditingType(new ArtifactOperationInfo(false, false,
-                                                                                       ArtifactOperationEnum.CREATE), foundArtifact.getArtifactChecksum());
-                                                       artifactsBusinessLogic.handleAuditing(auditingAction, resource, resource.getUniqueId(),
-                                                                       user, null, null, foundArtifact.getUniqueId(), responseFormat,
-                                                                       resource.getComponentType(), null);
-                                                       responseWrapper.setInnerElement(responseFormat);
-                                                       break;
-                                               }
-                                       }
-                               }
-                       }
-                       if (responseWrapper.isEmpty()) {
-                               for (ArtifactDefinition currArtifact : existingArtifactsToHandle) {
-                                       if (currArtifact.getIsFromCsar()) {
-                                               artifactsToDelete.add(new NonMetaArtifactInfo(currArtifact.getArtifactName(), null,
-                                                       currArtifact.getArtifactType(),
-                                                       currArtifact.getArtifactGroupType(), null, currArtifact.getUniqueId(),
-                                                       currArtifact.getIsFromCsar()));
-                                       } else {
-                                               artifactsToUpdate.add(new NonMetaArtifactInfo(currArtifact.getArtifactName(), null,
-                                                       currArtifact.getArtifactType(),
-                                                       currArtifact.getArtifactGroupType(), null, currArtifact.getUniqueId(),
-                                                       currArtifact.getIsFromCsar()));
-
-                                       }
-                               }
-                       }
-                       if (responseWrapper.isEmpty()) {
-                               if (!artifactsToUpload.isEmpty()) {
-                                       nodeTypeArtifactsToHandle.put(ArtifactOperationEnum.CREATE, artifactsToUpload);
-                               }
-                               if (!artifactsToUpdate.isEmpty()) {
-                                       nodeTypeArtifactsToHandle.put(ArtifactOperationEnum.UPDATE, artifactsToUpdate);
-                               }
-                               if (!artifactsToDelete.isEmpty()) {
-                                       nodeTypeArtifactsToHandle.put(ArtifactOperationEnum.DELETE, artifactsToDelete);
-                               }
-                       }
-                       if (!responseWrapper.isEmpty()) {
-                               nodeTypeArtifactsToHandleRes = Either.right(responseWrapper.getInnerElement());
-                       }
-               } catch (Exception e) {
-                       ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR);
-                       responseWrapper.setInnerElement(responseFormat);
-                       log.debug("Exception occurred when findNodeTypeArtifactsToHandle, error is:{}", e.getMessage(), e);
-               }
-               return nodeTypeArtifactsToHandleRes;
-       }
-
-       ImmutablePair<String, String> buildNestedToscaResourceName(final String nodeResourceType,
-                                                                                                                          final String vfResourceName,
-                                                                                                                          final String nodeTypeFullName) {
-               String actualType;
-               String actualVfName;
-               if (ResourceTypeEnum.CVFC.name()
-                       .equals(nodeResourceType)) {
-                       actualVfName = vfResourceName + ResourceTypeEnum.CVFC.name();
-                       actualType = ResourceTypeEnum.VFC.name();
-               } else {
-                       actualVfName = vfResourceName;
-                       actualType = nodeResourceType;
-               }
-               String nameWithouNamespacePrefix;
-               try {
-                       final String nodeTypeNamePrefix = getNodeTypeNamePrefix(nodeTypeFullName);
-                       log.debug("####### buildNestedToscaResourceName nodeResourceType {}, vfResourceName {}, "
-                                       + "nodeTypeFullName {}, actualType {}, vfResourceName {} ",     nodeResourceType, vfResourceName,
-                               nodeTypeFullName, actualType, vfResourceName);
-                       final StringBuilder toscaResourceName = new StringBuilder(nodeTypeNamePrefix);
-
-                       if (!nodeTypeFullName.contains(nodeTypeNamePrefix)) {
-                               nameWithouNamespacePrefix = nodeTypeFullName;
-                       } else {
-                               nameWithouNamespacePrefix = nodeTypeFullName.substring(nodeTypeNamePrefix.length());
-                       }
-                       final String[] findTypes = nameWithouNamespacePrefix.split("\\.");
-                       String actualName;
-                       if (nodeResourceType.equalsIgnoreCase(findTypes[0])){
-                               actualName = nameWithouNamespacePrefix.substring(nodeResourceType.length());
-                       } else {
-                               actualName = "." + nameWithouNamespacePrefix;
-                       }
-
-                       if (actualName.startsWith(Constants.ABSTRACT)) {
-                               toscaResourceName.append(nodeResourceType.toLowerCase()).append('.')
-                                       .append(ValidationUtils.convertToSystemName(actualVfName));
-                       } else {
-                               toscaResourceName.append(actualType.toLowerCase()).append('.')
-                                       .append(ValidationUtils.convertToSystemName(actualVfName)).append('.').append(Constants.ABSTRACT);
-                       }
-                       final StringBuilder previousToscaResourceName = new StringBuilder(toscaResourceName);
-                       final String[] actualNames = actualName.split("\\.");
-                       if (actualNames.length < 3) {
-                               return new ImmutablePair<>(toscaResourceName.append(actualName.toLowerCase()).toString(),
-                                       previousToscaResourceName.append(actualName).toString());
-                       }
-                       return new ImmutablePair<>(toscaResourceName.append(actualName.toLowerCase()).toString(),
-                               previousToscaResourceName.append(actualName.substring(actualNames[1].length() + 1)
-                                       .toLowerCase()).toString());
-               } catch (final Exception e) {
-                       log.debug("Exception occured when buildNestedToscaResourceName, error is:{}", e.getMessage(), e);
-                       throw new ByActionStatusComponentException(ActionStatus.INVALID_TOSCA_TEMPLATE, vfResourceName);
-               }
-       }
-
-       /**
-        * Extracts a Node Type Name prefix from the given Node Type Name.
-        *
-        * @param fullName Node Type Name
-        * @return Node Type Name Prefix
-        */
-       private String getNodeTypeNamePrefix(final String fullName) {
-               String tempPrefix = Constants.USER_DEFINED_RESOURCE_NAMESPACE_PREFIX;
-               final List<String> definedNodeTypeNamespaceList = getDefinedNodeTypeNamespaceList();
-               log.debug("************* getPrefiX fullName {} FROM {}", fullName, definedNodeTypeNamespaceList);
-               final Optional<String> validNameSpace = validateNodeTypeNamePrefix(fullName, definedNodeTypeNamespaceList);
-               if (validNameSpace.isPresent()) {
-                       tempPrefix = validNameSpace.get();
-               }
-               log.debug("************* getNodeTypeNamePrefix return fullName {} ", tempPrefix);
-               return tempPrefix;
-       }
-
-       @Override
-       public Either<UiComponentDataTransfer, ResponseFormat> getUiComponentDataTransferByComponentId(String resourceId,
-                                                                                                                                                                                                  List<String> dataParamsToReturn) {
-
-               ComponentParametersView paramsToReturn = new ComponentParametersView(dataParamsToReturn);
-               Either<Resource, StorageOperationStatus> resourceResultEither = toscaOperationFacade.getToscaElement(resourceId, paramsToReturn);
-
-               if (resourceResultEither.isRight()) {
-                       if (resourceResultEither.right().value() == StorageOperationStatus.NOT_FOUND) {
-                               log.debug("Failed to found resource with id {} ", resourceId);
-                               Either
-                                       .right(componentsUtils.getResponseFormat(ActionStatus.RESOURCE_NOT_FOUND, resourceId));
-                       }
-
-                       log.debug("failed to get resource by id {} with filters {}", resourceId, dataParamsToReturn);
-                       return Either.right(componentsUtils
-                                       .getResponseFormatByResource(componentsUtils.convertFromStorageResponse(resourceResultEither.right()
-                                                       .value()), ""));
-               }
-
-               Resource resource = resourceResultEither.left().value();
-               if (dataParamsToReturn.contains(ComponentFieldsEnum.INPUTS.getValue())) {
-                       ListUtils.emptyIfNull(resource.getInputs())
-                                       .forEach(input -> input.setConstraints(setInputConstraint(input)));
-               }
-
-               UiComponentDataTransfer dataTransfer = uiComponentDataConverter.getUiDataTransferFromResourceByParams(resource,
-                               dataParamsToReturn);
-               return Either.left(dataTransfer);
-       }
-
-       @Override
-       public Either<Component, ActionStatus> shouldUpgradeToLatestDerived(Component clonedComponent) {
-               Resource resource = (Resource) clonedComponent;
-               if (ModelConverter.isAtomicComponent(resource.getResourceType())) {
-                       Either<Component, StorageOperationStatus> shouldUpgradeToLatestDerived = toscaOperationFacade
-                                       .shouldUpgradeToLatestDerived(resource);
-                       if (shouldUpgradeToLatestDerived.isRight()) {
-                               return Either.right(componentsUtils.convertFromStorageResponse(shouldUpgradeToLatestDerived.right()
-                                               .value()));
-                       }
-                       return Either.left(shouldUpgradeToLatestDerived.left()
-                                       .value());
-               } else {
-                       return super.shouldUpgradeToLatestDerived(clonedComponent);
-               }
-       }
+        return Either.left(true);
+    }
+
+    public ICapabilityTypeOperation getCapabilityTypeOperation() {
+        return capabilityTypeOperation;
+    }
+
+    @Autowired
+    public void setCapabilityTypeOperation(ICapabilityTypeOperation capabilityTypeOperation) {
+        this.capabilityTypeOperation = capabilityTypeOperation;
+    }
+
+    public Boolean validatePropertiesDefaultValues(Resource resource) {
+        log.debug("validate resource properties default values");
+        List<PropertyDefinition> properties = resource.getProperties();
+        if (properties != null) {
+            iterateOverProperties(properties);
+        }
+        return true;
+    }
+
+    public void iterateOverProperties(List<PropertyDefinition> properties) {
+        String type = null;
+        String innerType = null;
+        for (PropertyDefinition property : properties) {
+            if (!propertyOperation.isPropertyTypeValid(property)) {
+                log.info("Invalid type for property {}", property);
+                throw new ByActionStatusComponentException(ActionStatus.INVALID_PROPERTY_TYPE, property.getType(), property.getName());
+            }
+            Map<String, DataTypeDefinition> allDataTypes = getAllDataTypes(applicationDataTypeCache);
+            type = property.getType();
+            if (type.equals(ToscaPropertyType.LIST.getType()) || type.equals(ToscaPropertyType.MAP.getType())) {
+                ResponseFormat responseFormat = validateMapOrListPropertyType(property, innerType, allDataTypes);
+                if (responseFormat != null) {
+                    break;
+                }
+            }
+            validateDefaultPropertyValue(property, allDataTypes, type, innerType);
+        }
+    }
+
+    private void validateDefaultPropertyValue(PropertyDefinition property, Map<String, DataTypeDefinition> allDataTypes, String type,
+                                              String innerType) {
+        if (!propertyOperation.isPropertyDefaultValueValid(property, allDataTypes)) {
+            log.info("Invalid default value for property {}", property);
+            ResponseFormat responseFormat;
+            if (type.equals(ToscaPropertyType.LIST.getType()) || type.equals(ToscaPropertyType.MAP.getType())) {
+                throw new ByActionStatusComponentException(ActionStatus.INVALID_COMPLEX_DEFAULT_VALUE, property.getName(), type, innerType,
+                    property.getDefaultValue());
+            }
+            throw new ByActionStatusComponentException(ActionStatus.INVALID_DEFAULT_VALUE, property.getName(), type, property.getDefaultValue());
+        }
+    }
+
+    private ResponseFormat validateMapOrListPropertyType(PropertyDefinition property, String innerType,
+                                                         Map<String, DataTypeDefinition> allDataTypes) {
+        ResponseFormat responseFormat = null;
+        ImmutablePair<String, Boolean> propertyInnerTypeValid = propertyOperation.isPropertyInnerTypeValid(property, allDataTypes);
+        innerType = propertyInnerTypeValid.getLeft();
+        if (!propertyInnerTypeValid.getRight().booleanValue()) {
+            log.info("Invalid inner type for property {}", property);
+            responseFormat = componentsUtils.getResponseFormat(ActionStatus.INVALID_PROPERTY_INNER_TYPE, innerType, property.getName());
+        }
+        return responseFormat;
+    }
+
+    @Override
+    public Either<List<String>, ResponseFormat> deleteMarkedComponents() {
+        return deleteMarkedComponents(ComponentTypeEnum.RESOURCE);
+    }
+
+    @Override
+    public ComponentInstanceBusinessLogic getComponentInstanceBL() {
+        return componentInstanceBusinessLogic;
+    }
+
+    private String getComponentTypeForResponse(Component component) {
+        String componentTypeForResponse = "SERVICE";
+        if (component instanceof Resource) {
+            componentTypeForResponse = ((Resource) component).getResourceType().name();
+        }
+        return componentTypeForResponse;
+    }
+
+    public Either<Resource, ResponseFormat> getLatestResourceFromCsarUuid(String csarUuid, User user) {
+        // validate user
+        if (user != null) {
+            validateUserExists(user);
+        }
+        // get resource from csar uuid
+        Either<Resource, StorageOperationStatus> either = toscaOperationFacade
+            .getLatestComponentByCsarOrName(ComponentTypeEnum.RESOURCE, csarUuid, "");
+        if (either.isRight()) {
+            ResponseFormat resp = componentsUtils.getResponseFormat(ActionStatus.RESOURCE_FROM_CSAR_NOT_FOUND, csarUuid);
+            return Either.right(resp);
+        }
+        return Either.left(either.left().value());
+    }
+
+    @Override
+    public Either<List<ComponentInstance>, ResponseFormat> getComponentInstancesFilteredByPropertiesAndInputs(String componentId, String userId) {
+        return null;
+    }
+
+    private Map<String, List<CapabilityDefinition>> getValidComponentInstanceCapabilities(String resourceId,
+                                                                                          Map<String, List<CapabilityDefinition>> defaultCapabilities,
+                                                                                          Map<String, List<UploadCapInfo>> uploadedCapabilities) {
+        Map<String, List<CapabilityDefinition>> validCapabilitiesMap = new HashMap<>();
+        uploadedCapabilities.forEach((k, v) -> addValidComponentInstanceCapabilities(k, v, resourceId, defaultCapabilities, validCapabilitiesMap));
+        return validCapabilitiesMap;
+    }
+
+    private void addValidComponentInstanceCapabilities(String key, List<UploadCapInfo> capabilities, String resourceId,
+                                                       Map<String, List<CapabilityDefinition>> defaultCapabilities,
+                                                       Map<String, List<CapabilityDefinition>> validCapabilitiesMap) {
+        String capabilityType = capabilities.get(0).getType();
+        if (defaultCapabilities.containsKey(capabilityType)) {
+            CapabilityDefinition defaultCapability = getCapability(resourceId, defaultCapabilities, capabilityType);
+            validateCapabilityProperties(capabilities, resourceId, defaultCapability);
+            List<CapabilityDefinition> validCapabilityList = new ArrayList<>();
+            validCapabilityList.add(defaultCapability);
+            validCapabilitiesMap.put(key, validCapabilityList);
+        } else {
+            throw new ByActionStatusComponentException(ActionStatus.MISSING_CAPABILITY_TYPE, capabilityType);
+        }
+    }
+
+    private void validateCapabilityProperties(List<UploadCapInfo> capabilities, String resourceId, CapabilityDefinition defaultCapability) {
+        if (CollectionUtils.isEmpty(defaultCapability.getProperties()) && isNotEmpty(capabilities.get(0).getProperties())) {
+            log.debug("Failed to validate capability {} of component {}. Property list is empty. ", defaultCapability.getName(), resourceId);
+            log.debug("Failed to update capability property values. Property list of fetched capability {} is empty. ", defaultCapability.getName());
+            throw new ByActionStatusComponentException(ActionStatus.PROPERTY_NOT_FOUND, resourceId);
+        } else if (isNotEmpty(capabilities.get(0).getProperties())) {
+            validateUniquenessUpdateUploadedComponentInstanceCapability(defaultCapability, capabilities.get(0));
+        }
+    }
+
+    private CapabilityDefinition getCapability(String resourceId, Map<String, List<CapabilityDefinition>> defaultCapabilities,
+                                               String capabilityType) {
+        CapabilityDefinition defaultCapability;
+        if (isNotEmpty(defaultCapabilities.get(capabilityType).get(0).getProperties())) {
+            defaultCapability = defaultCapabilities.get(capabilityType).get(0);
+        } else {
+            Either<Component, StorageOperationStatus> getFullComponentRes = toscaOperationFacade.getToscaFullElement(resourceId);
+            if (getFullComponentRes.isRight()) {
+                log.debug("Failed to get full component {}. Status is {}. ", resourceId, getFullComponentRes.right().value());
+                throw new ByActionStatusComponentException(ActionStatus.COMPONENT_NOT_FOUND, resourceId);
+            }
+            defaultCapability = getFullComponentRes.left().value().getCapabilities().get(capabilityType).get(0);
+        }
+        return defaultCapability;
+    }
+
+    private void validateUniquenessUpdateUploadedComponentInstanceCapability(CapabilityDefinition defaultCapability,
+                                                                             UploadCapInfo uploadedCapability) {
+        List<ComponentInstanceProperty> validProperties = new ArrayList<>();
+        Map<String, PropertyDefinition> defaultProperties = defaultCapability.getProperties().stream()
+            .collect(toMap(PropertyDefinition::getName, Function.identity()));
+        List<UploadPropInfo> uploadedProperties = uploadedCapability.getProperties();
+        for (UploadPropInfo property : uploadedProperties) {
+            String propertyName = property.getName().toLowerCase();
+            String propertyType = property.getType();
+            ComponentInstanceProperty validProperty;
+            if (defaultProperties.containsKey(propertyName) && propertTypeEqualsTo(defaultProperties, propertyName, propertyType)) {
+                throw new ByActionStatusComponentException(ActionStatus.PROPERTY_NAME_ALREADY_EXISTS, propertyName);
+            }
+            validProperty = new ComponentInstanceProperty();
+            validProperty.setName(propertyName);
+            if (property.getValue() != null) {
+                validProperty.setValue(property.getValue().toString());
+            }
+            validProperty.setDescription(property.getDescription());
+            validProperty.setPassword(property.isPassword());
+            validProperties.add(validProperty);
+        }
+        defaultCapability.setProperties(validProperties);
+    }
+
+    private boolean propertTypeEqualsTo(Map<String, PropertyDefinition> defaultProperties, String propertyName, String propertyType) {
+        return propertyType != null && !defaultProperties.get(propertyName).getType().equals(propertyType);
+    }
+
+    private Either<EnumMap<ArtifactOperationEnum, List<NonMetaArtifactInfo>>, ResponseFormat> organizeVfCsarArtifactsByArtifactOperation(
+        List<NonMetaArtifactInfo> artifactPathAndNameList, List<ArtifactDefinition> existingArtifactsToHandle, Resource resource, User user) {
+        EnumMap<ArtifactOperationEnum, List<NonMetaArtifactInfo>> nodeTypeArtifactsToHandle = new EnumMap<>(ArtifactOperationEnum.class);
+        Wrapper<ResponseFormat> responseWrapper = new Wrapper<>();
+        Either<EnumMap<ArtifactOperationEnum, List<NonMetaArtifactInfo>>, ResponseFormat> nodeTypeArtifactsToHandleRes = Either
+            .left(nodeTypeArtifactsToHandle);
+        try {
+            // add all found Csar artifacts to list to upload
+            List<NonMetaArtifactInfo> artifactsToUpload = new ArrayList<>(artifactPathAndNameList);
+            List<NonMetaArtifactInfo> artifactsToUpdate = new ArrayList<>();
+            List<NonMetaArtifactInfo> artifactsToDelete = new ArrayList<>();
+            for (NonMetaArtifactInfo currNewArtifact : artifactPathAndNameList) {
+                ArtifactDefinition foundArtifact;
+                if (!existingArtifactsToHandle.isEmpty()) {
+                    foundArtifact = existingArtifactsToHandle.stream().filter(a -> a.getArtifactName().equals(currNewArtifact.getArtifactName()))
+                        .findFirst().orElse(null);
+                    if (foundArtifact != null) {
+                        if (foundArtifact.getArtifactType().equals(currNewArtifact.getArtifactType())) {
+                            if (!foundArtifact.getArtifactChecksum().equals(currNewArtifact.getArtifactChecksum())) {
+                                currNewArtifact.setArtifactUniqueId(foundArtifact.getUniqueId());
+                                // if current artifact already exists, but has
+
+                                // different content, add him to the list to
+
+                                // update
+                                artifactsToUpdate.add(currNewArtifact);
+                            }
+                            // remove found artifact from the list of existing
+
+                            // artifacts to handle, because it was already
+
+                            // handled
+                            existingArtifactsToHandle.remove(foundArtifact);
+                            // and remove found artifact from the list to
+
+                            // upload, because it should either be updated or be
+
+                            // ignored
+                            artifactsToUpload.remove(currNewArtifact);
+                        } else {
+                            log.debug("Can't upload two artifact with the same name {}.", currNewArtifact.getArtifactName());
+                            ResponseFormat responseFormat = ResponseFormatManager.getInstance()
+                                .getResponseFormat(ActionStatus.ARTIFACT_ALREADY_EXIST_IN_DIFFERENT_TYPE_IN_CSAR, currNewArtifact.getArtifactName(),
+                                    currNewArtifact.getArtifactType(), foundArtifact.getArtifactType());
+                            AuditingActionEnum auditingAction = artifactsBusinessLogic
+                                .detectAuditingType(new ArtifactOperationInfo(false, false, ArtifactOperationEnum.CREATE),
+                                    foundArtifact.getArtifactChecksum());
+                            artifactsBusinessLogic
+                                .handleAuditing(auditingAction, resource, resource.getUniqueId(), user, null, null, foundArtifact.getUniqueId(),
+                                    responseFormat, resource.getComponentType(), null);
+                            responseWrapper.setInnerElement(responseFormat);
+                            break;
+                        }
+                    }
+                }
+            }
+            if (responseWrapper.isEmpty()) {
+                for (ArtifactDefinition currArtifact : existingArtifactsToHandle) {
+                    if (currArtifact.getIsFromCsar()) {
+                        artifactsToDelete.add(new NonMetaArtifactInfo(currArtifact.getArtifactName(), null, currArtifact.getArtifactType(),
+                            currArtifact.getArtifactGroupType(), null, currArtifact.getUniqueId(), currArtifact.getIsFromCsar()));
+                    } else {
+                        artifactsToUpdate.add(new NonMetaArtifactInfo(currArtifact.getArtifactName(), null, currArtifact.getArtifactType(),
+                            currArtifact.getArtifactGroupType(), null, currArtifact.getUniqueId(), currArtifact.getIsFromCsar()));
+                    }
+                }
+            }
+            if (responseWrapper.isEmpty()) {
+                if (!artifactsToUpload.isEmpty()) {
+                    nodeTypeArtifactsToHandle.put(ArtifactOperationEnum.CREATE, artifactsToUpload);
+                }
+                if (!artifactsToUpdate.isEmpty()) {
+                    nodeTypeArtifactsToHandle.put(ArtifactOperationEnum.UPDATE, artifactsToUpdate);
+                }
+                if (!artifactsToDelete.isEmpty()) {
+                    nodeTypeArtifactsToHandle.put(ArtifactOperationEnum.DELETE, artifactsToDelete);
+                }
+            }
+            if (!responseWrapper.isEmpty()) {
+                nodeTypeArtifactsToHandleRes = Either.right(responseWrapper.getInnerElement());
+            }
+        } catch (Exception e) {
+            ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR);
+            responseWrapper.setInnerElement(responseFormat);
+            log.debug("Exception occurred when findNodeTypeArtifactsToHandle, error is:{}", e.getMessage(), e);
+        }
+        return nodeTypeArtifactsToHandleRes;
+    }
+
+    ImmutablePair<String, String> buildNestedToscaResourceName(final String nodeResourceType, final String vfResourceName,
+                                                               final String nodeTypeFullName) {
+        String actualType;
+        String actualVfName;
+        if (ResourceTypeEnum.CVFC.name().equals(nodeResourceType)) {
+            actualVfName = vfResourceName + ResourceTypeEnum.CVFC.name();
+            actualType = ResourceTypeEnum.VFC.name();
+        } else {
+            actualVfName = vfResourceName;
+            actualType = nodeResourceType;
+        }
+        String nameWithouNamespacePrefix;
+        try {
+            final String nodeTypeNamePrefix = getNodeTypeNamePrefix(nodeTypeFullName);
+            log.debug("####### buildNestedToscaResourceName nodeResourceType {}, vfResourceName {}, "
+                    + "nodeTypeFullName {}, actualType {}, vfResourceName {} ", nodeResourceType, vfResourceName, nodeTypeFullName, actualType,
+                vfResourceName);
+            final StringBuilder toscaResourceName = new StringBuilder(nodeTypeNamePrefix);
+            if (!nodeTypeFullName.contains(nodeTypeNamePrefix)) {
+                nameWithouNamespacePrefix = nodeTypeFullName;
+            } else {
+                nameWithouNamespacePrefix = nodeTypeFullName.substring(nodeTypeNamePrefix.length());
+            }
+            final String[] findTypes = nameWithouNamespacePrefix.split("\\.");
+            String actualName;
+            if (nodeResourceType.equalsIgnoreCase(findTypes[0])) {
+                actualName = nameWithouNamespacePrefix.substring(nodeResourceType.length());
+            } else {
+                actualName = "." + nameWithouNamespacePrefix;
+            }
+            if (actualName.startsWith(Constants.ABSTRACT)) {
+                toscaResourceName.append(nodeResourceType.toLowerCase()).append('.').append(ValidationUtils.convertToSystemName(actualVfName));
+            } else {
+                toscaResourceName.append(actualType.toLowerCase()).append('.').append(ValidationUtils.convertToSystemName(actualVfName)).append('.')
+                    .append(Constants.ABSTRACT);
+            }
+            final StringBuilder previousToscaResourceName = new StringBuilder(toscaResourceName);
+            final String[] actualNames = actualName.split("\\.");
+            if (actualNames.length < 3) {
+                return new ImmutablePair<>(toscaResourceName.append(actualName.toLowerCase()).toString(),
+                    previousToscaResourceName.append(actualName).toString());
+            }
+            return new ImmutablePair<>(toscaResourceName.append(actualName.toLowerCase()).toString(),
+                previousToscaResourceName.append(actualName.substring(actualNames[1].length() + 1).toLowerCase()).toString());
+        } catch (final Exception e) {
+            log.debug("Exception occured when buildNestedToscaResourceName, error is:{}", e.getMessage(), e);
+            throw new ByActionStatusComponentException(ActionStatus.INVALID_TOSCA_TEMPLATE, vfResourceName);
+        }
+    }
+
+    /**
+     * Extracts a Node Type Name prefix from the given Node Type Name.
+     *
+     * @param fullName Node Type Name
+     * @return Node Type Name Prefix
+     */
+    private String getNodeTypeNamePrefix(final String fullName) {
+        String tempPrefix = Constants.USER_DEFINED_RESOURCE_NAMESPACE_PREFIX;
+        final List<String> definedNodeTypeNamespaceList = getDefinedNodeTypeNamespaceList();
+        log.debug("************* getPrefiX fullName {} FROM {}", fullName, definedNodeTypeNamespaceList);
+        final Optional<String> validNameSpace = validateNodeTypeNamePrefix(fullName, definedNodeTypeNamespaceList);
+        if (validNameSpace.isPresent()) {
+            tempPrefix = validNameSpace.get();
+        }
+        log.debug("************* getNodeTypeNamePrefix return fullName {} ", tempPrefix);
+        return tempPrefix;
+    }
+
+    @Override
+    public Either<UiComponentDataTransfer, ResponseFormat> getUiComponentDataTransferByComponentId(String resourceId,
+                                                                                                   List<String> dataParamsToReturn) {
+        ComponentParametersView paramsToReturn = new ComponentParametersView(dataParamsToReturn);
+        Either<Resource, StorageOperationStatus> resourceResultEither = toscaOperationFacade.getToscaElement(resourceId, paramsToReturn);
+        if (resourceResultEither.isRight()) {
+            if (resourceResultEither.right().value() == StorageOperationStatus.NOT_FOUND) {
+                log.debug("Failed to found resource with id {} ", resourceId);
+                Either.right(componentsUtils.getResponseFormat(ActionStatus.RESOURCE_NOT_FOUND, resourceId));
+            }
+            log.debug("failed to get resource by id {} with filters {}", resourceId, dataParamsToReturn);
+            return Either.right(
+                componentsUtils.getResponseFormatByResource(componentsUtils.convertFromStorageResponse(resourceResultEither.right().value()), ""));
+        }
+        Resource resource = resourceResultEither.left().value();
+        if (dataParamsToReturn.contains(ComponentFieldsEnum.INPUTS.getValue())) {
+            ListUtils.emptyIfNull(resource.getInputs()).forEach(input -> input.setConstraints(setInputConstraint(input)));
+        }
+        UiComponentDataTransfer dataTransfer = uiComponentDataConverter.getUiDataTransferFromResourceByParams(resource, dataParamsToReturn);
+        return Either.left(dataTransfer);
+    }
+
+    @Override
+    public Either<Component, ActionStatus> shouldUpgradeToLatestDerived(Component clonedComponent) {
+        Resource resource = (Resource) clonedComponent;
+        if (ModelConverter.isAtomicComponent(resource.getResourceType())) {
+            Either<Component, StorageOperationStatus> shouldUpgradeToLatestDerived = toscaOperationFacade.shouldUpgradeToLatestDerived(resource);
+            if (shouldUpgradeToLatestDerived.isRight()) {
+                return Either.right(componentsUtils.convertFromStorageResponse(shouldUpgradeToLatestDerived.right().value()));
+            }
+            return Either.left(shouldUpgradeToLatestDerived.left().value());
+        } else {
+            return super.shouldUpgradeToLatestDerived(clonedComponent);
+        }
+    }
 }
index 8ea1c2a..787bc3e 100644 (file)
  * Modifications copyright (c) 2019 Nokia
  * ================================================================================
  */
-
 package org.openecomp.sdc.be.components.impl;
 
 import static org.openecomp.sdc.be.model.jsonjanusgraph.operations.ToscaElementOperation.createDataType;
 import static org.openecomp.sdc.be.model.jsonjanusgraph.operations.ToscaElementOperation.createDataTypeDefinitionWithName;
-import static org.openecomp.sdc.be.utils.TypeUtils.setField;
 
 import fj.data.Either;
 import java.util.ArrayList;
@@ -102,33 +100,18 @@ import org.yaml.snakeyaml.Yaml;
 @Component("resourceImportManager")
 public class ResourceImportManager {
 
-    private static final Logger log = Logger.getLogger(ResourceImportManager.class);
-
     static final Pattern PROPERTY_NAME_PATTERN_IGNORE_LENGTH = Pattern.compile("[\\w\\-\\_\\d\\:]+");
+    private static final Logger log = Logger.getLogger(ResourceImportManager.class);
     private final InterfaceDefinitionHandler interfaceDefinitionHandler;
-
+    private final ComponentsUtils componentsUtils;
+    private final CapabilityTypeOperation capabilityTypeOperation;
     private ServletContext servletContext;
-
     private AuditingManager auditingManager;
     private ResourceBusinessLogic resourceBusinessLogic;
-
-    public ServiceBusinessLogic getServiceBusinessLogic() {
-        return serviceBusinessLogic;
-    }
-
-    public void setServiceBusinessLogic(ServiceBusinessLogic serviceBusinessLogic) {
-        this.serviceBusinessLogic = serviceBusinessLogic;
-    }
-
     @Autowired
     private ServiceBusinessLogic serviceBusinessLogic;
-
     private IGraphLockOperation graphLockOperation;
     private ToscaOperationFacade toscaOperationFacade;
-
-    private final ComponentsUtils componentsUtils;
-    private final CapabilityTypeOperation capabilityTypeOperation;
-
     private ResponseFormatManager responseFormatManager;
 
     @Autowired
@@ -139,88 +122,74 @@ public class ResourceImportManager {
         this.interfaceDefinitionHandler = interfaceDefinitionHandler;
     }
 
+    public ServiceBusinessLogic getServiceBusinessLogic() {
+        return serviceBusinessLogic;
+    }
+
+    public void setServiceBusinessLogic(ServiceBusinessLogic serviceBusinessLogic) {
+        this.serviceBusinessLogic = serviceBusinessLogic;
+    }
+
     @Autowired
     public void setToscaOperationFacade(ToscaOperationFacade toscaOperationFacade) {
         this.toscaOperationFacade = toscaOperationFacade;
     }
 
-    public ImmutablePair<Resource, ActionStatus> importNormativeResource(String resourceYml,
-                                                                         UploadResourceInfo resourceMetaData,
-                                                                         User creator, boolean createNewVersion,
-                                                                         boolean needLock) {
-
+    public ImmutablePair<Resource, ActionStatus> importNormativeResource(String resourceYml, UploadResourceInfo resourceMetaData, User creator,
+                                                                         boolean createNewVersion, boolean needLock) {
         LifecycleChangeInfoWithAction lifecycleChangeInfo = new LifecycleChangeInfoWithAction();
         lifecycleChangeInfo.setUserRemarks("certification on import");
-        Function<Resource, Boolean> validator = resource -> resourceBusinessLogic
-            .validatePropertiesDefaultValues(resource);
-
-        return importCertifiedResource(resourceYml, resourceMetaData, creator, validator, lifecycleChangeInfo, false,
-            createNewVersion, needLock, null, null, false, null, null, false);
+        Function<Resource, Boolean> validator = resource -> resourceBusinessLogic.validatePropertiesDefaultValues(resource);
+        return importCertifiedResource(resourceYml, resourceMetaData, creator, validator, lifecycleChangeInfo, false, createNewVersion, needLock,
+            null, null, false, null, null, false);
     }
 
-    public ImmutablePair<Resource, ActionStatus> importNormativeResourceFromCsar(String resourceYml,
-                                                                                 UploadResourceInfo resourceMetaData,
-                                                                                 User creator, boolean createNewVersion,
-                                                                                 boolean needLock) {
-
+    public ImmutablePair<Resource, ActionStatus> importNormativeResourceFromCsar(String resourceYml, UploadResourceInfo resourceMetaData,
+                                                                                 User creator, boolean createNewVersion, boolean needLock) {
         LifecycleChangeInfoWithAction lifecycleChangeInfo = new LifecycleChangeInfoWithAction();
         lifecycleChangeInfo.setUserRemarks("certification on import");
-        Function<Resource, Boolean> validator = resource -> resourceBusinessLogic
-            .validatePropertiesDefaultValues(resource);
-
-        return importCertifiedResource(resourceYml, resourceMetaData, creator, validator, lifecycleChangeInfo, false,
-            createNewVersion, needLock, null, null, false, null, null, false);
+        Function<Resource, Boolean> validator = resource -> resourceBusinessLogic.validatePropertiesDefaultValues(resource);
+        return importCertifiedResource(resourceYml, resourceMetaData, creator, validator, lifecycleChangeInfo, false, createNewVersion, needLock,
+            null, null, false, null, null, false);
     }
 
-    public ImmutablePair<Resource, ActionStatus> importCertifiedResource(String resourceYml,
-                                                                         UploadResourceInfo resourceMetaData,
-                                                                         User creator,
+    public ImmutablePair<Resource, ActionStatus> importCertifiedResource(String resourceYml, UploadResourceInfo resourceMetaData, User creator,
                                                                          Function<Resource, Boolean> validationFunction,
-                                                                         LifecycleChangeInfoWithAction lifecycleChangeInfo,
-                                                                         boolean isInTransaction,
+                                                                         LifecycleChangeInfoWithAction lifecycleChangeInfo, boolean isInTransaction,
                                                                          boolean createNewVersion, boolean needLock,
                                                                          Map<ArtifactOperationEnum, List<ArtifactDefinition>> nodeTypeArtifactsToHandle,
                                                                          List<ArtifactDefinition> nodeTypesNewCreatedArtifacts,
-                                                                         boolean forceCertificationAllowed,
-                                                                         CsarInfo csarInfo, String nodeName,
+                                                                         boolean forceCertificationAllowed, CsarInfo csarInfo, String nodeName,
                                                                          boolean isNested) {
         Resource resource = new Resource();
         ImmutablePair<Resource, ActionStatus> responsePair = new ImmutablePair<>(resource, ActionStatus.CREATED);
         Either<ImmutablePair<Resource, ActionStatus>, ResponseFormat> response = Either.left(responsePair);
-
         String latestCertifiedResourceId = null;
         try {
             boolean shouldBeCertified = nodeTypeArtifactsToHandle == null || nodeTypeArtifactsToHandle.isEmpty();
             setConstantMetaData(resource, shouldBeCertified);
             setMetaDataFromJson(resourceMetaData, resource);
-
             populateResourceFromYaml(resourceYml, resource);
-
             validationFunction.apply(resource);
             if (!createNewVersion) {
-                Either<Resource, StorageOperationStatus> latestByName = toscaOperationFacade
-                    .getLatestByName(resource.getName());
+                Either<Resource, StorageOperationStatus> latestByName = toscaOperationFacade.getLatestByName(resource.getName());
                 if (latestByName.isLeft()) {
-                    throw new ByActionStatusComponentException(ActionStatus.COMPONENT_NAME_ALREADY_EXIST,
-                        resource.getName());
+                    throw new ByActionStatusComponentException(ActionStatus.COMPONENT_NAME_ALREADY_EXIST, resource.getName());
                 }
             } else {
-                final Either<Resource, StorageOperationStatus> component = toscaOperationFacade.getComponentByNameAndVendorRelease(resource.getComponentType(), resource.getName(), resource.getVendorRelease(), JsonParseFlagEnum.ParseAll);
+                final Either<Resource, StorageOperationStatus> component = toscaOperationFacade
+                    .getComponentByNameAndVendorRelease(resource.getComponentType(), resource.getName(), resource.getVendorRelease(),
+                        JsonParseFlagEnum.ParseAll);
                 if (component.isLeft()) {
-                    throw new ByActionStatusComponentException(ActionStatus.COMPONENT_VERSION_ALREADY_EXIST,
-                        resource.getName());
+                    throw new ByActionStatusComponentException(ActionStatus.COMPONENT_VERSION_ALREADY_EXIST, resource.getName());
                 }
             }
             resource = resourceBusinessLogic
-                .createOrUpdateResourceByImport(resource, creator, true, isInTransaction, needLock, csarInfo, nodeName,
-                    isNested).left;
+                .createOrUpdateResourceByImport(resource, creator, true, isInTransaction, needLock, csarInfo, nodeName, isNested).left;
             Resource changeStateResponse;
-
             if (nodeTypeArtifactsToHandle != null && !nodeTypeArtifactsToHandle.isEmpty()) {
-                Either<List<ArtifactDefinition>, ResponseFormat> handleNodeTypeArtifactsRes =
-                    resourceBusinessLogic
-                        .handleNodeTypeArtifacts(resource, nodeTypeArtifactsToHandle, nodeTypesNewCreatedArtifacts,
-                            creator, isInTransaction, false);
+                Either<List<ArtifactDefinition>, ResponseFormat> handleNodeTypeArtifactsRes = resourceBusinessLogic
+                    .handleNodeTypeArtifacts(resource, nodeTypeArtifactsToHandle, nodeTypesNewCreatedArtifacts, creator, isInTransaction, false);
                 if (handleNodeTypeArtifactsRes.isRight()) {
                     //TODO: should be used more correct action
                     throw new ByActionStatusComponentException(ActionStatus.GENERAL_ERROR);
@@ -228,10 +197,8 @@ public class ResourceImportManager {
             }
             latestCertifiedResourceId = getLatestCertifiedResourceId(resource);
             changeStateResponse = resourceBusinessLogic
-                .propagateStateToCertified(creator, resource, lifecycleChangeInfo, isInTransaction, needLock,
-                    forceCertificationAllowed);
-            responsePair = new ImmutablePair<>(changeStateResponse, response.left()
-                .value().right);
+                .propagateStateToCertified(creator, resource, lifecycleChangeInfo, isInTransaction, needLock, forceCertificationAllowed);
+            responsePair = new ImmutablePair<>(changeStateResponse, response.left().value().right);
         } catch (RuntimeException e) {
             handleImportResourceException(resourceMetaData, creator, true, e);
         } finally {
@@ -240,7 +207,6 @@ public class ResourceImportManager {
                 graphLockOperation.unlockComponent(latestCertifiedResourceId, NodeTypeEnum.Resource);
             }
         }
-
         return responsePair;
     }
 
@@ -279,45 +245,34 @@ public class ResourceImportManager {
         }
     }
 
-    public ImmutablePair<Resource, ActionStatus> importUserDefinedResource(String resourceYml,
-                                                                           UploadResourceInfo resourceMetaData,
-                                                                           User creator, boolean isInTransaction) {
-
+    public ImmutablePair<Resource, ActionStatus> importUserDefinedResource(String resourceYml, UploadResourceInfo resourceMetaData, User creator,
+                                                                           boolean isInTransaction) {
         Resource resource = new Resource();
         ImmutablePair<Resource, ActionStatus> responsePair = new ImmutablePair<>(resource, ActionStatus.CREATED);
-
         try {
             setMetaDataFromJson(resourceMetaData, resource);
-
             populateResourceFromYaml(resourceYml, resource);
-
             // currently import VF isn't supported. In future will be supported
+
             // import VF only with CSAR file!!
             if (ResourceTypeEnum.VF == resource.getResourceType()) {
                 log.debug("Now import VF isn't supported. It will be supported in future with CSAR file only");
                 throw new ByActionStatusComponentException(ActionStatus.RESTRICTED_OPERATION);
             }
-
             resourceBusinessLogic.validateDerivedFromNotEmpty(creator, resource, AuditingActionEnum.CREATE_RESOURCE);
             Boolean validatePropertiesTypes = resourceBusinessLogic.validatePropertiesDefaultValues(resource);
-
-            responsePair = resourceBusinessLogic.createOrUpdateResourceByImport(resource, creator,
-                false, isInTransaction, true, null, null, false);
-
+            responsePair = resourceBusinessLogic.createOrUpdateResourceByImport(resource, creator, false, isInTransaction, true, null, null, false);
         } catch (RuntimeException e) {
             handleImportResourceException(resourceMetaData, creator, false, e);
         }
         return responsePair;
-
     }
 
     private void populateResourceFromYaml(String resourceYml, Resource resource) {
-        @SuppressWarnings("unchecked")
-        Object ymlObj = new Yaml().load(resourceYml);
+        @SuppressWarnings("unchecked") Object ymlObj = new Yaml().load(resourceYml);
         if (ymlObj instanceof Map) {
             Map<String, Object> toscaJsonAll = (Map<String, Object>) ymlObj;
             Map<String, Object> toscaJson = toscaJsonAll;
-
             // Checks if exist and builds the node_types map
             if (toscaJsonAll.containsKey(TypeUtils.ToscaTagNamesEnum.NODE_TYPES.getElementName())
                 && resource.getResourceType() != ResourceTypeEnum.CVFC) {
@@ -326,8 +281,8 @@ public class ResourceImportManager {
                     toscaJsonAll.get(TypeUtils.ToscaTagNamesEnum.NODE_TYPES.getElementName()));
             }
             final List<Object> foundElements = new ArrayList<>();
-            final Either<List<Object>, ResultStatusEnum> toscaElements = ImportUtils.findToscaElements(toscaJsonAll,
-                ToscaTagNamesEnum.DATA_TYPES.getElementName(), ToscaElementTypeEnum.MAP, foundElements);
+            final Either<List<Object>, ResultStatusEnum> toscaElements = ImportUtils
+                .findToscaElements(toscaJsonAll, ToscaTagNamesEnum.DATA_TYPES.getElementName(), ToscaElementTypeEnum.MAP, foundElements);
             if (toscaElements.isLeft()) {
                 final Map<String, Object> toscaAttributes = (Map<String, Object>) foundElements.get(0);
                 if (MapUtils.isNotEmpty(toscaAttributes)) {
@@ -347,7 +302,6 @@ public class ResourceImportManager {
         } else {
             throw new ByActionStatusComponentException(ActionStatus.GENERAL_ERROR);
         }
-
     }
 
     private void setToscaResourceName(Map<String, Object> toscaJson, Resource resource) {
@@ -366,16 +320,13 @@ public class ResourceImportManager {
             Map<String, Object> jsonInterfaces = toscaInterfaces.left().value();
             Map<String, InterfaceDefinition> moduleInterfaces = new HashMap<>();
             for (final Entry<String, Object> interfaceNameValue : jsonInterfaces.entrySet()) {
-                final Either<InterfaceDefinition, ResultStatusEnum> eitherInterface =
-                    createModuleInterface(interfaceNameValue.getValue());
+                final Either<InterfaceDefinition, ResultStatusEnum> eitherInterface = createModuleInterface(interfaceNameValue.getValue());
                 if (eitherInterface.isRight()) {
-                    log.info("error when creating interface:{}, for resource:{}", interfaceNameValue.getKey(),
-                        resource.getName());
+                    log.info("error when creating interface:{}, for resource:{}", interfaceNameValue.getKey(), resource.getName());
                 } else {
                     final InterfaceDefinition interfaceDefinition = eitherInterface.left().value();
                     moduleInterfaces.put(interfaceNameValue.getKey(), interfaceDefinition);
                 }
-
             }
             if (!moduleInterfaces.isEmpty()) {
                 resource.setInterfaces(moduleInterfaces);
@@ -390,13 +341,11 @@ public class ResourceImportManager {
                 interfaceDefinition.setType((String) interfaceJson);
                 return Either.left(interfaceDefinition);
             }
-
             if (interfaceJson instanceof Map) {
                 final Map<String, Object> interfaceJsonMap = (Map<String, Object>) interfaceJson;
                 final InterfaceDefinition interfaceDefinition = interfaceDefinitionHandler.create(interfaceJsonMap);
                 return Either.left(interfaceDefinition);
             }
-
             return Either.right(ResultStatusEnum.GENERAL_ERROR);
         } catch (final Exception e) {
             BeEcompErrorManager.getInstance().logBeSystemError("Import Resource- create interface");
@@ -415,6 +364,7 @@ public class ResourceImportManager {
             // Checking for name duplication
             Set<String> reqNames = new HashSet<>();
             // Getting flattened list of capabilities of parent node - cap name
+
             // to cap type
             Map<String, String> reqName2TypeMap = getReqName2Type(parentResource);
             for (Object jsonRequirementObj : jsonRequirements) {
@@ -423,15 +373,11 @@ public class ResourceImportManager {
                 String requirementName = requirementJsonWrapper.keySet().iterator().next();
                 String reqNameLowerCase = requirementName.toLowerCase();
                 if (reqNames.contains(reqNameLowerCase)) {
-                    log.debug(
-                        "More than one requirement with same name {} (case-insensitive) in imported TOSCA file is invalid",
-                        reqNameLowerCase);
-                    throw new ByActionStatusComponentException(ActionStatus.IMPORT_DUPLICATE_REQ_CAP_NAME,
-                        "requirement", reqNameLowerCase);
+                    log.debug("More than one requirement with same name {} (case-insensitive) in imported TOSCA file is invalid", reqNameLowerCase);
+                    throw new ByActionStatusComponentException(ActionStatus.IMPORT_DUPLICATE_REQ_CAP_NAME, "requirement", reqNameLowerCase);
                 }
                 reqNames.add(reqNameLowerCase);
-                RequirementDefinition requirementDef = createRequirementFromImportFile(requirementJsonWrapper
-                    .get(requirementName));
+                RequirementDefinition requirementDef = createRequirementFromImportFile(requirementJsonWrapper.get(requirementName));
                 requirementDef.setName(requirementName);
                 if (moduleRequirements.containsKey(requirementDef.getCapability())) {
                     moduleRequirements.get(requirementDef.getCapability()).add(requirementDef);
@@ -440,51 +386,39 @@ public class ResourceImportManager {
                     list.add(requirementDef);
                     moduleRequirements.put(requirementDef.getCapability(), list);
                 }
-
                 // Validating against req/cap of "derived from" node
-                Boolean validateVsParentCap = validateCapNameVsDerived(reqName2TypeMap, requirementDef
-                    .getCapability(), requirementDef.getName());
+                Boolean validateVsParentCap = validateCapNameVsDerived(reqName2TypeMap, requirementDef.getCapability(), requirementDef.getName());
                 if (!validateVsParentCap) {
                     String parentResourceName = parentResource != null ? parentResource.getName() : "";
-                    log.debug("Requirement with name {} already exists in parent {}", requirementDef.getName(),
-                        parentResourceName);
-                    throw new ByActionStatusComponentException(ActionStatus.IMPORT_REQ_CAP_NAME_EXISTS_IN_DERIVED,
-                        "requirement", requirementDef
-                        .getName()
-                        .toLowerCase(), parentResourceName);
+                    log.debug("Requirement with name {} already exists in parent {}", requirementDef.getName(), parentResourceName);
+                    throw new ByActionStatusComponentException(ActionStatus.IMPORT_REQ_CAP_NAME_EXISTS_IN_DERIVED, "requirement",
+                        requirementDef.getName().toLowerCase(), parentResourceName);
                 }
             }
             if (moduleRequirements.size() > 0) {
                 resource.setRequirements(moduleRequirements);
             }
-
         }
     }
 
     private RequirementDefinition createRequirementFromImportFile(Object requirementJson) {
         RequirementDefinition requirement = new RequirementDefinition();
-
         if (requirementJson instanceof String) {
             String requirementJsonString = (String) requirementJson;
             requirement.setCapability(requirementJsonString);
         } else if (requirementJson instanceof Map) {
             Map<String, Object> requirementJsonMap = (Map<String, Object>) requirementJson;
             if (requirementJsonMap.containsKey(TypeUtils.ToscaTagNamesEnum.CAPABILITY.getElementName())) {
-                requirement.setCapability(
-                    (String) requirementJsonMap.get(TypeUtils.ToscaTagNamesEnum.CAPABILITY.getElementName()));
+                requirement.setCapability((String) requirementJsonMap.get(TypeUtils.ToscaTagNamesEnum.CAPABILITY.getElementName()));
             }
-
             if (requirementJsonMap.containsKey(TypeUtils.ToscaTagNamesEnum.NODE.getElementName())) {
                 requirement.setNode((String) requirementJsonMap.get(TypeUtils.ToscaTagNamesEnum.NODE.getElementName()));
             }
-
             if (requirementJsonMap.containsKey(TypeUtils.ToscaTagNamesEnum.RELATIONSHIP.getElementName())) {
-                requirement.setRelationship(
-                    (String) requirementJsonMap.get(TypeUtils.ToscaTagNamesEnum.RELATIONSHIP.getElementName()));
+                requirement.setRelationship((String) requirementJsonMap.get(TypeUtils.ToscaTagNamesEnum.RELATIONSHIP.getElementName()));
             }
             if (requirementJsonMap.containsKey(TypeUtils.ToscaTagNamesEnum.OCCURRENCES.getElementName())) {
-                List<Object> occurrencesList = (List) requirementJsonMap
-                    .get(TypeUtils.ToscaTagNamesEnum.OCCURRENCES.getElementName());
+                List<Object> occurrencesList = (List) requirementJsonMap.get(TypeUtils.ToscaTagNamesEnum.OCCURRENCES.getElementName());
                 validateOccurrences(occurrencesList);
                 requirement.setMinOccurrences(occurrencesList.get(0).toString());
                 requirement.setMaxOccurrences(occurrencesList.get(1).toString());
@@ -498,8 +432,7 @@ public class ResourceImportManager {
     private void setProperties(Map<String, Object> toscaJson, Resource resource) {
         Map<String, Object> reducedToscaJson = new HashMap<>(toscaJson);
         ImportUtils.removeElementFromJsonMap(reducedToscaJson, "capabilities");
-        Either<Map<String, PropertyDefinition>, ResultStatusEnum> properties = ImportUtils
-            .getProperties(reducedToscaJson);
+        Either<Map<String, PropertyDefinition>, ResultStatusEnum> properties = ImportUtils.getProperties(reducedToscaJson);
         if (properties.isLeft()) {
             List<PropertyDefinition> propertiesList = new ArrayList<>();
             Map<String, PropertyDefinition> value = properties.left().value();
@@ -507,11 +440,9 @@ public class ResourceImportManager {
                 for (Entry<String, PropertyDefinition> entry : value.entrySet()) {
                     String name = entry.getKey();
                     if (!PROPERTY_NAME_PATTERN_IGNORE_LENGTH.matcher(name).matches()) {
-                        log.debug("The property with invalid name {} occured upon import resource {}. ", name,
-                            resource.getName());
-                        throw new ByActionStatusComponentException(componentsUtils
-                            .convertFromResultStatusEnum(ResultStatusEnum.INVALID_PROPERTY_NAME,
-                                JsonPresentationFields.PROPERTY));
+                        log.debug("The property with invalid name {} occured upon import resource {}. ", name, resource.getName());
+                        throw new ByActionStatusComponentException(
+                            componentsUtils.convertFromResultStatusEnum(ResultStatusEnum.INVALID_PROPERTY_NAME, JsonPresentationFields.PROPERTY));
                     }
                     PropertyDefinition propertyDefinition = entry.getValue();
                     propertyDefinition.setName(name);
@@ -520,27 +451,22 @@ public class ResourceImportManager {
             }
             resource.setProperties(propertiesList);
         } else if (properties.right().value() != ResultStatusEnum.ELEMENT_NOT_FOUND) {
-            throw new ByActionStatusComponentException(componentsUtils.convertFromResultStatusEnum(properties
-                .right()
-                .value(), JsonPresentationFields.PROPERTY));
+            throw new ByActionStatusComponentException(
+                componentsUtils.convertFromResultStatusEnum(properties.right().value(), JsonPresentationFields.PROPERTY));
         }
     }
 
     private void setAttributes(final Map<String, Object> originalToscaJsonMap, final Resource resource) {
         final Map<String, Object> toscaJsonMap = new HashMap<>(originalToscaJsonMap);
         ImportUtils.removeElementFromJsonMap(toscaJsonMap, "capabilities");
-        final Either<Map<String, AttributeDefinition>, ResultStatusEnum> getAttributeEither = ImportUtils
-            .getAttributes(toscaJsonMap);
-
+        final Either<Map<String, AttributeDefinition>, ResultStatusEnum> getAttributeEither = ImportUtils.getAttributes(toscaJsonMap);
         if (getAttributeEither.isRight()) {
             final ResultStatusEnum resultStatus = getAttributeEither.right().value();
             if (resultStatus == ResultStatusEnum.ELEMENT_NOT_FOUND) {
                 return;
             }
-            throw new ByActionStatusComponentException(
-                componentsUtils.convertFromResultStatusEnum(resultStatus, JsonPresentationFields.ATTRIBUTES));
+            throw new ByActionStatusComponentException(componentsUtils.convertFromResultStatusEnum(resultStatus, JsonPresentationFields.ATTRIBUTES));
         }
-
         final List<AttributeDefinition> attributeDefinitionList = new ArrayList<>();
         final Map<String, AttributeDefinition> attributeMap = getAttributeEither.left().value();
         if (MapUtils.isEmpty(attributeMap)) {
@@ -549,11 +475,9 @@ public class ResourceImportManager {
         for (final Entry<String, AttributeDefinition> entry : attributeMap.entrySet()) {
             final String name = entry.getKey();
             if (!PROPERTY_NAME_PATTERN_IGNORE_LENGTH.matcher(name).matches()) {
-                log.debug("Detected attribute with invalid name '{}' during resource '{}' import. ",
-                    name, resource.getName());
-                throw new ByActionStatusComponentException(componentsUtils
-                    .convertFromResultStatusEnum(ResultStatusEnum.INVALID_ATTRIBUTE_NAME,
-                        JsonPresentationFields.ATTRIBUTES));
+                log.debug("Detected attribute with invalid name '{}' during resource '{}' import. ", name, resource.getName());
+                throw new ByActionStatusComponentException(
+                    componentsUtils.convertFromResultStatusEnum(ResultStatusEnum.INVALID_ATTRIBUTE_NAME, JsonPresentationFields.ATTRIBUTES));
             }
             final AttributeDefinition attributeDefinition = entry.getValue();
             attributeDefinition.setName(name);
@@ -570,9 +494,7 @@ public class ResourceImportManager {
             String derivedFrom = toscaDerivedFromElement.left().value();
             log.debug("Derived from TOSCA name is {}", derivedFrom);
             resource.setDerivedFrom(Arrays.asList(new String[]{derivedFrom}));
-            Either<Resource, StorageOperationStatus> latestByToscaResourceName = toscaOperationFacade
-                .getLatestByToscaResourceName(derivedFrom);
-
+            Either<Resource, StorageOperationStatus> latestByToscaResourceName = toscaOperationFacade.getLatestByToscaResourceName(derivedFrom);
             if (latestByToscaResourceName.isRight()) {
                 StorageOperationStatus operationStatus = latestByToscaResourceName.right().value();
                 if (operationStatus == StorageOperationStatus.NOT_FOUND) {
@@ -580,8 +502,7 @@ public class ResourceImportManager {
                 }
                 log.debug("Error when fetching parent resource {}, error: {}", derivedFrom, operationStatus);
                 ActionStatus convertFromStorageResponse = componentsUtils.convertFromStorageResponse(operationStatus);
-                BeEcompErrorManager.getInstance()
-                    .logBeComponentMissingError("Import TOSCA YAML", "resource", derivedFrom);
+                BeEcompErrorManager.getInstance().logBeComponentMissingError("Import TOSCA YAML", "resource", derivedFrom);
                 throw new ByActionStatusComponentException(convertFromStorageResponse, derivedFrom);
             }
             derivedFromResource = latestByToscaResourceName.left().value();
@@ -599,24 +520,19 @@ public class ResourceImportManager {
             Iterator<Entry<String, Object>> capabilitiesNameValue = jsonCapabilities.entrySet().iterator();
             Set<String> capNames = new HashSet<>();
             // Getting flattened list of capabilities of parent node - cap name
+
             // to cap type
             Map<String, String> capName2TypeMap = getCapName2Type(parentResource);
             while (capabilitiesNameValue.hasNext()) {
                 Entry<String, Object> capabilityNameValue = capabilitiesNameValue.next();
-
                 // Validating that no req/cap duplicates exist in imported YAML
                 String capNameLowerCase = capabilityNameValue.getKey().toLowerCase();
                 if (capNames.contains(capNameLowerCase)) {
-                    log.debug(
-                        "More than one capability with same name {} (case-insensitive) in imported TOSCA file is invalid",
-                        capNameLowerCase);
-                    throw new ByActionStatusComponentException(ActionStatus.IMPORT_DUPLICATE_REQ_CAP_NAME, "capability",
-                        capNameLowerCase);
+                    log.debug("More than one capability with same name {} (case-insensitive) in imported TOSCA file is invalid", capNameLowerCase);
+                    throw new ByActionStatusComponentException(ActionStatus.IMPORT_DUPLICATE_REQ_CAP_NAME, "capability", capNameLowerCase);
                 }
                 capNames.add(capNameLowerCase);
-
-                CapabilityDefinition capabilityDef = createCapabilityFromImportFile(capabilityNameValue
-                    .getValue());
+                CapabilityDefinition capabilityDef = createCapabilityFromImportFile(capabilityNameValue.getValue());
                 capabilityDef.setName(capabilityNameValue.getKey());
                 if (moduleCapabilities.containsKey(capabilityDef.getType())) {
                     moduleCapabilities.get(capabilityDef.getType()).add(capabilityDef);
@@ -625,22 +541,18 @@ public class ResourceImportManager {
                     list.add(capabilityDef);
                     moduleCapabilities.put(capabilityDef.getType(), list);
                 }
-
                 // Validating against req/cap of "derived from" node
-                Boolean validateVsParentCap = validateCapNameVsDerived(capName2TypeMap, capabilityDef
-                    .getType(), capabilityDef.getName());
-
+                Boolean validateVsParentCap = validateCapNameVsDerived(capName2TypeMap, capabilityDef.getType(), capabilityDef.getName());
                 if (!validateVsParentCap) {
                     // Here parentResource is for sure not null, so it's
+
                     // null-safe
+
                     // Check added to avoid sonar warning
                     String parentResourceName = parentResource != null ? parentResource.getName() : "";
-                    log.debug("Capability with name {} already exists in parent {}", capabilityDef.getName(),
-                        parentResourceName);
-                    throw new ByActionStatusComponentException(ActionStatus.IMPORT_REQ_CAP_NAME_EXISTS_IN_DERIVED,
-                        "capability", capabilityDef
-                        .getName()
-                        .toLowerCase(), parentResourceName);
+                    log.debug("Capability with name {} already exists in parent {}", capabilityDef.getName(), parentResourceName);
+                    throw new ByActionStatusComponentException(ActionStatus.IMPORT_REQ_CAP_NAME_EXISTS_IN_DERIVED, "capability",
+                        capabilityDef.getName().toLowerCase(), parentResourceName);
                 }
             }
             if (moduleCapabilities.size() > 0) {
@@ -659,12 +571,11 @@ public class ResourceImportManager {
                         String nameLowerCase = capDefinition.getName().toLowerCase();
                         if (capName2type.get(nameLowerCase) != null) {
                             String parentResourceName = parentResource.getName();
-                            log.debug("Resource with name {} has more than one capability with name {}, ignoring case",
-                                parentResourceName, nameLowerCase);
-                            BeEcompErrorManager.getInstance()
-                                .logInternalDataError("Import resource", "Parent resource " + parentResourceName
-                                        + " of imported resource has one or more capabilities with name " + nameLowerCase,
-                                    ErrorSeverity.ERROR);
+                            log.debug("Resource with name {} has more than one capability with name {}, ignoring case", parentResourceName,
+                                nameLowerCase);
+                            BeEcompErrorManager.getInstance().logInternalDataError("Import resource",
+                                "Parent resource " + parentResourceName + " of imported resource has one or more capabilities with name "
+                                    + nameLowerCase, ErrorSeverity.ERROR);
                             throw new ByActionStatusComponentException(ActionStatus.GENERAL_ERROR);
                         }
                         capName2type.put(nameLowerCase, capDefinition.getType());
@@ -685,12 +596,11 @@ public class ResourceImportManager {
                         String nameLowerCase = reqDefinition.getName().toLowerCase();
                         if (reqName2type.get(nameLowerCase) != null) {
                             String parentResourceName = parentResource.getName();
-                            log.debug("Resource with name {} has more than one requirement with name {}, ignoring case",
-                                parentResourceName, nameLowerCase);
-                            BeEcompErrorManager.getInstance()
-                                .logInternalDataError("Import resource", "Parent resource " + parentResourceName
-                                        + " of imported resource has one or more requirements with name " + nameLowerCase,
-                                    ErrorSeverity.ERROR);
+                            log.debug("Resource with name {} has more than one requirement with name {}, ignoring case", parentResourceName,
+                                nameLowerCase);
+                            BeEcompErrorManager.getInstance().logInternalDataError("Import resource",
+                                "Parent resource " + parentResourceName + " of imported resource has one or more requirements with name "
+                                    + nameLowerCase, ErrorSeverity.ERROR);
                             throw new ByActionStatusComponentException(ActionStatus.GENERAL_ERROR);
                         }
                         reqName2type.put(nameLowerCase, reqDefinition.getCapability());
@@ -701,26 +611,21 @@ public class ResourceImportManager {
         return reqName2type;
     }
 
-    private Boolean validateCapNameVsDerived(Map<String, String> parentCapName2Type, String childCapabilityType,
-                                             String reqCapName) {
+    private Boolean validateCapNameVsDerived(Map<String, String> parentCapName2Type, String childCapabilityType, String reqCapName) {
         String capNameLowerCase = reqCapName.toLowerCase();
         log.trace("Validating capability {} vs parent resource", capNameLowerCase);
         String parentCapType = parentCapName2Type.get(capNameLowerCase);
         if (parentCapType != null) {
             if (childCapabilityType.equals(parentCapType)) {
-                log.debug(
-                    "Capability with name {} is of same type {} for imported resource and its parent - this is OK",
-                    capNameLowerCase, childCapabilityType);
+                log.debug("Capability with name {} is of same type {} for imported resource and its parent - this is OK", capNameLowerCase,
+                    childCapabilityType);
                 return true;
             }
             Either<Boolean, StorageOperationStatus> capabilityTypeDerivedFrom = capabilityTypeOperation
                 .isCapabilityTypeDerivedFrom(childCapabilityType, parentCapType);
             if (capabilityTypeDerivedFrom.isRight()) {
                 log.debug("Couldn't check whether imported resource capability derives from its parent's capability");
-                throw new ByActionStatusComponentException(
-                    componentsUtils.convertFromStorageResponse(capabilityTypeDerivedFrom
-                        .right()
-                        .value()));
+                throw new ByActionStatusComponentException(componentsUtils.convertFromStorageResponse(capabilityTypeDerivedFrom.right().value()));
             }
             return capabilityTypeDerivedFrom.left().value();
         }
@@ -728,9 +633,7 @@ public class ResourceImportManager {
     }
 
     private CapabilityDefinition createCapabilityFromImportFile(Object capabilityJson) {
-
         CapabilityDefinition capabilityDefinition = new CapabilityDefinition();
-
         if (capabilityJson instanceof String) {
             String capabilityJsonString = (String) capabilityJson;
             capabilityDefinition.setType(capabilityJsonString);
@@ -738,66 +641,48 @@ public class ResourceImportManager {
             Map<String, Object> capabilityJsonMap = (Map<String, Object>) capabilityJson;
             // Type
             if (capabilityJsonMap.containsKey(TypeUtils.ToscaTagNamesEnum.TYPE.getElementName())) {
-                capabilityDefinition
-                    .setType((String) capabilityJsonMap.get(TypeUtils.ToscaTagNamesEnum.TYPE.getElementName()));
+                capabilityDefinition.setType((String) capabilityJsonMap.get(TypeUtils.ToscaTagNamesEnum.TYPE.getElementName()));
             }
             // ValidSourceTypes
             if (capabilityJsonMap.containsKey(TypeUtils.ToscaTagNamesEnum.VALID_SOURCE_TYPES.getElementName())) {
-                capabilityDefinition.setValidSourceTypes(
-                    (List<String>) capabilityJsonMap.get(TypeUtils.ToscaTagNamesEnum.VALID_SOURCE_TYPES
-                        .getElementName()));
+                capabilityDefinition
+                    .setValidSourceTypes((List<String>) capabilityJsonMap.get(TypeUtils.ToscaTagNamesEnum.VALID_SOURCE_TYPES.getElementName()));
             }
             // ValidSourceTypes
             if (capabilityJsonMap.containsKey(TypeUtils.ToscaTagNamesEnum.DESCRIPTION.getElementName())) {
-                capabilityDefinition.setDescription(
-                    (String) capabilityJsonMap.get(TypeUtils.ToscaTagNamesEnum.DESCRIPTION.getElementName()));
+                capabilityDefinition.setDescription((String) capabilityJsonMap.get(TypeUtils.ToscaTagNamesEnum.DESCRIPTION.getElementName()));
             }
             if (capabilityJsonMap.containsKey(TypeUtils.ToscaTagNamesEnum.OCCURRENCES.getElementName())) {
-                List<Object> occurrencesList = (List) capabilityJsonMap
-                    .get(TypeUtils.ToscaTagNamesEnum.OCCURRENCES.getElementName());
+                List<Object> occurrencesList = (List) capabilityJsonMap.get(TypeUtils.ToscaTagNamesEnum.OCCURRENCES.getElementName());
                 validateOccurrences(occurrencesList);
                 capabilityDefinition.setMinOccurrences(occurrencesList.get(0).toString());
                 capabilityDefinition.setMaxOccurrences(occurrencesList.get(1).toString());
             }
             if (capabilityJsonMap.containsKey(TypeUtils.ToscaTagNamesEnum.PROPERTIES.getElementName())) {
-
-                Either<Map<String, PropertyDefinition>, ResultStatusEnum> propertiesRes = ImportUtils
-                    .getProperties(capabilityJsonMap);
+                Either<Map<String, PropertyDefinition>, ResultStatusEnum> propertiesRes = ImportUtils.getProperties(capabilityJsonMap);
                 if (propertiesRes.isRight()) {
                     throw new ByActionStatusComponentException(ActionStatus.PROPERTY_NOT_FOUND);
                 } else {
-                    propertiesRes.left()
-                        .value()
-                        .entrySet()
-                        .stream()
-                        .forEach(e -> e.getValue().setName(e.getKey().toLowerCase()));
-                    List<ComponentInstanceProperty> capabilityProperties = propertiesRes.left()
-                        .value()
-                        .values()
-                        .stream()
-                        .map(p -> new ComponentInstanceProperty(p, p
-                            .getDefaultValue(), null))
-                        .collect(Collectors.toList());
+                    propertiesRes.left().value().entrySet().stream().forEach(e -> e.getValue().setName(e.getKey().toLowerCase()));
+                    List<ComponentInstanceProperty> capabilityProperties = propertiesRes.left().value().values().stream()
+                        .map(p -> new ComponentInstanceProperty(p, p.getDefaultValue(), null)).collect(Collectors.toList());
                     capabilityDefinition.setProperties(capabilityProperties);
                 }
             }
-
         } else if (!(capabilityJson instanceof List)) {
             throw new ByActionStatusComponentException(ActionStatus.INVALID_YAML);
         }
         return capabilityDefinition;
     }
 
-    private void handleImportResourceException(UploadResourceInfo resourceMetaData, User user, boolean isNormative,
-                                               RuntimeException e) {
+    private void handleImportResourceException(UploadResourceInfo resourceMetaData, User user, boolean isNormative, RuntimeException e) {
         ResponseFormat responseFormat;
         ComponentException newException;
         if (e instanceof ComponentException) {
             ComponentException componentException = (ComponentException) e;
             responseFormat = componentException.getResponseFormat();
             if (responseFormat == null) {
-                responseFormat = getResponseFormatManager()
-                    .getResponseFormat(componentException.getActionStatus(), componentException.getParams());
+                responseFormat = getResponseFormatManager().getResponseFormat(componentException.getActionStatus(), componentException.getParams());
             }
             newException = componentException;
         } else {
@@ -811,8 +696,7 @@ public class ResourceImportManager {
         throw newException;
     }
 
-    private void auditErrorImport(UploadResourceInfo resourceMetaData, User user, ResponseFormat errorResponseWrapper,
-                                  boolean isNormative) {
+    private void auditErrorImport(UploadResourceInfo resourceMetaData, User user, ResponseFormat errorResponseWrapper, boolean isNormative) {
         String version, lifeCycleState;
         if (isNormative) {
             version = TypeUtils.getFirstCertifiedVersionVersion();
@@ -820,44 +704,27 @@ public class ResourceImportManager {
         } else {
             version = "";
             lifeCycleState = LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT.name();
-
         }
-
         String message = "";
         if (errorResponseWrapper.getMessageId() != null) {
             message = errorResponseWrapper.getMessageId() + ": ";
         }
         message += errorResponseWrapper.getFormattedMessage();
-
         AuditEventFactory factory = new AuditImportResourceAdminEventFactory(
-            CommonAuditData.newBuilder()
-                .status(errorResponseWrapper.getStatus())
-                .description(message)
-                .requestId(ThreadLocalsHolder.getUuid())
-                .build(),
-            new ResourceCommonInfo(resourceMetaData.getName(), ComponentTypeEnum.RESOURCE.getValue()),
-            ResourceVersionInfo.newBuilder()
-                .state(lifeCycleState)
-                .version(version)
-                .build(),
-            ResourceVersionInfo.newBuilder()
-                .state("")
-                .version("")
-                .build(),
-            "", user, "");
+            CommonAuditData.newBuilder().status(errorResponseWrapper.getStatus()).description(message).requestId(ThreadLocalsHolder.getUuid())
+                .build(), new ResourceCommonInfo(resourceMetaData.getName(), ComponentTypeEnum.RESOURCE.getValue()),
+            ResourceVersionInfo.newBuilder().state(lifeCycleState).version(version).build(),
+            ResourceVersionInfo.newBuilder().state("").version("").build(), "", user, "");
         getAuditingManager().auditEvent(factory);
-
     }
 
     private void setMetaDataFromJson(final UploadResourceInfo resourceMetaData, final Resource resource) {
         this.populateResourceMetadata(resourceMetaData, resource);
         resource.setCreatorUserId(resourceMetaData.getContactId());
-
         final String payloadData = resourceMetaData.getPayloadData();
         if (payloadData != null) {
             resource.setToscaVersion(getToscaVersion(payloadData));
         }
-
         final List<CategoryDefinition> categories = resourceMetaData.getCategories();
         calculateResourceIsAbstract(resource, categories);
     }
@@ -869,8 +736,8 @@ public class ResourceImportManager {
 
     private String getToscaVersion(final String payloadData) {
         final Map<String, Object> mappedToscaTemplate = decodePayload(payloadData);
-        final Either<String, ResultStatusEnum> findFirstToscaStringElement =
-            ImportUtils.findFirstToscaStringElement(mappedToscaTemplate, TypeUtils.ToscaTagNamesEnum.TOSCA_VERSION);
+        final Either<String, ResultStatusEnum> findFirstToscaStringElement = ImportUtils
+            .findFirstToscaStringElement(mappedToscaTemplate, TypeUtils.ToscaTagNamesEnum.TOSCA_VERSION);
         if (findFirstToscaStringElement.isLeft()) {
             return findFirstToscaStringElement.left().value();
         } else {
@@ -882,8 +749,7 @@ public class ResourceImportManager {
         if (categories != null && !categories.isEmpty()) {
             CategoryDefinition categoryDef = categories.get(0);
             resource.setAbstract(false);
-            if (categoryDef != null && categoryDef.getName() != null && categoryDef.getName()
-                .equals(Constants.ABSTRACT_CATEGORY_NAME)) {
+            if (categoryDef != null && categoryDef.getName() != null && categoryDef.getName().equals(Constants.ABSTRACT_CATEGORY_NAME)) {
                 SubCategoryDefinition subCategoryDef = categoryDef.getSubcategories().get(0);
                 if (subCategoryDef != null && subCategoryDef.getName().equals(Constants.ABSTRACT_SUBCATEGORY)) {
                     resource.setAbstract(true);
@@ -907,16 +773,13 @@ public class ResourceImportManager {
         resource.setHighestVersion(ImportUtils.Constants.NORMATIVE_TYPE_HIGHEST_VERSION);
         resource.setVendorName(ImportUtils.Constants.VENDOR_NAME);
         resource.setVendorRelease(ImportUtils.Constants.VENDOR_RELEASE);
-
     }
 
     private void validateOccurrences(List<Object> occurrensesList) {
-
         if (!ValidationUtils.validateListNotEmpty(occurrensesList)) {
             log.debug("Occurrenses list empty");
             throw new ByActionStatusComponentException(ActionStatus.INVALID_OCCURRENCES);
         }
-
         if (occurrensesList.size() < 2) {
             log.debug("Occurrenses list size not 2");
             throw new ByActionStatusComponentException(ActionStatus.INVALID_OCCURRENCES);
@@ -935,7 +798,6 @@ public class ResourceImportManager {
             log.debug("Invalid occurrenses format.low_bound occurrense negative {}", minOccurrences);
             throw new ByActionStatusComponentException(ActionStatus.INVALID_OCCURRENCES);
         }
-
         if (maxObj instanceof String) {
             if (!"UNBOUNDED".equals(maxObj)) {
                 log.debug("Invalid occurrenses format. Max occurrence is {}", maxObj);
@@ -948,10 +810,8 @@ public class ResourceImportManager {
                 log.debug("Invalid occurrenses format.  Max occurrence is {}", maxObj);
                 throw new ByActionStatusComponentException(ActionStatus.INVALID_OCCURRENCES);
             }
-
             if (maxOccurrences <= 0 || maxOccurrences < minOccurrences) {
-                log.debug("Invalid occurrenses format.  min occurrence is {}, Max occurrence is {}", minOccurrences,
-                    maxOccurrences);
+                log.debug("Invalid occurrenses format.  min occurrence is {}, Max occurrence is {}", minOccurrences, maxOccurrences);
                 throw new ByActionStatusComponentException(ActionStatus.INVALID_OCCURRENCES);
             }
         }
@@ -980,10 +840,19 @@ public class ResourceImportManager {
         return servletContext;
     }
 
+    public void setServletContext(ServletContext servletContext) {
+        this.servletContext = servletContext;
+    }
+
     public AuditingManager getAuditingManager() {
         return auditingManager;
     }
 
+    @Autowired
+    public void setAuditingManager(AuditingManager auditingManager) {
+        this.auditingManager = auditingManager;
+    }
+
     public ResponseFormatManager getResponseFormatManager() {
         return responseFormatManager;
     }
@@ -1010,31 +879,19 @@ public class ResourceImportManager {
         this.graphLockOperation = graphLockOperation;
     }
 
-    public void setServletContext(ServletContext servletContext) {
-        this.servletContext = servletContext;
-    }
-
-    @Autowired
-    public void setAuditingManager(AuditingManager auditingManager) {
-        this.auditingManager = auditingManager;
-    }
-
     private List<DataTypeDefinition> extractDataTypeFromJson(final ResourceBusinessLogic resourceBusinessLogic,
                                                              final Map<String, Object> foundElements) {
         final List<DataTypeDefinition> dataTypeDefinitionList = new ArrayList<>();
         if (MapUtils.isNotEmpty(foundElements)) {
-            final Either<Map<String, DataTypeDefinition>, JanusGraphOperationStatus> dataTypeCacheAll =
-                resourceBusinessLogic.dataTypeCache.getAll();
+            final Either<Map<String, DataTypeDefinition>, JanusGraphOperationStatus> dataTypeCacheAll = resourceBusinessLogic.dataTypeCache.getAll();
             if (dataTypeCacheAll.isLeft()) {
                 for (final Entry<String, Object> attributeNameValue : foundElements.entrySet()) {
                     final Object value = attributeNameValue.getValue();
                     if (value instanceof Map) {
-                        final DataTypeDefinition dataTypeDefinition =
-                            createDataTypeDefinitionWithName(attributeNameValue);
-                        final DataTypeDefinition dataTypeDefinitionParent =
-                            dataTypeCacheAll.left().value().get(dataTypeDefinition.getDerivedFromName());
+                        final DataTypeDefinition dataTypeDefinition = createDataTypeDefinitionWithName(attributeNameValue);
+                        final DataTypeDefinition dataTypeDefinitionParent = dataTypeCacheAll.left().value()
+                            .get(dataTypeDefinition.getDerivedFromName());
                         dataTypeDefinition.setDerivedFrom(dataTypeDefinitionParent);
-
                         dataTypeDefinitionList.add(dataTypeDefinition);
                     } else {
                         dataTypeDefinitionList.add(createDataType(String.valueOf(value)));
index 2cb03fe..875bcb2 100644 (file)
@@ -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.
@@ -17,7 +17,6 @@
  * limitations under the License.
  * ============LICENSE_END=========================================================
  */
-
 package org.openecomp.sdc.be.components.impl;
 
 import org.openecomp.sdc.be.config.ConfigurationManager;
@@ -33,9 +32,9 @@ import org.openecomp.sdc.exception.ServiceException;
 
 public class ResponseFormatManager {
 
+    private static final Logger log = Logger.getLogger(ResponseFormatManager.class);
     private volatile static ResponseFormatManager instance;
     private static ConfigurationManager configurationManager;
-    private static final Logger log = Logger.getLogger(ResponseFormatManager.class);
 
     public static ResponseFormatManager getInstance() {
         if (instance == null) {
index ad1f818..a87fdb6 100644 (file)
@@ -19,7 +19,6 @@
  * Modifications copyright (c) 2019 Nokia
  * ================================================================================
  */
-
 package org.openecomp.sdc.be.components.impl;
 
 import static org.apache.commons.collections.CollectionUtils.isNotEmpty;
@@ -165,10 +164,10 @@ import org.springframework.beans.factory.annotation.Autowired;
 import org.springframework.http.HttpStatus;
 import org.springframework.web.context.WebApplicationContext;
 
-
 @org.springframework.stereotype.Component("serviceBusinessLogic")
 public class ServiceBusinessLogic extends ComponentBusinessLogic {
 
+    static final String IS_VALID = "isValid";
     private static final String THE_SERVICE_WITH_SYSTEM_NAME_LOCKED = "The service with system name {} locked. ";
     private static final String FAILED_TO_LOCK_SERVICE_RESPONSE_IS = "Failed to lock service {}. Response is {}. ";
     private static final String AUDIT_BEFORE_SENDING_RESPONSE = "audit before sending response";
@@ -176,71 +175,40 @@ public class ServiceBusinessLogic extends ComponentBusinessLogic {
     private static final String INITIAL_VERSION = "0.1";
     private static final String STATUS_SUCCESS_200 = "200";
     private static final String STATUS_DEPLOYED = "DEPLOYED";
-    static final String IS_VALID = "isValid";
     private static final String PLACE_HOLDER_RESOURCE_TYPES = "validForResourceTypes";
-
-    private ForwardingPathOperation forwardingPathOperation;
-    private AuditCassandraDao auditCassandraDao;
-
     private final IDistributionEngine distributionEngine;
     private final ComponentInstanceBusinessLogic componentInstanceBusinessLogic;
     private final ServiceDistributionValidation serviceDistributionValidation;
     private final ForwardingPathValidator forwardingPathValidator;
     private final UiComponentDataConverter uiComponentDataConverter;
-
+    private ForwardingPathOperation forwardingPathOperation;
+    private AuditCassandraDao auditCassandraDao;
     private ServiceTypeValidator serviceTypeValidator;
     private List<ServiceCreationPlugin> serviceCreationPluginList;
-
-    @Autowired
-    public void setServiceTypeValidator(ServiceTypeValidator serviceTypeValidator) {
-        this.serviceTypeValidator = serviceTypeValidator;
-    }
-
-
     private ServiceFunctionValidator serviceFunctionValidator;
-
-    @Autowired
-    public void setServiceFunctionValidator(ServiceFunctionValidator serviceFunctionValidator) {
-        this.serviceFunctionValidator = serviceFunctionValidator;
-    }
-
     @Autowired
     private ServiceRoleValidator serviceRoleValidator;
-
     @Autowired
     private ServiceInstantiationTypeValidator serviceInstantiationTypeValidator;
-
     @Autowired
     private ServiceCategoryValidator serviceCategoryValidator;
-
     @Autowired
     private ServiceValidator serviceValidator;
 
-
     @Autowired
-    public ServiceBusinessLogic(IElementOperation elementDao,
-                                IGroupOperation groupOperation,
-                                IGroupInstanceOperation groupInstanceOperation,
-                                IGroupTypeOperation groupTypeOperation,
-                                GroupBusinessLogic groupBusinessLogic,
-                                InterfaceOperation interfaceOperation,
-                                InterfaceLifecycleOperation interfaceLifecycleTypeOperation,
-                                ArtifactsBusinessLogic artifactsBusinessLogic,
+    public ServiceBusinessLogic(IElementOperation elementDao, IGroupOperation groupOperation, IGroupInstanceOperation groupInstanceOperation,
+                                IGroupTypeOperation groupTypeOperation, GroupBusinessLogic groupBusinessLogic, InterfaceOperation interfaceOperation,
+                                InterfaceLifecycleOperation interfaceLifecycleTypeOperation, ArtifactsBusinessLogic artifactsBusinessLogic,
                                 IDistributionEngine distributionEngine, ComponentInstanceBusinessLogic componentInstanceBusinessLogic,
                                 ServiceDistributionValidation serviceDistributionValidation, ForwardingPathValidator forwardingPathValidator,
-                                UiComponentDataConverter uiComponentDataConverter,
-                                ArtifactsOperations artifactToscaOperation,
-                                ComponentContactIdValidator componentContactIdValidator,
-                                ComponentNameValidator componentNameValidator,
-                                ComponentTagsValidator componentTagsValidator,
-                                ComponentValidator componentValidator,
-                                ComponentIconValidator componentIconValidator,
-                                ComponentProjectCodeValidator componentProjectCodeValidator,
+                                UiComponentDataConverter uiComponentDataConverter, ArtifactsOperations artifactToscaOperation,
+                                ComponentContactIdValidator componentContactIdValidator, ComponentNameValidator componentNameValidator,
+                                ComponentTagsValidator componentTagsValidator, ComponentValidator componentValidator,
+                                ComponentIconValidator componentIconValidator, ComponentProjectCodeValidator componentProjectCodeValidator,
                                 ComponentDescriptionValidator componentDescriptionValidator) {
-        super(elementDao, groupOperation, groupInstanceOperation, groupTypeOperation, groupBusinessLogic,
-            interfaceOperation, interfaceLifecycleTypeOperation, artifactsBusinessLogic, artifactToscaOperation, componentContactIdValidator,
-                componentNameValidator, componentTagsValidator, componentValidator,
-                componentIconValidator, componentProjectCodeValidator, componentDescriptionValidator);
+        super(elementDao, groupOperation, groupInstanceOperation, groupTypeOperation, groupBusinessLogic, interfaceOperation,
+            interfaceLifecycleTypeOperation, artifactsBusinessLogic, artifactToscaOperation, componentContactIdValidator, componentNameValidator,
+            componentTagsValidator, componentValidator, componentIconValidator, componentProjectCodeValidator, componentDescriptionValidator);
         this.distributionEngine = distributionEngine;
         this.componentInstanceBusinessLogic = componentInstanceBusinessLogic;
         this.serviceDistributionValidation = serviceDistributionValidation;
@@ -248,12 +216,20 @@ public class ServiceBusinessLogic extends ComponentBusinessLogic {
         this.uiComponentDataConverter = uiComponentDataConverter;
     }
 
+    @Autowired
+    public void setServiceTypeValidator(ServiceTypeValidator serviceTypeValidator) {
+        this.serviceTypeValidator = serviceTypeValidator;
+    }
+
+    @Autowired
+    public void setServiceFunctionValidator(ServiceFunctionValidator serviceFunctionValidator) {
+        this.serviceFunctionValidator = serviceFunctionValidator;
+    }
 
     public Either<List<Map<String, Object>>, ResponseFormat> getComponentAuditRecords(String componentVersion, String componentUUID, String userId) {
         validateUserExists(userId);
         Either<List<Map<String, Object>>, ActionStatus> result;
         try {
-
             // Certified Version
             if (componentVersion.endsWith(".0")) {
                 Either<List<ResourceAdminEvent>, ActionStatus> eitherAuditingForCertified = auditCassandraDao.getByServiceInstanceId(componentUUID);
@@ -271,229 +247,154 @@ public class ServiceBusinessLogic extends ComponentBusinessLogic {
             log.debug("get Audit Records failed with exception {}", e);
             result = Either.right(ActionStatus.GENERAL_ERROR);
         }
-
         if (result.isRight()) {
             return Either.right(componentsUtils.getResponseFormat(result.right().value()));
         } else {
             return Either.left(result.left().value());
         }
-
     }
 
-    public Either<List<Operation>, ResponseFormat> addServiceConsumptionData(String serviceId,
-                                                                             String serviceInstanceId,
-                                                                             String operationId,
-                                                                             List<ServiceConsumptionData> serviceConsumptionDataList,
-                                                                             String userId) {
+    public Either<List<Operation>, ResponseFormat> addServiceConsumptionData(String serviceId, String serviceInstanceId, String operationId,
+                                                                             List<ServiceConsumptionData> serviceConsumptionDataList, String userId) {
         List<Operation> operationList = new ArrayList<>();
-
-        Either<Service, StorageOperationStatus> serviceEither =
-                toscaOperationFacade.getToscaElement(serviceId);
-        if(serviceEither.isRight()) {
-            return Either.right(componentsUtils.getResponseFormat
-                    (serviceEither.right().value()));
+        Either<Service, StorageOperationStatus> serviceEither = toscaOperationFacade.getToscaElement(serviceId);
+        if (serviceEither.isRight()) {
+            return Either.right(componentsUtils.getResponseFormat(serviceEither.right().value()));
         }
-
         Service service = serviceEither.left().value();
-
-
-        StorageOperationStatus storageOperationStatus =
-                graphLockOperation.lockComponent(service.getUniqueId(), NodeTypeEnum.Service);
+        StorageOperationStatus storageOperationStatus = graphLockOperation.lockComponent(service.getUniqueId(), NodeTypeEnum.Service);
         if (storageOperationStatus != StorageOperationStatus.OK) {
             return Either.right(componentsUtils.getResponseFormat(storageOperationStatus));
         }
-
         try {
             for (ServiceConsumptionData serviceConsumptionData : serviceConsumptionDataList) {
-                Either<Operation, ResponseFormat> operationEither =
-                        addPropertyServiceConsumption(serviceId, serviceInstanceId, operationId,
-                                userId, serviceConsumptionData);
-
+                Either<Operation, ResponseFormat> operationEither = addPropertyServiceConsumption(serviceId, serviceInstanceId, operationId, userId,
+                    serviceConsumptionData);
                 if (operationEither.isRight()) {
                     return Either.right(operationEither.right().value());
                 }
-
                 operationList.add(operationEither.left().value());
             }
-
             janusGraphDao.commit();
             return Either.left(operationList);
         } catch (Exception e) {
             janusGraphDao.rollback();
             return Either.right(componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR));
-
         } finally {
             graphLockOperation.unlockComponent(service.getUniqueId(), NodeTypeEnum.Service);
-
         }
     }
 
-    public Either <Operation, ResponseFormat> addPropertyServiceConsumption(String serviceId,
-                                                                            String serviceInstanceId,
-                                                                            String operationId,
-                                                                            String userId,
-                                                                            ServiceConsumptionData serviceConsumptionData) {
+    public Either<Operation, ResponseFormat> addPropertyServiceConsumption(String serviceId, String serviceInstanceId, String operationId,
+                                                                           String userId, ServiceConsumptionData serviceConsumptionData) {
         validateUserExists(userId);
-
-        Either<Service, StorageOperationStatus> serviceEither =
-                toscaOperationFacade.getToscaElement(serviceId);
-        if(serviceEither.isRight()) {
-            return Either.right(componentsUtils.getResponseFormat(serviceEither.right
-                    ().value()));
+        Either<Service, StorageOperationStatus> serviceEither = toscaOperationFacade.getToscaElement(serviceId);
+        if (serviceEither.isRight()) {
+            return Either.right(componentsUtils.getResponseFormat(serviceEither.right().value()));
         }
-
         Service parentService = serviceEither.left().value();
-
         List<ComponentInstance> componentInstances = parentService.getComponentInstances();
-        if(CollectionUtils.isEmpty(componentInstances)) {
-            return Either.right(componentsUtils.getResponseFormat(ActionStatus
-                    .INTERFACE_OPERATION_NOT_FOUND, serviceInstanceId));
+        if (CollectionUtils.isEmpty(componentInstances)) {
+            return Either.right(componentsUtils.getResponseFormat(ActionStatus.INTERFACE_OPERATION_NOT_FOUND, serviceInstanceId));
         }
-
-        Optional<ComponentInstance> serviceInstanceCandidate =
-                componentInstances.stream().filter(instance -> instance.getUniqueId().equals
-                        (serviceInstanceId)).findAny();
-
-        if(!serviceInstanceCandidate.isPresent()) {
-            return Either.right(componentsUtils.getResponseFormat(ActionStatus
-                    .INTERFACE_OPERATION_NOT_FOUND, serviceInstanceId));
+        Optional<ComponentInstance> serviceInstanceCandidate = componentInstances.stream()
+            .filter(instance -> instance.getUniqueId().equals(serviceInstanceId)).findAny();
+        if (!serviceInstanceCandidate.isPresent()) {
+            return Either.right(componentsUtils.getResponseFormat(ActionStatus.INTERFACE_OPERATION_NOT_FOUND, serviceInstanceId));
         }
-
-        Map<String, List<ComponentInstanceInterface>> componentInstancesInterfaces =
-                parentService.getComponentInstancesInterfaces();
-        if(MapUtils.isEmpty(componentInstancesInterfaces)) {
-            return Either.right(componentsUtils.getResponseFormat(ActionStatus
-                    .INTERFACE_OPERATION_NOT_FOUND, serviceInstanceId));
+        Map<String, List<ComponentInstanceInterface>> componentInstancesInterfaces = parentService.getComponentInstancesInterfaces();
+        if (MapUtils.isEmpty(componentInstancesInterfaces)) {
+            return Either.right(componentsUtils.getResponseFormat(ActionStatus.INTERFACE_OPERATION_NOT_FOUND, serviceInstanceId));
         }
-
         List<InterfaceDefinition> interfaces = new ArrayList<>();
-        for(ComponentInstanceInterface componentInstanceInterface :
-                componentInstancesInterfaces.get(serviceInstanceId)) {
+        for (ComponentInstanceInterface componentInstanceInterface : componentInstancesInterfaces.get(serviceInstanceId)) {
             interfaces.add(componentInstanceInterface);
         }
-
         ComponentInstance serviceInstance = serviceInstanceCandidate.get();
-        Optional<InterfaceDefinition> interfaceCandidate = InterfaceOperationUtils
-                .getInterfaceDefinitionFromOperationId(interfaces, operationId);
-
-        if(!interfaceCandidate.isPresent()) {
-            return Either.right(componentsUtils.getResponseFormat(ActionStatus
-                    .INTERFACE_OPERATION_NOT_FOUND, serviceInstanceId));
+        Optional<InterfaceDefinition> interfaceCandidate = InterfaceOperationUtils.getInterfaceDefinitionFromOperationId(interfaces, operationId);
+        if (!interfaceCandidate.isPresent()) {
+            return Either.right(componentsUtils.getResponseFormat(ActionStatus.INTERFACE_OPERATION_NOT_FOUND, serviceInstanceId));
         }
-
         InterfaceDefinition interfaceDefinition = interfaceCandidate.get();
         Map<String, Operation> operations = interfaceDefinition.getOperationsMap();
-        if(MapUtils.isEmpty(operations)) {
-            return Either.right(componentsUtils.getResponseFormat(ActionStatus
-                    .INTERFACE_OPERATION_NOT_FOUND, serviceInstanceId));
+        if (MapUtils.isEmpty(operations)) {
+            return Either.right(componentsUtils.getResponseFormat(ActionStatus.INTERFACE_OPERATION_NOT_FOUND, serviceInstanceId));
         }
-
         Operation operation = operations.get(operationId);
         Either<Operation, ResponseFormat> operationEither = Either.left(operation);
-
         ListDataDefinition<OperationInputDefinition> inputs = operation.getInputs();
-        Optional<OperationInputDefinition> inputCandidate =
-                getOperationInputByInputId(serviceConsumptionData, inputs);
-
-        if(!inputCandidate.isPresent()) {
+        Optional<OperationInputDefinition> inputCandidate = getOperationInputByInputId(serviceConsumptionData, inputs);
+        if (!inputCandidate.isPresent()) {
             return Either.right(new ResponseFormat(HttpStatus.NOT_FOUND.value()));
         }
-
         OperationInputDefinition operationInputDefinition = inputCandidate.get();
         // add data to operation
-
-        if(Objects.nonNull(serviceConsumptionData.getValue()))  {
-            operationEither =
-                    handleConsumptionValue(parentService, serviceInstanceId, serviceConsumptionData, operation,
-                            operationInputDefinition);
+        if (Objects.nonNull(serviceConsumptionData.getValue())) {
+            operationEither = handleConsumptionValue(parentService, serviceInstanceId, serviceConsumptionData, operation, operationInputDefinition);
         }
-
-        if(operationEither.isRight()) {
+        if (operationEither.isRight()) {
             return Either.right(operationEither.right().value());
         }
-
         Operation updatedOperation = operationEither.left().value();
         operations.remove(operationId);
         operations.put(operationId, updatedOperation);
         interfaceDefinition.setOperationsMap(operations);
-
         parentService.getComponentInstances().remove(serviceInstance);
-        if(CollectionUtils.isEmpty(parentService.getComponentInstances())) {
+        if (CollectionUtils.isEmpty(parentService.getComponentInstances())) {
             parentService.setComponentInstances(new ArrayList<>());
         }
-
         Map<String, Object> instanceInterfaces =
-                MapUtils.isEmpty(serviceInstance.getInterfaces())? new HashMap<>() : serviceInstance.getInterfaces();
+            MapUtils.isEmpty(serviceInstance.getInterfaces()) ? new HashMap<>() : serviceInstance.getInterfaces();
         instanceInterfaces.remove(interfaceDefinition.getUniqueId());
         instanceInterfaces.put(interfaceDefinition.getUniqueId(), interfaceDefinition);
         serviceInstance.setInterfaces(instanceInterfaces);
-
         removeComponentInstanceInterfaceByInterfaceId(interfaceDefinition.getUniqueId(), componentInstancesInterfaces.get(serviceInstanceId));
-        componentInstancesInterfaces.get(serviceInstanceId).add(new ComponentInstanceInterface(interfaceDefinition.getUniqueId(), interfaceDefinition));
-
+        componentInstancesInterfaces.get(serviceInstanceId)
+            .add(new ComponentInstanceInterface(interfaceDefinition.getUniqueId(), interfaceDefinition));
         parentService.getComponentInstances().add(serviceInstance);
-
         StorageOperationStatus status = toscaOperationFacade.updateComponentInstanceInterfaces(parentService, serviceInstanceId);
-
-        if(status != StorageOperationStatus.OK) {
-            return Either.right(componentsUtils.getResponseFormat(ActionStatus
-                    .INTERFACE_OPERATION_NOT_FOUND, serviceInstanceId));
+        if (status != StorageOperationStatus.OK) {
+            return Either.right(componentsUtils.getResponseFormat(ActionStatus.INTERFACE_OPERATION_NOT_FOUND, serviceInstanceId));
         }
-
         return Either.left(operation);
     }
 
-    private void removeComponentInstanceInterfaceByInterfaceId(String interfaceIdToRemove,
-                                                               List<ComponentInstanceInterface> instanceInterfaces) {
-        if(CollectionUtils.isEmpty(instanceInterfaces)) {
+    private void removeComponentInstanceInterfaceByInterfaceId(String interfaceIdToRemove, List<ComponentInstanceInterface> instanceInterfaces) {
+        if (CollectionUtils.isEmpty(instanceInterfaces)) {
             return;
         }
-
-        Optional<ComponentInstanceInterface> interfaceToRemove =
-                instanceInterfaces.stream().filter(instInterface -> instInterface.getUniqueId().equals
-                        (interfaceIdToRemove)).findAny();
-
-        if(interfaceToRemove.isPresent()) {
+        Optional<ComponentInstanceInterface> interfaceToRemove = instanceInterfaces.stream()
+            .filter(instInterface -> instInterface.getUniqueId().equals(interfaceIdToRemove)).findAny();
+        if (interfaceToRemove.isPresent()) {
             instanceInterfaces.remove(interfaceToRemove.get());
         }
-
     }
 
-    private Either<Operation, ResponseFormat> handleConsumptionValue(Service containerService,
-                                                                     String serviceInstanceId,
-                                                                     ServiceConsumptionData serviceConsumptionData,
-                                                                     Operation operation,
-                                                                     OperationInputDefinition
-                                                                             operationInputDefinition) {
+    private Either<Operation, ResponseFormat> handleConsumptionValue(Service containerService, String serviceInstanceId,
+                                                                     ServiceConsumptionData serviceConsumptionData, Operation operation,
+                                                                     OperationInputDefinition operationInputDefinition) {
         String source = serviceConsumptionData.getSource();
         String consumptionValue = serviceConsumptionData.getValue();
         String type = serviceConsumptionData.getType();
-        String operationIdentifier = consumptionValue.contains(".")
-                ? consumptionValue.substring(0, consumptionValue.lastIndexOf('.'))
-                : consumptionValue;
-
+        String operationIdentifier =
+            consumptionValue.contains(".") ? consumptionValue.substring(0, consumptionValue.lastIndexOf('.')) : consumptionValue;
         ServiceConsumptionSource sourceValue = ServiceConsumptionSource.getSourceValue(source);
-
-        if(STATIC.equals(sourceValue)) {
+        if (STATIC.equals(sourceValue)) {
             // Validate constraint on input value
-            Either<Boolean, ResponseFormat> constraintValidationResult =
-                    validateOperationInputConstraint(operationInputDefinition, consumptionValue, type);
-
+            Either<Boolean, ResponseFormat> constraintValidationResult = validateOperationInputConstraint(operationInputDefinition, consumptionValue,
+                type);
             if (constraintValidationResult.isRight()) {
                 return Either.right(constraintValidationResult.right().value());
             }
-            return handleConsumptionStaticValue(consumptionValue, type, operation,
-                    operationInputDefinition);
+            return handleConsumptionStaticValue(consumptionValue, type, operation, operationInputDefinition);
         }
-
         if (Objects.isNull(sourceValue)) {
             List<PropertyDefinition> propertyDefinitions;
             Map<String, List<CapabilityDefinition>> capabilities = null;
             String componentName;
             List<OperationOutputDefinition> outputs = null;
             if (source.equals(containerService.getUniqueId())) {
-                Either<Service, StorageOperationStatus> serviceToTakePropEither =
-                        toscaOperationFacade.getToscaElement(source);
+                Either<Service, StorageOperationStatus> serviceToTakePropEither = toscaOperationFacade.getToscaElement(source);
                 if (serviceToTakePropEither.isRight()) {
                     return Either.right(componentsUtils.getResponseFormat(serviceToTakePropEither.right().value()));
                 }
@@ -502,13 +403,12 @@ public class ServiceBusinessLogic extends ComponentBusinessLogic {
                 sourceValue = SERVICE_INPUT;
                 propertyDefinitions = service.getProperties();
                 componentName = service.getName();
-                outputs = InterfaceOperationUtils.getOtherOperationOutputsOfComponent(operationIdentifier,
-                        service.getInterfaces()).getListToscaDataDefinition();
+                outputs = InterfaceOperationUtils.getOtherOperationOutputsOfComponent(operationIdentifier, service.getInterfaces())
+                    .getListToscaDataDefinition();
             } else {
                 Optional<ComponentInstance> getComponentInstance = containerService.getComponentInstanceById(source);
-                if(!getComponentInstance.isPresent()){
-                    return Either.right(componentsUtils.getResponseFormat(
-                            ActionStatus.COMPONENT_INSTANCE_NOT_FOUND_ON_CONTAINER, source));
+                if (!getComponentInstance.isPresent()) {
+                    return Either.right(componentsUtils.getResponseFormat(ActionStatus.COMPONENT_INSTANCE_NOT_FOUND_ON_CONTAINER, source));
                 }
                 ComponentInstance componentInstance = getComponentInstance.get();
                 operationInputDefinition.setSource(componentInstance.getUniqueId());
@@ -516,185 +416,143 @@ public class ServiceBusinessLogic extends ComponentBusinessLogic {
                 capabilities = componentInstance.getCapabilities();
                 componentName = source.equals(serviceInstanceId) ? SELF : componentInstance.getName();
                 if (MapUtils.isNotEmpty(componentInstance.getInterfaces())) {
-                    Map<String, InterfaceDataDefinition> componentInstanceInterfaces =
-                            componentInstance.getInterfaces().entrySet().stream()
-                                    .collect(Collectors.toMap((Map.Entry::getKey),
-                                            (interfaceEntry -> (InterfaceDataDefinition) interfaceEntry.getValue())));
-                    outputs = InterfaceOperationUtils.getOtherOperationOutputsOfComponent(operationIdentifier,
-                            componentInstanceInterfaces).getListToscaDataDefinition();
+                    Map<String, InterfaceDataDefinition> componentInstanceInterfaces = componentInstance.getInterfaces().entrySet().stream()
+                        .collect(Collectors.toMap((Map.Entry::getKey), (interfaceEntry -> (InterfaceDataDefinition) interfaceEntry.getValue())));
+                    outputs = InterfaceOperationUtils.getOtherOperationOutputsOfComponent(operationIdentifier, componentInstanceInterfaces)
+                        .getListToscaDataDefinition();
                 }
             }
-
-            if(sourceValue == ServiceConsumptionSource.SERVICE_INPUT) {
+            if (sourceValue == ServiceConsumptionSource.SERVICE_INPUT) {
                 //The operation input in service consumption has been mapped to an input in the parent service
-                return handleConsumptionInputValue(consumptionValue, containerService, operation,
-                        operationInputDefinition);
+                return handleConsumptionInputValue(consumptionValue, containerService, operation, operationInputDefinition);
             }
-            return handleConsumptionPropertyValue(operation, operationInputDefinition,
-                    serviceConsumptionData, propertyDefinitions, capabilities, outputs, componentName);
+            return handleConsumptionPropertyValue(operation, operationInputDefinition, serviceConsumptionData, propertyDefinitions, capabilities,
+                outputs, componentName);
         }
-
         operationInputDefinition.setToscaPresentationValue(JsonPresentationFields.SOURCE, source);
         operationInputDefinition.setSource(source);
-
         return Either.left(operation);
     }
 
     private Optional<OperationInputDefinition> getOperationInputByInputId(ServiceConsumptionData serviceConsumptionData,
                                                                           ListDataDefinition<OperationInputDefinition> inputs) {
-
-        if(CollectionUtils.isEmpty(inputs.getListToscaDataDefinition())) {
+        if (CollectionUtils.isEmpty(inputs.getListToscaDataDefinition())) {
             return Optional.empty();
         }
-
-        return inputs.getListToscaDataDefinition().stream().filter(operationInput -> operationInput.getInputId().equals
-                (serviceConsumptionData.getInputId()))
-                .findAny();
+        return inputs.getListToscaDataDefinition().stream()
+            .filter(operationInput -> operationInput.getInputId().equals(serviceConsumptionData.getInputId())).findAny();
     }
 
-    private Either<Operation, ResponseFormat> handleConsumptionPropertyValue(
-            Operation operation, OperationInputDefinition operationInputDefinition,
-            ServiceConsumptionData serviceConsumptionData, List<PropertyDefinition> properties,Map<String,
-            List<CapabilityDefinition>> capabilities,
-            List<OperationOutputDefinition> outputs,  String componentName) {
-
+    private Either<Operation, ResponseFormat> handleConsumptionPropertyValue(Operation operation, OperationInputDefinition operationInputDefinition,
+                                                                             ServiceConsumptionData serviceConsumptionData,
+                                                                             List<PropertyDefinition> properties,
+                                                                             Map<String, List<CapabilityDefinition>> capabilities,
+                                                                             List<OperationOutputDefinition> outputs, String componentName) {
         if (CollectionUtils.isEmpty(properties) && CollectionUtils.isEmpty(outputs)) {
             return Either.left(operation);
         }
         String consumptionValue = serviceConsumptionData.getValue();
-
-        if (CollectionUtils.isNotEmpty(outputs)
-                && isOperationInputMappedToOtherOperationOutput(getOperationOutputName(consumptionValue), outputs)) {
-            return handleConsumptionInputMappedToOperationOutput(operation, operationInputDefinition, outputs,
-                    consumptionValue, componentName);
+        if (CollectionUtils.isNotEmpty(outputs) && isOperationInputMappedToOtherOperationOutput(getOperationOutputName(consumptionValue), outputs)) {
+            return handleConsumptionInputMappedToOperationOutput(operation, operationInputDefinition, outputs, consumptionValue, componentName);
         }
-
         if (CollectionUtils.isNotEmpty(properties) && PropertiesUtils.isNodeProperty(consumptionValue, properties)) {
-            return handleConsumptionInputMappedToProperty(operation, operationInputDefinition, serviceConsumptionData,
-                    properties, componentName);
+            return handleConsumptionInputMappedToProperty(operation, operationInputDefinition, serviceConsumptionData, properties, componentName);
         }
-
         if (MapUtils.isNotEmpty(capabilities)) {
-            return handleConsumptionInputMappedToCapabilityProperty(operation, operationInputDefinition,
-                    serviceConsumptionData, capabilities, componentName);
+            return handleConsumptionInputMappedToCapabilityProperty(operation, operationInputDefinition, serviceConsumptionData, capabilities,
+                componentName);
         }
-
         return Either.left(operation);
     }
 
     private Either<Operation, ResponseFormat> handleConsumptionInputMappedToProperty(Operation operation,
-                                                                                     OperationInputDefinition operationInputDefinition, ServiceConsumptionData serviceConsumptionData,
+                                                                                     OperationInputDefinition operationInputDefinition,
+                                                                                     ServiceConsumptionData serviceConsumptionData,
                                                                                      List<PropertyDefinition> properties, String componentName) {
-        Optional<PropertyDefinition> servicePropertyCandidate =
-                properties.stream().filter(property -> property.getName()
-                        .equals(serviceConsumptionData.getValue())).findAny();
-
+        Optional<PropertyDefinition> servicePropertyCandidate = properties.stream()
+            .filter(property -> property.getName().equals(serviceConsumptionData.getValue())).findAny();
         if (servicePropertyCandidate.isPresent()) {
-            boolean isInputTypeSimilarToOperation =
-                    isAssignedValueFromValidType(operationInputDefinition.getType(),
-                            servicePropertyCandidate.get());
-
+            boolean isInputTypeSimilarToOperation = isAssignedValueFromValidType(operationInputDefinition.getType(), servicePropertyCandidate.get());
             if (!isInputTypeSimilarToOperation) {
-                return Either.right(componentsUtils.getResponseFormat(
-                        ActionStatus.INVALID_CONSUMPTION_TYPE, operationInputDefinition.getType()));
+                return Either.right(componentsUtils.getResponseFormat(ActionStatus.INVALID_CONSUMPTION_TYPE, operationInputDefinition.getType()));
             }
-
-            addPropertyToInputValue(componentName, operation, operationInputDefinition,
-                    servicePropertyCandidate.get());
+            addPropertyToInputValue(componentName, operation, operationInputDefinition, servicePropertyCandidate.get());
         }
         return Either.left(operation);
     }
 
     private Either<Operation, ResponseFormat> handleConsumptionInputMappedToOperationOutput(Operation operation,
-                                                                                            OperationInputDefinition operationInputDefinition, List<OperationOutputDefinition> outputs,
+                                                                                            OperationInputDefinition operationInputDefinition,
+                                                                                            List<OperationOutputDefinition> outputs,
                                                                                             String consumptionValue, String componentName) {
         String outputName = getOperationOutputName(consumptionValue);
-        Optional<OperationOutputDefinition> servicePropertyOutputCandidate = outputs.stream()
-                .filter(output -> output.getName().equals(outputName)).findAny();
+        Optional<OperationOutputDefinition> servicePropertyOutputCandidate = outputs.stream().filter(output -> output.getName().equals(outputName))
+            .findAny();
         if (servicePropertyOutputCandidate.isPresent()) {
-            boolean isInputTypeSimilarToOperation =
-                    isAssignedValueFromValidType(operationInputDefinition.getType(),
-                            servicePropertyOutputCandidate.get());
+            boolean isInputTypeSimilarToOperation = isAssignedValueFromValidType(operationInputDefinition.getType(),
+                servicePropertyOutputCandidate.get());
             if (!isInputTypeSimilarToOperation) {
-                return Either.right(componentsUtils.getResponseFormat(
-                        ActionStatus.INVALID_CONSUMPTION_TYPE, operationInputDefinition.getType()));
+                return Either.right(componentsUtils.getResponseFormat(ActionStatus.INVALID_CONSUMPTION_TYPE, operationInputDefinition.getType()));
             }
             addOutputToInputValue(componentName, consumptionValue, operation, operationInputDefinition);
         }
         return Either.left(operation);
     }
 
-    private void addPropertyToInputValue(String componentName, Operation operation,
-                                         OperationInputDefinition operationInputDefinition,
+    private void addPropertyToInputValue(String componentName, Operation operation, OperationInputDefinition operationInputDefinition,
                                          PropertyDefinition serviceProperty) {
         Map<String, List<String>> getProperty = new HashMap<>();
         List<String> getPropertyValues = new ArrayList<>();
         getPropertyValues.add(componentName);
         getPropertyValues.add(serviceProperty.getName());
         getProperty.put(ToscaFunctions.GET_PROPERTY.getFunctionName(), getPropertyValues);
-
         operationInputDefinition.setSourceProperty(serviceProperty.getUniqueId());
         operation.getInputs().delete(operationInputDefinition);
-        operationInputDefinition.setToscaPresentationValue(JsonPresentationFields.GET_PROPERTY,
-                getPropertyValues);
+        operationInputDefinition.setToscaPresentationValue(JsonPresentationFields.GET_PROPERTY, getPropertyValues);
         operationInputDefinition.setValue((new Gson()).toJson(getProperty));
         operation.getInputs().add(operationInputDefinition);
     }
 
-    private void addOutputToInputValue(String componentName, String consumptionValue,
-                                       Operation operation, OperationInputDefinition operationInputDefinition) {
-        Map<String, List<String>> getOperationOutput =
-                InterfaceOperationUtils.createMappedOutputDefaultValue(componentName, consumptionValue);
+    private void addOutputToInputValue(String componentName, String consumptionValue, Operation operation,
+                                       OperationInputDefinition operationInputDefinition) {
+        Map<String, List<String>> getOperationOutput = InterfaceOperationUtils.createMappedOutputDefaultValue(componentName, consumptionValue);
         operation.getInputs().delete(operationInputDefinition);
-        operationInputDefinition.setToscaPresentationValue(JsonPresentationFields.GET_OPERATION_OUTPUT,
-                getOperationOutput);
+        operationInputDefinition.setToscaPresentationValue(JsonPresentationFields.GET_OPERATION_OUTPUT, getOperationOutput);
         operationInputDefinition.setValue((new Gson()).toJson(getOperationOutput));
         operation.getInputs().add(operationInputDefinition);
     }
 
-    public Either<Operation, ResponseFormat> handleConsumptionStaticValue(String value, String type,
-                                                                          Operation operation,
-                                                                          OperationInputDefinition
-                                                                                  operationInputDefinition) {
-        boolean isInputTypeSimilarToOperation =
-                isAssignedValueFromValidType(type, value);
-
-        if(!isInputTypeSimilarToOperation) {
-            return Either.right(componentsUtils.getResponseFormat(
-                    ActionStatus.INVALID_CONSUMPTION_TYPE, type));
+    public Either<Operation, ResponseFormat> handleConsumptionStaticValue(String value, String type, Operation operation,
+                                                                          OperationInputDefinition operationInputDefinition) {
+        boolean isInputTypeSimilarToOperation = isAssignedValueFromValidType(type, value);
+        if (!isInputTypeSimilarToOperation) {
+            return Either.right(componentsUtils.getResponseFormat(ActionStatus.INVALID_CONSUMPTION_TYPE, type));
+        }
+        //Validate Constraint and Value
+        Either<Boolean, ResponseFormat> constraintValidationResponse = validateOperationInputConstraint(operationInputDefinition, value, type);
+        if (constraintValidationResponse.isRight()) {
+            return Either.right(constraintValidationResponse.right().value());
         }
-
-               //Validate Constraint and Value
-               Either<Boolean, ResponseFormat> constraintValidationResponse =
-                               validateOperationInputConstraint(operationInputDefinition, value, type);
-               if(constraintValidationResponse.isRight()) {
-                       return Either.right(constraintValidationResponse.right().value());
-               }
-
         addStaticValueToInputOperation(value, operation, operationInputDefinition);
-
         return Either.left(operation);
     }
 
-       private Either<Boolean, ResponseFormat> validateOperationInputConstraint(
-                       OperationInputDefinition operationInputDefinition, String value, String type) {
-               ComponentInstanceProperty propertyDefinition = new ComponentInstanceProperty();
-               propertyDefinition.setType(operationInputDefinition.getParentPropertyType());
-
-               InputDefinition inputDefinition = new InputDefinition();
-               inputDefinition.setDefaultValue(value);
-               inputDefinition.setInputPath(operationInputDefinition.getSubPropertyInputPath());
-               inputDefinition.setType(type);
-               if (Objects.nonNull(operationInputDefinition.getParentPropertyType())) {
-                inputDefinition.setProperties(Collections.singletonList(propertyDefinition));
-               }
-
-               return PropertyValueConstraintValidationUtil.getInstance()
-                               .validatePropertyConstraints(Collections.singletonList(inputDefinition), applicationDataTypeCache);
-       }
+    private Either<Boolean, ResponseFormat> validateOperationInputConstraint(OperationInputDefinition operationInputDefinition, String value,
+                                                                             String type) {
+        ComponentInstanceProperty propertyDefinition = new ComponentInstanceProperty();
+        propertyDefinition.setType(operationInputDefinition.getParentPropertyType());
+        InputDefinition inputDefinition = new InputDefinition();
+        inputDefinition.setDefaultValue(value);
+        inputDefinition.setInputPath(operationInputDefinition.getSubPropertyInputPath());
+        inputDefinition.setType(type);
+        if (Objects.nonNull(operationInputDefinition.getParentPropertyType())) {
+            inputDefinition.setProperties(Collections.singletonList(propertyDefinition));
+        }
+        return PropertyValueConstraintValidationUtil.getInstance()
+            .validatePropertyConstraints(Collections.singletonList(inputDefinition), applicationDataTypeCache);
+    }
 
-       private void addStaticValueToInputOperation(String value, Operation operation,
-                                                OperationInputDefinition operationInputDefinition) {
+    private void addStaticValueToInputOperation(String value, Operation operation, OperationInputDefinition operationInputDefinition) {
         operation.getInputs().delete(operationInputDefinition);
         operationInputDefinition.setSource(STATIC.getSource());
         operationInputDefinition.setSourceProperty(null);
@@ -702,31 +560,21 @@ public class ServiceBusinessLogic extends ComponentBusinessLogic {
         operation.getInputs().add(operationInputDefinition);
     }
 
-    private Either<Operation, ResponseFormat>  handleConsumptionInputValue(String inputId,
-                                                                           Service service,
-                                                                           Operation operation,
-                                                                           OperationInputDefinition
-                                                                                   operationInputDefinition) {
+    private Either<Operation, ResponseFormat> handleConsumptionInputValue(String inputId, Service service, Operation operation,
+                                                                          OperationInputDefinition operationInputDefinition) {
         List<InputDefinition> serviceInputs = service.getInputs();
-        Optional<InputDefinition> inputForValue =
-                serviceInputs.stream().filter(input -> input.getUniqueId().contains(inputId)).findAny();
-
-        if(inputForValue.isPresent()) {
-            boolean isInputTypeSimilarToOperation =
-                    isAssignedValueFromValidType(operationInputDefinition.getType(), inputForValue.get());
-
-            if(!isInputTypeSimilarToOperation) {
-                return Either.right(componentsUtils.getResponseFormat(
-                        ActionStatus.INVALID_CONSUMPTION_TYPE, operationInputDefinition.getType()));
+        Optional<InputDefinition> inputForValue = serviceInputs.stream().filter(input -> input.getUniqueId().contains(inputId)).findAny();
+        if (inputForValue.isPresent()) {
+            boolean isInputTypeSimilarToOperation = isAssignedValueFromValidType(operationInputDefinition.getType(), inputForValue.get());
+            if (!isInputTypeSimilarToOperation) {
+                return Either.right(componentsUtils.getResponseFormat(ActionStatus.INVALID_CONSUMPTION_TYPE, operationInputDefinition.getType()));
             }
             addGetInputValueToOperationInput(operation, operationInputDefinition, inputForValue.get());
         }
-
         return Either.left(operation);
     }
 
-    private void addGetInputValueToOperationInput(Operation operation,
-                                                  OperationInputDefinition operationInputDefinition,
+    private void addGetInputValueToOperationInput(Operation operation, OperationInputDefinition operationInputDefinition,
                                                   InputDefinition inputForValue) {
         operation.getInputs().delete(operationInputDefinition);
         Map<String, String> getInputMap = new HashMap<>();
@@ -739,38 +587,31 @@ public class ServiceBusinessLogic extends ComponentBusinessLogic {
 
     private Either<List<Map<String, Object>>, ActionStatus> getAuditRecordsForUncertifiedComponent(String componentUUID, String componentVersion) {
         // First Query
-        Either<List<ResourceAdminEvent>, ActionStatus> eitherprevVerAudit = auditCassandraDao.getAuditByServiceIdAndPrevVersion(componentUUID, componentVersion);
-
+        Either<List<ResourceAdminEvent>, ActionStatus> eitherprevVerAudit = auditCassandraDao
+            .getAuditByServiceIdAndPrevVersion(componentUUID, componentVersion);
         if (eitherprevVerAudit.isRight()) {
             return Either.right(eitherprevVerAudit.right().value());
         }
-
         // Second Query
-        Either<List<ResourceAdminEvent>, ActionStatus> eitherCurrVerAudit = auditCassandraDao.getAuditByServiceIdAndCurrVersion(componentUUID, componentVersion);
+        Either<List<ResourceAdminEvent>, ActionStatus> eitherCurrVerAudit = auditCassandraDao
+            .getAuditByServiceIdAndCurrVersion(componentUUID, componentVersion);
         if (eitherCurrVerAudit.isRight()) {
             return Either.right(eitherCurrVerAudit.right().value());
         }
-
-
         Either<List<ResourceAdminEvent>, ActionStatus> eitherArchiveRestoreList = getArchiveRestoreEventList(componentUUID);
         if (eitherArchiveRestoreList.isRight()) {
             return Either.right(eitherArchiveRestoreList.right().value());
         }
-
         List<Map<String, Object>> prevVerAuditList = getAuditingFieldsList(eitherprevVerAudit.left().value());
         List<Map<String, Object>> currVerAuditList = getAuditingFieldsList(eitherCurrVerAudit.left().value());
-
         List<Map<String, Object>> duplicateElements = new ArrayList<>();
         duplicateElements.addAll(prevVerAuditList);
         duplicateElements.retainAll(currVerAuditList);
-
         List<Map<String, Object>> joinedNonDuplicatedList = new ArrayList<>();
         joinedNonDuplicatedList.addAll(prevVerAuditList);
         joinedNonDuplicatedList.removeAll(duplicateElements);
         joinedNonDuplicatedList.addAll(currVerAuditList);
         joinedNonDuplicatedList.addAll(getAuditingFieldsList(eitherArchiveRestoreList.left().value()));
-
-
         return Either.left(joinedNonDuplicatedList);
     }
 
@@ -780,17 +621,14 @@ public class ServiceBusinessLogic extends ComponentBusinessLogic {
         if (eitherArchiveAudit.isRight()) {
             return Either.right(eitherArchiveAudit.right().value());
         }
-
         // Restore Query
         Either<List<ResourceAdminEvent>, ActionStatus> eitherRestoreAudit = auditCassandraDao.getRestoreAuditByServiceInstanceId(componentUUID);
         if (eitherRestoreAudit.isRight()) {
             return Either.right(eitherRestoreAudit.right().value());
         }
-
         List<ResourceAdminEvent> archiveAudit = new ArrayList<>();
         archiveAudit.addAll(eitherArchiveAudit.left().value());
         archiveAudit.addAll(eitherRestoreAudit.left().value());
-
         return Either.left(archiveAudit);
     }
 
@@ -805,7 +643,6 @@ public class ServiceBusinessLogic extends ComponentBusinessLogic {
     }
 
     private List<Map<String, Object>> getAuditingFieldsList(List<? extends AuditingGenericEvent> prevVerAuditList) {
-
         List<Map<String, Object>> prevVerAudit = new ArrayList<>();
         for (AuditingGenericEvent auditEvent : prevVerAuditList) {
             auditEvent.fillFields();
@@ -817,17 +654,14 @@ public class ServiceBusinessLogic extends ComponentBusinessLogic {
     /**
      * createService
      *
-     * @param service
-     *            - Service
-     * @param user
-     *            - modifier data (userId)
+     * @param service - Service
+     * @param user    - modifier data (userId)
      * @return Either<Service, responseFormat>
      */
     public Either<Service, ResponseFormat> createService(Service service, User user) {
-
         // get user details
         user = validateUser(user, "Create Service", service, AuditingActionEnum.CREATE_RESOURCE, false);
-        log.debug("User returned from validation: "+ user.toString());
+        log.debug("User returned from validation: " + user.toString());
         // validate user role
         validateUserRole(user, service, new ArrayList<>(), AuditingActionEnum.CREATE_RESOURCE, null);
         service.setCreatorUserId(user.getUserId());
@@ -844,11 +678,7 @@ public class ServiceBusinessLogic extends ComponentBusinessLogic {
         if (createServiceResponse.isRight()) {
             return createServiceResponse;
         }
-        return createServiceByDao(service, user)
-                .left()
-                .bind(c -> updateCatalog(c, ChangeTypeEnum.LIFECYCLE)
-                        .left()
-                        .map (r -> (Service) r));
+        return createServiceByDao(service, user).left().bind(c -> updateCatalog(c, ChangeTypeEnum.LIFECYCLE).left().map(r -> (Service) r));
     }
 
     private void checkFieldsForOverideAttampt(Service service) {
@@ -860,17 +690,13 @@ public class ServiceBusinessLogic extends ComponentBusinessLogic {
 
     private Either<Service, ResponseFormat> createServiceByDao(final Service service, final User user) {
         log.debug("send service {} to dao for create", service.getComponentMetadataDefinition().getMetadataDataDefinition().getName());
-
         Either<Boolean, ResponseFormat> lockResult = lockComponentByName(service.getSystemName(), service, "Create Service");
         if (lockResult.isRight()) {
             ResponseFormat responseFormat = lockResult.right().value();
-            componentsUtils.auditComponentAdmin(responseFormat, user, service, AuditingActionEnum.CREATE_RESOURCE,
-                ComponentTypeEnum.SERVICE);
+            componentsUtils.auditComponentAdmin(responseFormat, user, service, AuditingActionEnum.CREATE_RESOURCE, ComponentTypeEnum.SERVICE);
             return Either.right(responseFormat);
         }
-
         log.debug("System name locked is {}, status = {}", service.getSystemName(), lockResult);
-
         try {
             createMandatoryArtifactsData(service, user);
             createServiceApiArtifactsData(service, user);
@@ -879,20 +705,19 @@ public class ServiceBusinessLogic extends ComponentBusinessLogic {
             generatePropertiesFromGenericType(service, genericType);
             generateAndAddInputsFromGenericTypeProperties(service, genericType);
             beforeCreate(service);
-
             Either<Service, StorageOperationStatus> dataModelResponse = toscaOperationFacade.createToscaComponent(service);
             if (dataModelResponse.isLeft()) {
                 log.debug("Service '{}' created successfully", service.getName());
                 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.CREATED);
-                componentsUtils.auditComponentAdmin(responseFormat, user, service, AuditingActionEnum.CREATE_RESOURCE,
-                    ComponentTypeEnum.SERVICE);
+                componentsUtils.auditComponentAdmin(responseFormat, user, service, AuditingActionEnum.CREATE_RESOURCE, ComponentTypeEnum.SERVICE);
                 ASDCKpiApi.countCreatedServicesKPI();
                 return Either.left(dataModelResponse.left().value());
             }
-            ResponseFormat responseFormat = componentsUtils.getResponseFormatByComponent(componentsUtils.convertFromStorageResponse(dataModelResponse.right().value()), service, ComponentTypeEnum.SERVICE);
+            ResponseFormat responseFormat = componentsUtils
+                .getResponseFormatByComponent(componentsUtils.convertFromStorageResponse(dataModelResponse.right().value()), service,
+                    ComponentTypeEnum.SERVICE);
             log.debug(AUDIT_BEFORE_SENDING_RESPONSE);
-            componentsUtils.auditComponentAdmin(responseFormat, user, service, AuditingActionEnum.CREATE_RESOURCE,
-                ComponentTypeEnum.SERVICE);
+            componentsUtils.auditComponentAdmin(responseFormat, user, service, AuditingActionEnum.CREATE_RESOURCE, ComponentTypeEnum.SERVICE);
             return Either.right(responseFormat);
         } finally {
             graphLockOperation.unlockComponentByName(service.getSystemName(), service.getUniqueId(), NodeTypeEnum.Service);
@@ -903,36 +728,29 @@ public class ServiceBusinessLogic extends ComponentBusinessLogic {
         if (CollectionUtils.isEmpty(serviceCreationPluginList)) {
             return;
         }
-        serviceCreationPluginList.stream()
-            .sorted(Comparator.comparingInt(ServiceCreationPlugin::getOrder))
-            .forEach(serviceCreationPlugin -> {
-                try {
-                    serviceCreationPlugin.beforeCreate(service);
-                } catch (final Exception e) {
-                    log.error("An error has occurred while running the serviceCreationPlugin '{}'",
-                        serviceCreationPlugin.getClass(), e);
-                }
-            });
+        serviceCreationPluginList.stream().sorted(Comparator.comparingInt(ServiceCreationPlugin::getOrder)).forEach(serviceCreationPlugin -> {
+            try {
+                serviceCreationPlugin.beforeCreate(service);
+            } catch (final Exception e) {
+                log.error("An error has occurred while running the serviceCreationPlugin '{}'", serviceCreationPlugin.getClass(), e);
+            }
+        });
     }
 
     private void generatePropertiesFromGenericType(final Service service, final Resource genericType) {
         if (CollectionUtils.isEmpty(genericType.getProperties())) {
             return;
         }
-        final List<PropertyDefinition> genericTypePropertyList = genericType.getProperties().stream()
-            .map(PropertyDefinition::new)
-            .peek(propertyDefinition -> propertyDefinition.setUniqueId(null))
-            .collect(Collectors.toList());
+        final List<PropertyDefinition> genericTypePropertyList = genericType.getProperties().stream().map(PropertyDefinition::new)
+            .peek(propertyDefinition -> propertyDefinition.setUniqueId(null)).collect(Collectors.toList());
         if (service.getProperties() == null) {
             service.setProperties(new ArrayList<>(genericTypePropertyList));
         } else {
             List<PropertyDefinition> servicePropertyList = service.getProperties();
             genericTypePropertyList.stream()
-                .filter(property -> servicePropertyList.stream()
-                    .noneMatch(property1 -> property1.getName().equals(property.getName())))
+                .filter(property -> servicePropertyList.stream().noneMatch(property1 -> property1.getName().equals(property.getName())))
                 .forEach(servicePropertyList::add);
         }
-
         service.getProperties().forEach(propertyDefinition -> propertyDefinition.setUniqueId(null));
     }
 
@@ -941,15 +759,15 @@ public class ServiceBusinessLogic extends ComponentBusinessLogic {
         // create mandatory artifacts
 
         // TODO it must be removed after that artifact uniqueId creation will be
+
         // moved to ArtifactOperation
         String serviceUniqueId = service.getUniqueId();
         Map<String, ArtifactDefinition> artifactMap = service.getServiceApiArtifacts();
-        if (artifactMap == null)
+        if (artifactMap == null) {
             artifactMap = new HashMap<>();
-
+        }
         Map<String, Object> serviceApiArtifacts = ConfigurationManager.getConfigurationManager().getConfiguration().getServiceApiArtifacts();
         List<String> exludeServiceCategory = ConfigurationManager.getConfigurationManager().getConfiguration().getExcludeServiceCategory();
-
         List<CategoryDefinition> categories = service.getCategories();
         boolean isCreateArtifact = true;
         if (categories != null && exludeServiceCategory != null && !exludeServiceCategory.isEmpty()) {
@@ -959,59 +777,53 @@ public class ServiceBusinessLogic extends ComponentBusinessLogic {
                     break;
                 }
             }
-
         }
-
         if (serviceApiArtifacts != null && isCreateArtifact) {
             Set<String> keys = serviceApiArtifacts.keySet();
             for (String serviceApiArtifactName : keys) {
                 Map<String, Object> artifactInfoMap = (Map<String, Object>) serviceApiArtifacts.get(serviceApiArtifactName);
-                ArtifactDefinition artifactDefinition = createArtifactDefinition(serviceUniqueId, serviceApiArtifactName, artifactInfoMap, user, true);
+                ArtifactDefinition artifactDefinition = createArtifactDefinition(serviceUniqueId, serviceApiArtifactName, artifactInfoMap, user,
+                    true);
                 artifactDefinition.setArtifactGroupType(ArtifactGroupTypeEnum.SERVICE_API);
                 artifactMap.put(artifactDefinition.getArtifactLabel(), artifactDefinition);
             }
-
             service.setServiceApiArtifacts(artifactMap);
         }
     }
 
     @VisibleForTesting
     protected Either<Service, ResponseFormat> validateServiceBeforeCreate(Service service, User user, AuditingActionEnum actionEnum) {
-
         try {
-            serviceValidator.validate(user,service,actionEnum);
+            serviceValidator.validate(user, service, actionEnum);
         } catch (ComponentException exp) {
             ResponseFormat responseFormat = componentsUtils.getResponseFormat(exp);
-            componentsUtils.auditComponentAdmin(responseFormat, user, service,
-                    AuditingActionEnum.CREATE_SERVICE, ComponentTypeEnum.SERVICE);
+            componentsUtils.auditComponentAdmin(responseFormat, user, service, AuditingActionEnum.CREATE_SERVICE, ComponentTypeEnum.SERVICE);
             throw exp;
         }
-
         service.setCreatorFullName(user.getFirstName() + " " + user.getLastName());
         service.setContactId(service.getContactId().toLowerCase());
-
         // Generate invariant UUID - must be here and not in operation since it
+
         // should stay constant during clone
         String invariantUUID = UniqueIdBuilder.buildInvariantUUID();
         service.setInvariantUUID(invariantUUID);
-
         return Either.left(service);
     }
 
     public Either<Map<String, Boolean>, ResponseFormat> validateServiceNameExists(String serviceName, String userId) {
         validateUserExists(userId);
-
-        Either<Boolean, StorageOperationStatus> dataModelResponse = toscaOperationFacade.validateComponentNameUniqueness(serviceName, null, ComponentTypeEnum.SERVICE);
+        Either<Boolean, StorageOperationStatus> dataModelResponse = toscaOperationFacade
+            .validateComponentNameUniqueness(serviceName, null, ComponentTypeEnum.SERVICE);
         // DE242223
         janusGraphDao.commit();
-
         if (dataModelResponse.isLeft()) {
             Map<String, Boolean> result = new HashMap<>();
             result.put(IS_VALID, dataModelResponse.left().value());
             log.debug("validation was successfully performed.");
             return Either.left(result);
         }
-        ResponseFormat responseFormat = componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(dataModelResponse.right().value()));
+        ResponseFormat responseFormat = componentsUtils
+            .getResponseFormat(componentsUtils.convertFromStorageResponse(dataModelResponse.right().value()));
         return Either.right(responseFormat);
     }
 
@@ -1036,19 +848,16 @@ public class ServiceBusinessLogic extends ComponentBusinessLogic {
         user = validateUser(user, "updateServiceMetadata", serviceUpdate, null, false);
         // validate user role
         validateUserRole(user, serviceUpdate, new ArrayList<>(), null, null);
-
         Either<Service, StorageOperationStatus> storageStatus = toscaOperationFacade.getToscaElement(serviceId);
         if (storageStatus.isRight()) {
-            return Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(storageStatus.right().value(), ComponentTypeEnum.SERVICE), ""));
+            return Either.right(componentsUtils
+                .getResponseFormat(componentsUtils.convertFromStorageResponse(storageStatus.right().value(), ComponentTypeEnum.SERVICE), ""));
         }
-
         Service currentService = storageStatus.left().value();
-
         if (!ComponentValidationUtils.canWorkOnComponent(currentService, user.getUserId())) {
             log.info("Restricted operation for user: {}, on service: {}", user.getUserId(), currentService.getCreatorUserId());
             return Either.right(componentsUtils.getResponseFormat(ActionStatus.RESTRICTED_OPERATION));
         }
-
         Either<Service, ResponseFormat> validationRsponse = validateAndUpdateServiceMetadata(user, currentService, serviceUpdate);
         if (validationRsponse.isRight()) {
             log.info("service update metadata: validations field.");
@@ -1056,30 +865,23 @@ public class ServiceBusinessLogic extends ComponentBusinessLogic {
         }
         Service serviceToUpdate = validationRsponse.left().value();
         // lock resource
-
         lockComponent(serviceId, currentService, "Update Service Metadata");
         try {
-            return toscaOperationFacade.updateToscaElement(serviceToUpdate)
-                    .right()
-                    .map(rf -> {
-                        janusGraphDao.rollback();
-                        BeEcompErrorManager.getInstance().logBeSystemError("Update Service Metadata");
-                        log.debug("failed to update sevice {}", serviceToUpdate.getUniqueId());
-                        return (componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR));
-                       })
-                    .left()
-                    .bind(c ->  updateCatalogAndCommit(c));
-
+            return toscaOperationFacade.updateToscaElement(serviceToUpdate).right().map(rf -> {
+                janusGraphDao.rollback();
+                BeEcompErrorManager.getInstance().logBeSystemError("Update Service Metadata");
+                log.debug("failed to update sevice {}", serviceToUpdate.getUniqueId());
+                return (componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR));
+            }).left().bind(c -> updateCatalogAndCommit(c));
         } finally {
             graphLockOperation.unlockComponent(serviceId, NodeTypeEnum.Service);
         }
     }
 
-    private Either<Service, ResponseFormat> updateCatalogAndCommit(Service service){
-        Either<Service, ResponseFormat> res = updateCatalog(service, ChangeTypeEnum.LIFECYCLE).left().map(s -> (Service)s);
+    private Either<Service, ResponseFormat> updateCatalogAndCommit(Service service) {
+        Either<Service, ResponseFormat> res = updateCatalog(service, ChangeTypeEnum.LIFECYCLE).left().map(s -> (Service) s);
         janusGraphDao.commit();
         return res;
-
     }
 
     public Set<String> deleteForwardingPaths(String serviceId, Set<String> pathIdsToDelete, User user, boolean lock) {
@@ -1089,7 +891,8 @@ public class ServiceBusinessLogic extends ComponentBusinessLogic {
         validateUserRole(user, serviceToDelete, new ArrayList<>(), null, null);
         Either<Service, StorageOperationStatus> storageStatus = toscaOperationFacade.getToscaElement(serviceId);
         if (storageStatus.isRight()) {
-            throw new ByActionStatusComponentException(componentsUtils.convertFromStorageResponse(storageStatus.right().value(), ComponentTypeEnum.SERVICE), "");
+            throw new ByActionStatusComponentException(
+                componentsUtils.convertFromStorageResponse(storageStatus.right().value(), ComponentTypeEnum.SERVICE), "");
         }
         Service service = storageStatus.left().value();
         Either<Set<String>, StorageOperationStatus> result = null;
@@ -1098,27 +901,26 @@ public class ServiceBusinessLogic extends ComponentBusinessLogic {
                 lockComponent(service.getUniqueId(), service, "Delete Forwarding Path on Service");
             } catch (ComponentException e) {
                 janusGraphDao.rollback();
-                throw new ByActionStatusComponentException(componentsUtils.convertFromStorageResponse
-                        (storageStatus.right().value(), ComponentTypeEnum.SERVICE), "");
+                throw new ByActionStatusComponentException(
+                    componentsUtils.convertFromStorageResponse(storageStatus.right().value(), ComponentTypeEnum.SERVICE), "");
             }
         }
-        try{
-            result = forwardingPathOperation.deleteForwardingPath(service ,pathIdsToDelete);
+        try {
+            result = forwardingPathOperation.deleteForwardingPath(servicepathIdsToDelete);
             if (result.isRight()) {
                 log.debug(FAILED_TO_LOCK_SERVICE_RESPONSE_IS, service.getName(), result.right().value());
                 janusGraphDao.rollback();
-                throw new ByActionStatusComponentException(componentsUtils.convertFromStorageResponse
-                        (storageStatus.right().value(), ComponentTypeEnum.SERVICE));
+                throw new ByActionStatusComponentException(
+                    componentsUtils.convertFromStorageResponse(storageStatus.right().value(), ComponentTypeEnum.SERVICE));
             }
             janusGraphDao.commit();
             log.debug(THE_SERVICE_WITH_SYSTEM_NAME_LOCKED, service.getSystemName());
-
-        } catch (ComponentException e){
+        } catch (ComponentException e) {
             log.error("Exception occurred during delete forwarding path : {}", e.getMessage(), e);
             janusGraphDao.rollback();
             throw new ByActionStatusComponentException(ActionStatus.GENERAL_ERROR);
         } finally {
-              graphLockOperation.unlockComponent(service.getUniqueId(), NodeTypeEnum.Service);
+            graphLockOperation.unlockComponent(service.getUniqueId(), NodeTypeEnum.Service);
         }
         return result.left().value();
     }
@@ -1127,19 +929,19 @@ public class ServiceBusinessLogic extends ComponentBusinessLogic {
         Service serviceToDelete = new Service();
         serviceToDelete.setUniqueId(serviceId);
         serviceToDelete.setForwardingPaths(new HashMap<>());
-        pathIdsToDelete.forEach(pathIdToDelete ->  serviceToDelete.getForwardingPaths().put(pathIdToDelete, new ForwardingPathDataDefinition()));
+        pathIdsToDelete.forEach(pathIdToDelete -> serviceToDelete.getForwardingPaths().put(pathIdToDelete, new ForwardingPathDataDefinition()));
         return serviceToDelete;
     }
 
     public Service updateForwardingPath(String serviceId, Service serviceUpdate, User user, boolean lock) {
-        return createOrUpdateForwardingPath(serviceId, serviceUpdate, user, true,"updateForwardingPath", lock);
+        return createOrUpdateForwardingPath(serviceId, serviceUpdate, user, true, "updateForwardingPath", lock);
     }
 
     public Service createForwardingPath(String serviceId, Service serviceUpdate, User user, boolean lock) {
         return createOrUpdateForwardingPath(serviceId, serviceUpdate, user, false, "createForwardingPath", lock);
     }
 
-    private ForwardingPathDataDefinition  getTrimmedValues(ForwardingPathDataDefinition path){
+    private ForwardingPathDataDefinition getTrimmedValues(ForwardingPathDataDefinition path) {
         ForwardingPathDataDefinition dataDefinition = new ForwardingPathDataDefinition(path.getName());
         dataDefinition.setName(Strings.nullToEmpty(path.getName()).trim());
         dataDefinition.setProtocol(Strings.nullToEmpty(path.getProtocol()).trim());
@@ -1148,46 +950,38 @@ public class ServiceBusinessLogic extends ComponentBusinessLogic {
         dataDefinition.setPathElements(path.getPathElements());
         dataDefinition.setDescription(path.getDescription());
         dataDefinition.setToscaResourceName(path.getToscaResourceName());
-        return  dataDefinition;
+        return dataDefinition;
     }
 
-    private Service createOrUpdateForwardingPath(String serviceId, Service serviceUpdate, User user, boolean isUpdate, String errorContext, boolean lock) {
+    private Service createOrUpdateForwardingPath(String serviceId, Service serviceUpdate, User user, boolean isUpdate, String errorContext,
+                                                 boolean lock) {
         validateUserAndRole(serviceUpdate, user, errorContext);
-
         Map<String, ForwardingPathDataDefinition> forwardingPaths = serviceUpdate.getForwardingPaths();
-
-        Map<String, ForwardingPathDataDefinition> trimmedForwardingPaths =
-                forwardingPaths.entrySet().stream().collect(Collectors.toMap(Map.Entry::getKey,
-                        entry -> new ForwardingPathDataDefinition(getTrimmedValues(entry.getValue()))));
-
-        forwardingPathValidator.validateForwardingPaths(trimmedForwardingPaths.values(),
-                serviceId, isUpdate);
-
+        Map<String, ForwardingPathDataDefinition> trimmedForwardingPaths = forwardingPaths.entrySet().stream()
+            .collect(Collectors.toMap(Map.Entry::getKey, entry -> new ForwardingPathDataDefinition(getTrimmedValues(entry.getValue()))));
+        forwardingPathValidator.validateForwardingPaths(trimmedForwardingPaths.values(), serviceId, isUpdate);
         Either<Service, StorageOperationStatus> serviceStorageOperationStatusEither = toscaOperationFacade.getToscaElement(serviceId);
-
-        if(serviceStorageOperationStatusEither.isRight()){
+        if (serviceStorageOperationStatusEither.isRight()) {
             StorageOperationStatus errorStatus = serviceStorageOperationStatusEither.right().value();
             log.debug("Failed to fetch service information by service id, error {}", errorStatus);
             throw new ByActionStatusComponentException(componentsUtils.convertFromStorageResponse(errorStatus));
         }
         Service storedService = serviceStorageOperationStatusEither.left().value();
-
         Either<ForwardingPathDataDefinition, StorageOperationStatus> result;
         Component component = getForwardingPathOriginComponent();
         final String toscaResourceName;
-        if (  component.getComponentType() == ComponentTypeEnum.RESOURCE) {
+        if (component.getComponentType() == ComponentTypeEnum.RESOURCE) {
             toscaResourceName = ((Resource) component).getToscaResourceName();
         } else {
             toscaResourceName = "";
         }
         if (lock) {
-           lockComponent(storedService.getUniqueId(), storedService, "Add or Update Forwarding Path on Service");
-           log.debug(THE_SERVICE_WITH_SYSTEM_NAME_LOCKED, storedService.getSystemName());
+            lockComponent(storedService.getUniqueId(), storedService, "Add or Update Forwarding Path on Service");
+            log.debug(THE_SERVICE_WITH_SYSTEM_NAME_LOCKED, storedService.getSystemName());
         }
         Map<String, ForwardingPathDataDefinition> resultMap = new HashMap<>();
         try {
             trimmedForwardingPaths.values().forEach(fp -> fp.setToscaResourceName(toscaResourceName));
-
             populateForwardingPaths(serviceId, isUpdate, trimmedForwardingPaths, resultMap);
             janusGraphDao.commit();
         } finally {
@@ -1199,7 +993,8 @@ public class ServiceBusinessLogic extends ComponentBusinessLogic {
     }
 
     private Component getForwardingPathOriginComponent() {
-        Either<Component, StorageOperationStatus> forwardingPathOrigin = toscaOperationFacade.getLatestByName(ForwardingPathUtils.FORWARDING_PATH_NODE_NAME);
+        Either<Component, StorageOperationStatus> forwardingPathOrigin = toscaOperationFacade
+            .getLatestByName(ForwardingPathUtils.FORWARDING_PATH_NODE_NAME);
         if (forwardingPathOrigin.isRight()) {
             StorageOperationStatus errorStatus = forwardingPathOrigin.right().value();
             log.debug("Failed to fetch normative forwarding path resource by tosca name, error {}", errorStatus);
@@ -1208,7 +1003,8 @@ public class ServiceBusinessLogic extends ComponentBusinessLogic {
         return forwardingPathOrigin.left().value();
     }
 
-    private void populateForwardingPaths(String serviceId, boolean isUpdate, Map<String, ForwardingPathDataDefinition> trimmedForwardingPaths, Map<String, ForwardingPathDataDefinition> resultMap) {
+    private void populateForwardingPaths(String serviceId, boolean isUpdate, Map<String, ForwardingPathDataDefinition> trimmedForwardingPaths,
+                                         Map<String, ForwardingPathDataDefinition> resultMap) {
         Either<ForwardingPathDataDefinition, StorageOperationStatus> result;
         try {
             for (ForwardingPathDataDefinition forwardingPathDataDefinition : trimmedForwardingPaths.values()) {
@@ -1219,24 +1015,22 @@ public class ServiceBusinessLogic extends ComponentBusinessLogic {
                 }
                 if (result.isRight()) {
                     janusGraphDao.rollback();
-                    throw new ByResponseFormatComponentException(componentsUtils.getResponseFormat(
-                        componentsUtils.convertFromStorageResponse(result.right().value(), ComponentTypeEnum.SERVICE),
-                        ""));
+                    throw new ByResponseFormatComponentException(componentsUtils
+                        .getResponseFormat(componentsUtils.convertFromStorageResponse(result.right().value(), ComponentTypeEnum.SERVICE), ""));
                 } else {
                     ForwardingPathDataDefinition fpDataDefinition = result.left().value();
                     resultMap.put(fpDataDefinition.getUniqueId(), forwardingPathDataDefinition);
                 }
             }
-
         } catch (ComponentException e) {
             janusGraphDao.rollback();
-            log.error("Exception occurred during add or update forwarding path property values: {}",
-                    e.getMessage(), e);
+            log.error("Exception occurred during add or update forwarding path property values: {}", e.getMessage(), e);
             throw new ByActionStatusComponentException(ActionStatus.GENERAL_ERROR);
         }
     }
 
-    private Service createServiceWithForwardingPathForResponse(String serviceId, Map<String,ForwardingPathDataDefinition> forwardingPathDataDefinitionMap) {
+    private Service createServiceWithForwardingPathForResponse(String serviceId,
+                                                               Map<String, ForwardingPathDataDefinition> forwardingPathDataDefinitionMap) {
         Service service = new Service();
         service.setUniqueId(serviceId);
         service.setForwardingPaths(forwardingPathDataDefinitionMap);
@@ -1250,87 +1044,70 @@ public class ServiceBusinessLogic extends ComponentBusinessLogic {
 
     @VisibleForTesting
     Either<Service, ResponseFormat> validateAndUpdateServiceMetadata(User user, Service currentService, Service serviceUpdate) {
-
         try {
             boolean hasBeenCertified = ValidationUtils.hasBeenCertified(currentService.getVersion());
-            Either<Boolean, ResponseFormat> response = validateAndUpdateCategory(user, currentService, serviceUpdate, hasBeenCertified, UPDATE_SERVICE_METADATA);
+            Either<Boolean, ResponseFormat> response = validateAndUpdateCategory(user, currentService, serviceUpdate, hasBeenCertified,
+                UPDATE_SERVICE_METADATA);
             if (response.isRight()) {
                 ResponseFormat errorResponse = response.right().value();
                 return Either.right(errorResponse);
             }
-
             verifyValuesAreIdentical(serviceUpdate.getCreatorUserId(), currentService.getCreatorUserId(), "creatorUserId");
             verifyValuesAreIdentical(serviceUpdate.getCreatorFullName(), currentService.getCreatorFullName(), "creatorFullName");
             verifyValuesAreIdentical(serviceUpdate.getLastUpdaterUserId(), currentService.getLastUpdaterUserId(), "lastUpdaterUserId");
             verifyValuesAreIdentical(serviceUpdate.getLastUpdaterFullName(), currentService.getLastUpdaterFullName(), "lastUpdaterFullName");
-
             response = validateAndUpdateServiceName(user, currentService, serviceUpdate, hasBeenCertified, null);
             if (response.isRight()) {
                 return Either.right(response.right().value());
             }
-
             verifyValuesAreIdentical(serviceUpdate.getDistributionStatus(), currentService.getDistributionStatus(), "distributionStatus");
-
             if (serviceUpdate.getProjectCode() != null) {
                 response = validateAndUpdateProjectCode(user, currentService, serviceUpdate, UPDATE_SERVICE_METADATA);
                 if (response.isRight()) {
                     return Either.right(response.right().value());
                 }
             }
-
             response = validateAndUpdateIcon(user, currentService, serviceUpdate, hasBeenCertified, UPDATE_SERVICE_METADATA);
             if (response.isRight()) {
                 return Either.right(response.right().value());
             }
-
             verifyValuesAreIdentical(serviceUpdate.getCreationDate(), currentService.getCreationDate(), "creationDate");
             verifyValuesAreIdentical(serviceUpdate.getVersion(), currentService.getVersion(), "version");
-
             response = validateAndUpdateDescription(user, currentService, serviceUpdate, UPDATE_SERVICE_METADATA);
             if (response.isRight()) {
                 return Either.right(response.right().value());
             }
-
             response = validateAndUpdateTags(user, currentService, serviceUpdate, UPDATE_SERVICE_METADATA);
             if (response.isRight()) {
                 return Either.right(response.right().value());
             }
-
             response = validateAndUpdateContactId(user, currentService, serviceUpdate, UPDATE_SERVICE_METADATA);
             if (response.isRight()) {
                 return Either.right(response.right().value());
             }
-
             verifyValuesAreIdentical(serviceUpdate.getLastUpdateDate(), currentService.getLastUpdateDate(), "lastUpdateDate");
             verifyValuesAreIdentical(serviceUpdate.getLifecycleState(), currentService.getLifecycleState(), "lifecycleState");
             verifyValuesAreIdentical(serviceUpdate.isHighestVersion(), currentService.isHighestVersion(), "isHighestVersion");
             verifyValuesAreIdentical(serviceUpdate.getUUID(), currentService.getUUID(), "uuid");
-
             validateAndUpdateServiceType(currentService, serviceUpdate);
             validateAndUpdateServiceFunction(currentService, serviceUpdate);
-
             response = validateAndUpdateServiceRole(user, currentService, serviceUpdate, UPDATE_SERVICE_METADATA);
             if (response.isRight()) {
                 return Either.right(response.right().value());
             }
-
             response = validateAndUpdateInstantiationTypeValue(user, currentService, serviceUpdate, UPDATE_SERVICE_METADATA);
             if (response.isRight()) {
                 return Either.right(response.right().value());
             }
-
             verifyValuesAreIdentical(serviceUpdate.getInvariantUUID(), currentService.getInvariantUUID(), "invariantUUID");
-
             validateAndUpdateEcompNaming(currentService, serviceUpdate);
-
             currentService.setEnvironmentContext(serviceUpdate.getEnvironmentContext());
             currentService.setCategorySpecificMetadata(serviceUpdate.getCategorySpecificMetadata());
             return Either.left(currentService);
-
         } catch (ComponentException exception) {
             ResponseFormat responseFormat = componentsUtils.getResponseFormat(exception);
-            componentsUtils.auditComponentAdmin(responseFormat, user, serviceUpdate,
-                    AuditingActionEnum.UPDATE_SERVICE_METADATA, ComponentTypeEnum.SERVICE);
+            componentsUtils
+                .auditComponentAdmin(responseFormat, user, serviceUpdate, AuditingActionEnum.UPDATE_SERVICE_METADATA, ComponentTypeEnum.SERVICE);
             return Either.right(responseFormat);
         }
     }
@@ -1358,7 +1135,8 @@ public class ServiceBusinessLogic extends ComponentBusinessLogic {
         }
     }
 
-    private Either<Boolean, ResponseFormat> validateAndUpdateContactId(User user, Service currentService, Service serviceUpdate, AuditingActionEnum audatingAction) {
+    private Either<Boolean, ResponseFormat> validateAndUpdateContactId(User user, Service currentService, Service serviceUpdate,
+                                                                       AuditingActionEnum audatingAction) {
         String contactIdUpdated = serviceUpdate.getContactId();
         String contactIdCurrent = currentService.getContactId();
         if (!contactIdCurrent.equals(contactIdUpdated)) {
@@ -1368,7 +1146,8 @@ public class ServiceBusinessLogic extends ComponentBusinessLogic {
         return Either.left(true);
     }
 
-    private Either<Boolean, ResponseFormat> validateAndUpdateTags(User user, Service currentService, Service serviceUpdate, AuditingActionEnum audatingAction) {
+    private Either<Boolean, ResponseFormat> validateAndUpdateTags(User user, Service currentService, Service serviceUpdate,
+                                                                  AuditingActionEnum audatingAction) {
         List<String> tagsUpdated = serviceUpdate.getTags();
         List<String> tagsCurrent = currentService.getTags();
         if (tagsUpdated == null || tagsUpdated.isEmpty()) {
@@ -1376,7 +1155,6 @@ public class ServiceBusinessLogic extends ComponentBusinessLogic {
             componentsUtils.auditComponentAdmin(responseFormat, user, serviceUpdate, audatingAction, ComponentTypeEnum.SERVICE);
             return Either.right(responseFormat);
         }
-
         if (!(tagsCurrent.containsAll(tagsUpdated) && tagsUpdated.containsAll(tagsCurrent))) {
             componentTagsValidator.validateAndCorrectField(user, serviceUpdate, audatingAction);
             currentService.setTags(tagsUpdated);
@@ -1384,7 +1162,8 @@ public class ServiceBusinessLogic extends ComponentBusinessLogic {
         return Either.left(true);
     }
 
-    private Either<Boolean, ResponseFormat> validateAndUpdateDescription(User user, Service currentService, Service serviceUpdate, AuditingActionEnum audatingAction) {
+    private Either<Boolean, ResponseFormat> validateAndUpdateDescription(User user, Service currentService, Service serviceUpdate,
+                                                                         AuditingActionEnum audatingAction) {
         String descriptionUpdated = serviceUpdate.getDescription();
         String descriptionCurrent = currentService.getDescription();
         if (!descriptionCurrent.equals(descriptionUpdated)) {
@@ -1394,12 +1173,11 @@ public class ServiceBusinessLogic extends ComponentBusinessLogic {
         return Either.left(true);
     }
 
-    private Either<Boolean, ResponseFormat> validateAndUpdateProjectCode(User user, Service currentService, Service serviceUpdate, AuditingActionEnum audatingAction) {
+    private Either<Boolean, ResponseFormat> validateAndUpdateProjectCode(User user, Service currentService, Service serviceUpdate,
+                                                                         AuditingActionEnum audatingAction) {
         String projectCodeUpdated = serviceUpdate.getProjectCode();
         String projectCodeCurrent = currentService.getProjectCode();
-        if (StringUtils.isEmpty(projectCodeCurrent)
-                || !projectCodeCurrent.equals(projectCodeUpdated)) {
-
+        if (StringUtils.isEmpty(projectCodeCurrent) || !projectCodeCurrent.equals(projectCodeUpdated)) {
             try {
                 componentProjectCodeValidator.validateAndCorrectField(user, serviceUpdate, audatingAction);
             } catch (ComponentException exp) {
@@ -1407,12 +1185,12 @@ public class ServiceBusinessLogic extends ComponentBusinessLogic {
                 return Either.right(errorRespons);
             }
             currentService.setProjectCode(projectCodeUpdated);
-
         }
         return Either.left(true);
     }
 
-    private Either<Boolean, ResponseFormat> validateAndUpdateIcon(User user, Service currentService, Service serviceUpdate, boolean hasBeenCertified, AuditingActionEnum audatingAction) {
+    private Either<Boolean, ResponseFormat> validateAndUpdateIcon(User user, Service currentService, Service serviceUpdate, boolean hasBeenCertified,
+                                                                  AuditingActionEnum audatingAction) {
         String iconUpdated = serviceUpdate.getIcon();
         String iconCurrent = currentService.getIcon();
         if (!iconCurrent.equals(iconUpdated)) {
@@ -1428,7 +1206,8 @@ public class ServiceBusinessLogic extends ComponentBusinessLogic {
         return Either.left(true);
     }
 
-    private Either<Boolean, ResponseFormat> validateAndUpdateServiceName(User user, Service currentService, Service serviceUpdate, boolean hasBeenCertified, AuditingActionEnum auditingAction) {
+    private Either<Boolean, ResponseFormat> validateAndUpdateServiceName(User user, Service currentService, Service serviceUpdate,
+                                                                         boolean hasBeenCertified, AuditingActionEnum auditingAction) {
         String serviceNameUpdated = serviceUpdate.getName();
         String serviceNameCurrent = currentService.getName();
         if (!serviceNameCurrent.equals(serviceNameUpdated)) {
@@ -1440,9 +1219,10 @@ public class ServiceBusinessLogic extends ComponentBusinessLogic {
                     return Either.right(exp.getResponseFormat());
                 }
                 currentService.setName(serviceNameUpdated);
-                currentService.getComponentMetadataDefinition().getMetadataDataDefinition().setNormalizedName(ValidationUtils.normaliseComponentName(serviceNameUpdated));
-                currentService.getComponentMetadataDefinition().getMetadataDataDefinition().setSystemName(ValidationUtils.convertToSystemName(serviceNameUpdated));
-
+                currentService.getComponentMetadataDefinition().getMetadataDataDefinition()
+                    .setNormalizedName(ValidationUtils.normaliseComponentName(serviceNameUpdated));
+                currentService.getComponentMetadataDefinition().getMetadataDataDefinition()
+                    .setSystemName(ValidationUtils.convertToSystemName(serviceNameUpdated));
             } else {
                 log.info("service name {} cannot be updated once the service has been certified once.", serviceNameUpdated);
                 ResponseFormat errorResponse = componentsUtils.getResponseFormat(ActionStatus.SERVICE_NAME_CANNOT_BE_CHANGED);
@@ -1470,7 +1250,8 @@ public class ServiceBusinessLogic extends ComponentBusinessLogic {
         }
     }
 
-    private Either<Boolean, ResponseFormat> validateAndUpdateServiceRole(User user, Service currentService, Service updatedService, AuditingActionEnum auditingAction) {
+    private Either<Boolean, ResponseFormat> validateAndUpdateServiceRole(User user, Service currentService, Service updatedService,
+                                                                         AuditingActionEnum auditingAction) {
         String updatedServiceRole = updatedService.getServiceRole();
         String currentServiceRole = currentService.getServiceRole();
         if (!currentServiceRole.equals(updatedServiceRole)) {
@@ -1486,8 +1267,9 @@ public class ServiceBusinessLogic extends ComponentBusinessLogic {
         return Either.left(true);
     }
 
-    private Either<Boolean, ResponseFormat> validateAndUpdateInstantiationTypeValue(User user, Service currentService, Service updatedService, AuditingActionEnum auditingAction) {
-        String updatedInstaType= updatedService.getInstantiationType();
+    private Either<Boolean, ResponseFormat> validateAndUpdateInstantiationTypeValue(User user, Service currentService, Service updatedService,
+                                                                                    AuditingActionEnum auditingAction) {
+        String updatedInstaType = updatedService.getInstantiationType();
         String currentInstaType = currentService.getInstantiationType();
         if (!currentInstaType.equals(updatedInstaType)) {
             try {
@@ -1502,7 +1284,8 @@ public class ServiceBusinessLogic extends ComponentBusinessLogic {
         return Either.left(true);
     }
 
-    private Either<Boolean, ResponseFormat> validateAndUpdateCategory(User user, Service currentService, Service serviceUpdate, boolean hasBeenCertified, AuditingActionEnum audatingAction) {
+    private Either<Boolean, ResponseFormat> validateAndUpdateCategory(User user, Service currentService, Service serviceUpdate,
+                                                                      boolean hasBeenCertified, AuditingActionEnum audatingAction) {
         try {
             List<CategoryDefinition> categoryUpdated = serviceUpdate.getCategories();
             List<CategoryDefinition> categoryCurrent = currentService.getCategories();
@@ -1520,32 +1303,27 @@ public class ServiceBusinessLogic extends ComponentBusinessLogic {
             return Either.right(exp.getResponseFormat());
         }
         return Either.left(true);
-
     }
 
     public Either<ServiceRelations, ResponseFormat> getServiceComponentsRelations(String serviceId, User user) {
         Either<Service, ResponseFormat> serviceResponseFormatEither = getService(serviceId, user);
-        if (serviceResponseFormatEither.isRight()){
+        if (serviceResponseFormatEither.isRight()) {
             return Either.right(serviceResponseFormatEither.right().value());
         }
-        final ServiceRelations serviceRelations = new ForwardingPathUtils().convertServiceToServiceRelations(serviceResponseFormatEither.left().value());
+        final ServiceRelations serviceRelations = new ForwardingPathUtils()
+            .convertServiceToServiceRelations(serviceResponseFormatEither.left().value());
         return Either.left(serviceRelations);
-
-
     }
 
     public ResponseFormat deleteService(String serviceId, User user) {
         ResponseFormat responseFormat;
-
         validateUserExists(user);
         Either<Service, StorageOperationStatus> serviceStatus = toscaOperationFacade.getToscaElement(serviceId);
         if (serviceStatus.isRight()) {
             log.debug("failed to get service {}", serviceId);
             return componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(serviceStatus.right().value()), "");
         }
-
         Service service = serviceStatus.left().value();
-
         StorageOperationStatus result = StorageOperationStatus.OK;
         try {
             lockComponent(service, "Mark service to delete");
@@ -1557,9 +1335,9 @@ public class ServiceBusinessLogic extends ComponentBusinessLogic {
                 responseFormat = componentsUtils.getResponseFormatByResource(actionStatus, service.getName());
             }
             return responseFormat;
-        }catch (ComponentException e){
+        } catch (ComponentException e) {
             return e.getResponseFormat();
-        }finally {
+        } finally {
             if (result == null || result != StorageOperationStatus.OK) {
                 log.warn("operation failed. do rollback");
                 BeEcompErrorManager.getInstance().logBeSystemError("Delete Service");
@@ -1577,15 +1355,12 @@ public class ServiceBusinessLogic extends ComponentBusinessLogic {
         String ecompErrorContext = "delete service";
         validateUserNotEmpty(user, ecompErrorContext);
         user = validateUserExists(user);
-
         Either<Service, ResponseFormat> getResult = getServiceByNameAndVersion(serviceName, version, user.getUserId());
         if (getResult.isRight()) {
             return getResult.right().value();
         }
         Service service = getResult.left().value();
-
         StorageOperationStatus result = StorageOperationStatus.OK;
-
         try {
             lockComponent(service, "Mark service to delete");
             result = markComponentToDelete(service);
@@ -1596,11 +1371,10 @@ public class ServiceBusinessLogic extends ComponentBusinessLogic {
                 responseFormat = componentsUtils.getResponseFormatByResource(actionStatus, service.getName());
             }
             return responseFormat;
-
-        }catch (ComponentException e){
+        } catch (ComponentException e) {
             result = StorageOperationStatus.GENERAL_ERROR;
             return componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR);
-        }finally {
+        } finally {
             if (result == null || result != StorageOperationStatus.OK) {
                 log.warn("operation failed. do rollback");
                 BeEcompErrorManager.getInstance().logBeSystemError("Delete Service");
@@ -1617,30 +1391,29 @@ public class ServiceBusinessLogic extends ComponentBusinessLogic {
         String ecompErrorContext = "Get service";
         validateUserNotEmpty(user, ecompErrorContext);
         validateUserExists(user);
-
         Either<Service, StorageOperationStatus> storageStatus = toscaOperationFacade.getToscaElement(serviceId);
         if (storageStatus.isRight()) {
             log.debug("failed to get service by id {}", serviceId);
-            return Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(storageStatus.right().value(), ComponentTypeEnum.SERVICE), serviceId));
+            return Either.right(componentsUtils
+                .getResponseFormat(componentsUtils.convertFromStorageResponse(storageStatus.right().value(), ComponentTypeEnum.SERVICE), serviceId));
         }
-
-        if(!(storageStatus.left().value() instanceof Service)){
-            return Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(StorageOperationStatus.NOT_FOUND), serviceId));
+        if (!(storageStatus.left().value() instanceof Service)) {
+            return Either
+                .right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(StorageOperationStatus.NOT_FOUND), serviceId));
         }
         Service service = storageStatus.left().value();
         return Either.left(service);
-
-
-
-
     }
 
     public Either<Service, ResponseFormat> getServiceByNameAndVersion(String serviceName, String serviceVersion, String userId) {
         validateUserExists(userId);
-        Either<Service, StorageOperationStatus> storageStatus = toscaOperationFacade.getComponentByNameAndVersion(ComponentTypeEnum.SERVICE, serviceName, serviceVersion);
+        Either<Service, StorageOperationStatus> storageStatus = toscaOperationFacade
+            .getComponentByNameAndVersion(ComponentTypeEnum.SERVICE, serviceName, serviceVersion);
         if (storageStatus.isRight()) {
             log.debug("failed to get service by name {} and version {}", serviceName, serviceVersion);
-            return Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(storageStatus.right().value(), ComponentTypeEnum.SERVICE), serviceName));
+            return Either.right(componentsUtils
+                .getResponseFormat(componentsUtils.convertFromStorageResponse(storageStatus.right().value(), ComponentTypeEnum.SERVICE),
+                    serviceName));
         }
         Service service = storageStatus.left().value();
         return Either.left(service);
@@ -1651,15 +1424,16 @@ public class ServiceBusinessLogic extends ComponentBusinessLogic {
         // create mandatory artifacts
 
         // TODO it must be removed after that artifact uniqueId creation will be
+
         // moved to ArtifactOperation
         String serviceUniqueId = service.getUniqueId();
         Map<String, ArtifactDefinition> artifactMap = service.getArtifacts();
-        if (artifactMap == null)
+        if (artifactMap == null) {
             artifactMap = new HashMap<>();
-
-        Map<String, Object> informationalServiceArtifacts = ConfigurationManager.getConfigurationManager().getConfiguration().getInformationalServiceArtifacts();
+        }
+        Map<String, Object> informationalServiceArtifacts = ConfigurationManager.getConfigurationManager().getConfiguration()
+            .getInformationalServiceArtifacts();
         List<String> exludeServiceCategory = ConfigurationManager.getConfigurationManager().getConfiguration().getExcludeServiceCategory();
-
         String category = service.getCategories().get(0).getName();
         boolean isCreateArtifact = true;
         if (category != null && exludeServiceCategory != null && !exludeServiceCategory.isEmpty()) {
@@ -1669,26 +1443,23 @@ public class ServiceBusinessLogic extends ComponentBusinessLogic {
                     break;
                 }
             }
-
         }
-
         if (informationalServiceArtifacts != null && isCreateArtifact) {
             Set<String> keys = informationalServiceArtifacts.keySet();
             for (String informationalServiceArtifactName : keys) {
                 Map<String, Object> artifactInfoMap = (Map<String, Object>) informationalServiceArtifacts.get(informationalServiceArtifactName);
-                ArtifactDefinition artifactDefinition = createArtifactDefinition(serviceUniqueId, informationalServiceArtifactName, artifactInfoMap, user, false);
+                ArtifactDefinition artifactDefinition = createArtifactDefinition(serviceUniqueId, informationalServiceArtifactName, artifactInfoMap,
+                    user, false);
                 artifactMap.put(artifactDefinition.getArtifactLabel(), artifactDefinition);
-
             }
-
             service.setArtifacts(artifactMap);
         }
     }
 
-    private ArtifactDefinition createArtifactDefinition(String serviceId, String logicalName, Map<String, Object> artifactInfoMap, User user, Boolean isServiceApi) {
-
-        ArtifactDefinition artifactInfo = artifactsBusinessLogic.createArtifactPlaceHolderInfo(serviceId, logicalName, artifactInfoMap, user, ArtifactGroupTypeEnum.INFORMATIONAL);
-
+    private ArtifactDefinition createArtifactDefinition(String serviceId, String logicalName, Map<String, Object> artifactInfoMap, User user,
+                                                        Boolean isServiceApi) {
+        ArtifactDefinition artifactInfo = artifactsBusinessLogic
+            .createArtifactPlaceHolderInfo(serviceId, logicalName, artifactInfoMap, user, ArtifactGroupTypeEnum.INFORMATIONAL);
         if (isServiceApi) {
             artifactInfo.setMandatory(false);
             artifactInfo.setServiceApi(true);
@@ -1702,21 +1473,21 @@ public class ServiceBusinessLogic extends ComponentBusinessLogic {
         return configuredEnvName;
     }
 
-    public Either<String, ResponseFormat> activateServiceOnTenantEnvironment(String serviceId, String envId, User modifier, ServiceDistributionReqInfo data) {
-
-        Either<ActivationRequestInformation, ResponseFormat> activationRequestInformationEither = serviceDistributionValidation.validateActivateServiceRequest(serviceId, envId, modifier, data);
+    public Either<String, ResponseFormat> activateServiceOnTenantEnvironment(String serviceId, String envId, User modifier,
+                                                                             ServiceDistributionReqInfo data) {
+        Either<ActivationRequestInformation, ResponseFormat> activationRequestInformationEither = serviceDistributionValidation
+            .validateActivateServiceRequest(serviceId, envId, modifier, data);
         if (activationRequestInformationEither.isRight()) {
             return Either.right(activationRequestInformationEither.right().value());
         }
-
         ActivationRequestInformation activationRequestInformation = activationRequestInformationEither.left().value();
-
         String did = ThreadLocalsHolder.getUuid();
         Service service = activationRequestInformation.getServiceToActivate();
         return buildAndSendServiceNotification(service, envId, did, activationRequestInformation.getWorkloadContext(), modifier);
     }
 
-    private Either<String, ResponseFormat> buildAndSendServiceNotification(Service service, String envId, String did, String workloadContext, User modifier) {
+    private Either<String, ResponseFormat> buildAndSendServiceNotification(Service service, String envId, String did, String workloadContext,
+                                                                           User modifier) {
         String envName = getEnvNameFromConfiguration();
         INotificationData notificationData = distributionEngine.buildServiceForDistribution(service, did, workloadContext);
         ActionStatus notifyServiceResponse = distributionEngine.notifyService(did, service, notificationData, envId, envName, modifier);
@@ -1731,21 +1502,19 @@ public class ServiceBusinessLogic extends ComponentBusinessLogic {
     }
 
     public Either<Service, ResponseFormat> activateDistribution(String serviceId, String envName, User modifier, HttpServletRequest request) {
-
         User user = validateUserExists(modifier.getUserId());
         validateUserRole(user, Collections.singletonList(Role.DESIGNER));
         Either<Service, ResponseFormat> result;
         ResponseFormat response;
         Service updatedService;
         String did = ThreadLocalsHolder.getUuid();
-         // DE194021
+        // DE194021
         String configuredEnvName = ConfigurationManager.getConfigurationManager().getDistributionEngineConfiguration().getEnvironments().get(0);
         if (configuredEnvName != null && !configuredEnvName.equals(envName)) {
             log.trace("Update environment name to be {} instead of {}", configuredEnvName, envName);
             envName = configuredEnvName;
         }
         // DE194021
-
         ServletContext servletContext = request.getSession().getServletContext();
         boolean isDistributionEngineUp = getHealthCheckBL(servletContext).isDistributionEngineUp(); // DE
         if (!isDistributionEngineUp) {
@@ -1754,16 +1523,13 @@ public class ServiceBusinessLogic extends ComponentBusinessLogic {
             response = componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR);
             return Either.right(response);
         }
-
         Either<Service, StorageOperationStatus> serviceRes = toscaOperationFacade.getToscaElement(serviceId);
         if (serviceRes.isRight()) {
             log.debug("failed retrieving service");
-            response = componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(serviceRes.right().value(), ComponentTypeEnum.SERVICE), serviceId);
+            response = componentsUtils
+                .getResponseFormat(componentsUtils.convertFromStorageResponse(serviceRes.right().value(), ComponentTypeEnum.SERVICE), serviceId);
             componentsUtils.auditComponent(response, user, null, AuditingActionEnum.DISTRIBUTION_STATE_CHANGE_REQUEST,
-                    new ResourceCommonInfo(ComponentTypeEnum.SERVICE.getValue()),
-                    ResourceVersionInfo.newBuilder()
-                            .build(),
-                    did);
+                new ResourceCommonInfo(ComponentTypeEnum.SERVICE.getValue()), ResourceVersionInfo.newBuilder().build(), did);
             return Either.right(response);
         }
         Service service = serviceRes.left().value();
@@ -1773,7 +1539,8 @@ public class ServiceBusinessLogic extends ComponentBusinessLogic {
         }
         if (service.getLifecycleState() != LifecycleStateEnum.CERTIFIED) {
             log.info("service {} is  not available for distribution. Should be in certified state", service.getUniqueId());
-            ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.SERVICE_NOT_AVAILABLE_FOR_DISTRIBUTION, service.getVersion(), service.getName());
+            ResponseFormat responseFormat = componentsUtils
+                .getResponseFormat(ActionStatus.SERVICE_NOT_AVAILABLE_FOR_DISTRIBUTION, service.getVersion(), service.getName());
             return Either.right(responseFormat);
         }
         String dcurrStatus = service.getDistributionStatus().name();
@@ -1783,7 +1550,8 @@ public class ServiceBusinessLogic extends ComponentBusinessLogic {
             INotificationData notificationData = distributionEngine.buildServiceForDistribution(service, did, null);
             ActionStatus notifyServiceResponse = distributionEngine.notifyService(did, service, notificationData, envName, user);
             if (notifyServiceResponse == ActionStatus.OK) {
-                Either<Service, ResponseFormat> updateStateRes = updateDistributionStatusForActivation(service, user, DistributionStatusEnum.DISTRIBUTED);
+                Either<Service, ResponseFormat> updateStateRes = updateDistributionStatusForActivation(service, user,
+                    DistributionStatusEnum.DISTRIBUTED);
                 if (updateStateRes.isLeft() && updateStateRes.left().value() != null) {
                     updatedService = updateStateRes.left().value();
                     updatedStatus = updatedService.getDistributionStatus().name();
@@ -1801,28 +1569,22 @@ public class ServiceBusinessLogic extends ComponentBusinessLogic {
                 result = Either.right(response);
             }
         } else {
-            response = componentsUtils.getResponseFormatByDE(componentsUtils.convertFromStorageResponse(readyForDistribution, ComponentTypeEnum.SERVICE), envName);
+            response = componentsUtils
+                .getResponseFormatByDE(componentsUtils.convertFromStorageResponse(readyForDistribution, ComponentTypeEnum.SERVICE), envName);
             result = Either.right(response);
         }
         componentsUtils.auditComponent(response, user, service, AuditingActionEnum.DISTRIBUTION_STATE_CHANGE_REQUEST,
-                new ResourceCommonInfo(service.getName(),ComponentTypeEnum.SERVICE.getValue()),
-                ResourceVersionInfo.newBuilder()
-                        .distributionStatus(dcurrStatus)
-                        .build(),
-                ResourceVersionInfo.newBuilder()
-                        .distributionStatus(updatedStatus)
-                        .build(),
-                null, null, did);
+            new ResourceCommonInfo(service.getName(), ComponentTypeEnum.SERVICE.getValue()),
+            ResourceVersionInfo.newBuilder().distributionStatus(dcurrStatus).build(),
+            ResourceVersionInfo.newBuilder().distributionStatus(updatedStatus).build(), null, null, did);
         return result;
     }
 
     // convert to private after deletion of temp url
     public Either<Service, ResponseFormat> updateDistributionStatusForActivation(Service service, User user, DistributionStatusEnum state) {
-
         validateUserExists(user.getUserId());
-
         String serviceId = service.getUniqueId();
-         lockComponent(serviceId, service, "updateDistributionStatusForActivation");
+        lockComponent(serviceId, service, "updateDistributionStatusForActivation");
         try {
             Either<Service, StorageOperationStatus> result = toscaOperationFacade.updateDistributionStatus(service, user, state);
             if (result.isRight()) {
@@ -1840,38 +1602,33 @@ public class ServiceBusinessLogic extends ComponentBusinessLogic {
     }
 
     public Either<Service, ResponseFormat> markDistributionAsDeployed(String serviceId, String did, User user) {
-
         validateUserExists(user.getUserId());
         log.debug("mark distribution deployed");
-
         AuditingActionEnum auditAction = AuditingActionEnum.DISTRIBUTION_DEPLOY;
         Either<Service, StorageOperationStatus> getServiceResponse = toscaOperationFacade.getToscaElement(serviceId);
         if (getServiceResponse.isRight()) {
-            BeEcompErrorManager.getInstance().logBeComponentMissingError("markDistributionAsDeployed", ComponentTypeEnum.SERVICE.getValue(), serviceId);
+            BeEcompErrorManager.getInstance()
+                .logBeComponentMissingError("markDistributionAsDeployed", ComponentTypeEnum.SERVICE.getValue(), serviceId);
             log.debug("service {} not found", serviceId);
-            ResponseFormat responseFormat = auditDeployError(did, user, auditAction, null, componentsUtils.convertFromStorageResponse(getServiceResponse.right().value(), ComponentTypeEnum.SERVICE), "");
-
+            ResponseFormat responseFormat = auditDeployError(did, user, auditAction, null,
+                componentsUtils.convertFromStorageResponse(getServiceResponse.right().value(), ComponentTypeEnum.SERVICE), "");
             return Either.right(responseFormat);
         }
-
         Service service = getServiceResponse.left().value();
         user = validateRoleForDeploy(did, user, auditAction, service);
         return checkDistributionAndDeploy(did, user, auditAction, service);
-
     }
 
     public Either<Service, ResponseFormat> generateVfModuleArtifacts(Service service, User modifier, boolean shouldLock, boolean inTransaction) {
         Function<ComponentInstance, List<ArtifactGenerator<ArtifactDefinition>>> artifactTaskGeneratorCreator = ri ->
-                // Only one VF Module Artifact per instance - add it to a list of one
-                buildArtifactGenList(service, modifier, shouldLock, inTransaction, ri);
-
+            // Only one VF Module Artifact per instance - add it to a list of one
+            buildArtifactGenList(service, modifier, shouldLock, inTransaction, ri);
         return generateDeploymentArtifacts(service, artifactTaskGeneratorCreator);
-
     }
 
-    private List<ArtifactGenerator<ArtifactDefinition>> buildArtifactGenList(Service service, User modifier, boolean shouldLock, boolean inTransaction, ComponentInstance ri) {
+    private List<ArtifactGenerator<ArtifactDefinition>> buildArtifactGenList(Service service, User modifier, boolean shouldLock,
+                                                                             boolean inTransaction, ComponentInstance ri) {
         List<ArtifactGenerator<ArtifactDefinition>> asList = new ArrayList<>();
-
         if (ri.getOriginType() == OriginTypeEnum.VF) {
             asList = Arrays.asList(new VfModuleArtifactGenerator(modifier, ri, service, shouldLock, inTransaction));
         }
@@ -1880,25 +1637,25 @@ public class ServiceBusinessLogic extends ComponentBusinessLogic {
 
     private List<GroupInstance> collectGroupsInstanceForCompInstance(ComponentInstance currVF) {
         Map<String, ArtifactDefinition> deploymentArtifacts = currVF.getDeploymentArtifacts();
-        if(currVF.getGroupInstances() != null){
+        if (currVF.getGroupInstances() != null) {
             currVF.getGroupInstances().forEach(gi -> gi.alignArtifactsUuid(deploymentArtifacts));
         }
         return currVF.getGroupInstances();
     }
 
-    private ArtifactDefinition getVfModuleInstArtifactForCompInstance(ComponentInstance currVF, Service service, Wrapper<String> payloadWrapper, Wrapper<ResponseFormat> responseWrapper) {
+    private ArtifactDefinition getVfModuleInstArtifactForCompInstance(ComponentInstance currVF, Service service, Wrapper<String> payloadWrapper,
+                                                                      Wrapper<ResponseFormat> responseWrapper) {
         ArtifactDefinition vfModuleAertifact = null;
         if (MapUtils.isNotEmpty(currVF.getDeploymentArtifacts())) {
-            final Optional<ArtifactDefinition> optionalVfModuleArtifact =
-                currVF.getDeploymentArtifacts().values().stream()
-                    .filter(p -> p.getArtifactType().equals(ArtifactTypeEnum.VF_MODULES_METADATA.getType()))
-                    .findAny();
+            final Optional<ArtifactDefinition> optionalVfModuleArtifact = currVF.getDeploymentArtifacts().values().stream()
+                .filter(p -> p.getArtifactType().equals(ArtifactTypeEnum.VF_MODULES_METADATA.getType())).findAny();
             if (optionalVfModuleArtifact.isPresent()) {
                 vfModuleAertifact = optionalVfModuleArtifact.get();
             }
         }
         if (vfModuleAertifact == null) {
-            Either<ArtifactDefinition, ResponseFormat> createVfModuleArtifact = createVfModuleArtifact(currVF, service, payloadWrapper.getInnerElement());
+            Either<ArtifactDefinition, ResponseFormat> createVfModuleArtifact = createVfModuleArtifact(currVF, service,
+                payloadWrapper.getInnerElement());
             if (createVfModuleArtifact.isLeft()) {
                 vfModuleAertifact = createVfModuleArtifact.left().value();
             } else {
@@ -1916,16 +1673,14 @@ public class ServiceBusinessLogic extends ComponentBusinessLogic {
                 vfModulePayloads.add(modulePayload);
             }
             vfModulePayloads.sort(VfModuleArtifactPayload::compareByGroupName);
-
             final Gson gson = new GsonBuilder().setPrettyPrinting().create();
-
             String vfModulePayloadString = gson.toJson(vfModulePayloads);
             payloadWrapper.setInnerElement(vfModulePayloadString);
         }
-
     }
 
-    private Either<ArtifactDefinition, ResponseFormat> generateVfModuleInstanceArtifact(User modifier, ComponentInstance currVFInstance, Service service, boolean shouldLock, boolean inTransaction) {
+    private Either<ArtifactDefinition, ResponseFormat> generateVfModuleInstanceArtifact(User modifier, ComponentInstance currVFInstance,
+                                                                                        Service service, boolean shouldLock, boolean inTransaction) {
         ArtifactDefinition vfModuleArtifact = null;
         Wrapper<ResponseFormat> responseWrapper = new Wrapper<>();
         Wrapper<String> payloadWrapper = new Wrapper<>();
@@ -1937,23 +1692,27 @@ public class ServiceBusinessLogic extends ComponentBusinessLogic {
             vfModuleArtifact = getVfModuleInstArtifactForCompInstance(currVFInstance, service, payloadWrapper, responseWrapper);
         }
         if (responseWrapper.isEmpty() && vfModuleArtifact != null) {
-            vfModuleArtifact = fillVfModulePayload(modifier, currVFInstance, vfModuleArtifact, shouldLock, inTransaction, payloadWrapper, responseWrapper, service);
+            vfModuleArtifact = fillVfModulePayload(modifier, currVFInstance, vfModuleArtifact, shouldLock, inTransaction, payloadWrapper,
+                responseWrapper, service);
         }
-
         Either<ArtifactDefinition, ResponseFormat> result;
         if (responseWrapper.isEmpty()) {
             result = Either.left(vfModuleArtifact);
         } else {
             result = Either.right(responseWrapper.getInnerElement());
         }
-
         return result;
     }
 
-    private ArtifactDefinition fillVfModulePayload(User modifier, ComponentInstance currVF, ArtifactDefinition vfModuleArtifact, boolean shouldLock, boolean inTransaction, Wrapper<String> payloadWrapper, Wrapper<ResponseFormat> responseWrapper, Service service) {
+    private ArtifactDefinition fillVfModulePayload(User modifier, ComponentInstance currVF, ArtifactDefinition vfModuleArtifact, boolean shouldLock,
+                                                   boolean inTransaction, Wrapper<String> payloadWrapper, Wrapper<ResponseFormat> responseWrapper,
+                                                   Service service) {
         ArtifactDefinition result = null;
-        Either<ArtifactDefinition, ResponseFormat> eitherPayload = artifactsBusinessLogic.generateArtifactPayload(vfModuleArtifact, ComponentTypeEnum.RESOURCE_INSTANCE, service, currVF.getName(), modifier, shouldLock, inTransaction, System::currentTimeMillis,
-                () -> Either.left(artifactsBusinessLogic.createEsArtifactData(vfModuleArtifact, payloadWrapper.getInnerElement().getBytes(StandardCharsets.UTF_8))), currVF.getUniqueId());
+        Either<ArtifactDefinition, ResponseFormat> eitherPayload = artifactsBusinessLogic
+            .generateArtifactPayload(vfModuleArtifact, ComponentTypeEnum.RESOURCE_INSTANCE, service, currVF.getName(), modifier, shouldLock,
+                inTransaction, System::currentTimeMillis, () -> Either.left(
+                    artifactsBusinessLogic.createEsArtifactData(vfModuleArtifact, payloadWrapper.getInnerElement().getBytes(StandardCharsets.UTF_8))),
+                currVF.getUniqueId());
         if (eitherPayload.isLeft()) {
             result = eitherPayload.left().value();
         } else {
@@ -1962,15 +1721,13 @@ public class ServiceBusinessLogic extends ComponentBusinessLogic {
         if (result == null) {
             result = vfModuleArtifact;
         }
-
         return result;
     }
 
-    private Either<ArtifactDefinition, ResponseFormat> createVfModuleArtifact(ComponentInstance currVF, Service service, String vfModulePayloadString) {
-
+    private Either<ArtifactDefinition, ResponseFormat> createVfModuleArtifact(ComponentInstance currVF, Service service,
+                                                                              String vfModulePayloadString) {
         ArtifactDefinition vfModuleArtifactDefinition = new ArtifactDefinition();
         String newCheckSum = null;
-
         vfModuleArtifactDefinition.setDescription("Auto-generated VF Modules information artifact");
         vfModuleArtifactDefinition.setArtifactDisplayName("Vf Modules Metadata");
         vfModuleArtifactDefinition.setArtifactType(ArtifactTypeEnum.VF_MODULES_METADATA.getType());
@@ -1983,54 +1740,54 @@ public class ServiceBusinessLogic extends ComponentBusinessLogic {
             newCheckSum = GeneralUtility.calculateMD5Base64EncodedByByteArray(vfModulePayloadString.getBytes());
         }
         vfModuleArtifactDefinition.setArtifactChecksum(newCheckSum);
-
-        Either<ArtifactDefinition, StorageOperationStatus> addArtifactToComponent = artifactToscaOperation.addArtifactToComponent(
-                vfModuleArtifactDefinition, service, NodeTypeEnum.ResourceInstance, true, currVF.getUniqueId());
-
+        Either<ArtifactDefinition, StorageOperationStatus> addArtifactToComponent = artifactToscaOperation
+            .addArtifactToComponent(vfModuleArtifactDefinition, service, NodeTypeEnum.ResourceInstance, true, currVF.getUniqueId());
         Either<ArtifactDefinition, ResponseFormat> result;
         if (addArtifactToComponent.isLeft()) {
             result = Either.left(addArtifactToComponent.left().value());
         } else {
-            result = Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(addArtifactToComponent.right().value())));
+            result = Either
+                .right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(addArtifactToComponent.right().value())));
         }
-
         return result;
     }
 
     public Either<Service, ResponseFormat> generateHeatEnvArtifacts(Service service, User modifier, boolean shouldLock, boolean inTransaction) {
-
         Function<ComponentInstance, List<ArtifactGenerator<ArtifactDefinition>>> artifactTaskGeneratorCreator = resourceInstance ->
-                // Get All Deployment Artifacts
-                service.getComponentInstances().stream().filter(ri -> ri != null && ri == resourceInstance).filter(ri -> ri.getDeploymentArtifacts() != null).flatMap(ri -> ri.getDeploymentArtifacts().values().stream()).
-                        // Filter in Only Heat Env
-                                filter(depArtifact -> ArtifactTypeEnum.HEAT_ENV.getType().equals(depArtifact.getArtifactType())).
-                        // Create ArtifactGenerator from those Artifacts
-                                map(depArtifact -> new HeatEnvArtifactGenerator(depArtifact, service, resourceInstance.getName(), modifier, shouldLock, inTransaction, resourceInstance.getUniqueId())).collect(Collectors.toList());
-
+            // Get All Deployment Artifacts
+            service.getComponentInstances().stream().filter(ri -> ri != null && ri == resourceInstance)
+                .filter(ri -> ri.getDeploymentArtifacts() != null).flatMap(ri -> ri.getDeploymentArtifacts().values().stream()).
+                // Filter in Only Heat Env
+                    filter(depArtifact -> ArtifactTypeEnum.HEAT_ENV.getType().equals(depArtifact.getArtifactType())).
+                // Create ArtifactGenerator from those Artifacts
+                    map(
+                    depArtifact -> new HeatEnvArtifactGenerator(depArtifact, service, resourceInstance.getName(), modifier, shouldLock, inTransaction,
+                        resourceInstance.getUniqueId())).collect(Collectors.toList());
         return generateDeploymentArtifacts(service, artifactTaskGeneratorCreator);
-
     }
 
-    private <CallVal> Either<Service, ResponseFormat> generateDeploymentArtifacts(Service service, Function<ComponentInstance, List<ArtifactGenerator<CallVal>>> artifactTaskGeneratorCreator) {
-
+    private <CallVal> Either<Service, ResponseFormat> generateDeploymentArtifacts(Service service,
+                                                                                  Function<ComponentInstance, List<ArtifactGenerator<CallVal>>> artifactTaskGeneratorCreator) {
         // Get Flat List of (Callable) ArtifactGenerator for all the RI in the
+
         // service
         if (service.getComponentInstances() != null) {
-            List<ArtifactGenerator<CallVal>> artifactGenList = service.getComponentInstances().stream().flatMap(ri -> artifactTaskGeneratorCreator.apply(ri).stream()).collect(Collectors.toList());
+            List<ArtifactGenerator<CallVal>> artifactGenList = service.getComponentInstances().stream()
+                .flatMap(ri -> artifactTaskGeneratorCreator.apply(ri).stream()).collect(Collectors.toList());
             if (artifactGenList != null && !artifactGenList.isEmpty()) {
                 Either<Service, ResponseFormat> callRes = checkDeploymentArtifact(artifactGenList);
-                if (callRes != null) return callRes;
+                if (callRes != null) {
+                    return callRes;
+                }
             }
         }
         Either<Service, StorageOperationStatus> storageStatus = toscaOperationFacade.getToscaFullElement(service.getUniqueId());
         if (storageStatus.isRight()) {
-            return Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(storageStatus.right().value(), ComponentTypeEnum.SERVICE), ""));
+            return Either.right(componentsUtils
+                .getResponseFormat(componentsUtils.convertFromStorageResponse(storageStatus.right().value(), ComponentTypeEnum.SERVICE), ""));
         }
-
         Service currentService = storageStatus.left().value();
-
         return Either.left(currentService);
-
     }
 
     private <CallVal> Either<Service, ResponseFormat> checkDeploymentArtifact(List<ArtifactGenerator<CallVal>> artifactGenList) {
@@ -2050,61 +1807,8 @@ public class ServiceBusinessLogic extends ComponentBusinessLogic {
         return null;
     }
 
-    abstract class ArtifactGenerator<CallVal> implements Callable<Either<CallVal, ResponseFormat>> {
-
-    }
-
-    @Getter
-    class HeatEnvArtifactGenerator extends ArtifactGenerator<ArtifactDefinition> {
-        private ArtifactDefinition artifactDefinition;
-        private Service service;
-        private String resourceInstanceName;
-        private User modifier;
-        private String instanceId;
-        private boolean shouldLock;
-        private boolean inTransaction;
-
-        HeatEnvArtifactGenerator(ArtifactDefinition artifactDefinition, Service service, String resourceInstanceName, User modifier, boolean shouldLock, boolean inTransaction, String instanceId) {
-            this.artifactDefinition = artifactDefinition;
-            this.service = service;
-            this.resourceInstanceName = resourceInstanceName;
-            this.modifier = modifier;
-            this.shouldLock = shouldLock;
-            this.instanceId = instanceId;
-            this.inTransaction = inTransaction;
-        }
-
-        @Override
-        public Either<ArtifactDefinition, ResponseFormat> call() throws Exception {
-            return artifactsBusinessLogic.forceGenerateHeatEnvArtifact(artifactDefinition, ComponentTypeEnum.RESOURCE_INSTANCE, service, resourceInstanceName, modifier, shouldLock, inTransaction, instanceId);
-        }
-
-    }
-
-    class VfModuleArtifactGenerator extends ArtifactGenerator<ArtifactDefinition> {
-        private User user;
-        private ComponentInstance componentInstance;
-        private Service service;
-        boolean shouldLock;
-        boolean inTransaction;
-
-        @Override
-        public Either<ArtifactDefinition, ResponseFormat> call() throws Exception {
-            return generateVfModuleInstanceArtifact(user, componentInstance, service, shouldLock, inTransaction);
-        }
-
-        private VfModuleArtifactGenerator(User user, ComponentInstance componentInstance, Service service, boolean shouldLock, boolean inTransaction) {
-            super();
-            this.user = user;
-            this.componentInstance = componentInstance;
-            this.service = service;
-            this.shouldLock = shouldLock;
-            this.inTransaction = inTransaction;
-        }
-
-    }
-
-    private synchronized Either<Service, ResponseFormat> checkDistributionAndDeploy(String distributionId, User user, AuditingActionEnum auditAction, Service service) {
+    private synchronized Either<Service, ResponseFormat> checkDistributionAndDeploy(String distributionId, User user, AuditingActionEnum auditAction,
+                                                                                    Service service) {
         boolean isDeployed = isDistributionDeployed(distributionId);
         if (isDeployed) {
             return Either.left(service);
@@ -2113,15 +1817,16 @@ public class ServiceBusinessLogic extends ComponentBusinessLogic {
         if (distributionSuccess.isRight()) {
             return Either.right(distributionSuccess.right().value());
         }
-
         log.debug("mark distribution {} as deployed - success", distributionId);
-        componentsUtils.auditServiceDistributionDeployed(service.getName(), service.getVersion(), service.getUUID(), distributionId, STATUS_DEPLOYED, "OK", user);
+        componentsUtils
+            .auditServiceDistributionDeployed(service.getName(), service.getVersion(), service.getUUID(), distributionId, STATUS_DEPLOYED, "OK",
+                user);
         return Either.left(service);
     }
 
     private boolean isDistributionDeployed(String distributionId) {
-        Either<List<DistributionDeployEvent>, ActionStatus> alreadyDeployed = auditCassandraDao.getDistributionDeployByStatus(distributionId, AuditingActionEnum.DISTRIBUTION_DEPLOY.getName(), STATUS_DEPLOYED);
-
+        Either<List<DistributionDeployEvent>, ActionStatus> alreadyDeployed = auditCassandraDao
+            .getDistributionDeployByStatus(distributionId, AuditingActionEnum.DISTRIBUTION_DEPLOY.getName(), STATUS_DEPLOYED);
         boolean isDeployed = false;
         if (alreadyDeployed.isLeft() && !alreadyDeployed.left().value().isEmpty()) {
             // already deployed
@@ -2132,16 +1837,14 @@ public class ServiceBusinessLogic extends ComponentBusinessLogic {
     }
 
     protected Either<Boolean, ResponseFormat> checkDistributionSuccess(String did, User user, AuditingActionEnum auditAction, Service service) {
-
         log.trace("checkDistributionSuccess");
         // get all "DRequest" records for this distribution
-
-        Either<List<ResourceAdminEvent>, ActionStatus> distRequestsResponse = auditCassandraDao.getDistributionRequest(did, AuditingActionEnum.DISTRIBUTION_STATE_CHANGE_REQUEST.getName());
+        Either<List<ResourceAdminEvent>, ActionStatus> distRequestsResponse = auditCassandraDao
+            .getDistributionRequest(did, AuditingActionEnum.DISTRIBUTION_STATE_CHANGE_REQUEST.getName());
         if (distRequestsResponse.isRight()) {
             ResponseFormat error = auditDeployError(did, user, auditAction, service, distRequestsResponse.right().value());
             return Either.right(error);
         }
-
         List<ResourceAdminEvent> distributionRequests = distRequestsResponse.left().value();
         if (distributionRequests.isEmpty()) {
             BeEcompErrorManager.getInstance().logBeDistributionMissingError("markDistributionAsDeployed", did);
@@ -2157,14 +1860,13 @@ public class ServiceBusinessLogic extends ComponentBusinessLogic {
                 break;
             }
         }
-
         // get all "DNotify" records for this distribution
-        Either<List<DistributionNotificationEvent>, ActionStatus> distNotificationsResponse = auditCassandraDao.getDistributionNotify(did, AuditingActionEnum.DISTRIBUTION_NOTIFY.getName());
+        Either<List<DistributionNotificationEvent>, ActionStatus> distNotificationsResponse = auditCassandraDao
+            .getDistributionNotify(did, AuditingActionEnum.DISTRIBUTION_NOTIFY.getName());
         if (distNotificationsResponse.isRight()) {
             ResponseFormat error = auditDeployError(did, user, auditAction, service, distNotificationsResponse.right().value());
             return Either.right(error);
         }
-
         List<DistributionNotificationEvent> distributionNotifications = distNotificationsResponse.left().value();
         boolean isNotificationsSucceeded = false;
         for (DistributionNotificationEvent event : distributionNotifications) {
@@ -2174,10 +1876,8 @@ public class ServiceBusinessLogic extends ComponentBusinessLogic {
                 break;
             }
         }
-
         // if request failed OR there are notifications that failed
         if (!(isRequestSucceeded && isNotificationsSucceeded)) {
-
             log.info("distribution {} has failed", did);
             ResponseFormat error = componentsUtils.getResponseFormat(ActionStatus.DISTRIBUTION_REQUESTED_FAILED, did);
             auditDeployError(did, user, auditAction, service, ActionStatus.DISTRIBUTION_REQUESTED_FAILED, did);
@@ -2186,17 +1886,18 @@ public class ServiceBusinessLogic extends ComponentBusinessLogic {
         return Either.left(true);
     }
 
-    private ResponseFormat auditDeployError(String did, User user, AuditingActionEnum auditAction, Service service, ActionStatus status, String... params) {
-
+    private ResponseFormat auditDeployError(String did, User user, AuditingActionEnum auditAction, Service service, ActionStatus status,
+                                            String... params) {
         ResponseFormat error = componentsUtils.getResponseFormat(status, params);
         String message = "";
         if (error.getMessageId() != null) {
             message = error.getMessageId() + ": ";
         }
         message += error.getFormattedMessage();
-
         if (service != null) {
-            componentsUtils.auditServiceDistributionDeployed(service.getName(), service.getVersion(), service.getUUID(), did, error.getStatus().toString(), message, user);
+            componentsUtils
+                .auditServiceDistributionDeployed(service.getName(), service.getVersion(), service.getUUID(), did, error.getStatus().toString(),
+                    message, user);
         } else {
             componentsUtils.auditServiceDistributionDeployed("", "", "", did, error.getStatus().toString(), message, user);
         }
@@ -2209,9 +1910,9 @@ public class ServiceBusinessLogic extends ComponentBusinessLogic {
         List<Role> roles = new ArrayList<>();
         roles.add(Role.ADMIN);
         roles.add(Role.DESIGNER);
-        try{
+        try {
             validateUserRole(user, service, roles, auditAction, null);
-        } catch (ByActionStatusComponentException e){
+        } catch (ByActionStatusComponentException e) {
             log.info("role {} is not allowed to perform this action", user.getRole());
             auditDeployError(did, user, auditAction, service, e.getActionStatus());
             throw e;
@@ -2221,28 +1922,27 @@ public class ServiceBusinessLogic extends ComponentBusinessLogic {
 
     @Override
     public void setDeploymentArtifactsPlaceHolder(Component component, User user) {
-        if(component instanceof Service){
+        if (component instanceof Service) {
             Service service = (Service) component;
             Map<String, ArtifactDefinition> artifactMap = service.getDeploymentArtifacts();
             if (artifactMap == null) {
                 artifactMap = new HashMap<>();
             }
             service.setDeploymentArtifacts(artifactMap);
-        }else if(component instanceof Resource){
+        } else if (component instanceof Resource) {
             Resource resource = (Resource) component;
             Map<String, ArtifactDefinition> artifactMap = resource.getDeploymentArtifacts();
             if (artifactMap == null) {
                 artifactMap = new HashMap<>();
             }
-            Map<String, Object> deploymentResourceArtifacts = ConfigurationManager.getConfigurationManager()
-                                                                      .getConfiguration().getDeploymentResourceArtifacts();
+            Map<String, Object> deploymentResourceArtifacts = ConfigurationManager.getConfigurationManager().getConfiguration()
+                .getDeploymentResourceArtifacts();
             if (deploymentResourceArtifacts != null) {
                 Map<String, ArtifactDefinition> finalArtifactMap = artifactMap;
-                deploymentResourceArtifacts.forEach((k, v)->processDeploymentResourceArtifacts(user, resource, finalArtifactMap, k,v));
+                deploymentResourceArtifacts.forEach((k, v) -> processDeploymentResourceArtifacts(user, resource, finalArtifactMap, k, v));
             }
             resource.setDeploymentArtifacts(artifactMap);
         }
-
     }
 
     private void processDeploymentResourceArtifacts(User user, Resource resource, Map<String, ArtifactDefinition> artifactMap, String k, Object v) {
@@ -2254,15 +1954,12 @@ public class ServiceBusinessLogic extends ComponentBusinessLogic {
                 return;
             }
         } else {
-            log.info("resource types for artifact placeholder {} were not defined. default is all resources",
-                    k);
+            log.info("resource types for artifact placeholder {} were not defined. default is all resources", k);
         }
         if (artifactsBusinessLogic != null) {
-            ArtifactDefinition artifactDefinition = artifactsBusinessLogic.createArtifactPlaceHolderInfo(
-                    resource.getUniqueId(), k, (Map<String, Object>) v,
-                    user, ArtifactGroupTypeEnum.DEPLOYMENT);
-            if (artifactDefinition != null
-                    && !artifactMap.containsKey(artifactDefinition.getArtifactLabel())) {
+            ArtifactDefinition artifactDefinition = artifactsBusinessLogic
+                .createArtifactPlaceHolderInfo(resource.getUniqueId(), k, (Map<String, Object>) v, user, ArtifactGroupTypeEnum.DEPLOYMENT);
+            if (artifactDefinition != null && !artifactMap.containsKey(artifactDefinition.getArtifactLabel())) {
                 artifactMap.put(artifactDefinition.getArtifactLabel(), artifactDefinition);
             }
         }
@@ -2274,7 +1971,8 @@ public class ServiceBusinessLogic extends ComponentBusinessLogic {
     }
 
     private HealthCheckBusinessLogic getHealthCheckBL(ServletContext context) {
-        WebAppContextWrapper webApplicationContextWrapper = (WebAppContextWrapper) context.getAttribute(Constants.WEB_APPLICATION_CONTEXT_WRAPPER_ATTR);
+        WebAppContextWrapper webApplicationContextWrapper = (WebAppContextWrapper) context
+            .getAttribute(Constants.WEB_APPLICATION_CONTEXT_WRAPPER_ATTR);
         WebApplicationContext webApplicationContext = webApplicationContextWrapper.getWebAppContext(context);
         return webApplicationContext.getBean(HealthCheckBusinessLogic.class);
     }
@@ -2286,16 +1984,14 @@ public class ServiceBusinessLogic extends ComponentBusinessLogic {
 
     @Override
     public Either<List<ComponentInstance>, ResponseFormat> getComponentInstancesFilteredByPropertiesAndInputs(String componentId, String userId) {
-
         validateUserExists(userId);
         Either<Component, StorageOperationStatus> getComponentRes = toscaOperationFacade.getToscaElement(componentId, JsonParseFlagEnum.ParseAll);
         if (getComponentRes.isRight()) {
-            ResponseFormat responseFormat = componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(getComponentRes.right().value()));
+            ResponseFormat responseFormat = componentsUtils
+                .getResponseFormat(componentsUtils.convertFromStorageResponse(getComponentRes.right().value()));
             return Either.right(responseFormat);
         }
-
         List<ComponentInstance> componentInstances = getComponentRes.left().value().getComponentInstances();
-
         return Either.left(componentInstances);
     }
 
@@ -2305,11 +2001,12 @@ public class ServiceBusinessLogic extends ComponentBusinessLogic {
     }
 
     /**
-     * updates group instance with new property values in case of successful update of group instance related component instance will be updated with new modification time and related service will be updated with new last update date
-     *
+     * updates group instance with new property values in case of successful update of group instance related component instance will be updated with
+     * new modification time and related service will be updated with new last update date
      */
-    public Either<List<GroupInstanceProperty>, ResponseFormat> updateGroupInstancePropertyValues(User modifier, String serviceId, String componentInstanceId, String groupInstanceId, List<GroupInstanceProperty> newProperties) {
-
+    public Either<List<GroupInstanceProperty>, ResponseFormat> updateGroupInstancePropertyValues(User modifier, String serviceId,
+                                                                                                 String componentInstanceId, String groupInstanceId,
+                                                                                                 List<GroupInstanceProperty> newProperties) {
         Either<List<GroupInstanceProperty>, ResponseFormat> actionResult = null;
         Either<ImmutablePair<Component, User>, ResponseFormat> validateUserAndComponentRes;
         Component component = null;
@@ -2332,9 +2029,11 @@ public class ServiceBusinessLogic extends ComponentBusinessLogic {
                 }
             }
             if (actionResult == null) {
-                actionResult = validateAndUpdateGroupInstancePropertyValuesAndContainingParents(component, componentInstanceId, groupInstanceId, newProperties);
+                actionResult = validateAndUpdateGroupInstancePropertyValuesAndContainingParents(component, componentInstanceId, groupInstanceId,
+                    newProperties);
                 if (actionResult.isRight()) {
-                    log.debug("Failed to validate and update group instance {} property values and containing parents. The message is {}. ", groupInstanceId, actionResult.right().value().getFormattedMessage());
+                    log.debug("Failed to validate and update group instance {} property values and containing parents. The message is {}. ",
+                        groupInstanceId, actionResult.right().value().getFormattedMessage());
                 }
             }
         } catch (Exception e) {
@@ -2348,8 +2047,10 @@ public class ServiceBusinessLogic extends ComponentBusinessLogic {
         return actionResult;
     }
 
-    private Either<List<GroupInstanceProperty>, ResponseFormat> validateAndUpdateGroupInstancePropertyValuesAndContainingParents(Component component, String componentInstanceId, String groupInstanceId, List<GroupInstanceProperty> newProperties) {
-
+    private Either<List<GroupInstanceProperty>, ResponseFormat> validateAndUpdateGroupInstancePropertyValuesAndContainingParents(Component component,
+                                                                                                                                 String componentInstanceId,
+                                                                                                                                 String groupInstanceId,
+                                                                                                                                 List<GroupInstanceProperty> newProperties) {
         Either<List<GroupInstanceProperty>, ResponseFormat> actionResult = null;
         Either<ImmutablePair<ComponentInstance, GroupInstance>, ResponseFormat> findGroupInstanceRes;
         Either<ImmutablePair<ComponentMetadataData, ComponentInstanceData>, ResponseFormat> updateParentsModificationTimeRes;
@@ -2366,18 +2067,23 @@ public class ServiceBusinessLogic extends ComponentBusinessLogic {
         if (actionResult == null) {
             oldGroupInstance = findGroupInstanceRes.left().value().getValue();
             relatedComponentInstance = findGroupInstanceRes.left().value().getKey();
-            updateGroupInstanceResult = groupBusinessLogic.validateAndUpdateGroupInstancePropertyValues(component.getUniqueId(), componentInstanceId, oldGroupInstance, newProperties);
+            updateGroupInstanceResult = groupBusinessLogic
+                .validateAndUpdateGroupInstancePropertyValues(component.getUniqueId(), componentInstanceId, oldGroupInstance, newProperties);
             if (updateGroupInstanceResult.isRight()) {
-                log.debug("#validateAndUpdateGroupInstancePropertyValuesAndContainingParents - Failed to update group instance {} property values. ", oldGroupInstance.getName());
+                log.debug("#validateAndUpdateGroupInstancePropertyValuesAndContainingParents - Failed to update group instance {} property values. ",
+                    oldGroupInstance.getName());
                 actionResult = Either.right(updateGroupInstanceResult.right().value());
             }
         }
         if (actionResult == null) {
             updatedGroupInstance = updateGroupInstanceResult.left().value();
             if (!oldGroupInstance.getModificationTime().equals(updatedGroupInstance.getModificationTime())) {
-                updateParentsModificationTimeRes = updateParentsModificationTimeAndCustomizationUuid(component, relatedComponentInstance, updatedGroupInstance, inTransaction);
+                updateParentsModificationTimeRes = updateParentsModificationTimeAndCustomizationUuid(component, relatedComponentInstance,
+                    updatedGroupInstance, inTransaction);
                 if (updateParentsModificationTimeRes.isRight()) {
-                    log.debug("#validateAndUpdateGroupInstancePropertyValuesAndContainingParents - Failed to update modification time for group instance {}. ", oldGroupInstance.getName());
+                    log.debug(
+                        "#validateAndUpdateGroupInstancePropertyValuesAndContainingParents - Failed to update modification time for group instance {}. ",
+                        oldGroupInstance.getName());
                     actionResult = Either.right(updateParentsModificationTimeRes.right().value());
                 }
             }
@@ -2388,30 +2094,33 @@ public class ServiceBusinessLogic extends ComponentBusinessLogic {
         return actionResult;
     }
 
-    private Either<ImmutablePair<ComponentMetadataData, ComponentInstanceData>, ResponseFormat> updateParentsModificationTimeAndCustomizationUuid(Component component, ComponentInstance relatedComponentInstance, GroupInstance updatedGroupInstance,
-                                                                                                                                                  boolean inTranscation) {
-
+    private Either<ImmutablePair<ComponentMetadataData, ComponentInstanceData>, ResponseFormat> updateParentsModificationTimeAndCustomizationUuid(
+        Component component, ComponentInstance relatedComponentInstance, GroupInstance updatedGroupInstance, boolean inTranscation) {
         Either<ImmutablePair<ComponentMetadataData, ComponentInstanceData>, ResponseFormat> actionResult;
         Either<ComponentMetadataData, StorageOperationStatus> serviceMetadataUpdateResult;
-        Either<ComponentInstanceData, ResponseFormat> updateComponentInstanceRes = componentInstanceBusinessLogic.updateComponentInstanceModificationTimeAndCustomizationUuid(relatedComponentInstance, NodeTypeEnum.ResourceInstance,
+        Either<ComponentInstanceData, ResponseFormat> updateComponentInstanceRes = componentInstanceBusinessLogic
+            .updateComponentInstanceModificationTimeAndCustomizationUuid(relatedComponentInstance, NodeTypeEnum.ResourceInstance,
                 updatedGroupInstance.getModificationTime(), inTranscation);
         if (updateComponentInstanceRes.isRight()) {
-            log.debug("Failed to update component instance {} after update of group instance {}. ", relatedComponentInstance.getName(), updatedGroupInstance.getName());
+            log.debug("Failed to update component instance {} after update of group instance {}. ", relatedComponentInstance.getName(),
+                updatedGroupInstance.getName());
             actionResult = Either.right(updateComponentInstanceRes.right().value());
         } else {
             serviceMetadataUpdateResult = toscaOperationFacade.updateComponentLastUpdateDateOnGraph(component);
             if (serviceMetadataUpdateResult.isRight()) {
-                log.debug("Failed to update service {} after update of component instance {} with new property values of group instance {}. ", component.getName(), relatedComponentInstance.getName(), updatedGroupInstance.getName());
-                actionResult = Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(serviceMetadataUpdateResult.right().value())));
+                log.debug("Failed to update service {} after update of component instance {} with new property values of group instance {}. ",
+                    component.getName(), relatedComponentInstance.getName(), updatedGroupInstance.getName());
+                actionResult = Either.right(
+                    componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(serviceMetadataUpdateResult.right().value())));
             } else {
-                actionResult = Either.left(new ImmutablePair<>(serviceMetadataUpdateResult.left().value(), updateComponentInstanceRes.left().value()));
+                actionResult = Either
+                    .left(new ImmutablePair<>(serviceMetadataUpdateResult.left().value(), updateComponentInstanceRes.left().value()));
             }
         }
         return actionResult;
     }
 
     private Either<ImmutablePair<Component, User>, ResponseFormat> validateUserAndComponent(String serviceId, User modifier) {
-
         Either<ImmutablePair<Component, User>, ResponseFormat> result = null;
         User currUser = null;
         Component component = null;
@@ -2425,7 +2134,8 @@ public class ServiceBusinessLogic extends ComponentBusinessLogic {
             try {
                 component = validateComponentExists(serviceId, ComponentTypeEnum.SERVICE, null);
                 if (!ComponentValidationUtils.canWorkOnComponent(component, currUser.getUserId())) {
-                    log.info("#validateUserAndComponent - Restricted operation for user: {}, on service: {}", currUser.getUserId(), component.getCreatorUserId());
+                    log.info("#validateUserAndComponent - Restricted operation for user: {}, on service: {}", currUser.getUserId(),
+                        component.getCreatorUserId());
                     return Either.right(componentsUtils.getResponseFormat(ActionStatus.RESTRICTED_OPERATION));
                 }
             } catch (ComponentException e) {
@@ -2433,27 +2143,31 @@ public class ServiceBusinessLogic extends ComponentBusinessLogic {
                 result = Either.right(e.getResponseFormat());
             }
         }
-
         if (result == null) {
             result = Either.left(new ImmutablePair<>(component, currUser));
         }
         return result;
     }
 
-    private Either<ImmutablePair<ComponentInstance, GroupInstance>, ResponseFormat> findGroupInstanceOnRelatedComponentInstance(Component component, String componentInstanceId, String groupInstanceId) {
-
+    private Either<ImmutablePair<ComponentInstance, GroupInstance>, ResponseFormat> findGroupInstanceOnRelatedComponentInstance(Component component,
+                                                                                                                                String componentInstanceId,
+                                                                                                                                String groupInstanceId) {
         Either<ImmutablePair<ComponentInstance, GroupInstance>, ResponseFormat> actionResult = null;
         GroupInstance groupInstance = null;
         ComponentInstance foundComponentInstance = findRelatedComponentInstance(component, componentInstanceId);
         if (foundComponentInstance == null) {
             log.debug("Component instance {} not found on service {}. ", componentInstanceId, component.getName());
-            actionResult = Either.right(componentsUtils.getResponseFormat(ActionStatus.COMPONENT_INSTANCE_NOT_FOUND_ON_CONTAINER, componentInstanceId, "resource instance", "service", component.getName()));
-        }
-        else if (isNotEmpty(foundComponentInstance.getGroupInstances())) {
-            groupInstance = foundComponentInstance.getGroupInstances().stream().filter(gi -> gi.getUniqueId().equals(groupInstanceId)).findFirst().orElse(null);
+            actionResult = Either.right(componentsUtils
+                .getResponseFormat(ActionStatus.COMPONENT_INSTANCE_NOT_FOUND_ON_CONTAINER, componentInstanceId, "resource instance", "service",
+                    component.getName()));
+        } else if (isNotEmpty(foundComponentInstance.getGroupInstances())) {
+            groupInstance = foundComponentInstance.getGroupInstances().stream().filter(gi -> gi.getUniqueId().equals(groupInstanceId)).findFirst()
+                .orElse(null);
             if (groupInstance == null) {
                 log.debug("Group instance {} not found on component instance {}. ", groupInstanceId, foundComponentInstance.getName());
-                actionResult = Either.right(componentsUtils.getResponseFormat(ActionStatus.GROUP_INSTANCE_NOT_FOUND_ON_COMPONENT_INSTANCE, groupInstanceId, foundComponentInstance.getName()));
+                actionResult = Either.right(componentsUtils
+                    .getResponseFormat(ActionStatus.GROUP_INSTANCE_NOT_FOUND_ON_COMPONENT_INSTANCE, groupInstanceId,
+                        foundComponentInstance.getName()));
             }
         }
         if (actionResult == null) {
@@ -2465,7 +2179,8 @@ public class ServiceBusinessLogic extends ComponentBusinessLogic {
     private ComponentInstance findRelatedComponentInstance(Component component, String componentInstanceId) {
         ComponentInstance componentInstance = null;
         if (isNotEmpty(component.getComponentInstances())) {
-            componentInstance = component.getComponentInstances().stream().filter(ci -> ci.getUniqueId().equals(componentInstanceId)).findFirst().orElse(null);
+            componentInstance = component.getComponentInstances().stream().filter(ci -> ci.getUniqueId().equals(componentInstanceId)).findFirst()
+                .orElse(null);
         }
         return componentInstance;
     }
@@ -2479,28 +2194,24 @@ public class ServiceBusinessLogic extends ComponentBusinessLogic {
         return Either.left(user);
     }
 
-    public Either<UiComponentDataTransfer, ResponseFormat> getUiComponentDataTransferByComponentId(String serviceId, List<String> dataParamsToReturn) {
-
+    public Either<UiComponentDataTransfer, ResponseFormat> getUiComponentDataTransferByComponentId(String serviceId,
+                                                                                                   List<String> dataParamsToReturn) {
         ComponentParametersView paramsToReturn = new ComponentParametersView(dataParamsToReturn);
         paramsToReturn.setIgnoreComponentInstancesProperties(false);
         Either<Service, StorageOperationStatus> serviceResultEither = toscaOperationFacade.getToscaElement(serviceId, paramsToReturn);
-
         if (serviceResultEither.isRight()) {
-            if(serviceResultEither.right().value() == StorageOperationStatus.NOT_FOUND) {
+            if (serviceResultEither.right().value() == StorageOperationStatus.NOT_FOUND) {
                 log.debug("#getUiComponentDataTransferByComponentId - Failed to find service with id {} ", serviceId);
                 return Either.right(componentsUtils.getResponseFormat(ActionStatus.SERVICE_NOT_FOUND, serviceId));
             }
-
             log.debug("#getUiComponentDataTransferByComponentId - failed to get service by id {} with filters {}", serviceId, dataParamsToReturn);
-            return Either.right(componentsUtils.getResponseFormatByResource(componentsUtils.convertFromStorageResponse(serviceResultEither.right().value()), ""));
+            return Either.right(
+                componentsUtils.getResponseFormatByResource(componentsUtils.convertFromStorageResponse(serviceResultEither.right().value()), ""));
         }
-
         Service service = serviceResultEither.left().value();
-               if (dataParamsToReturn.contains(ComponentFieldsEnum.INPUTS.getValue())) {
-                       ListUtils.emptyIfNull(service.getInputs())
-                                       .forEach(input -> input.setConstraints(setInputConstraint(input)));
-               }
-
+        if (dataParamsToReturn.contains(ComponentFieldsEnum.INPUTS.getValue())) {
+            ListUtils.emptyIfNull(service.getInputs()).forEach(input -> input.setConstraints(setInputConstraint(input)));
+        }
         UiComponentDataTransfer dataTransfer = uiComponentDataConverter.getUiDataTransferFromServiceByParams(service, dataParamsToReturn);
         return Either.left(dataTransfer);
     }
@@ -2514,4 +2225,62 @@ public class ServiceBusinessLogic extends ComponentBusinessLogic {
         Either<Service, StorageOperationStatus> latestByName = toscaOperationFacade.getLatestByServiceName(serviceName);
         return latestByName.isLeft();
     }
+
+    abstract class ArtifactGenerator<CallVal> implements Callable<Either<CallVal, ResponseFormat>> {
+
+    }
+
+    @Getter
+    class HeatEnvArtifactGenerator extends ArtifactGenerator<ArtifactDefinition> {
+
+        private ArtifactDefinition artifactDefinition;
+        private Service service;
+        private String resourceInstanceName;
+        private User modifier;
+        private String instanceId;
+        private boolean shouldLock;
+        private boolean inTransaction;
+
+        HeatEnvArtifactGenerator(ArtifactDefinition artifactDefinition, Service service, String resourceInstanceName, User modifier,
+                                 boolean shouldLock, boolean inTransaction, String instanceId) {
+            this.artifactDefinition = artifactDefinition;
+            this.service = service;
+            this.resourceInstanceName = resourceInstanceName;
+            this.modifier = modifier;
+            this.shouldLock = shouldLock;
+            this.instanceId = instanceId;
+            this.inTransaction = inTransaction;
+        }
+
+        @Override
+        public Either<ArtifactDefinition, ResponseFormat> call() throws Exception {
+            return artifactsBusinessLogic
+                .forceGenerateHeatEnvArtifact(artifactDefinition, ComponentTypeEnum.RESOURCE_INSTANCE, service, resourceInstanceName, modifier,
+                    shouldLock, inTransaction, instanceId);
+        }
+    }
+
+    class VfModuleArtifactGenerator extends ArtifactGenerator<ArtifactDefinition> {
+
+        boolean shouldLock;
+        boolean inTransaction;
+        private User user;
+        private ComponentInstance componentInstance;
+        private Service service;
+
+        private VfModuleArtifactGenerator(User user, ComponentInstance componentInstance, Service service, boolean shouldLock,
+                                          boolean inTransaction) {
+            super();
+            this.user = user;
+            this.componentInstance = componentInstance;
+            this.service = service;
+            this.shouldLock = shouldLock;
+            this.inTransaction = inTransaction;
+        }
+
+        @Override
+        public Either<ArtifactDefinition, ResponseFormat> call() throws Exception {
+            return generateVfModuleInstanceArtifact(user, componentInstance, service, shouldLock, inTransaction);
+        }
+    }
 }
index 0ffceda..2956abf 100644 (file)
  */
 package org.openecomp.sdc.be.components.impl;
 
+import static java.util.stream.Collectors.joining;
+import static java.util.stream.Collectors.toList;
+import static java.util.stream.Collectors.toMap;
+import static org.apache.commons.collections.CollectionUtils.isNotEmpty;
+import static org.openecomp.sdc.be.components.impl.ImportUtils.findFirstToscaStringElement;
+import static org.openecomp.sdc.be.components.impl.ImportUtils.getPropertyJsonStringValue;
+import static org.openecomp.sdc.be.tosca.CsarUtils.VF_NODE_TYPE_ARTIFACTS_PATH_PATTERN;
+
 import fj.data.Either;
+import java.util.ArrayList;
+import java.util.Collection;
+import java.util.EnumMap;
+import java.util.HashMap;
+import java.util.HashSet;
+import java.util.Iterator;
+import java.util.List;
+import java.util.Map;
+import java.util.Optional;
+import java.util.Set;
+import java.util.regex.Pattern;
 import lombok.Getter;
 import lombok.Setter;
 import org.apache.commons.collections.CollectionUtils;
@@ -117,32 +136,11 @@ import org.openecomp.sdc.exception.ResponseFormat;
 import org.springframework.beans.factory.annotation.Autowired;
 import org.yaml.snakeyaml.Yaml;
 
-import java.util.ArrayList;
-import java.util.Collection;
-import java.util.EnumMap;
-import java.util.HashMap;
-import java.util.HashSet;
-import java.util.Iterator;
-import java.util.List;
-import java.util.Map;
-import java.util.Optional;
-import java.util.Set;
-import java.util.regex.Pattern;
-
-import static java.util.stream.Collectors.joining;
-import static java.util.stream.Collectors.toList;
-import static java.util.stream.Collectors.toMap;
-import static org.apache.commons.collections.CollectionUtils.isNotEmpty;
-import static org.openecomp.sdc.be.components.impl.ImportUtils.findFirstToscaStringElement;
-import static org.openecomp.sdc.be.components.impl.ImportUtils.getPropertyJsonStringValue;
-import static org.openecomp.sdc.be.tosca.CsarUtils.VF_NODE_TYPE_ARTIFACTS_PATH_PATTERN;
-
 @Getter
 @Setter
 @org.springframework.stereotype.Component("serviceImportBusinessLogic")
 public class ServiceImportBusinessLogic {
 
-    private final UiComponentDataConverter uiComponentDataConverter;
     private static final String INITIAL_VERSION = "0.1";
     private static final String CREATE_RESOURCE = "Create Resource";
     private static final String IN_RESOURCE = "  in resource {} ";
@@ -153,25 +151,18 @@ public class ServiceImportBusinessLogic {
     private static final String PLACE_HOLDER_RESOURCE_TYPES = "validForResourceTypes";
     private static final String CREATE_RESOURCE_VALIDATE_CAPABILITY_TYPES = "Create Resource - validateCapabilityTypesCreate";
     private static final String CATEGORY_IS_EMPTY = "Resource category is empty";
-
-    @Autowired
-    private ServiceBusinessLogic serviceBusinessLogic;
-
-    public ServiceBusinessLogic getServiceBusinessLogic() {
-        return serviceBusinessLogic;
-    }
-
-    public void setServiceBusinessLogic(ServiceBusinessLogic serviceBusinessLogic) {
-        this.serviceBusinessLogic = serviceBusinessLogic;
-    }
-
-    @Autowired
-    private CsarBusinessLogic csarBusinessLogic;
+    private static final Logger log = Logger.getLogger(ServiceImportBusinessLogic.class);
+    private final UiComponentDataConverter uiComponentDataConverter;
+    private final ComponentInstanceBusinessLogic componentInstanceBusinessLogic;
     @Autowired
     protected ComponentsUtils componentsUtils;
     @Autowired
     protected ToscaOperationFacade toscaOperationFacade;
     @Autowired
+    private ServiceBusinessLogic serviceBusinessLogic;
+    @Autowired
+    private CsarBusinessLogic csarBusinessLogic;
+    @Autowired
     private CsarArtifactsAndGroupsBusinessLogic csarArtifactsAndGroupsBusinessLogic;
     @Autowired
     private LifecycleBusinessLogic lifecycleBusinessLogic;
@@ -182,33 +173,30 @@ public class ServiceImportBusinessLogic {
     @Autowired
     private ServiceImportParseLogic serviceImportParseLogic;
 
-    private static final Logger log = Logger.getLogger(ServiceImportBusinessLogic.class);
-
     @Autowired
-    public ServiceImportBusinessLogic(IElementOperation elementDao,
-                                      IGroupOperation groupOperation,
-                                      IGroupInstanceOperation groupInstanceOperation,
-                                      IGroupTypeOperation groupTypeOperation,
-                                      GroupBusinessLogic groupBusinessLogic,
-                                      InterfaceOperation interfaceOperation,
-                                      InterfaceLifecycleOperation interfaceLifecycleTypeOperation,
-                                      ArtifactsBusinessLogic artifactsBusinessLogic,
-                                      IDistributionEngine distributionEngine, ComponentInstanceBusinessLogic componentInstanceBusinessLogic,
+    public ServiceImportBusinessLogic(IElementOperation elementDao, IGroupOperation groupOperation, IGroupInstanceOperation groupInstanceOperation,
+                                      IGroupTypeOperation groupTypeOperation, GroupBusinessLogic groupBusinessLogic,
+                                      InterfaceOperation interfaceOperation, InterfaceLifecycleOperation interfaceLifecycleTypeOperation,
+                                      ArtifactsBusinessLogic artifactsBusinessLogic, IDistributionEngine distributionEngine,
+                                      ComponentInstanceBusinessLogic componentInstanceBusinessLogic,
                                       ServiceDistributionValidation serviceDistributionValidation, ForwardingPathValidator forwardingPathValidator,
                                       UiComponentDataConverter uiComponentDataConverter, NodeFilterOperation serviceFilterOperation,
                                       NodeFilterValidator serviceFilterValidator, ArtifactsOperations artifactToscaOperation,
-                                      ComponentContactIdValidator componentContactIdValidator,
-                                      ComponentNameValidator componentNameValidator,
-                                      ComponentTagsValidator componentTagsValidator,
-                                      ComponentValidator componentValidator,
-                                      ComponentIconValidator componentIconValidator,
-                                      ComponentProjectCodeValidator componentProjectCodeValidator,
+                                      ComponentContactIdValidator componentContactIdValidator, ComponentNameValidator componentNameValidator,
+                                      ComponentTagsValidator componentTagsValidator, ComponentValidator componentValidator,
+                                      ComponentIconValidator componentIconValidator, ComponentProjectCodeValidator componentProjectCodeValidator,
                                       ComponentDescriptionValidator componentDescriptionValidator) {
         this.componentInstanceBusinessLogic = componentInstanceBusinessLogic;
         this.uiComponentDataConverter = uiComponentDataConverter;
     }
 
-    private final ComponentInstanceBusinessLogic componentInstanceBusinessLogic;
+    public ServiceBusinessLogic getServiceBusinessLogic() {
+        return serviceBusinessLogic;
+    }
+
+    public void setServiceBusinessLogic(ServiceBusinessLogic serviceBusinessLogic) {
+        this.serviceBusinessLogic = serviceBusinessLogic;
+    }
 
     public Service createService(Service service, AuditingActionEnum auditingAction, User user, Map<String, byte[]> csarUIPayload,
                                  String payloadName) {
@@ -221,13 +209,10 @@ public class ServiceImportBusinessLogic {
         service.setInstantiationType("A-la-carte");
         service.setEnvironmentContext("General_Revenue-Bearing");
         service.setEcompGeneratedNaming(true);
-
         try {
             serviceBusinessLogic.validateServiceBeforeCreate(service, user, auditingAction);
-
             log.debug("enter createService,validateServiceBeforeCreate success");
             String csarUUID = payloadName == null ? service.getCsarUUID() : payloadName;
-
             log.debug("enter createService,get csarUUID:{}", csarUUID);
             csarBusinessLogic.validateCsarBeforeCreate(service, csarUUID);
             log.debug("CsarUUID is {} - going to create resource from CSAR", csarUUID);
@@ -242,36 +227,30 @@ public class ServiceImportBusinessLogic {
         log.trace("************* created successfully from YAML, resource TOSCA ");
         try {
             CsarInfo csarInfo = csarBusinessLogic.getCsarInfo(service, null, user, csarUIPayload, csarUUID);
-
             Map<String, NodeTypeInfo> nodeTypesInfo = csarInfo.extractNodeTypesInfo();
             Either<Map<String, EnumMap<ArtifactOperationEnum, List<ArtifactDefinition>>>, ResponseFormat> findNodeTypesArtifactsToHandleRes = serviceImportParseLogic
-                .findNodeTypesArtifactsToHandle(
-                    nodeTypesInfo, csarInfo, service);
+                .findNodeTypesArtifactsToHandle(nodeTypesInfo, csarInfo, service);
             if (findNodeTypesArtifactsToHandleRes.isRight()) {
-                log.debug("failed to find node types for update with artifacts during import csar {}. ",
-                    csarInfo.getCsarUUID());
+                log.debug("failed to find node types for update with artifacts during import csar {}. ", csarInfo.getCsarUUID());
                 throw new ComponentException(findNodeTypesArtifactsToHandleRes.right().value());
             }
-            return createServiceFromYaml(service, csarInfo.getMainTemplateContent(), csarInfo.getMainTemplateName(),
-                nodeTypesInfo, csarInfo, findNodeTypesArtifactsToHandleRes.left().value(), true, false,
-                null);
+            return createServiceFromYaml(service, csarInfo.getMainTemplateContent(), csarInfo.getMainTemplateName(), nodeTypesInfo, csarInfo,
+                findNodeTypesArtifactsToHandleRes.left().value(), true, false, null);
         } catch (Exception e) {
             log.debug("Exception occured when createServiceFromCsar,error is:{}", e.getMessage(), e);
             throw new ComponentException(ActionStatus.GENERAL_ERROR);
         }
     }
 
-    protected Service createServiceFromYaml(Service service, String topologyTemplateYaml,
-                                            String yamlName, Map<String, NodeTypeInfo> nodeTypesInfo, CsarInfo csarInfo,
+    protected Service createServiceFromYaml(Service service, String topologyTemplateYaml, String yamlName, Map<String, NodeTypeInfo> nodeTypesInfo,
+                                            CsarInfo csarInfo,
                                             Map<String, EnumMap<ArtifactsBusinessLogic.ArtifactOperationEnum, List<ArtifactDefinition>>> nodeTypesArtifactsToCreate,
                                             boolean shouldLock, boolean inTransaction, String nodeName) {
-
         List<ArtifactDefinition> createdArtifacts = new ArrayList<>();
         Service createdService;
         CreateServiceFromYamlParameter csfyp = new CreateServiceFromYamlParameter();
         try {
-            ParsedToscaYamlInfo
-                parsedToscaYamlInfo = csarBusinessLogic
+            ParsedToscaYamlInfo parsedToscaYamlInfo = csarBusinessLogic
                 .getParsedToscaYamlInfo(topologyTemplateYaml, yamlName, nodeTypesInfo, csarInfo, nodeName, service);
             if (MapUtils.isEmpty(parsedToscaYamlInfo.getInstances())) {
                 throw new ComponentException(ActionStatus.NOT_TOPOLOGY_TOSCA_TEMPLATE, yamlName);
@@ -284,7 +263,6 @@ public class ServiceImportBusinessLogic {
             csfyp.setNodeTypesInfo(nodeTypesInfo);
             csfyp.setCsarInfo(csarInfo);
             csfyp.setNodeName(nodeName);
-
             createdService = createServiceAndRIsFromYaml(service, false, nodeTypesArtifactsToCreate, shouldLock, inTransaction, csfyp);
             log.debug("#createResourceFromYaml - The resource {} has been created ", service.getName());
         } catch (ComponentException e) {
@@ -300,7 +278,6 @@ public class ServiceImportBusinessLogic {
     protected Service createServiceAndRIsFromYaml(Service service, boolean isNormative,
                                                   Map<String, EnumMap<ArtifactsBusinessLogic.ArtifactOperationEnum, List<ArtifactDefinition>>> nodeTypesArtifactsToCreate,
                                                   boolean shouldLock, boolean inTransaction, CreateServiceFromYamlParameter csfyp) {
-
         List<ArtifactDefinition> nodeTypesNewCreatedArtifacts = new ArrayList<>();
         String yamlName = csfyp.getYamlName();
         ParsedToscaYamlInfo parsedToscaYamlInfo = csfyp.getParsedToscaYamlInfo();
@@ -309,7 +286,6 @@ public class ServiceImportBusinessLogic {
         Map<String, NodeTypeInfo> nodeTypesInfo = csfyp.getNodeTypesInfo();
         CsarInfo csarInfo = csfyp.getCsarInfo();
         String nodeName = csfyp.getNodeName();
-
         if (shouldLock) {
             Either<Boolean, ResponseFormat> lockResult = serviceBusinessLogic.lockComponentByName(service.getSystemName(), service, CREATE_RESOURCE);
             if (lockResult.isRight()) {
@@ -322,18 +298,13 @@ public class ServiceImportBusinessLogic {
             log.trace("************* createResourceFromYaml before full create resource {}", yamlName);
             service = serviceImportParseLogic.createServiceTransaction(service, csarInfo.getModifier(), isNormative);
             log.trace("************* Going to add inputs from yaml {}", yamlName);
-
             Map<String, InputDefinition> inputs = parsedToscaYamlInfo.getInputs();
             service = serviceImportParseLogic.createInputsOnService(service, inputs);
             log.trace("************* Finish to add inputs from yaml {}", yamlName);
-
-            Map<String, UploadComponentInstanceInfo> uploadComponentInstanceInfoMap = parsedToscaYamlInfo
-                .getInstances();
+            Map<String, UploadComponentInstanceInfo> uploadComponentInstanceInfoMap = parsedToscaYamlInfo.getInstances();
             log.trace("************* Going to create nodes, RI's and Relations  from yaml {}", yamlName);
-
-            service = createRIAndRelationsFromYaml(yamlName, service, uploadComponentInstanceInfoMap,
-                topologyTemplateYaml, nodeTypesNewCreatedArtifacts, nodeTypesInfo, csarInfo,
-                nodeTypesArtifactsToCreate, nodeName);
+            service = createRIAndRelationsFromYaml(yamlName, service, uploadComponentInstanceInfoMap, topologyTemplateYaml,
+                nodeTypesNewCreatedArtifacts, nodeTypesInfo, csarInfo, nodeTypesArtifactsToCreate, nodeName);
             log.trace("************* Finished to create nodes, RI and Relation  from yaml {}", yamlName);
             Either<Map<String, GroupDefinition>, ResponseFormat> validateUpdateVfGroupNamesRes = serviceBusinessLogic.groupBusinessLogic
                 .validateUpdateVfGroupNames(parsedToscaYamlInfo.getGroups(), service.getSystemName());
@@ -343,13 +314,11 @@ public class ServiceImportBusinessLogic {
             }
             Map<String, GroupDefinition> groups;
             log.trace("************* Going to add groups from yaml {}", yamlName);
-
             if (!validateUpdateVfGroupNamesRes.left().value().isEmpty()) {
                 groups = validateUpdateVfGroupNamesRes.left().value();
             } else {
                 groups = parsedToscaYamlInfo.getGroups();
             }
-
             Either<Service, ResponseFormat> createGroupsOnResource = createGroupsOnResource(service, groups);
             if (createGroupsOnResource.isRight()) {
                 serviceImportParseLogic.rollback(inTransaction, service, createdArtifacts, nodeTypesNewCreatedArtifacts);
@@ -357,13 +326,9 @@ public class ServiceImportBusinessLogic {
             }
             service = createGroupsOnResource.left().value();
             log.trace("************* Going to add artifacts from yaml {}", yamlName);
-
-            NodeTypeInfoToUpdateArtifacts nodeTypeInfoToUpdateArtifacts = new NodeTypeInfoToUpdateArtifacts(nodeName,
-                nodeTypesArtifactsToCreate);
-
-            Either<Service, ResponseFormat> createArtifactsEither = createOrUpdateArtifacts(
-                ArtifactsBusinessLogic.ArtifactOperationEnum.CREATE, createdArtifacts, yamlName,
-                csarInfo, service, nodeTypeInfoToUpdateArtifacts, inTransaction, shouldLock);
+            NodeTypeInfoToUpdateArtifacts nodeTypeInfoToUpdateArtifacts = new NodeTypeInfoToUpdateArtifacts(nodeName, nodeTypesArtifactsToCreate);
+            Either<Service, ResponseFormat> createArtifactsEither = createOrUpdateArtifacts(ArtifactsBusinessLogic.ArtifactOperationEnum.CREATE,
+                createdArtifacts, yamlName, csarInfo, service, nodeTypeInfoToUpdateArtifacts, inTransaction, shouldLock);
             if (createArtifactsEither.isRight()) {
                 serviceImportParseLogic.rollback(inTransaction, service, createdArtifacts, nodeTypesNewCreatedArtifacts);
                 throw new ComponentException(createArtifactsEither.right().value());
@@ -379,27 +344,24 @@ public class ServiceImportBusinessLogic {
                 serviceBusinessLogic.janusGraphDao.commit();
             }
             if (shouldLock) {
-                serviceBusinessLogic.graphLockOperation.unlockComponentByName(service.getSystemName(), service.getUniqueId(),
-                    NodeTypeEnum.Resource);
+                serviceBusinessLogic.graphLockOperation.unlockComponentByName(service.getSystemName(), service.getUniqueId(), NodeTypeEnum.Resource);
             }
         }
     }
 
-    protected Either<Resource, ResponseFormat> createOrUpdateArtifacts(
-        ArtifactsBusinessLogic.ArtifactOperationEnum operation, List<ArtifactDefinition> createdArtifacts,
-        String yamlFileName, CsarInfo csarInfo, Resource preparedResource,
-        NodeTypeInfoToUpdateArtifacts nodeTypeInfoToUpdateArtifacts, boolean inTransaction, boolean shouldLock) {
-
+    protected Either<Resource, ResponseFormat> createOrUpdateArtifacts(ArtifactsBusinessLogic.ArtifactOperationEnum operation,
+                                                                       List<ArtifactDefinition> createdArtifacts, String yamlFileName,
+                                                                       CsarInfo csarInfo, Resource preparedResource,
+                                                                       NodeTypeInfoToUpdateArtifacts nodeTypeInfoToUpdateArtifacts,
+                                                                       boolean inTransaction, boolean shouldLock) {
         String nodeName = nodeTypeInfoToUpdateArtifacts.getNodeName();
         Resource resource = preparedResource;
-
         Map<String, EnumMap<ArtifactsBusinessLogic.ArtifactOperationEnum, List<ArtifactDefinition>>> nodeTypesArtifactsToHandle = nodeTypeInfoToUpdateArtifacts
             .getNodeTypesArtifactsToHandle();
         if (preparedResource.getResourceType() == ResourceTypeEnum.VF) {
             if (nodeName != null && nodeTypesArtifactsToHandle.get(nodeName) != null && !nodeTypesArtifactsToHandle.get(nodeName).isEmpty()) {
-                Either<List<ArtifactDefinition>, ResponseFormat> handleNodeTypeArtifactsRes =
-                    handleNodeTypeArtifacts(preparedResource, nodeTypesArtifactsToHandle.get(nodeName), createdArtifacts, csarInfo.getModifier(),
-                        inTransaction, true);
+                Either<List<ArtifactDefinition>, ResponseFormat> handleNodeTypeArtifactsRes = handleNodeTypeArtifacts(preparedResource,
+                    nodeTypesArtifactsToHandle.get(nodeName), createdArtifacts, csarInfo.getModifier(), inTransaction, true);
                 if (handleNodeTypeArtifactsRes.isRight()) {
                     return Either.right(handleNodeTypeArtifactsRes.right().value());
                 }
@@ -416,28 +378,25 @@ public class ServiceImportBusinessLogic {
         return Either.left(resource);
     }
 
-    protected Either<Resource, ResponseFormat> handleVfCsarArtifacts(Resource resource, CsarInfo csarInfo,
-                                                                     List<ArtifactDefinition> createdArtifacts,
+    protected Either<Resource, ResponseFormat> handleVfCsarArtifacts(Resource resource, CsarInfo csarInfo, List<ArtifactDefinition> createdArtifacts,
                                                                      ArtifactOperationInfo artifactOperation, boolean shouldLock,
                                                                      boolean inTransaction) {
         if (csarInfo.getCsar() != null) {
             createOrUpdateSingleNonMetaArtifactToComstants(resource, csarInfo, artifactOperation, shouldLock, inTransaction);
-
-            Either<Resource, ResponseFormat> eitherCreateResult = createOrUpdateNonMetaArtifacts(csarInfo, resource,
-                createdArtifacts, shouldLock, inTransaction, artifactOperation);
+            Either<Resource, ResponseFormat> eitherCreateResult = createOrUpdateNonMetaArtifacts(csarInfo, resource, createdArtifacts, shouldLock,
+                inTransaction, artifactOperation);
             if (eitherCreateResult.isRight()) {
                 return Either.right(eitherCreateResult.right().value());
             }
             Either<Resource, StorageOperationStatus> eitherGerResource = toscaOperationFacade.getToscaElement(resource.getUniqueId());
             if (eitherGerResource.isRight()) {
-                ResponseFormat responseFormat = componentsUtils.getResponseFormatByResource(
-                    componentsUtils.convertFromStorageResponse(eitherGerResource.right().value()), resource);
+                ResponseFormat responseFormat = componentsUtils
+                    .getResponseFormatByResource(componentsUtils.convertFromStorageResponse(eitherGerResource.right().value()), resource);
                 return Either.right(responseFormat);
             }
             resource = eitherGerResource.left().value();
             Either<ImmutablePair<String, String>, ResponseFormat> artifacsMetaCsarStatus = CsarValidationUtils
                 .getArtifactsMeta(csarInfo.getCsar(), csarInfo.getCsarUUID(), componentsUtils);
-
             if (artifacsMetaCsarStatus.isLeft()) {
                 return getResourceResponseFormatEither(resource, csarInfo, createdArtifacts, artifactOperation, shouldLock, inTransaction,
                     artifacsMetaCsarStatus);
@@ -465,17 +424,13 @@ public class ServiceImportBusinessLogic {
                 }
             }
         }
-        createOrUpdateSingleNonMetaArtifact(resource, csarInfo,
-            CsarUtils.ARTIFACTS_PATH + Constants.VENDOR_LICENSE_MODEL, Constants.VENDOR_LICENSE_MODEL,
-            ArtifactTypeEnum.VENDOR_LICENSE.getType(), ArtifactGroupTypeEnum.DEPLOYMENT,
-            Constants.VENDOR_LICENSE_LABEL, Constants.VENDOR_LICENSE_DISPLAY_NAME,
-            Constants.VENDOR_LICENSE_DESCRIPTION, vendorLicenseModelId, artifactOperation, null, true, shouldLock,
-            inTransaction);
-        createOrUpdateSingleNonMetaArtifact(resource, csarInfo,
-            CsarUtils.ARTIFACTS_PATH + Constants.VF_LICENSE_MODEL, Constants.VF_LICENSE_MODEL,
-            ArtifactTypeEnum.VF_LICENSE.getType(), ArtifactGroupTypeEnum.DEPLOYMENT, Constants.VF_LICENSE_LABEL,
-            Constants.VF_LICENSE_DISPLAY_NAME, Constants.VF_LICENSE_DESCRIPTION, vfLicenseModelId,
+        createOrUpdateSingleNonMetaArtifact(resource, csarInfo, CsarUtils.ARTIFACTS_PATH + Constants.VENDOR_LICENSE_MODEL,
+            Constants.VENDOR_LICENSE_MODEL, ArtifactTypeEnum.VENDOR_LICENSE.getType(), ArtifactGroupTypeEnum.DEPLOYMENT,
+            Constants.VENDOR_LICENSE_LABEL, Constants.VENDOR_LICENSE_DISPLAY_NAME, Constants.VENDOR_LICENSE_DESCRIPTION, vendorLicenseModelId,
             artifactOperation, null, true, shouldLock, inTransaction);
+        createOrUpdateSingleNonMetaArtifact(resource, csarInfo, CsarUtils.ARTIFACTS_PATH + Constants.VF_LICENSE_MODEL, Constants.VF_LICENSE_MODEL,
+            ArtifactTypeEnum.VF_LICENSE.getType(), ArtifactGroupTypeEnum.DEPLOYMENT, Constants.VF_LICENSE_LABEL, Constants.VF_LICENSE_DISPLAY_NAME,
+            Constants.VF_LICENSE_DESCRIPTION, vfLicenseModelId, artifactOperation, null, true, shouldLock, inTransaction);
     }
 
     protected Either<Resource, ResponseFormat> getResourceResponseFormatEither(Resource resource, CsarInfo csarInfo,
@@ -489,12 +444,11 @@ public class ServiceImportBusinessLogic {
             Either<Resource, ResponseFormat> createArtifactsFromCsar;
             if (ArtifactOperationEnum.isCreateOrLink(artifactOperation.getArtifactOperationEnum())) {
                 createArtifactsFromCsar = csarArtifactsAndGroupsBusinessLogic
-                    .createResourceArtifactsFromCsar(csarInfo, resource, artifactsContents, artifactsFileName,
-                        createdArtifacts);
+                    .createResourceArtifactsFromCsar(csarInfo, resource, artifactsContents, artifactsFileName, createdArtifacts);
             } else {
                 Either<Component, ResponseFormat> result = csarArtifactsAndGroupsBusinessLogic
-                    .updateResourceArtifactsFromCsar(csarInfo, resource, artifactsContents, artifactsFileName,
-                        createdArtifacts, shouldLock, inTransaction);
+                    .updateResourceArtifactsFromCsar(csarInfo, resource, artifactsContents, artifactsFileName, createdArtifacts, shouldLock,
+                        inTransaction);
                 if ((result.left().value() instanceof Resource) && result.isLeft()) {
                     Resource service1 = (Resource) result.left().value();
                     createArtifactsFromCsar = Either.left(service1);
@@ -522,11 +476,10 @@ public class ServiceImportBusinessLogic {
         try {
             Either<List<CsarUtils.NonMetaArtifactInfo>, String> artifactPathAndNameList = getValidArtifactNames(csarInfo, collectedWarningMessages);
             if (artifactPathAndNameList.isRight()) {
-                return Either.right(getComponentsUtils().getResponseFormatByArtifactId(
-                    ActionStatus.ARTIFACT_NAME_INVALID, artifactPathAndNameList.right().value()));
+                return Either.right(
+                    getComponentsUtils().getResponseFormatByArtifactId(ActionStatus.ARTIFACT_NAME_INVALID, artifactPathAndNameList.right().value()));
             }
             EnumMap<ArtifactsBusinessLogic.ArtifactOperationEnum, List<CsarUtils.NonMetaArtifactInfo>> vfCsarArtifactsToHandle = null;
-
             if (ArtifactsBusinessLogic.ArtifactOperationEnum.isCreateOrLink(artifactOperation.getArtifactOperationEnum())) {
                 vfCsarArtifactsToHandle = new EnumMap<>(ArtifactsBusinessLogic.ArtifactOperationEnum.class);
                 vfCsarArtifactsToHandle.put(artifactOperation.getArtifactOperationEnum(), artifactPathAndNameList.left().value());
@@ -558,30 +511,21 @@ public class ServiceImportBusinessLogic {
 
     protected Either<Resource, ResponseFormat> createOrUpdateNonMetaArtifacts(CsarInfo csarInfo, Resource resource,
                                                                               List<ArtifactDefinition> createdArtifacts, boolean shouldLock,
-                                                                              boolean inTransaction,
-                                                                              ArtifactOperationInfo artifactOperation) {
+                                                                              boolean inTransaction, ArtifactOperationInfo artifactOperation) {
         return createOrUpdateNonMetaArtifactsComp(csarInfo, resource, createdArtifacts, shouldLock, inTransaction, artifactOperation);
     }
 
     protected <T extends Component> Either<T, ResponseFormat> processCsarArtifacts(CsarInfo csarInfo, Component comp,
                                                                                    List<ArtifactDefinition> createdArtifacts, boolean shouldLock,
-                                                                                   boolean inTransaction,
-                                                                                   Either<T, ResponseFormat> resStatus,
+                                                                                   boolean inTransaction, Either<T, ResponseFormat> resStatus,
                                                                                    EnumMap<ArtifactsBusinessLogic.ArtifactOperationEnum, List<CsarUtils.NonMetaArtifactInfo>> vfCsarArtifactsToHandle) {
         for (Map.Entry<ArtifactsBusinessLogic.ArtifactOperationEnum, List<CsarUtils.NonMetaArtifactInfo>> currArtifactOperationPair : vfCsarArtifactsToHandle
             .entrySet()) {
-            Optional<ResponseFormat> optionalCreateInDBError =
-                currArtifactOperationPair.getValue().stream()
-                    .map(e -> createOrUpdateSingleNonMetaArtifact(comp, csarInfo, e.getPath(),
-                        e.getArtifactName(), e.getArtifactType(),
-                        e.getArtifactGroupType(), e.getArtifactLabel(), e.getDisplayName(),
-                        CsarUtils.ARTIFACT_CREATED_FROM_CSAR, e.getArtifactUniqueId(),
-                        new ArtifactOperationInfo(false, false,
-                            currArtifactOperationPair.getKey()),
-                        createdArtifacts, e.isFromCsar(), shouldLock, inTransaction))
-                    .filter(Either::isRight).
-                    map(e -> e.right().value()).
-                    findAny();
+            Optional<ResponseFormat> optionalCreateInDBError = currArtifactOperationPair.getValue().stream().map(
+                e -> createOrUpdateSingleNonMetaArtifact(comp, csarInfo, e.getPath(), e.getArtifactName(), e.getArtifactType(),
+                    e.getArtifactGroupType(), e.getArtifactLabel(), e.getDisplayName(), CsarUtils.ARTIFACT_CREATED_FROM_CSAR, e.getArtifactUniqueId(),
+                    new ArtifactOperationInfo(false, false, currArtifactOperationPair.getKey()), createdArtifacts, e.isFromCsar(), shouldLock,
+                    inTransaction)).filter(Either::isRight).map(e -> e.right().value()).findAny();
             if (optionalCreateInDBError.isPresent()) {
                 resStatus = Either.right(optionalCreateInDBError.get());
                 break;
@@ -590,17 +534,14 @@ public class ServiceImportBusinessLogic {
         return resStatus;
     }
 
-    protected Either<Boolean, ResponseFormat> createOrUpdateSingleNonMetaArtifact(Component component, CsarInfo csarInfo,
-                                                                                  String artifactPath, String artifactFileName, String artifactType,
-                                                                                  ArtifactGroupTypeEnum artifactGroupType,
-                                                                                  String artifactLabel, String artifactDisplayName,
-                                                                                  String artifactDescription, String artifactId,
-                                                                                  ArtifactOperationInfo operation,
+    protected Either<Boolean, ResponseFormat> createOrUpdateSingleNonMetaArtifact(Component component, CsarInfo csarInfo, String artifactPath,
+                                                                                  String artifactFileName, String artifactType,
+                                                                                  ArtifactGroupTypeEnum artifactGroupType, String artifactLabel,
+                                                                                  String artifactDisplayName, String artifactDescription,
+                                                                                  String artifactId, ArtifactOperationInfo operation,
                                                                                   List<ArtifactDefinition> createdArtifacts, boolean isFromCsar,
-                                                                                  boolean shouldLock,
-                                                                                  boolean inTransaction) {
+                                                                                  boolean shouldLock, boolean inTransaction) {
         byte[] artifactFileBytes = null;
-
         if (csarInfo.getCsar().containsKey(artifactPath)) {
             artifactFileBytes = csarInfo.getCsar().get(artifactPath);
         }
@@ -609,33 +550,27 @@ public class ServiceImportBusinessLogic {
             || operation.getArtifactOperationEnum() == ArtifactsBusinessLogic.ArtifactOperationEnum.DELETE) {
             if (serviceImportParseLogic.isArtifactDeletionRequired(artifactId, artifactFileBytes, isFromCsar)) {
                 Either<ArtifactDefinition, ResponseFormat> handleDelete = serviceBusinessLogic.artifactsBusinessLogic
-                    .handleDelete(component.getUniqueId(), artifactId, csarInfo.getModifier(), component,
-                        shouldLock, inTransaction);
+                    .handleDelete(component.getUniqueId(), artifactId, csarInfo.getModifier(), component, shouldLock, inTransaction);
                 if (handleDelete.isRight()) {
                     result = Either.right(handleDelete.right().value());
                 }
                 return result;
             }
             if (org.apache.commons.lang.StringUtils.isEmpty(artifactId) && artifactFileBytes != null) {
-                operation = new ArtifactOperationInfo(false, false,
-                    ArtifactsBusinessLogic.ArtifactOperationEnum.CREATE);
+                operation = new ArtifactOperationInfo(false, false, ArtifactsBusinessLogic.ArtifactOperationEnum.CREATE);
             }
         }
         if (artifactFileBytes != null) {
             Map<String, Object> vendorLicenseModelJson = ArtifactUtils
-                .buildJsonForUpdateArtifact(artifactId, artifactFileName,
-                    artifactType, artifactGroupType, artifactLabel, artifactDisplayName, artifactDescription,
-                    artifactFileBytes, null, isFromCsar);
+                .buildJsonForUpdateArtifact(artifactId, artifactFileName, artifactType, artifactGroupType, artifactLabel, artifactDisplayName,
+                    artifactDescription, artifactFileBytes, null, isFromCsar);
             Either<Either<ArtifactDefinition, Operation>, ResponseFormat> eitherNonMetaArtifacts = csarArtifactsAndGroupsBusinessLogic
-                .createOrUpdateCsarArtifactFromJson(
-                    component, csarInfo.getModifier(), vendorLicenseModelJson, operation);
-            serviceImportParseLogic
-                .addNonMetaCreatedArtifactsToSupportRollback(operation, createdArtifacts, eitherNonMetaArtifacts);
+                .createOrUpdateCsarArtifactFromJson(component, csarInfo.getModifier(), vendorLicenseModelJson, operation);
+            serviceImportParseLogic.addNonMetaCreatedArtifactsToSupportRollback(operation, createdArtifacts, eitherNonMetaArtifacts);
             if (eitherNonMetaArtifacts.isRight()) {
-                BeEcompErrorManager.getInstance()
-                    .logInternalFlowError("UploadLicenseArtifact", "Failed to upload license artifact: "
-                            + artifactFileName + "With csar uuid: " + csarInfo.getCsarUUID(),
-                        BeEcompErrorManager.ErrorSeverity.WARNING);
+                BeEcompErrorManager.getInstance().logInternalFlowError("UploadLicenseArtifact",
+                    "Failed to upload license artifact: " + artifactFileName + "With csar uuid: " + csarInfo.getCsarUUID(),
+                    BeEcompErrorManager.ErrorSeverity.WARNING);
                 return Either.right(eitherNonMetaArtifacts.right().value());
             }
         }
@@ -655,7 +590,6 @@ public class ServiceImportBusinessLogic {
                 return Either.right(changeStateResponse.right().value());
             }
             nodeTypeResource = changeStateResponse.left().value();
-
             List<ArtifactDefinition> handledNodeTypeArtifacts = new ArrayList<>();
             log.debug("************* Going to handle artifacts of node type resource {}. ", nodeTypeResource.getName());
             for (Map.Entry<ArtifactsBusinessLogic.ArtifactOperationEnum, List<ArtifactDefinition>> curOperationEntry : nodeTypeArtifactsToHandle
@@ -663,13 +597,10 @@ public class ServiceImportBusinessLogic {
                 ArtifactsBusinessLogic.ArtifactOperationEnum curOperation = curOperationEntry.getKey();
                 List<ArtifactDefinition> curArtifactsToHandle = curOperationEntry.getValue();
                 if (curArtifactsToHandle != null && !curArtifactsToHandle.isEmpty()) {
-                    log.debug("************* Going to {} artifact to vfc {}", curOperation.name(),
-                        nodeTypeResource.getName());
+                    log.debug("************* Going to {} artifact to vfc {}", curOperation.name(), nodeTypeResource.getName());
                     handleNodeTypeArtifactsRequestRes = serviceBusinessLogic.artifactsBusinessLogic
-                        .handleArtifactsRequestForInnerVfcComponent(curArtifactsToHandle, nodeTypeResource, user,
-                            createdArtifacts, new ArtifactOperationInfo(false,
-                                ignoreLifecycleState, curOperation),
-                            false, inTransaction);
+                        .handleArtifactsRequestForInnerVfcComponent(curArtifactsToHandle, nodeTypeResource, user, createdArtifacts,
+                            new ArtifactOperationInfo(false, ignoreLifecycleState, curOperation), false, inTransaction);
                     if (ArtifactsBusinessLogic.ArtifactOperationEnum.isCreateOrLink(curOperation)) {
                         createdArtifacts.addAll(handleNodeTypeArtifactsRequestRes);
                     }
@@ -692,11 +623,10 @@ public class ServiceImportBusinessLogic {
         try {
             if (!resource.getComponentMetadataDefinition().getMetadataDataDefinition().getState()
                 .equals(LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT.name())) {
-                Either<? extends Component, ResponseFormat> checkoutRes = lifecycleBusinessLogic.changeComponentState(
-                    resource.getComponentType(), resource.getUniqueId(), user, LifeCycleTransitionEnum.CHECKOUT,
-                    new LifecycleChangeInfoWithAction(CERTIFICATION_ON_IMPORT,
-                        LifecycleChangeInfoWithAction.LifecycleChanceActionEnum.CREATE_FROM_CSAR),
-                    inTransaction, true);
+                Either<? extends Component, ResponseFormat> checkoutRes = lifecycleBusinessLogic
+                    .changeComponentState(resource.getComponentType(), resource.getUniqueId(), user, LifeCycleTransitionEnum.CHECKOUT,
+                        new LifecycleChangeInfoWithAction(CERTIFICATION_ON_IMPORT,
+                            LifecycleChangeInfoWithAction.LifecycleChanceActionEnum.CREATE_FROM_CSAR), inTransaction, true);
                 if (checkoutRes.isRight()) {
                     checkoutResourceRes = Either.right(checkoutRes.right().value());
                 } else {
@@ -708,32 +638,27 @@ public class ServiceImportBusinessLogic {
         } catch (Exception e) {
             ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR);
             checkoutResourceRes = Either.right(responseFormat);
-            log.debug("Exception occured when checkoutResource {} , error is:{}", resource.getName(), e.getMessage(),
-                e);
+            log.debug("Exception occured when checkoutResource {} , error is:{}", resource.getName(), e.getMessage(), e);
         }
         return checkoutResourceRes;
     }
 
-    protected Either<Service, ResponseFormat> createOrUpdateArtifacts(
-        ArtifactOperationEnum operation, List<ArtifactDefinition> createdArtifacts,
-        String yamlFileName, CsarInfo csarInfo, Service preparedService,
-        NodeTypeInfoToUpdateArtifacts nodeTypeInfoToUpdateArtifacts, boolean inTransaction, boolean shouldLock) {
-
+    protected Either<Service, ResponseFormat> createOrUpdateArtifacts(ArtifactOperationEnum operation, List<ArtifactDefinition> createdArtifacts,
+                                                                      String yamlFileName, CsarInfo csarInfo, Service preparedService,
+                                                                      NodeTypeInfoToUpdateArtifacts nodeTypeInfoToUpdateArtifacts,
+                                                                      boolean inTransaction, boolean shouldLock) {
         Either<Service, ResponseFormat> createdCsarArtifactsEither = handleVfCsarArtifacts(preparedService, csarInfo, createdArtifacts,
             new ArtifactOperationInfo(false, false, operation), shouldLock, inTransaction);
         log.trace("************* Finished to add artifacts from yaml {}", yamlFileName);
         if (createdCsarArtifactsEither.isRight()) {
             return createdCsarArtifactsEither;
         }
-
         return Either.left(createdCsarArtifactsEither.left().value());
     }
 
-    protected Either<Service, ResponseFormat> handleVfCsarArtifacts(Service service, CsarInfo csarInfo,
-                                                                    List<ArtifactDefinition> createdArtifacts,
+    protected Either<Service, ResponseFormat> handleVfCsarArtifacts(Service service, CsarInfo csarInfo, List<ArtifactDefinition> createdArtifacts,
                                                                     ArtifactOperationInfo artifactOperation, boolean shouldLock,
                                                                     boolean inTransaction) {
-
         if (csarInfo.getCsar() != null) {
             String vendorLicenseModelId = null;
             String vfLicenseModelId = null;
@@ -750,34 +675,29 @@ public class ServiceImportBusinessLogic {
                     }
                 }
             }
-            createOrUpdateSingleNonMetaArtifact(service, csarInfo,
-                CsarUtils.ARTIFACTS_PATH + Constants.VENDOR_LICENSE_MODEL, Constants.VENDOR_LICENSE_MODEL,
-                ArtifactTypeEnum.VENDOR_LICENSE.getType(), ArtifactGroupTypeEnum.DEPLOYMENT,
-                Constants.VENDOR_LICENSE_LABEL, Constants.VENDOR_LICENSE_DISPLAY_NAME,
-                Constants.VENDOR_LICENSE_DESCRIPTION, vendorLicenseModelId, artifactOperation, null, true, shouldLock,
-                inTransaction);
-            createOrUpdateSingleNonMetaArtifact(service, csarInfo,
-                CsarUtils.ARTIFACTS_PATH + Constants.VF_LICENSE_MODEL, Constants.VF_LICENSE_MODEL,
-                ArtifactTypeEnum.VF_LICENSE.getType(), ArtifactGroupTypeEnum.DEPLOYMENT, Constants.VF_LICENSE_LABEL,
-                Constants.VF_LICENSE_DISPLAY_NAME, Constants.VF_LICENSE_DESCRIPTION, vfLicenseModelId,
+            createOrUpdateSingleNonMetaArtifact(service, csarInfo, CsarUtils.ARTIFACTS_PATH + Constants.VENDOR_LICENSE_MODEL,
+                Constants.VENDOR_LICENSE_MODEL, ArtifactTypeEnum.VENDOR_LICENSE.getType(), ArtifactGroupTypeEnum.DEPLOYMENT,
+                Constants.VENDOR_LICENSE_LABEL, Constants.VENDOR_LICENSE_DISPLAY_NAME, Constants.VENDOR_LICENSE_DESCRIPTION, vendorLicenseModelId,
                 artifactOperation, null, true, shouldLock, inTransaction);
-
-            Either<Service, ResponseFormat> eitherCreateResult = createOrUpdateNonMetaArtifacts(csarInfo, service,
-                createdArtifacts, shouldLock, inTransaction, artifactOperation);
+            createOrUpdateSingleNonMetaArtifact(service, csarInfo, CsarUtils.ARTIFACTS_PATH + Constants.VF_LICENSE_MODEL, Constants.VF_LICENSE_MODEL,
+                ArtifactTypeEnum.VF_LICENSE.getType(), ArtifactGroupTypeEnum.DEPLOYMENT, Constants.VF_LICENSE_LABEL,
+                Constants.VF_LICENSE_DISPLAY_NAME, Constants.VF_LICENSE_DESCRIPTION, vfLicenseModelId, artifactOperation, null, true, shouldLock,
+                inTransaction);
+            Either<Service, ResponseFormat> eitherCreateResult = createOrUpdateNonMetaArtifacts(csarInfo, service, createdArtifacts, shouldLock,
+                inTransaction, artifactOperation);
             if (eitherCreateResult.isRight()) {
                 return Either.right(eitherCreateResult.right().value());
             }
-            Either<Service, StorageOperationStatus> eitherGerResource = toscaOperationFacade
-                .getToscaElement(service.getUniqueId());
+            Either<Service, StorageOperationStatus> eitherGerResource = toscaOperationFacade.getToscaElement(service.getUniqueId());
             if (eitherGerResource.isRight()) {
-                ResponseFormat responseFormat = componentsUtils.getResponseFormatByComponent(
-                    componentsUtils.convertFromStorageResponse(eitherGerResource.right().value()), service, ComponentTypeEnum.SERVICE);
+                ResponseFormat responseFormat = componentsUtils
+                    .getResponseFormatByComponent(componentsUtils.convertFromStorageResponse(eitherGerResource.right().value()), service,
+                        ComponentTypeEnum.SERVICE);
                 return Either.right(responseFormat);
             }
             service = eitherGerResource.left().value();
             Either<ImmutablePair<String, String>, ResponseFormat> artifacsMetaCsarStatus = CsarValidationUtils
                 .getArtifactsMeta(csarInfo.getCsar(), csarInfo.getCsarUUID(), componentsUtils);
-
             if (artifacsMetaCsarStatus.isLeft()) {
                 String artifactsFileName = artifacsMetaCsarStatus.left().value().getKey();
                 String artifactsContents = artifacsMetaCsarStatus.left().value().getValue();
@@ -810,8 +730,7 @@ public class ServiceImportBusinessLogic {
 
     protected Either<Service, ResponseFormat> createOrUpdateNonMetaArtifacts(CsarInfo csarInfo, Service resource,
                                                                              List<ArtifactDefinition> createdArtifacts, boolean shouldLock,
-                                                                             boolean inTransaction,
-                                                                             ArtifactOperationInfo artifactOperation) {
+                                                                             boolean inTransaction, ArtifactOperationInfo artifactOperation) {
         return createOrUpdateNonMetaArtifactsComp(csarInfo, resource, createdArtifacts, shouldLock, inTransaction, artifactOperation);
     }
 
@@ -825,7 +744,6 @@ public class ServiceImportBusinessLogic {
             existingArtifacts.addAll(component.getArtifacts().values());
         }
         existingArtifacts = existingArtifacts.stream().filter(this::isNonMetaArtifact).collect(toList());
-
         List<String> artifactsToIgnore = new ArrayList<>();
         if (component.getGroups() != null) {
             component.getGroups().forEach(g -> {
@@ -834,8 +752,7 @@ public class ServiceImportBusinessLogic {
                 }
             });
         }
-        existingArtifacts = existingArtifacts.stream()
-            .filter(a -> !artifactsToIgnore.contains(a.getUniqueId())).collect(toList());
+        existingArtifacts = existingArtifacts.stream().filter(a -> !artifactsToIgnore.contains(a.getUniqueId())).collect(toList());
         return organizeVfCsarArtifactsByArtifactOperation(artifactPathAndNameList, existingArtifacts, component, user);
     }
 
@@ -849,8 +766,7 @@ public class ServiceImportBusinessLogic {
 
     private boolean isValidArtifactType(ArtifactDefinition artifact) {
         boolean result = true;
-        if (artifact.getArtifactType() == null
-            || ArtifactTypeEnum.findType(artifact.getArtifactType()).equals(ArtifactTypeEnum.VENDOR_LICENSE)
+        if (artifact.getArtifactType() == null || ArtifactTypeEnum.findType(artifact.getArtifactType()).equals(ArtifactTypeEnum.VENDOR_LICENSE)
             || ArtifactTypeEnum.findType(artifact.getArtifactType()).equals(ArtifactTypeEnum.VF_LICENSE)) {
             result = false;
         }
@@ -858,8 +774,8 @@ public class ServiceImportBusinessLogic {
     }
 
     protected Either<EnumMap<ArtifactsBusinessLogic.ArtifactOperationEnum, List<CsarUtils.NonMetaArtifactInfo>>, ResponseFormat> organizeVfCsarArtifactsByArtifactOperation(
-        List<CsarUtils.NonMetaArtifactInfo> artifactPathAndNameList, List<ArtifactDefinition> existingArtifactsToHandle,
-        Component component, User user) {
+        List<CsarUtils.NonMetaArtifactInfo> artifactPathAndNameList, List<ArtifactDefinition> existingArtifactsToHandle, Component component,
+        User user) {
         EnumMap<ArtifactsBusinessLogic.ArtifactOperationEnum, List<CsarUtils.NonMetaArtifactInfo>> nodeTypeArtifactsToHandle = new EnumMap<>(
             ArtifactsBusinessLogic.ArtifactOperationEnum.class);
         Wrapper<ResponseFormat> responseWrapper = new Wrapper<>();
@@ -871,14 +787,11 @@ public class ServiceImportBusinessLogic {
             List<CsarUtils.NonMetaArtifactInfo> artifactsToDelete = new ArrayList<>();
             for (CsarUtils.NonMetaArtifactInfo currNewArtifact : artifactPathAndNameList) {
                 ArtifactDefinition foundArtifact;
-
                 if (!existingArtifactsToHandle.isEmpty()) {
-                    foundArtifact = existingArtifactsToHandle.stream()
-                        .filter(a -> a.getArtifactName().equals(currNewArtifact.getArtifactName())).findFirst()
-                        .orElse(null);
+                    foundArtifact = existingArtifactsToHandle.stream().filter(a -> a.getArtifactName().equals(currNewArtifact.getArtifactName()))
+                        .findFirst().orElse(null);
                     if (foundArtifact != null) {
-                        if (ArtifactTypeEnum.findType(foundArtifact.getArtifactType()).equals(currNewArtifact
-                            .getArtifactType())) {
+                        if (ArtifactTypeEnum.findType(foundArtifact.getArtifactType()).equals(currNewArtifact.getArtifactType())) {
                             if (!foundArtifact.getArtifactChecksum().equals(currNewArtifact.getArtifactChecksum())) {
                                 currNewArtifact.setArtifactUniqueId(foundArtifact.getUniqueId());
                                 artifactsToUpdate.add(currNewArtifact);
@@ -886,18 +799,16 @@ public class ServiceImportBusinessLogic {
                             existingArtifactsToHandle.remove(foundArtifact);
                             artifactsToUpload.remove(currNewArtifact);
                         } else {
-                            log.debug("Can't upload two artifact with the same name {}.",
-                                currNewArtifact.getArtifactName());
-                            ResponseFormat responseFormat = ResponseFormatManager.getInstance().getResponseFormat(
-                                ActionStatus.ARTIFACT_ALREADY_EXIST_IN_DIFFERENT_TYPE_IN_CSAR,
-                                currNewArtifact.getArtifactName(), currNewArtifact.getArtifactType(),
-                                foundArtifact.getArtifactType());
+                            log.debug("Can't upload two artifact with the same name {}.", currNewArtifact.getArtifactName());
+                            ResponseFormat responseFormat = ResponseFormatManager.getInstance()
+                                .getResponseFormat(ActionStatus.ARTIFACT_ALREADY_EXIST_IN_DIFFERENT_TYPE_IN_CSAR, currNewArtifact.getArtifactName(),
+                                    currNewArtifact.getArtifactType(), foundArtifact.getArtifactType());
                             AuditingActionEnum auditingAction = serviceBusinessLogic.artifactsBusinessLogic
-                                .detectAuditingType(new ArtifactOperationInfo(false, false,
-                                    ArtifactsBusinessLogic.ArtifactOperationEnum.CREATE), foundArtifact.getArtifactChecksum());
-                            serviceBusinessLogic.artifactsBusinessLogic.handleAuditing(auditingAction, component, component.getUniqueId(),
-                                user, null, null, foundArtifact.getUniqueId(), responseFormat,
-                                component.getComponentType(), null);
+                                .detectAuditingType(new ArtifactOperationInfo(false, false, ArtifactsBusinessLogic.ArtifactOperationEnum.CREATE),
+                                    foundArtifact.getArtifactChecksum());
+                            serviceBusinessLogic.artifactsBusinessLogic
+                                .handleAuditing(auditingAction, component, component.getUniqueId(), user, null, null, foundArtifact.getUniqueId(),
+                                    responseFormat, component.getComponentType(), null);
                             responseWrapper.setInnerElement(responseFormat);
                             break;
                         }
@@ -940,7 +851,6 @@ public class ServiceImportBusinessLogic {
         return nodeTypeArtifactsToHandleRes;
     }
 
-
     public ComponentsUtils getComponentsUtils() {
         return this.componentsUtils;
     }
@@ -951,15 +861,10 @@ public class ServiceImportBusinessLogic {
 
     protected Either<List<CsarUtils.NonMetaArtifactInfo>, String> getValidArtifactNames(CsarInfo csarInfo,
                                                                                         Map<String, Set<List<String>>> collectedWarningMessages) {
-        List<CsarUtils.NonMetaArtifactInfo> artifactPathAndNameList =
-            csarInfo.getCsar().entrySet().stream()
-                .filter(e -> Pattern.compile(VF_NODE_TYPE_ARTIFACTS_PATH_PATTERN).matcher(e.getKey())
-                    .matches())
-                .map(e -> CsarUtils.validateNonMetaArtifact(e.getKey(), e.getValue(),
-                    collectedWarningMessages))
-                .filter(Either::isLeft)
-                .map(e -> e.left().value())
-                .collect(toList());
+        List<CsarUtils.NonMetaArtifactInfo> artifactPathAndNameList = csarInfo.getCsar().entrySet().stream()
+            .filter(e -> Pattern.compile(VF_NODE_TYPE_ARTIFACTS_PATH_PATTERN).matcher(e.getKey()).matches())
+            .map(e -> CsarUtils.validateNonMetaArtifact(e.getKey(), e.getValue(), collectedWarningMessages)).filter(Either::isLeft)
+            .map(e -> e.left().value()).collect(toList());
         Pattern englishNumbersAndUnderScoresOnly = Pattern.compile(CsarUtils.VALID_ENGLISH_ARTIFACT_NAME);
         for (CsarUtils.NonMetaArtifactInfo nonMetaArtifactInfo : artifactPathAndNameList) {
             if (!englishNumbersAndUnderScoresOnly.matcher(nonMetaArtifactInfo.getDisplayName()).matches()) {
@@ -969,25 +874,24 @@ public class ServiceImportBusinessLogic {
         return Either.left(artifactPathAndNameList);
     }
 
-    protected Either<Service, ResponseFormat> createGroupsOnResource(Service service,
-                                                                     Map<String, GroupDefinition> groups) {
+    protected Either<Service, ResponseFormat> createGroupsOnResource(Service service, Map<String, GroupDefinition> groups) {
         if (groups != null && !groups.isEmpty()) {
             List<GroupDefinition> groupsAsList = updateGroupsMembersUsingResource(groups, service);
             serviceImportParseLogic.handleGroupsProperties(service, groups);
             serviceImportParseLogic.fillGroupsFinalFields(groupsAsList);
-            Either<List<GroupDefinition>, ResponseFormat> createGroups = serviceBusinessLogic.groupBusinessLogic.createGroups(service,
-                groupsAsList, true);
+            Either<List<GroupDefinition>, ResponseFormat> createGroups = serviceBusinessLogic.groupBusinessLogic
+                .createGroups(service, groupsAsList, true);
             if (createGroups.isRight()) {
                 return Either.right(createGroups.right().value());
             }
         } else {
             return Either.left(service);
         }
-        Either<Service, StorageOperationStatus> updatedResource = toscaOperationFacade
-            .getToscaElement(service.getUniqueId());
+        Either<Service, StorageOperationStatus> updatedResource = toscaOperationFacade.getToscaElement(service.getUniqueId());
         if (updatedResource.isRight()) {
-            ResponseFormat responseFormat = componentsUtils.getResponseFormatByComponent(
-                componentsUtils.convertFromStorageResponse(updatedResource.right().value()), service, ComponentTypeEnum.SERVICE);
+            ResponseFormat responseFormat = componentsUtils
+                .getResponseFormatByComponent(componentsUtils.convertFromStorageResponse(updatedResource.right().value()), service,
+                    ComponentTypeEnum.SERVICE);
             return Either.right(responseFormat);
         }
         return Either.left(updatedResource.left().value());
@@ -1008,8 +912,7 @@ public class ServiceImportBusinessLogic {
                 updatedGroupDefinition.setMembers(null);
                 Map<String, String> members = groupDefinition.getMembers();
                 if (members != null) {
-                    serviceImportParseLogic
-                        .updateGroupMembers(groups, updatedGroupDefinition, component, componentInstances, groupName, members);
+                    serviceImportParseLogic.updateGroupMembers(groups, updatedGroupDefinition, component, componentInstances, groupName, members);
                 }
                 result.add(updatedGroupDefinition);
             }
@@ -1017,7 +920,6 @@ public class ServiceImportBusinessLogic {
         return result;
     }
 
-
     protected Resource createRIAndRelationsFromYaml(String yamlName, Resource resource,
                                                     Map<String, UploadComponentInstanceInfo> uploadComponentInstanceInfoMap,
                                                     String topologyTemplateYaml, List<ArtifactDefinition> nodeTypesNewCreatedArtifacts,
@@ -1026,11 +928,10 @@ public class ServiceImportBusinessLogic {
                                                     String nodeName) {
         try {
             log.debug("************* Going to create all nodes {}", yamlName);
-            handleNodeTypes(yamlName, resource, topologyTemplateYaml, false, nodeTypesArtifactsToCreate, nodeTypesNewCreatedArtifacts,
-                nodeTypesInfo, csarInfo, nodeName);
+            handleNodeTypes(yamlName, resource, topologyTemplateYaml, false, nodeTypesArtifactsToCreate, nodeTypesNewCreatedArtifacts, nodeTypesInfo,
+                csarInfo, nodeName);
             log.debug("************* Going to create all resource instances {}", yamlName);
-            resource = createResourceInstances(yamlName, resource,
-                uploadComponentInstanceInfoMap, csarInfo.getCreatedNodes());
+            resource = createResourceInstances(yamlName, resource, uploadComponentInstanceInfoMap, csarInfo.getCreatedNodes());
             log.debug("************* Finished to create all resource instances {}", yamlName);
             resource = createResourceInstancesRelations(csarInfo.getModifier(), yamlName, resource, uploadComponentInstanceInfoMap);
             log.debug("************* Going to create positions {}", yamlName);
@@ -1043,64 +944,61 @@ public class ServiceImportBusinessLogic {
     }
 
     protected Resource createResourceInstancesRelations(User user, String yamlName, Resource resource,
-                                                      Map<String, UploadComponentInstanceInfo> uploadResInstancesMap) {
-            log.debug("#createResourceInstancesRelations - Going to create relations ");
-
-            List<ComponentInstance> componentInstancesList = resource.getComponentInstances();
-            if (((MapUtils.isEmpty(uploadResInstancesMap) || CollectionUtils.isEmpty(componentInstancesList)) &&
-                    resource.getResourceType() != ResourceTypeEnum.PNF)) { // PNF can have no resource instances
-                log.debug("#createResourceInstancesRelations - No instances found in the resource {} is empty, yaml template file name {}, ", resource.getUniqueId(), yamlName);
-                BeEcompErrorManager.getInstance().logInternalDataError("createResourceInstancesRelations", "No instances found in a resource or nn yaml template. ", BeEcompErrorManager.ErrorSeverity.ERROR);
-                throw new ComponentException(componentsUtils.getResponseFormat(ActionStatus.NOT_TOPOLOGY_TOSCA_TEMPLATE, yamlName));
-            }
-            Map<String, List<ComponentInstanceProperty>> instProperties = new HashMap<>();
-            Map<ComponentInstance, Map<String, List<CapabilityDefinition>>> instCapabilities = new HashMap<>();
-            Map<ComponentInstance, Map<String, List<RequirementDefinition>>> instRequirements = new HashMap<>();
-            Map<String, Map<String, ArtifactDefinition>> instDeploymentArtifacts = new HashMap<>();
-            Map<String, Map<String, ArtifactDefinition>> instArtifacts = new HashMap<>();
-            Map<String, List<AttributeDefinition>> instAttributes = new HashMap<>();
-            Map<String, Resource> originCompMap = new HashMap<>();
-            List<RequirementCapabilityRelDef> relations = new ArrayList<>();
-            Map<String, List<ComponentInstanceInput>> instInputs = new HashMap<>();
-
-            log.debug("enter ServiceImportBusinessLogic createResourceInstancesRelations#createResourceInstancesRelations - Before get all datatypes. ");
-            if(serviceBusinessLogic.dataTypeCache!=null){
-                Either<Map<String, DataTypeDefinition>, JanusGraphOperationStatus> allDataTypes = serviceBusinessLogic.dataTypeCache.getAll();
-                if (allDataTypes.isRight()) {
-                    JanusGraphOperationStatus status = allDataTypes.right().value();
-                    BeEcompErrorManager.getInstance().logInternalFlowError("UpdatePropertyValueOnComponentInstance",
-                            "Failed to update property value on instance. Status is " + status, BeEcompErrorManager.ErrorSeverity.ERROR);
-                    throw new ComponentException(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(
-                            DaoStatusConverter.convertJanusGraphStatusToStorageStatus(status)), yamlName));
-                }
-                Resource finalResource = resource;
-                uploadResInstancesMap
-                        .values()
-                        .forEach(i -> processComponentInstance(yamlName, finalResource, componentInstancesList, allDataTypes,
-                                instProperties, instCapabilities, instRequirements, instDeploymentArtifacts,
-                                instArtifacts, instAttributes, originCompMap, instInputs, i));
-            }
-            serviceImportParseLogic.associateComponentInstancePropertiesToComponent(yamlName, resource, instProperties);
-            serviceImportParseLogic.associateComponentInstanceInputsToComponent(yamlName, resource, instInputs);
-            serviceImportParseLogic
-                    .associateDeploymentArtifactsToInstances(user, yamlName, resource, instDeploymentArtifacts);
-            serviceImportParseLogic.associateArtifactsToInstances(yamlName, resource, instArtifacts);
-            serviceImportParseLogic.associateOrAddCalculatedCapReq(yamlName, resource, instCapabilities, instRequirements);
-            serviceImportParseLogic.associateInstAttributeToComponentToInstances(yamlName, resource, instAttributes);
-            resource = serviceImportParseLogic.getResourceAfterCreateRelations(resource);
-
-            serviceImportParseLogic
-                    .addRelationsToRI(yamlName, resource, uploadResInstancesMap, componentInstancesList, relations);
-            serviceImportParseLogic.associateResourceInstances(yamlName, resource, relations);
-            handleSubstitutionMappings(resource, uploadResInstancesMap);
-            log.debug("************* in create relations, getResource start");
-            Either<Resource, StorageOperationStatus> eitherGetResource = toscaOperationFacade.getToscaElement(resource.getUniqueId());
-            log.debug("************* in create relations, getResource end");
-            if (eitherGetResource.isRight()) {
-                throw new ComponentException(componentsUtils.getResponseFormatByResource(
-                        componentsUtils.convertFromStorageResponse(eitherGetResource.right().value()), resource));
-            }
-            return eitherGetResource.left().value();
+                                                        Map<String, UploadComponentInstanceInfo> uploadResInstancesMap) {
+        log.debug("#createResourceInstancesRelations - Going to create relations ");
+        List<ComponentInstance> componentInstancesList = resource.getComponentInstances();
+        if (((MapUtils.isEmpty(uploadResInstancesMap) || CollectionUtils.isEmpty(componentInstancesList)) &&
+            resource.getResourceType() != ResourceTypeEnum.PNF)) { // PNF can have no resource instances
+            log.debug("#createResourceInstancesRelations - No instances found in the resource {} is empty, yaml template file name {}, ",
+                resource.getUniqueId(), yamlName);
+            BeEcompErrorManager.getInstance()
+                .logInternalDataError("createResourceInstancesRelations", "No instances found in a resource or nn yaml template. ",
+                    BeEcompErrorManager.ErrorSeverity.ERROR);
+            throw new ComponentException(componentsUtils.getResponseFormat(ActionStatus.NOT_TOPOLOGY_TOSCA_TEMPLATE, yamlName));
+        }
+        Map<String, List<ComponentInstanceProperty>> instProperties = new HashMap<>();
+        Map<ComponentInstance, Map<String, List<CapabilityDefinition>>> instCapabilities = new HashMap<>();
+        Map<ComponentInstance, Map<String, List<RequirementDefinition>>> instRequirements = new HashMap<>();
+        Map<String, Map<String, ArtifactDefinition>> instDeploymentArtifacts = new HashMap<>();
+        Map<String, Map<String, ArtifactDefinition>> instArtifacts = new HashMap<>();
+        Map<String, List<AttributeDefinition>> instAttributes = new HashMap<>();
+        Map<String, Resource> originCompMap = new HashMap<>();
+        List<RequirementCapabilityRelDef> relations = new ArrayList<>();
+        Map<String, List<ComponentInstanceInput>> instInputs = new HashMap<>();
+        log.debug("enter ServiceImportBusinessLogic createResourceInstancesRelations#createResourceInstancesRelations - Before get all datatypes. ");
+        if (serviceBusinessLogic.dataTypeCache != null) {
+            Either<Map<String, DataTypeDefinition>, JanusGraphOperationStatus> allDataTypes = serviceBusinessLogic.dataTypeCache.getAll();
+            if (allDataTypes.isRight()) {
+                JanusGraphOperationStatus status = allDataTypes.right().value();
+                BeEcompErrorManager.getInstance().logInternalFlowError("UpdatePropertyValueOnComponentInstance",
+                    "Failed to update property value on instance. Status is " + status, BeEcompErrorManager.ErrorSeverity.ERROR);
+                throw new ComponentException(componentsUtils
+                    .getResponseFormat(componentsUtils.convertFromStorageResponse(DaoStatusConverter.convertJanusGraphStatusToStorageStatus(status)),
+                        yamlName));
+            }
+            Resource finalResource = resource;
+            uploadResInstancesMap.values().forEach(
+                i -> processComponentInstance(yamlName, finalResource, componentInstancesList, allDataTypes, instProperties, instCapabilities,
+                    instRequirements, instDeploymentArtifacts, instArtifacts, instAttributes, originCompMap, instInputs, i));
+        }
+        serviceImportParseLogic.associateComponentInstancePropertiesToComponent(yamlName, resource, instProperties);
+        serviceImportParseLogic.associateComponentInstanceInputsToComponent(yamlName, resource, instInputs);
+        serviceImportParseLogic.associateDeploymentArtifactsToInstances(user, yamlName, resource, instDeploymentArtifacts);
+        serviceImportParseLogic.associateArtifactsToInstances(yamlName, resource, instArtifacts);
+        serviceImportParseLogic.associateOrAddCalculatedCapReq(yamlName, resource, instCapabilities, instRequirements);
+        serviceImportParseLogic.associateInstAttributeToComponentToInstances(yamlName, resource, instAttributes);
+        resource = serviceImportParseLogic.getResourceAfterCreateRelations(resource);
+        serviceImportParseLogic.addRelationsToRI(yamlName, resource, uploadResInstancesMap, componentInstancesList, relations);
+        serviceImportParseLogic.associateResourceInstances(yamlName, resource, relations);
+        handleSubstitutionMappings(resource, uploadResInstancesMap);
+        log.debug("************* in create relations, getResource start");
+        Either<Resource, StorageOperationStatus> eitherGetResource = toscaOperationFacade.getToscaElement(resource.getUniqueId());
+        log.debug("************* in create relations, getResource end");
+        if (eitherGetResource.isRight()) {
+            throw new ComponentException(
+                componentsUtils.getResponseFormatByResource(componentsUtils.convertFromStorageResponse(eitherGetResource.right().value()), resource));
+        }
+        return eitherGetResource.left().value();
     }
 
     protected void processProperty(Resource resource, ComponentInstance currentCompInstance, Map<String, DataTypeDefinition> allDataTypes,
@@ -1109,8 +1007,7 @@ public class ServiceImportBusinessLogic {
         UploadPropInfo propertyInfo = propertyList.get(0);
         String propName = propertyInfo.getName();
         if (!currPropertiesMap.containsKey(propName)) {
-            throw new ComponentException(componentsUtils.getResponseFormat(ActionStatus.PROPERTY_NOT_FOUND,
-                propName));
+            throw new ComponentException(componentsUtils.getResponseFormat(ActionStatus.PROPERTY_NOT_FOUND, propName));
         }
         processProperty(allDataTypes, currPropertiesMap, instPropList, propertyInfo, propName, resource.getInputs());
     }
@@ -1120,7 +1017,6 @@ public class ServiceImportBusinessLogic {
                                  List<InputDefinition> inputs2) {
         InputDefinition curPropertyDef = currPropertiesMap.get(propName);
         ComponentInstanceInput property = null;
-
         String value = null;
         List<GetInputValueDataDefinition> getInputs = null;
         boolean isValidate = true;
@@ -1128,17 +1024,14 @@ public class ServiceImportBusinessLogic {
             getInputs = propertyInfo.getGet_input();
             isValidate = getInputs == null || getInputs.isEmpty();
             if (isValidate) {
-                value = getPropertyJsonStringValue(propertyInfo.getValue(),
-                    curPropertyDef.getType());
+                value = getPropertyJsonStringValue(propertyInfo.getValue(), curPropertyDef.getType());
             } else {
-                value = getPropertyJsonStringValue(propertyInfo.getValue(),
-                    TypeUtils.ToscaTagNamesEnum.GET_INPUT.getElementName());
+                value = getPropertyJsonStringValue(propertyInfo.getValue(), TypeUtils.ToscaTagNamesEnum.GET_INPUT.getElementName());
             }
         }
         property = new ComponentInstanceInput(curPropertyDef, value, null);
         String validPropertyVAlue = serviceBusinessLogic.validatePropValueBeforeCreate(property, value, isValidate, allDataTypes);
         property.setValue(validPropertyVAlue);
-
         if (isNotEmpty(getInputs)) {
             List<GetInputValueDataDefinition> getInputValues = new ArrayList<>();
             for (GetInputValueDataDefinition getInput : getInputs) {
@@ -1146,16 +1039,13 @@ public class ServiceImportBusinessLogic {
                 if (CollectionUtils.isEmpty(inputs)) {
                     throw new ComponentException(componentsUtils.getResponseFormat(ActionStatus.INVALID_CONTENT));
                 }
-
-                Optional<InputDefinition> optional = inputs.stream()
-                    .filter(p -> p.getName().equals(getInput.getInputName())).findAny();
+                Optional<InputDefinition> optional = inputs.stream().filter(p -> p.getName().equals(getInput.getInputName())).findAny();
                 if (!optional.isPresent()) {
                     throw new ComponentException(componentsUtils.getResponseFormat(ActionStatus.INVALID_CONTENT));
                 }
                 InputDefinition input = optional.get();
                 getInput.setInputId(input.getUniqueId());
                 getInputValues.add(getInput);
-
                 GetInputValueDataDefinition getInputIndex = getInput.getGetInputIndex();
                 processGetInput(getInputValues, inputs, getInputIndex);
             }
@@ -1169,22 +1059,20 @@ public class ServiceImportBusinessLogic {
         if (resource.getResourceType() == ResourceTypeEnum.VF) {
             Either<Resource, StorageOperationStatus> getResourceRes = toscaOperationFacade.getToscaFullElement(resource.getUniqueId());
             if (getResourceRes.isRight()) {
-                ResponseFormat responseFormat = componentsUtils.getResponseFormatByResource(
-                    componentsUtils.convertFromStorageResponse(getResourceRes.right().value()), resource);
+                ResponseFormat responseFormat = componentsUtils
+                    .getResponseFormatByResource(componentsUtils.convertFromStorageResponse(getResourceRes.right().value()), resource);
                 throw new ComponentException(responseFormat);
             }
-            getResourceRes = updateCalculatedCapReqWithSubstitutionMappings(getResourceRes.left().value(),
-                uploadResInstancesMap);
+            getResourceRes = updateCalculatedCapReqWithSubstitutionMappings(getResourceRes.left().value(), uploadResInstancesMap);
             if (getResourceRes.isRight()) {
-                ResponseFormat responseFormat = componentsUtils.getResponseFormatByResource(
-                    componentsUtils.convertFromStorageResponse(getResourceRes.right().value()), resource);
+                ResponseFormat responseFormat = componentsUtils
+                    .getResponseFormatByResource(componentsUtils.convertFromStorageResponse(getResourceRes.right().value()), resource);
                 throw new ComponentException(responseFormat);
             }
         }
     }
 
-    protected Resource createResourceInstances(String yamlName, Resource resource,
-                                               Map<String, UploadComponentInstanceInfo> uploadResInstancesMap,
+    protected Resource createResourceInstances(String yamlName, Resource resource, Map<String, UploadComponentInstanceInfo> uploadResInstancesMap,
                                                Map<String, Resource> nodeNamespaceMap) {
         Either<Resource, ResponseFormat> eitherResource = null;
         log.debug("createResourceInstances is {} - going to create resource instanse from CSAR", yamlName);
@@ -1197,14 +1085,11 @@ public class ServiceImportBusinessLogic {
             nodeNamespaceMap.forEach((k, v) -> existingNodeTypeMap.put(v.getToscaResourceName(), v));
         }
         Map<ComponentInstance, Resource> resourcesInstancesMap = new HashMap<>();
-        uploadResInstancesMap
-            .values()
+        uploadResInstancesMap.values()
             .forEach(i -> createAndAddResourceInstance(i, yamlName, resource, nodeNamespaceMap, existingNodeTypeMap, resourcesInstancesMap));
-
         if (MapUtils.isNotEmpty(resourcesInstancesMap)) {
             try {
-                toscaOperationFacade.associateComponentInstancesToComponent(resource,
-                    resourcesInstancesMap, false, false);
+                toscaOperationFacade.associateComponentInstancesToComponent(resource, resourcesInstancesMap, false, false);
             } catch (StorageException exp) {
                 if (exp.getStorageOperationStatus() != null && exp.getStorageOperationStatus() != StorageOperationStatus.OK) {
                     log.debug("Failed to add component instances to container component {}", resource.getName());
@@ -1220,37 +1105,34 @@ public class ServiceImportBusinessLogic {
             .getToscaElement(resource.getUniqueId(), serviceImportParseLogic.getComponentWithInstancesFilter());
         log.debug("*************finished to get resource {}", resource.getUniqueId());
         if (eitherGetResource.isRight()) {
-            ResponseFormat responseFormat = componentsUtils.getResponseFormatByResource(
-                componentsUtils.convertFromStorageResponse(eitherGetResource.right().value()), resource);
+            ResponseFormat responseFormat = componentsUtils
+                .getResponseFormatByResource(componentsUtils.convertFromStorageResponse(eitherGetResource.right().value()), resource);
             throw new ComponentException(responseFormat);
         }
         if (CollectionUtils.isEmpty(eitherGetResource.left().value().getComponentInstances()) &&
             resource.getResourceType() != ResourceTypeEnum.PNF) { // PNF can have no resource instances
             log.debug("Error when create resource instance from csar. ComponentInstances list empty");
-            BeEcompErrorManager.getInstance().logBeDaoSystemError(
-                "Error when create resource instance from csar. ComponentInstances list empty");
+            BeEcompErrorManager.getInstance().logBeDaoSystemError("Error when create resource instance from csar. ComponentInstances list empty");
             throw new ComponentException(componentsUtils.getResponseFormat(ActionStatus.NOT_TOPOLOGY_TOSCA_TEMPLATE));
         }
         return eitherGetResource.left().value();
     }
 
-    protected void handleNodeTypes(String yamlName, Resource resource,
-                                   String topologyTemplateYaml, boolean needLock,
+    protected void handleNodeTypes(String yamlName, Resource resource, String topologyTemplateYaml, boolean needLock,
                                    Map<String, EnumMap<ArtifactsBusinessLogic.ArtifactOperationEnum, List<ArtifactDefinition>>> nodeTypesArtifactsToHandle,
-                                   List<ArtifactDefinition> nodeTypesNewCreatedArtifacts, Map<String, NodeTypeInfo> nodeTypesInfo,
-                                   CsarInfo csarInfo, String nodeName) {
+                                   List<ArtifactDefinition> nodeTypesNewCreatedArtifacts, Map<String, NodeTypeInfo> nodeTypesInfo, CsarInfo csarInfo,
+                                   String nodeName) {
         try {
             for (Map.Entry<String, NodeTypeInfo> nodeTypeEntry : nodeTypesInfo.entrySet()) {
                 if (nodeTypeEntry.getValue().isNested()) {
-
-                    handleNestedVfc(resource, nodeTypesArtifactsToHandle, nodeTypesNewCreatedArtifacts,
-                        nodeTypesInfo, csarInfo, nodeTypeEntry.getKey());
+                    handleNestedVfc(resource, nodeTypesArtifactsToHandle, nodeTypesNewCreatedArtifacts, nodeTypesInfo, csarInfo,
+                        nodeTypeEntry.getKey());
                     log.trace("************* finished to create node {}", nodeTypeEntry.getKey());
                 }
             }
             Map<String, Object> mappedToscaTemplate = null;
-            if (org.apache.commons.lang.StringUtils.isNotEmpty(nodeName) && MapUtils.isNotEmpty(nodeTypesInfo)
-                && nodeTypesInfo.containsKey(nodeName)) {
+            if (org.apache.commons.lang.StringUtils.isNotEmpty(nodeName) && MapUtils.isNotEmpty(nodeTypesInfo) && nodeTypesInfo
+                .containsKey(nodeName)) {
                 mappedToscaTemplate = nodeTypesInfo.get(nodeName).getMappedToscaTemplate();
             }
             if (MapUtils.isEmpty(mappedToscaTemplate)) {
@@ -1259,8 +1141,8 @@ public class ServiceImportBusinessLogic {
             createResourcesFromYamlNodeTypesList(yamlName, resource, mappedToscaTemplate, needLock, nodeTypesArtifactsToHandle,
                 nodeTypesNewCreatedArtifacts, nodeTypesInfo, csarInfo);
         } catch (ComponentException e) {
-            ResponseFormat responseFormat = e.getResponseFormat() != null ? e.getResponseFormat()
-                : componentsUtils.getResponseFormat(e.getActionStatus(), e.getParams());
+            ResponseFormat responseFormat =
+                e.getResponseFormat() != null ? e.getResponseFormat() : componentsUtils.getResponseFormat(e.getActionStatus(), e.getParams());
             componentsUtils.auditResource(responseFormat, csarInfo.getModifier(), resource, AuditingActionEnum.IMPORT_RESOURCE);
             throw e;
         } catch (StorageException e) {
@@ -1281,8 +1163,8 @@ public class ServiceImportBusinessLogic {
         try {
             String yamlName = nodesInfo.get(nodeName).getTemplateFileName();
             Map<String, Object> nestedVfcJsonMap = nodesInfo.get(nodeName).getMappedToscaTemplate();
-            createResourcesFromYamlNodeTypesList(yamlName, service, nestedVfcJsonMap, false,
-                nodesArtifactsToHandle, createdArtifacts, nodesInfo, csarInfo);
+            createResourcesFromYamlNodeTypesList(yamlName, service, nestedVfcJsonMap, false, nodesArtifactsToHandle, createdArtifacts, nodesInfo,
+                csarInfo);
             log.debug("************* Finished to create node types from yaml {}", yamlName);
             if (nestedVfcJsonMap.containsKey(TypeUtils.ToscaTagNamesEnum.TOPOLOGY_TEMPLATE.getElementName())) {
                 log.debug("************* Going to handle complex VFC from yaml {}", yamlName);
@@ -1301,15 +1183,12 @@ public class ServiceImportBusinessLogic {
                                        String nodeName) {
         String yamlName = nodesInfo.get(nodeName).getTemplateFileName();
         Map<String, Object> nestedVfcJsonMap = nodesInfo.get(nodeName).getMappedToscaTemplate();
-
         log.debug("************* Going to create node types from yaml {}", yamlName);
-        createResourcesFromYamlNodeTypesList(yamlName, resource, nestedVfcJsonMap, false,
-            nodesArtifactsToHandle, createdArtifacts, nodesInfo, csarInfo);
-
+        createResourcesFromYamlNodeTypesList(yamlName, resource, nestedVfcJsonMap, false, nodesArtifactsToHandle, createdArtifacts, nodesInfo,
+            csarInfo);
         if (nestedVfcJsonMap.containsKey(TypeUtils.ToscaTagNamesEnum.TOPOLOGY_TEMPLATE.getElementName())) {
             log.debug("************* Going to handle complex VFC from yaml {}", yamlName);
-            resource = handleComplexVfc(resource, nodesArtifactsToHandle, createdArtifacts, nodesInfo,
-                csarInfo, nodeName, yamlName);
+            resource = handleComplexVfc(resource, nodesArtifactsToHandle, createdArtifacts, nodesInfo, csarInfo, nodeName, yamlName);
         }
         return resource;
     }
@@ -1324,29 +1203,27 @@ public class ServiceImportBusinessLogic {
             .getFullLatestComponentByToscaResourceName(newComplexVfc.getToscaResourceName());
         if (oldComplexVfcRes.isRight() && oldComplexVfcRes.right().value() == StorageOperationStatus.NOT_FOUND) {
             oldComplexVfcRes = toscaOperationFacade.getFullLatestComponentByToscaResourceName(
-                serviceImportParseLogic.buildNestedToscaResourceName(ResourceTypeEnum.VF.name(), csarInfo.getVfResourceName(),
-                    nodeName).getRight());
+                serviceImportParseLogic.buildNestedToscaResourceName(ResourceTypeEnum.VF.name(), csarInfo.getVfResourceName(), nodeName).getRight());
         }
         if (oldComplexVfcRes.isRight() && oldComplexVfcRes.right().value() != StorageOperationStatus.NOT_FOUND) {
             throw new ComponentException(ActionStatus.GENERAL_ERROR);
         } else if (oldComplexVfcRes.isLeft()) {
             log.debug(VALIDATE_DERIVED_BEFORE_UPDATE);
-            Either<Boolean, ResponseFormat> eitherValidation = serviceImportParseLogic.validateNestedDerivedFromDuringUpdate(
-                oldComplexVfcRes.left().value(), newComplexVfc,
-                ValidationUtils.hasBeenCertified(oldComplexVfcRes.left().value().getVersion()));
+            Either<Boolean, ResponseFormat> eitherValidation = serviceImportParseLogic
+                .validateNestedDerivedFromDuringUpdate(oldComplexVfcRes.left().value(), newComplexVfc,
+                    ValidationUtils.hasBeenCertified(oldComplexVfcRes.left().value().getVersion()));
             if (eitherValidation.isLeft()) {
                 oldComplexVfc = oldComplexVfcRes.left().value();
             }
         }
-        newComplexVfc = handleComplexVfc(nodesArtifactsToHandle, createdArtifacts, nodesInfo, csarInfo, nodeName, yamlName,
-            oldComplexVfc, newComplexVfc);
+        newComplexVfc = handleComplexVfc(nodesArtifactsToHandle, createdArtifacts, nodesInfo, csarInfo, nodeName, yamlName, oldComplexVfc,
+            newComplexVfc);
         csarInfo.getCreatedNodesToscaResourceNames().put(nodeName, newComplexVfc.getToscaResourceName());
-        LifecycleChangeInfoWithAction lifecycleChangeInfo = new LifecycleChangeInfoWithAction(
-            CERTIFICATION_ON_IMPORT, LifecycleChangeInfoWithAction.LifecycleChanceActionEnum.CREATE_FROM_CSAR);
+        LifecycleChangeInfoWithAction lifecycleChangeInfo = new LifecycleChangeInfoWithAction(CERTIFICATION_ON_IMPORT,
+            LifecycleChangeInfoWithAction.LifecycleChanceActionEnum.CREATE_FROM_CSAR);
         log.debug("Going to certify cvfc {}. ", newComplexVfc.getName());
         final Resource result = serviceImportParseLogic
-            .propagateStateToCertified(csarInfo.getModifier(), newComplexVfc, lifecycleChangeInfo, true, false,
-                true);
+            .propagateStateToCertified(csarInfo.getModifier(), newComplexVfc, lifecycleChangeInfo, true, false, true);
         csarInfo.getCreatedNodes().put(nodeName, result);
         csarInfo.removeNodeFromQueue();
         return result;
@@ -1356,8 +1233,7 @@ public class ServiceImportBusinessLogic {
                                                                       boolean needLock,
                                                                       Map<String, EnumMap<ArtifactOperationEnum, List<ArtifactDefinition>>> nodeTypesArtifactsToHandle,
                                                                       List<ArtifactDefinition> nodeTypesNewCreatedArtifacts,
-                                                                      Map<String, NodeTypeInfo> nodeTypesInfo,
-                                                                      CsarInfo csarInfo) {
+                                                                      Map<String, NodeTypeInfo> nodeTypesInfo, CsarInfo csarInfo) {
         Either<String, ImportUtils.ResultStatusEnum> toscaVersion = findFirstToscaStringElement(mappedToscaTemplate,
             TypeUtils.ToscaTagNamesEnum.TOSCA_VERSION);
         if (toscaVersion.isRight()) {
@@ -1379,28 +1255,21 @@ public class ServiceImportBusinessLogic {
         Resource vfcCreated = null;
         while (nodesNameValueIter.hasNext()) {
             Map.Entry<String, Object> nodeType = nodesNameValueIter.next();
-            Map<ArtifactsBusinessLogic.ArtifactOperationEnum, List<ArtifactDefinition>> nodeTypeArtifactsToHandle = nodeTypesArtifactsToHandle == null
-                || nodeTypesArtifactsToHandle.isEmpty() ? null
-                : nodeTypesArtifactsToHandle.get(nodeType.getKey());
-
+            Map<ArtifactsBusinessLogic.ArtifactOperationEnum, List<ArtifactDefinition>> nodeTypeArtifactsToHandle =
+                nodeTypesArtifactsToHandle == null || nodeTypesArtifactsToHandle.isEmpty() ? null : nodeTypesArtifactsToHandle.get(nodeType.getKey());
             if (nodeTypesInfo.containsKey(nodeType.getKey())) {
                 log.trace("************* Going to handle nested vfc {}", nodeType.getKey());
-                vfcCreated = handleNestedVfc(resource,
-                    nodeTypesArtifactsToHandle, nodeTypesNewCreatedArtifacts, nodeTypesInfo, csarInfo,
+                vfcCreated = handleNestedVfc(resource, nodeTypesArtifactsToHandle, nodeTypesNewCreatedArtifacts, nodeTypesInfo, csarInfo,
                     nodeType.getKey());
                 log.trace("************* Finished to handle nested vfc {}", nodeType.getKey());
-            } else if (csarInfo.getCreatedNodesToscaResourceNames() != null
-                && !csarInfo.getCreatedNodesToscaResourceNames().containsKey(nodeType.getKey())) {
+            } else if (csarInfo.getCreatedNodesToscaResourceNames() != null && !csarInfo.getCreatedNodesToscaResourceNames()
+                .containsKey(nodeType.getKey())) {
                 log.trace("************* Going to create node {}", nodeType.getKey());
                 ImmutablePair<Resource, ActionStatus> resourceCreated = createNodeTypeResourceFromYaml(yamlName, nodeType, csarInfo.getModifier(),
-                    mapToConvert,
-                    resource, needLock, nodeTypeArtifactsToHandle, nodeTypesNewCreatedArtifacts, true,
-                    csarInfo, true);
+                    mapToConvert, resource, needLock, nodeTypeArtifactsToHandle, nodeTypesNewCreatedArtifacts, true, csarInfo, true);
                 log.debug("************* Finished to create node {}", nodeType.getKey());
-
                 vfcCreated = resourceCreated.getLeft();
-                csarInfo.getCreatedNodesToscaResourceNames().put(nodeType.getKey(),
-                    vfcCreated.getToscaResourceName());
+                csarInfo.getCreatedNodesToscaResourceNames().put(nodeType.getKey(), vfcCreated.getToscaResourceName());
             }
             if (vfcCreated != null) {
                 csarInfo.getCreatedNodes().put(nodeType.getKey(), vfcCreated);
@@ -1409,21 +1278,18 @@ public class ServiceImportBusinessLogic {
         }
     }
 
-    protected ImmutablePair<Resource, ActionStatus> createNodeTypeResourceFromYaml(
-        String yamlName, Map.Entry<String, Object> nodeNameValue, User user, Map<String, Object> mapToConvert,
-        Resource resourceVf, boolean needLock,
-        Map<ArtifactOperationEnum, List<ArtifactDefinition>> nodeTypeArtifactsToHandle,
-        List<ArtifactDefinition> nodeTypesNewCreatedArtifacts, boolean forceCertificationAllowed, CsarInfo csarInfo,
-        boolean isNested) {
-        UploadResourceInfo resourceMetaData = serviceImportParseLogic
-            .fillResourceMetadata(yamlName, resourceVf, nodeNameValue.getKey(), user);
-
-        String singleVfcYaml = serviceImportParseLogic.buildNodeTypeYaml(nodeNameValue, mapToConvert,
-            resourceMetaData.getResourceType(), csarInfo);
+    protected ImmutablePair<Resource, ActionStatus> createNodeTypeResourceFromYaml(String yamlName, Map.Entry<String, Object> nodeNameValue,
+                                                                                   User user, Map<String, Object> mapToConvert, Resource resourceVf,
+                                                                                   boolean needLock,
+                                                                                   Map<ArtifactOperationEnum, List<ArtifactDefinition>> nodeTypeArtifactsToHandle,
+                                                                                   List<ArtifactDefinition> nodeTypesNewCreatedArtifacts,
+                                                                                   boolean forceCertificationAllowed, CsarInfo csarInfo,
+                                                                                   boolean isNested) {
+        UploadResourceInfo resourceMetaData = serviceImportParseLogic.fillResourceMetadata(yamlName, resourceVf, nodeNameValue.getKey(), user);
+        String singleVfcYaml = serviceImportParseLogic.buildNodeTypeYaml(nodeNameValue, mapToConvert, resourceMetaData.getResourceType(), csarInfo);
         user = serviceBusinessLogic.validateUser(user, "CheckIn Resource", resourceVf, AuditingActionEnum.CHECKIN_RESOURCE, true);
-        return serviceImportParseLogic.createResourceFromNodeType(singleVfcYaml, resourceMetaData, user, true, needLock,
-            nodeTypeArtifactsToHandle, nodeTypesNewCreatedArtifacts, forceCertificationAllowed, csarInfo,
-            nodeNameValue.getKey(), isNested);
+        return serviceImportParseLogic.createResourceFromNodeType(singleVfcYaml, resourceMetaData, user, true, needLock, nodeTypeArtifactsToHandle,
+            nodeTypesNewCreatedArtifacts, forceCertificationAllowed, csarInfo, nodeNameValue.getKey(), isNested);
     }
 
     protected Service createRIAndRelationsFromYaml(String yamlName, Service service,
@@ -1447,110 +1313,97 @@ public class ServiceImportBusinessLogic {
 
     protected Service createServiceInstancesRelations(User user, String yamlName, Service service,
                                                       Map<String, UploadComponentInstanceInfo> uploadResInstancesMap) {
-
-            log.debug("#createResourceInstancesRelations - Going to create relations ");
-            List<ComponentInstance> componentInstancesList = service.getComponentInstances();
-            if (((MapUtils.isEmpty(uploadResInstancesMap) || CollectionUtils.isEmpty(componentInstancesList)))) { // PNF can have no resource instances
-                log.debug("#createResourceInstancesRelations - No instances found in the resource {} is empty, yaml template file name {}, ",
+        log.debug("#createResourceInstancesRelations - Going to create relations ");
+        List<ComponentInstance> componentInstancesList = service.getComponentInstances();
+        if (((MapUtils.isEmpty(uploadResInstancesMap) || CollectionUtils.isEmpty(componentInstancesList)))) { // PNF can have no resource instances
+            log.debug("#createResourceInstancesRelations - No instances found in the resource {} is empty, yaml template file name {}, ",
                 service.getUniqueId(), yamlName);
-                BeEcompErrorManager.getInstance()
+            BeEcompErrorManager.getInstance()
                 .logInternalDataError("createResourceInstancesRelations", "No instances found in a component or nn yaml template. ",
                     BeEcompErrorManager.ErrorSeverity.ERROR);
-                throw new ComponentException(componentsUtils.getResponseFormat(ActionStatus.NOT_TOPOLOGY_TOSCA_TEMPLATE, yamlName));
-            }
-            Map<String, List<ComponentInstanceProperty>> instProperties = new HashMap<>();
-            Map<ComponentInstance, Map<String, List<CapabilityDefinition>>> instCapabilities = new HashMap<>();
-            Map<ComponentInstance, Map<String, List<RequirementDefinition>>> instRequirements = new HashMap<>();
-            Map<String, Map<String, ArtifactDefinition>> instDeploymentArtifacts = new HashMap<>();
-            Map<String, Map<String, ArtifactDefinition>> instArtifacts = new HashMap<>();
-            Map<String, List<AttributeDefinition>> instAttributes = new HashMap<>();
-            Map<String, Resource> originCompMap = new HashMap<>();
-            List<RequirementCapabilityRelDef> relations = new ArrayList<>();
-            Map<String, List<ComponentInstanceInput>> instInputs = new HashMap<>();
-
-            log.debug("enter ServiceImportBusinessLogic  createServiceInstancesRelations#createResourceInstancesRelations - Before get all datatypes. ");
-            if(serviceBusinessLogic.dataTypeCache!=null){
-                Either<Map<String, DataTypeDefinition>, JanusGraphOperationStatus> allDataTypes = serviceBusinessLogic.dataTypeCache.getAll();
-                if (allDataTypes.isRight()) {
-                    JanusGraphOperationStatus status = allDataTypes.right().value();
-                    BeEcompErrorManager.getInstance().logInternalFlowError("UpdatePropertyValueOnComponentInstance",
-                            "Failed to update property value on instance. Status is " + status, BeEcompErrorManager.ErrorSeverity.ERROR);
-                    throw new ComponentException(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(
-                            DaoStatusConverter.convertJanusGraphStatusToStorageStatus(status)), yamlName));
-                }
-                Service finalResource = service;
-                uploadResInstancesMap
-                        .values()
-                        .forEach(i -> processComponentInstance(yamlName, finalResource, componentInstancesList, allDataTypes,
-                                instProperties, instCapabilities, instRequirements, instDeploymentArtifacts,
-                                instArtifacts, instAttributes, originCompMap, instInputs, i));
-
-            }
-            serviceImportParseLogic.associateComponentInstancePropertiesToComponent(yamlName, service, instProperties);
-            serviceImportParseLogic.associateComponentInstanceInputsToComponent(yamlName, service, instInputs);
-            serviceImportParseLogic.associateDeploymentArtifactsToInstances(user, yamlName, service, instDeploymentArtifacts);
-            serviceImportParseLogic.associateArtifactsToInstances(yamlName, service, instArtifacts);
-            serviceImportParseLogic.associateOrAddCalculatedCapReq(yamlName, service, instCapabilities, instRequirements);
-            log.debug("enter createServiceInstancesRelations test,instRequirements:{},instCapabilities:{}",
-                    instRequirements, instCapabilities);
-            serviceImportParseLogic.associateInstAttributeToComponentToInstances(yamlName, service, instAttributes);
-            ToscaElement serviceTemplate = ModelConverter.convertToToscaElement(service);
-            Map<String, ListCapabilityDataDefinition> capabilities = serviceTemplate.getCapabilities();
-            Map<String, ListRequirementDataDefinition> requirements = serviceTemplate.getRequirements();
-
-            serviceImportParseLogic.associateCapabilitiesToService(yamlName, service, capabilities);
-            serviceImportParseLogic.associateRequirementsToService(yamlName, service, requirements);
-            service = getResourceAfterCreateRelations(service);
-
-            addRelationsToRI(yamlName, service, uploadResInstancesMap, componentInstancesList, relations);
-            serviceImportParseLogic.associateResourceInstances(yamlName, service, relations);
-            handleSubstitutionMappings(service, uploadResInstancesMap);
-            log.debug("************* in create relations, getResource start");
-            Either<Service, StorageOperationStatus> eitherGetResource = toscaOperationFacade.getToscaElement(service.getUniqueId());
-            log.debug("************* in create relations, getResource end");
-            if (eitherGetResource.isRight()) {
-                throw new ComponentException(componentsUtils.getResponseFormatByComponent(
-                        componentsUtils.convertFromStorageResponse(eitherGetResource.right().value()), service, service.getComponentType()));
-            }
-            return eitherGetResource.left().value();
-    }
-
-    protected void processComponentInstance(String yamlName, Component component,
-                                            List<ComponentInstance> componentInstancesList,
+            throw new ComponentException(componentsUtils.getResponseFormat(ActionStatus.NOT_TOPOLOGY_TOSCA_TEMPLATE, yamlName));
+        }
+        Map<String, List<ComponentInstanceProperty>> instProperties = new HashMap<>();
+        Map<ComponentInstance, Map<String, List<CapabilityDefinition>>> instCapabilities = new HashMap<>();
+        Map<ComponentInstance, Map<String, List<RequirementDefinition>>> instRequirements = new HashMap<>();
+        Map<String, Map<String, ArtifactDefinition>> instDeploymentArtifacts = new HashMap<>();
+        Map<String, Map<String, ArtifactDefinition>> instArtifacts = new HashMap<>();
+        Map<String, List<AttributeDefinition>> instAttributes = new HashMap<>();
+        Map<String, Resource> originCompMap = new HashMap<>();
+        List<RequirementCapabilityRelDef> relations = new ArrayList<>();
+        Map<String, List<ComponentInstanceInput>> instInputs = new HashMap<>();
+        log.debug("enter ServiceImportBusinessLogic  createServiceInstancesRelations#createResourceInstancesRelations - Before get all datatypes. ");
+        if (serviceBusinessLogic.dataTypeCache != null) {
+            Either<Map<String, DataTypeDefinition>, JanusGraphOperationStatus> allDataTypes = serviceBusinessLogic.dataTypeCache.getAll();
+            if (allDataTypes.isRight()) {
+                JanusGraphOperationStatus status = allDataTypes.right().value();
+                BeEcompErrorManager.getInstance().logInternalFlowError("UpdatePropertyValueOnComponentInstance",
+                    "Failed to update property value on instance. Status is " + status, BeEcompErrorManager.ErrorSeverity.ERROR);
+                throw new ComponentException(componentsUtils
+                    .getResponseFormat(componentsUtils.convertFromStorageResponse(DaoStatusConverter.convertJanusGraphStatusToStorageStatus(status)),
+                        yamlName));
+            }
+            Service finalResource = service;
+            uploadResInstancesMap.values().forEach(
+                i -> processComponentInstance(yamlName, finalResource, componentInstancesList, allDataTypes, instProperties, instCapabilities,
+                    instRequirements, instDeploymentArtifacts, instArtifacts, instAttributes, originCompMap, instInputs, i));
+        }
+        serviceImportParseLogic.associateComponentInstancePropertiesToComponent(yamlName, service, instProperties);
+        serviceImportParseLogic.associateComponentInstanceInputsToComponent(yamlName, service, instInputs);
+        serviceImportParseLogic.associateDeploymentArtifactsToInstances(user, yamlName, service, instDeploymentArtifacts);
+        serviceImportParseLogic.associateArtifactsToInstances(yamlName, service, instArtifacts);
+        serviceImportParseLogic.associateOrAddCalculatedCapReq(yamlName, service, instCapabilities, instRequirements);
+        log.debug("enter createServiceInstancesRelations test,instRequirements:{},instCapabilities:{}", instRequirements, instCapabilities);
+        serviceImportParseLogic.associateInstAttributeToComponentToInstances(yamlName, service, instAttributes);
+        ToscaElement serviceTemplate = ModelConverter.convertToToscaElement(service);
+        Map<String, ListCapabilityDataDefinition> capabilities = serviceTemplate.getCapabilities();
+        Map<String, ListRequirementDataDefinition> requirements = serviceTemplate.getRequirements();
+        serviceImportParseLogic.associateCapabilitiesToService(yamlName, service, capabilities);
+        serviceImportParseLogic.associateRequirementsToService(yamlName, service, requirements);
+        service = getResourceAfterCreateRelations(service);
+        addRelationsToRI(yamlName, service, uploadResInstancesMap, componentInstancesList, relations);
+        serviceImportParseLogic.associateResourceInstances(yamlName, service, relations);
+        handleSubstitutionMappings(service, uploadResInstancesMap);
+        log.debug("************* in create relations, getResource start");
+        Either<Service, StorageOperationStatus> eitherGetResource = toscaOperationFacade.getToscaElement(service.getUniqueId());
+        log.debug("************* in create relations, getResource end");
+        if (eitherGetResource.isRight()) {
+            throw new ComponentException(componentsUtils
+                .getResponseFormatByComponent(componentsUtils.convertFromStorageResponse(eitherGetResource.right().value()), service,
+                    service.getComponentType()));
+        }
+        return eitherGetResource.left().value();
+    }
+
+    protected void processComponentInstance(String yamlName, Component component, List<ComponentInstance> componentInstancesList,
                                             Either<Map<String, DataTypeDefinition>, JanusGraphOperationStatus> allDataTypes,
                                             Map<String, List<ComponentInstanceProperty>> instProperties,
                                             Map<ComponentInstance, Map<String, List<CapabilityDefinition>>> instCapabilties,
                                             Map<ComponentInstance, Map<String, List<RequirementDefinition>>> instRequirements,
                                             Map<String, Map<String, ArtifactDefinition>> instDeploymentArtifacts,
                                             Map<String, Map<String, ArtifactDefinition>> instArtifacts,
-                                            Map<String, List<AttributeDefinition>> instAttributes,
-                                            Map<String, Resource> originCompMap,
+                                            Map<String, List<AttributeDefinition>> instAttributes, Map<String, Resource> originCompMap,
                                             Map<String, List<ComponentInstanceInput>> instInputs,
                                             UploadComponentInstanceInfo uploadComponentInstanceInfo) {
         log.debug("enter ServiceImportBusinessLogic processComponentInstance");
         Optional<ComponentInstance> currentCompInstanceOpt = componentInstancesList.stream()
-            .filter(i -> i.getName().equals(uploadComponentInstanceInfo.getName()))
-            .findFirst();
+            .filter(i -> i.getName().equals(uploadComponentInstanceInfo.getName())).findFirst();
         if (!currentCompInstanceOpt.isPresent()) {
-            log.debug(COMPONENT_INSTANCE_WITH_NAME_IN_RESOURCE, uploadComponentInstanceInfo.getName(),
-                component.getUniqueId());
-            BeEcompErrorManager.getInstance().logInternalDataError(
-                COMPONENT_INSTANCE_WITH_NAME + uploadComponentInstanceInfo.getName() + IN_RESOURCE,
-                component.getUniqueId(), BeEcompErrorManager.ErrorSeverity.ERROR);
-            ResponseFormat responseFormat = componentsUtils
-                .getResponseFormat(ActionStatus.NOT_TOPOLOGY_TOSCA_TEMPLATE, yamlName);
+            log.debug(COMPONENT_INSTANCE_WITH_NAME_IN_RESOURCE, uploadComponentInstanceInfo.getName(), component.getUniqueId());
+            BeEcompErrorManager.getInstance()
+                .logInternalDataError(COMPONENT_INSTANCE_WITH_NAME + uploadComponentInstanceInfo.getName() + IN_RESOURCE, component.getUniqueId(),
+                    BeEcompErrorManager.ErrorSeverity.ERROR);
+            ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.NOT_TOPOLOGY_TOSCA_TEMPLATE, yamlName);
             throw new ComponentException(responseFormat);
         }
         ComponentInstance currentCompInstance = currentCompInstanceOpt.get();
         String resourceInstanceId = currentCompInstance.getUniqueId();
         Resource originResource = getOriginResource(yamlName, originCompMap, currentCompInstance);
-
         if (MapUtils.isNotEmpty(originResource.getRequirements())) {
             instRequirements.put(currentCompInstance, originResource.getRequirements());
         }
         if (MapUtils.isNotEmpty(originResource.getCapabilities())) {
-            processComponentInstanceCapabilities(allDataTypes, instCapabilties, uploadComponentInstanceInfo,
-                currentCompInstance, originResource);
+            processComponentInstanceCapabilities(allDataTypes, instCapabilties, uploadComponentInstanceInfo, currentCompInstance, originResource);
         }
         if (originResource.getDeploymentArtifacts() != null && !originResource.getDeploymentArtifacts().isEmpty()) {
             instDeploymentArtifacts.put(resourceInstanceId, originResource.getDeploymentArtifacts());
@@ -1562,27 +1415,24 @@ public class ServiceImportBusinessLogic {
             instAttributes.put(resourceInstanceId, originResource.getAttributes());
         }
         if (originResource.getResourceType() != ResourceTypeEnum.VF) {
-            ResponseFormat addPropertiesValueToRiRes = addPropertyValuesToRi(uploadComponentInstanceInfo, component,
-                originResource, currentCompInstance, instProperties, allDataTypes.left().value());
+            ResponseFormat addPropertiesValueToRiRes = addPropertyValuesToRi(uploadComponentInstanceInfo, component, originResource,
+                currentCompInstance, instProperties, allDataTypes.left().value());
             if (addPropertiesValueToRiRes.getStatus() != 200) {
                 throw new ComponentException(addPropertiesValueToRiRes);
             }
         } else {
-            addInputsValuesToRi(uploadComponentInstanceInfo, component,
-                originResource, currentCompInstance, instInputs, allDataTypes.left().value());
+            addInputsValuesToRi(uploadComponentInstanceInfo, component, originResource, currentCompInstance, instInputs, allDataTypes.left().value());
         }
     }
 
-
-    protected void addInputsValuesToRi(UploadComponentInstanceInfo uploadComponentInstanceInfo,
-                                       Component component, Resource originResource, ComponentInstance currentCompInstance,
-                                       Map<String, List<ComponentInstanceInput>> instInputs, Map<String, DataTypeDefinition> allDataTypes) {
+    protected void addInputsValuesToRi(UploadComponentInstanceInfo uploadComponentInstanceInfo, Component component, Resource originResource,
+                                       ComponentInstance currentCompInstance, Map<String, List<ComponentInstanceInput>> instInputs,
+                                       Map<String, DataTypeDefinition> allDataTypes) {
         Map<String, List<UploadPropInfo>> propMap = uploadComponentInstanceInfo.getProperties();
         try {
             if (MapUtils.isNotEmpty(propMap)) {
                 Map<String, InputDefinition> currPropertiesMap = new HashMap<>();
                 List<ComponentInstanceInput> instPropList = new ArrayList<>();
-
                 if (CollectionUtils.isEmpty(originResource.getInputs())) {
                     log.debug("failed to find properties ");
                     throw new ComponentException(componentsUtils.getResponseFormat(ActionStatus.PROPERTY_NOT_FOUND));
@@ -1607,8 +1457,7 @@ public class ServiceImportBusinessLogic {
         String propName = propertyInfo.getName();
         if (!currPropertiesMap.containsKey(propName)) {
             log.debug("failed to find property {} ", propName);
-            throw new ComponentException(componentsUtils.getResponseFormat(ActionStatus.PROPERTY_NOT_FOUND,
-                propName));
+            throw new ComponentException(componentsUtils.getResponseFormat(ActionStatus.PROPERTY_NOT_FOUND, propName));
         }
         processProperty(allDataTypes, currPropertiesMap, instPropList, propertyInfo, propName, component.getInputs());
     }
@@ -1617,8 +1466,7 @@ public class ServiceImportBusinessLogic {
                                    GetInputValueDataDefinition getInputIndex) {
         Optional<InputDefinition> optional;
         if (getInputIndex != null) {
-            optional = inputs.stream().filter(p -> p.getName().equals(getInputIndex.getInputName()))
-                .findAny();
+            optional = inputs.stream().filter(p -> p.getName().equals(getInputIndex.getInputName())).findAny();
             if (!optional.isPresent()) {
                 log.debug("Failed to find input {} ", getInputIndex.getInputName());
                 throw new ComponentException(componentsUtils.getResponseFormat(ActionStatus.INVALID_CONTENT));
@@ -1629,13 +1477,12 @@ public class ServiceImportBusinessLogic {
         }
     }
 
-    protected ResponseFormat addPropertyValuesToRi(UploadComponentInstanceInfo uploadComponentInstanceInfo,
-                                                   Component component, Resource originResource, ComponentInstance currentCompInstance,
+    protected ResponseFormat addPropertyValuesToRi(UploadComponentInstanceInfo uploadComponentInstanceInfo, Component component,
+                                                   Resource originResource, ComponentInstance currentCompInstance,
                                                    Map<String, List<ComponentInstanceProperty>> instProperties,
                                                    Map<String, DataTypeDefinition> allDataTypes) {
         Map<String, List<UploadPropInfo>> propMap = uploadComponentInstanceInfo.getProperties();
         Map<String, PropertyDefinition> currPropertiesMap = new HashMap<>();
-
         List<PropertyDefinition> listFromMap = originResource.getProperties();
         if ((propMap != null && !propMap.isEmpty()) && (listFromMap == null || listFromMap.isEmpty())) {
             log.debug("failed to find properties ");
@@ -1657,12 +1504,10 @@ public class ServiceImportBusinessLogic {
                 String propName = propertyInfo.getName();
                 if (!currPropertiesMap.containsKey(propName)) {
                     log.debug("failed to find property {} ", propName);
-                    return componentsUtils.getResponseFormat(ActionStatus.PROPERTY_NOT_FOUND,
-                        propName);
+                    return componentsUtils.getResponseFormat(ActionStatus.PROPERTY_NOT_FOUND, propName);
                 }
                 PropertyDefinition curPropertyDef = currPropertiesMap.get(propName);
                 ComponentInstanceProperty property = null;
-
                 String value = null;
                 List<GetInputValueDataDefinition> getInputs = null;
                 boolean isValidate = true;
@@ -1670,33 +1515,26 @@ public class ServiceImportBusinessLogic {
                     getInputs = propertyInfo.getGet_input();
                     isValidate = getInputs == null || getInputs.isEmpty();
                     if (isValidate) {
-                        value = getPropertyJsonStringValue(propertyInfo.getValue(),
-                            curPropertyDef.getType());
+                        value = getPropertyJsonStringValue(propertyInfo.getValue(), curPropertyDef.getType());
                     } else {
-                        value = getPropertyJsonStringValue(propertyInfo.getValue(),
-                            TypeUtils.ToscaTagNamesEnum.GET_INPUT.getElementName());
+                        value = getPropertyJsonStringValue(propertyInfo.getValue(), TypeUtils.ToscaTagNamesEnum.GET_INPUT.getElementName());
                     }
                 }
                 property = new ComponentInstanceProperty(curPropertyDef, value, null);
-
                 String validatePropValue = serviceBusinessLogic.validatePropValueBeforeCreate(property, value, isValidate, allDataTypes);
                 property.setValue(validatePropValue);
-
                 if (getInputs != null && !getInputs.isEmpty()) {
                     List<GetInputValueDataDefinition> getInputValues = new ArrayList<>();
                     for (GetInputValueDataDefinition getInput : getInputs) {
                         List<InputDefinition> inputs = component.getInputs();
                         if (inputs == null || inputs.isEmpty()) {
                             log.debug("Failed to add property {} to instance. Inputs list is empty ", property);
-                            serviceBusinessLogic.rollbackWithException(ActionStatus.INPUTS_NOT_FOUND, property.getGetInputValues()
-                                .stream()
-                                .map(GetInputValueDataDefinition::getInputName)
-                                .collect(toList()).toString());
+                            serviceBusinessLogic.rollbackWithException(ActionStatus.INPUTS_NOT_FOUND,
+                                property.getGetInputValues().stream().map(GetInputValueDataDefinition::getInputName).collect(toList()).toString());
                         }
                         InputDefinition input = serviceImportParseLogic.findInputByName(inputs, getInput);
                         getInput.setInputId(input.getUniqueId());
                         getInputValues.add(getInput);
-
                         GetInputValueDataDefinition getInputIndex = getInput.getGetInputIndex();
                         if (getInputIndex != null) {
                             input = serviceImportParseLogic.findInputByName(inputs, getInputIndex);
@@ -1728,10 +1566,9 @@ public class ServiceImportBusinessLogic {
         if (MapUtils.isNotEmpty(uploadComponentInstanceInfo.getCapabilities())) {
             originCapabilities = new HashMap<>();
             Map<String, Map<String, UploadPropInfo>> newPropertiesMap = new HashMap<>();
-            originResource.getCapabilities().forEach((k, v) -> serviceImportParseLogic
-                .addCapabilities(originCapabilities, k, v));
-            uploadComponentInstanceInfo.getCapabilities().values().forEach(l -> serviceImportParseLogic
-                .addCapabilitiesProperties(newPropertiesMap, l));
+            originResource.getCapabilities().forEach((k, v) -> serviceImportParseLogic.addCapabilities(originCapabilities, k, v));
+            uploadComponentInstanceInfo.getCapabilities().values()
+                .forEach(l -> serviceImportParseLogic.addCapabilitiesProperties(newPropertiesMap, l));
             updateCapabilityPropertiesValues(allDataTypes, originCapabilities, newPropertiesMap);
         } else {
             originCapabilities = originResource.getCapabilities();
@@ -1742,9 +1579,7 @@ public class ServiceImportBusinessLogic {
     protected void updateCapabilityPropertiesValues(Either<Map<String, DataTypeDefinition>, JanusGraphOperationStatus> allDataTypes,
                                                     Map<String, List<CapabilityDefinition>> originCapabilities,
                                                     Map<String, Map<String, UploadPropInfo>> newPropertiesMap) {
-        originCapabilities.values().stream()
-            .flatMap(Collection::stream)
-            .filter(c -> newPropertiesMap.containsKey(c.getName()))
+        originCapabilities.values().stream().flatMap(Collection::stream).filter(c -> newPropertiesMap.containsKey(c.getName()))
             .forEach(c -> updatePropertyValues(c.getProperties(), newPropertiesMap.get(c.getName()), allDataTypes.left().value()));
     }
 
@@ -1764,8 +1599,7 @@ public class ServiceImportBusinessLogic {
             if (isValidate) {
                 value = getPropertyJsonStringValue(propertyInfo.getValue(), property.getType());
             } else {
-                value = getPropertyJsonStringValue(propertyInfo.getValue(),
-                    TypeUtils.ToscaTagNamesEnum.GET_INPUT.getElementName());
+                value = getPropertyJsonStringValue(propertyInfo.getValue(), TypeUtils.ToscaTagNamesEnum.GET_INPUT.getElementName());
             }
         }
         property.setValue(value);
@@ -1779,8 +1613,8 @@ public class ServiceImportBusinessLogic {
             Either<Resource, StorageOperationStatus> getOriginResourceRes = toscaOperationFacade
                 .getToscaFullElement(currentCompInstance.getComponentUid());
             if (getOriginResourceRes.isRight()) {
-                ResponseFormat responseFormat = componentsUtils.getResponseFormat(
-                    componentsUtils.convertFromStorageResponse(getOriginResourceRes.right().value()), yamlName);
+                ResponseFormat responseFormat = componentsUtils
+                    .getResponseFormat(componentsUtils.convertFromStorageResponse(getOriginResourceRes.right().value()), yamlName);
                 throw new ComponentException(responseFormat);
             }
             originResource = getOriginResourceRes.left().value();
@@ -1795,15 +1629,16 @@ public class ServiceImportBusinessLogic {
         if (false) {
             Either<Resource, StorageOperationStatus> getResourceRes = toscaOperationFacade.getToscaFullElement(service.getUniqueId());
             if (getResourceRes.isRight()) {
-                ResponseFormat responseFormat = componentsUtils.getResponseFormatByComponent(
-                    componentsUtils.convertFromStorageResponse(getResourceRes.right().value()), service, ComponentTypeEnum.SERVICE);
+                ResponseFormat responseFormat = componentsUtils
+                    .getResponseFormatByComponent(componentsUtils.convertFromStorageResponse(getResourceRes.right().value()), service,
+                        ComponentTypeEnum.SERVICE);
                 throw new ComponentException(responseFormat);
             }
-            getResourceRes = updateCalculatedCapReqWithSubstitutionMappings(getResourceRes.left().value(),
-                uploadResInstancesMap);
+            getResourceRes = updateCalculatedCapReqWithSubstitutionMappings(getResourceRes.left().value(), uploadResInstancesMap);
             if (getResourceRes.isRight()) {
-                ResponseFormat responseFormat = componentsUtils.getResponseFormatByComponent(
-                    componentsUtils.convertFromStorageResponse(getResourceRes.right().value()), service, ComponentTypeEnum.SERVICE);
+                ResponseFormat responseFormat = componentsUtils
+                    .getResponseFormatByComponent(componentsUtils.convertFromStorageResponse(getResourceRes.right().value()), service,
+                        ComponentTypeEnum.SERVICE);
                 throw new ComponentException(responseFormat);
             }
         }
@@ -1814,19 +1649,16 @@ public class ServiceImportBusinessLogic {
         Either<Resource, StorageOperationStatus> updateRes = null;
         Map<ComponentInstance, Map<String, List<CapabilityDefinition>>> updatedInstCapabilities = new HashMap<>();
         Map<ComponentInstance, Map<String, List<RequirementDefinition>>> updatedInstRequirements = new HashMap<>();
-        StorageOperationStatus status = toscaOperationFacade
-            .deleteAllCalculatedCapabilitiesRequirements(resource.getUniqueId());
+        StorageOperationStatus status = toscaOperationFacade.deleteAllCalculatedCapabilitiesRequirements(resource.getUniqueId());
         if (status != StorageOperationStatus.OK && status != StorageOperationStatus.NOT_FOUND) {
-            log.debug(
-                "Failed to delete all calculated capabilities and requirements of resource {} upon update. Status is {}",
+            log.debug("Failed to delete all calculated capabilities and requirements of resource {} upon update. Status is {}",
                 resource.getUniqueId(), status);
             updateRes = Either.right(status);
         }
         if (updateRes == null) {
-            fillUpdatedInstCapabilitiesRequirements(resource.getComponentInstances(), uploadResInstancesMap,
-                updatedInstCapabilities, updatedInstRequirements);
-            status = toscaOperationFacade.associateOrAddCalculatedCapReq(updatedInstCapabilities, updatedInstRequirements,
-                resource);
+            fillUpdatedInstCapabilitiesRequirements(resource.getComponentInstances(), uploadResInstancesMap, updatedInstCapabilities,
+                updatedInstRequirements);
+            status = toscaOperationFacade.associateOrAddCalculatedCapReq(updatedInstCapabilities, updatedInstRequirements, resource);
             if (status != StorageOperationStatus.OK && status != StorageOperationStatus.NOT_FOUND) {
                 updateRes = Either.right(status);
             }
@@ -1842,30 +1674,25 @@ public class ServiceImportBusinessLogic {
                                                            Map<ComponentInstance, Map<String, List<CapabilityDefinition>>> updatedInstCapabilities,
                                                            Map<ComponentInstance, Map<String, List<RequirementDefinition>>> updatedInstRequirements) {
         componentInstances.stream().forEach(i -> {
-            fillUpdatedInstCapabilities(updatedInstCapabilities, i,
-                uploadResInstancesMap.get(i.getName()).getCapabilitiesNamesToUpdate());
-            fillUpdatedInstRequirements(updatedInstRequirements, i,
-                uploadResInstancesMap.get(i.getName()).getRequirementsNamesToUpdate());
+            fillUpdatedInstCapabilities(updatedInstCapabilities, i, uploadResInstancesMap.get(i.getName()).getCapabilitiesNamesToUpdate());
+            fillUpdatedInstRequirements(updatedInstRequirements, i, uploadResInstancesMap.get(i.getName()).getRequirementsNamesToUpdate());
         });
     }
 
-    protected void fillUpdatedInstCapabilities(
-        Map<ComponentInstance, Map<String, List<CapabilityDefinition>>> updatedInstCapabilties,
-        ComponentInstance instance, Map<String, String> capabilitiesNamesToUpdate) {
+    protected void fillUpdatedInstCapabilities(Map<ComponentInstance, Map<String, List<CapabilityDefinition>>> updatedInstCapabilties,
+                                               ComponentInstance instance, Map<String, String> capabilitiesNamesToUpdate) {
         Map<String, List<CapabilityDefinition>> updatedCapabilities = new HashMap<>();
         Set<String> updatedCapNames = new HashSet<>();
         if (MapUtils.isNotEmpty(capabilitiesNamesToUpdate)) {
             for (Map.Entry<String, List<CapabilityDefinition>> requirements : instance.getCapabilities().entrySet()) {
-                updatedCapabilities.put(requirements.getKey(),
-                    requirements.getValue().stream()
-                        .filter(c -> capabilitiesNamesToUpdate.containsKey(c.getName())
-                            && !updatedCapNames.contains(capabilitiesNamesToUpdate.get(c.getName())))
-                        .map(c -> {
-                            c.setParentName(c.getName());
-                            c.setName(capabilitiesNamesToUpdate.get(c.getName()));
-                            updatedCapNames.add(c.getName());
-                            return c;
-                        }).collect(toList()));
+                updatedCapabilities.put(requirements.getKey(), requirements.getValue().stream().filter(
+                    c -> capabilitiesNamesToUpdate.containsKey(c.getName()) && !updatedCapNames.contains(capabilitiesNamesToUpdate.get(c.getName())))
+                    .map(c -> {
+                        c.setParentName(c.getName());
+                        c.setName(capabilitiesNamesToUpdate.get(c.getName()));
+                        updatedCapNames.add(c.getName());
+                        return c;
+                    }).collect(toList()));
             }
         }
         if (MapUtils.isNotEmpty(updatedCapabilities)) {
@@ -1873,23 +1700,20 @@ public class ServiceImportBusinessLogic {
         }
     }
 
-    protected void fillUpdatedInstRequirements(
-        Map<ComponentInstance, Map<String, List<RequirementDefinition>>> updatedInstRequirements,
-        ComponentInstance instance, Map<String, String> requirementsNamesToUpdate) {
+    protected void fillUpdatedInstRequirements(Map<ComponentInstance, Map<String, List<RequirementDefinition>>> updatedInstRequirements,
+                                               ComponentInstance instance, Map<String, String> requirementsNamesToUpdate) {
         Map<String, List<RequirementDefinition>> updatedRequirements = new HashMap<>();
         Set<String> updatedReqNames = new HashSet<>();
         if (MapUtils.isNotEmpty(requirementsNamesToUpdate)) {
             for (Map.Entry<String, List<RequirementDefinition>> requirements : instance.getRequirements().entrySet()) {
-                updatedRequirements.put(requirements.getKey(),
-                    requirements.getValue().stream()
-                        .filter(r -> requirementsNamesToUpdate.containsKey(r.getName())
-                            && !updatedReqNames.contains(requirementsNamesToUpdate.get(r.getName())))
-                        .map(r -> {
-                            r.setParentName(r.getName());
-                            r.setName(requirementsNamesToUpdate.get(r.getName()));
-                            updatedReqNames.add(r.getName());
-                            return r;
-                        }).collect(toList()));
+                updatedRequirements.put(requirements.getKey(), requirements.getValue().stream().filter(
+                    r -> requirementsNamesToUpdate.containsKey(r.getName()) && !updatedReqNames.contains(requirementsNamesToUpdate.get(r.getName())))
+                    .map(r -> {
+                        r.setParentName(r.getName());
+                        r.setName(requirementsNamesToUpdate.get(r.getName()));
+                        updatedReqNames.add(r.getName());
+                        return r;
+                    }).collect(toList()));
             }
         }
         if (MapUtils.isNotEmpty(updatedRequirements)) {
@@ -1909,16 +1733,13 @@ public class ServiceImportBusinessLogic {
                 }
             }
             if (currentCompInstance == null) {
-                log.debug(COMPONENT_INSTANCE_WITH_NAME_IN_RESOURCE, uploadComponentInstanceInfo.getName(),
-                    service.getUniqueId());
-                BeEcompErrorManager.getInstance().logInternalDataError(
-                    COMPONENT_INSTANCE_WITH_NAME + uploadComponentInstanceInfo.getName() + IN_RESOURCE,
-                    service.getUniqueId(), BeEcompErrorManager.ErrorSeverity.ERROR);
-                ResponseFormat responseFormat = componentsUtils
-                    .getResponseFormat(ActionStatus.NOT_TOPOLOGY_TOSCA_TEMPLATE, yamlName);
+                log.debug(COMPONENT_INSTANCE_WITH_NAME_IN_RESOURCE, uploadComponentInstanceInfo.getName(), service.getUniqueId());
+                BeEcompErrorManager.getInstance()
+                    .logInternalDataError(COMPONENT_INSTANCE_WITH_NAME + uploadComponentInstanceInfo.getName() + IN_RESOURCE, service.getUniqueId(),
+                        BeEcompErrorManager.ErrorSeverity.ERROR);
+                ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.NOT_TOPOLOGY_TOSCA_TEMPLATE, yamlName);
                 throw new ComponentException(responseFormat);
             }
-
             ResponseFormat addRelationToRiRes = addRelationToRI(yamlName, service, entry.getValue(), relations);
             if (addRelationToRiRes.getStatus() != 200) {
                 throw new ComponentException(addRelationToRiRes);
@@ -1926,8 +1747,8 @@ public class ServiceImportBusinessLogic {
         }
     }
 
-    protected ResponseFormat addRelationToRI(String yamlName, Service service,
-                                             UploadComponentInstanceInfo nodesInfoValue, List<RequirementCapabilityRelDef> relations) {
+    protected ResponseFormat addRelationToRI(String yamlName, Service service, UploadComponentInstanceInfo nodesInfoValue,
+                                             List<RequirementCapabilityRelDef> relations) {
         List<ComponentInstance> componentInstancesList = service.getComponentInstances();
         ComponentInstance currentCompInstance = null;
         for (ComponentInstance compInstance : componentInstancesList) {
@@ -1937,17 +1758,14 @@ public class ServiceImportBusinessLogic {
             }
         }
         if (currentCompInstance == null) {
-            log.debug(COMPONENT_INSTANCE_WITH_NAME_IN_RESOURCE, nodesInfoValue.getName(),
-                service.getUniqueId());
-            BeEcompErrorManager.getInstance().logInternalDataError(
-                COMPONENT_INSTANCE_WITH_NAME + nodesInfoValue.getName() + IN_RESOURCE,
-                service.getUniqueId(), BeEcompErrorManager.ErrorSeverity.ERROR);
-            return componentsUtils.getResponseFormat(ActionStatus.NOT_TOPOLOGY_TOSCA_TEMPLATE,
-                yamlName);
+            log.debug(COMPONENT_INSTANCE_WITH_NAME_IN_RESOURCE, nodesInfoValue.getName(), service.getUniqueId());
+            BeEcompErrorManager.getInstance()
+                .logInternalDataError(COMPONENT_INSTANCE_WITH_NAME + nodesInfoValue.getName() + IN_RESOURCE, service.getUniqueId(),
+                    BeEcompErrorManager.ErrorSeverity.ERROR);
+            return componentsUtils.getResponseFormat(ActionStatus.NOT_TOPOLOGY_TOSCA_TEMPLATE, yamlName);
         }
         String resourceInstanceId = currentCompInstance.getUniqueId();
         Map<String, List<UploadReqInfo>> regMap = nodesInfoValue.getRequirements();
-
         if (regMap != null) {
             Iterator<Map.Entry<String, List<UploadReqInfo>>> nodesRegValue = regMap.entrySet().iterator();
             while (nodesRegValue.hasNext()) {
@@ -1959,18 +1777,14 @@ public class ServiceImportBusinessLogic {
                     RequirementCapabilityRelDef regCapRelDef = new RequirementCapabilityRelDef();
                     regCapRelDef.setFromNode(resourceInstanceId);
                     log.debug("try to find available requirement {} ", regName);
-                    Either<RequirementDefinition, ResponseFormat> eitherReqStatus = serviceImportParseLogic.findAviableRequiremen(regName,
-                        yamlName, nodesInfoValue, currentCompInstance,
-                        uploadRegInfo.getCapabilityName());
+                    Either<RequirementDefinition, ResponseFormat> eitherReqStatus = serviceImportParseLogic
+                        .findAviableRequiremen(regName, yamlName, nodesInfoValue, currentCompInstance, uploadRegInfo.getCapabilityName());
                     if (eitherReqStatus.isRight()) {
-                        log.debug("failed to find available requirement {} status is {}", regName,
-                            eitherReqStatus.right().value());
+                        log.debug("failed to find available requirement {} status is {}", regName, eitherReqStatus.right().value());
                         return eitherReqStatus.right().value();
                     }
-
                     RequirementDefinition validReq = eitherReqStatus.left().value();
-                    List<CapabilityRequirementRelationship> reqAndRelationshipPairList = regCapRelDef
-                        .getRelationships();
+                    List<CapabilityRequirementRelationship> reqAndRelationshipPairList = regCapRelDef.getRelationships();
                     if (reqAndRelationshipPairList == null) {
                         reqAndRelationshipPairList = new ArrayList<>();
                     }
@@ -1981,7 +1795,6 @@ public class ServiceImportBusinessLogic {
                     RelationshipImpl relationship = new RelationshipImpl();
                     relationship.setType(validReq.getCapability());
                     reqAndRelationshipPair.setRelationships(relationship);
-
                     ComponentInstance currentCapCompInstance = null;
                     for (ComponentInstance compInstance : componentInstancesList) {
                         if (compInstance.getName().equals(uploadRegInfo.getNode())) {
@@ -1990,28 +1803,24 @@ public class ServiceImportBusinessLogic {
                         }
                     }
                     if (currentCapCompInstance == null) {
-                        log.debug("The component instance  with name {} not found on resource {} ",
-                            uploadRegInfo.getNode(), service.getUniqueId());
-                        BeEcompErrorManager.getInstance().logInternalDataError(
-                            COMPONENT_INSTANCE_WITH_NAME + uploadRegInfo.getNode() + IN_RESOURCE,
-                            service.getUniqueId(), BeEcompErrorManager.ErrorSeverity.ERROR);
-                        return componentsUtils
-                            .getResponseFormat(ActionStatus.NOT_TOPOLOGY_TOSCA_TEMPLATE, yamlName);
+                        log.debug("The component instance  with name {} not found on resource {} ", uploadRegInfo.getNode(), service.getUniqueId());
+                        BeEcompErrorManager.getInstance()
+                            .logInternalDataError(COMPONENT_INSTANCE_WITH_NAME + uploadRegInfo.getNode() + IN_RESOURCE, service.getUniqueId(),
+                                BeEcompErrorManager.ErrorSeverity.ERROR);
+                        return componentsUtils.getResponseFormat(ActionStatus.NOT_TOPOLOGY_TOSCA_TEMPLATE, yamlName);
                     }
                     regCapRelDef.setToNode(currentCapCompInstance.getUniqueId());
                     log.debug("try to find aviable Capability  req name is {} ", validReq.getName());
-                    CapabilityDefinition aviableCapForRel = serviceImportParseLogic.findAvailableCapabilityByTypeOrName(validReq,
-                        currentCapCompInstance, uploadRegInfo);
+                    CapabilityDefinition aviableCapForRel = serviceImportParseLogic
+                        .findAvailableCapabilityByTypeOrName(validReq, currentCapCompInstance, uploadRegInfo);
                     reqAndRelationshipPair.setCapability(aviableCapForRel.getName());
                     reqAndRelationshipPair.setCapabilityUid(aviableCapForRel.getUniqueId());
                     reqAndRelationshipPair.setCapabilityOwnerId(aviableCapForRel.getOwnerId());
                     if (aviableCapForRel == null) {
                         BeEcompErrorManager.getInstance().logInternalDataError(
-                            "aviable capability was not found. req name is " + validReq.getName()
-                                + " component instance is " + currentCapCompInstance.getUniqueId(),
-                            service.getUniqueId(), BeEcompErrorManager.ErrorSeverity.ERROR);
-                        return componentsUtils
-                            .getResponseFormat(ActionStatus.NOT_TOPOLOGY_TOSCA_TEMPLATE, yamlName);
+                            "aviable capability was not found. req name is " + validReq.getName() + " component instance is " + currentCapCompInstance
+                                .getUniqueId(), service.getUniqueId(), BeEcompErrorManager.ErrorSeverity.ERROR);
+                        return componentsUtils.getResponseFormat(ActionStatus.NOT_TOPOLOGY_TOSCA_TEMPLATE, yamlName);
                     }
                     CapabilityRequirementRelationship capReqRel = new CapabilityRequirementRelationship();
                     capReqRel.setRelation(reqAndRelationshipPair);
@@ -2026,16 +1835,14 @@ public class ServiceImportBusinessLogic {
 
     protected Service getResourceAfterCreateRelations(Service service) {
         ComponentParametersView parametersView = serviceImportParseLogic.getComponentFilterAfterCreateRelations();
-        Either<Service, StorageOperationStatus> eitherGetResource = toscaOperationFacade
-            .getToscaElement(service.getUniqueId(), parametersView);
+        Either<Service, StorageOperationStatus> eitherGetResource = toscaOperationFacade.getToscaElement(service.getUniqueId(), parametersView);
         if (eitherGetResource.isRight()) {
             serviceImportParseLogic.throwComponentExceptionByResource(eitherGetResource.right().value(), service);
         }
         return eitherGetResource.left().value();
     }
 
-    protected Service createServiceInstances(String yamlName, Service service,
-                                             Map<String, UploadComponentInstanceInfo> uploadResInstancesMap,
+    protected Service createServiceInstances(String yamlName, Service service, Map<String, UploadComponentInstanceInfo> uploadResInstancesMap,
                                              Map<String, Resource> nodeNamespaceMap) {
         Either<Resource, ResponseFormat> eitherResource = null;
         log.debug("createResourceInstances is {} - going to create resource instanse from CSAR", yamlName);
@@ -2048,14 +1855,11 @@ public class ServiceImportBusinessLogic {
             nodeNamespaceMap.forEach((k, v) -> existingNodeTypeMap.put(v.getToscaResourceName(), v));
         }
         Map<ComponentInstance, Resource> resourcesInstancesMap = new HashMap<>();
-        uploadResInstancesMap
-            .values()
+        uploadResInstancesMap.values()
             .forEach(i -> createAndAddResourceInstance(i, yamlName, service, nodeNamespaceMap, existingNodeTypeMap, resourcesInstancesMap));
-
         if (MapUtils.isNotEmpty(resourcesInstancesMap)) {
             try {
-                toscaOperationFacade.associateComponentInstancesToComponent(service,
-                    resourcesInstancesMap, false, false);
+                toscaOperationFacade.associateComponentInstancesToComponent(service, resourcesInstancesMap, false, false);
             } catch (StorageException exp) {
                 if (exp.getStorageOperationStatus() != null && exp.getStorageOperationStatus() != StorageOperationStatus.OK) {
                     log.debug("Failed to add component instances to container component {}", service.getName());
@@ -2070,31 +1874,28 @@ public class ServiceImportBusinessLogic {
             .getToscaElement(service.getUniqueId(), serviceImportParseLogic.getComponentWithInstancesFilter());
         log.debug("*************finished to get resource {}", service.getUniqueId());
         if (eitherGetResource.isRight()) {
-            ResponseFormat responseFormat = componentsUtils.getResponseFormatByComponent(
-                componentsUtils.convertFromStorageResponse(eitherGetResource.right().value()), service, ComponentTypeEnum.SERVICE);
+            ResponseFormat responseFormat = componentsUtils
+                .getResponseFormatByComponent(componentsUtils.convertFromStorageResponse(eitherGetResource.right().value()), service,
+                    ComponentTypeEnum.SERVICE);
             throw new ComponentException(responseFormat);
         }
         if (CollectionUtils.isEmpty(eitherGetResource.left().value().getComponentInstances())) { // PNF can have no resource instances
             log.debug("Error when create resource instance from csar. ComponentInstances list empty");
-            BeEcompErrorManager.getInstance().logBeDaoSystemError(
-                "Error when create resource instance from csar. ComponentInstances list empty");
+            BeEcompErrorManager.getInstance().logBeDaoSystemError("Error when create resource instance from csar. ComponentInstances list empty");
             throw new ComponentException(componentsUtils.getResponseFormat(ActionStatus.NOT_TOPOLOGY_TOSCA_TEMPLATE));
         }
         return eitherGetResource.left().value();
     }
 
-    protected void createAndAddResourceInstance(UploadComponentInstanceInfo uploadComponentInstanceInfo, String yamlName,
-                                                Component component, Map<String, Resource> nodeNamespaceMap,
-                                                Map<String, Resource> existingnodeTypeMap, Map<ComponentInstance, Resource> resourcesInstancesMap) {
+    protected void createAndAddResourceInstance(UploadComponentInstanceInfo uploadComponentInstanceInfo, String yamlName, Component component,
+                                                Map<String, Resource> nodeNamespaceMap, Map<String, Resource> existingnodeTypeMap,
+                                                Map<ComponentInstance, Resource> resourcesInstancesMap) {
         log.debug("*************Going to create  resource instances {}", uploadComponentInstanceInfo.getName());
         try {
             if (nodeNamespaceMap.containsKey(uploadComponentInstanceInfo.getType())) {
-                uploadComponentInstanceInfo
-                    .setType(nodeNamespaceMap.get(uploadComponentInstanceInfo.getType()).getToscaResourceName());
+                uploadComponentInstanceInfo.setType(nodeNamespaceMap.get(uploadComponentInstanceInfo.getType()).getToscaResourceName());
             }
-            Resource refResource = validateResourceInstanceBeforeCreate(yamlName, uploadComponentInstanceInfo,
-                existingnodeTypeMap);
-
+            Resource refResource = validateResourceInstanceBeforeCreate(yamlName, uploadComponentInstanceInfo, existingnodeTypeMap);
             ComponentInstance componentInstance = new ComponentInstance();
             componentInstance.setComponentUid(refResource.getUniqueId());
             Collection<String> directives = uploadComponentInstanceInfo.getDirectives();
@@ -2103,25 +1904,23 @@ public class ServiceImportBusinessLogic {
             }
             UploadNodeFilterInfo uploadNodeFilterInfo = uploadComponentInstanceInfo.getUploadNodeFilterInfo();
             if (uploadNodeFilterInfo != null) {
-                componentInstance.setNodeFilter(new CINodeFilterUtils().getNodeFilterDataDefinition(uploadNodeFilterInfo,
-                    componentInstance.getUniqueId()));
+                componentInstance
+                    .setNodeFilter(new CINodeFilterUtils().getNodeFilterDataDefinition(uploadNodeFilterInfo, componentInstance.getUniqueId()));
             }
-
             ComponentTypeEnum containerComponentType = component.getComponentType();
             NodeTypeEnum containerNodeType = containerComponentType.getNodeType();
-            if (containerNodeType.equals(NodeTypeEnum.Resource)
-                && MapUtils.isNotEmpty(uploadComponentInstanceInfo.getCapabilities())
-                && MapUtils.isNotEmpty(refResource.getCapabilities())) {
+            if (containerNodeType.equals(NodeTypeEnum.Resource) && MapUtils.isNotEmpty(uploadComponentInstanceInfo.getCapabilities()) && MapUtils
+                .isNotEmpty(refResource.getCapabilities())) {
                 serviceImportParseLogic.setCapabilityNamesTypes(refResource.getCapabilities(), uploadComponentInstanceInfo.getCapabilities());
                 Map<String, List<CapabilityDefinition>> validComponentInstanceCapabilities = serviceImportParseLogic
-                    .getValidComponentInstanceCapabilities(
-                        refResource.getUniqueId(), refResource.getCapabilities(),
+                    .getValidComponentInstanceCapabilities(refResource.getUniqueId(), refResource.getCapabilities(),
                         uploadComponentInstanceInfo.getCapabilities());
                 componentInstance.setCapabilities(validComponentInstanceCapabilities);
             }
             if (!existingnodeTypeMap.containsKey(uploadComponentInstanceInfo.getType())) {
-                ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.INVALID_NODE_TEMPLATE,
-                    yamlName, uploadComponentInstanceInfo.getName(), uploadComponentInstanceInfo.getType());
+                ResponseFormat responseFormat = componentsUtils
+                    .getResponseFormat(ActionStatus.INVALID_NODE_TEMPLATE, yamlName, uploadComponentInstanceInfo.getName(),
+                        uploadComponentInstanceInfo.getType());
                 throw new ComponentException(responseFormat);
             }
             Resource origResource = existingnodeTypeMap.get(uploadComponentInstanceInfo.getType());
@@ -2143,8 +1942,8 @@ public class ServiceImportBusinessLogic {
                 Either<Resource, StorageOperationStatus> findResourceEither = toscaOperationFacade
                     .getLatestResourceByToscaResourceName(uploadComponentInstanceInfo.getType());
                 if (findResourceEither.isRight()) {
-                    ResponseFormat responseFormat = componentsUtils.getResponseFormat(
-                        componentsUtils.convertFromStorageResponse(findResourceEither.right().value()));
+                    ResponseFormat responseFormat = componentsUtils
+                        .getResponseFormat(componentsUtils.convertFromStorageResponse(findResourceEither.right().value()));
                     throw new ComponentException(responseFormat);
                 }
                 refResource = findResourceEither.left().value();
@@ -2152,14 +1951,16 @@ public class ServiceImportBusinessLogic {
             }
             String componentState = refResource.getComponentMetadataDefinition().getMetadataDataDefinition().getState();
             if (componentState.equals(LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT.name())) {
-                ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.ILLEGAL_COMPONENT_STATE,
-                    refResource.getComponentType().getValue(), refResource.getName(), componentState);
+                ResponseFormat responseFormat = componentsUtils
+                    .getResponseFormat(ActionStatus.ILLEGAL_COMPONENT_STATE, refResource.getComponentType().getValue(), refResource.getName(),
+                        componentState);
                 throw new ComponentException(responseFormat);
             }
             if (!ModelConverter.isAtomicComponent(refResource) && refResource.getResourceType() != ResourceTypeEnum.VF) {
                 log.debug("validateResourceInstanceBeforeCreate -  ref resource type is  ", refResource.getResourceType());
-                ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.INVALID_NODE_TEMPLATE,
-                    yamlName, uploadComponentInstanceInfo.getName(), uploadComponentInstanceInfo.getType());
+                ResponseFormat responseFormat = componentsUtils
+                    .getResponseFormat(ActionStatus.INVALID_NODE_TEMPLATE, yamlName, uploadComponentInstanceInfo.getName(),
+                        uploadComponentInstanceInfo.getType());
                 throw new ComponentException(responseFormat);
             }
             return refResource;
@@ -2168,8 +1969,7 @@ public class ServiceImportBusinessLogic {
         }
     }
 
-    protected void handleServiceNodeTypes(String yamlName, Service service,
-                                          String topologyTemplateYaml, boolean needLock,
+    protected void handleServiceNodeTypes(String yamlName, Service service, String topologyTemplateYaml, boolean needLock,
                                           Map<String, EnumMap<ArtifactsBusinessLogic.ArtifactOperationEnum, List<ArtifactDefinition>>> nodeTypesArtifactsToHandle,
                                           List<ArtifactDefinition> nodeTypesNewCreatedArtifacts, Map<String, NodeTypeInfo> nodeTypesInfo,
                                           CsarInfo csarInfo, String nodeName) {
@@ -2177,14 +1977,14 @@ public class ServiceImportBusinessLogic {
             for (Map.Entry<String, NodeTypeInfo> nodeTypeEntry : nodeTypesInfo.entrySet()) {
                 boolean isResourceNotExisted = validateResourceNotExisted(nodeTypeEntry.getKey());
                 if (nodeTypeEntry.getValue().isNested() && isResourceNotExisted) {
-                    handleNestedVF(service, nodeTypesArtifactsToHandle, nodeTypesNewCreatedArtifacts,
-                        nodeTypesInfo, csarInfo, nodeTypeEntry.getKey());
+                    handleNestedVF(service, nodeTypesArtifactsToHandle, nodeTypesNewCreatedArtifacts, nodeTypesInfo, csarInfo,
+                        nodeTypeEntry.getKey());
                     log.trace("************* finished to create node {}", nodeTypeEntry.getKey());
                 }
             }
             Map<String, Object> mappedToscaTemplate = null;
-            if (org.apache.commons.lang.StringUtils.isNotEmpty(nodeName) && MapUtils.isNotEmpty(nodeTypesInfo)
-                && nodeTypesInfo.containsKey(nodeName)) {
+            if (org.apache.commons.lang.StringUtils.isNotEmpty(nodeName) && MapUtils.isNotEmpty(nodeTypesInfo) && nodeTypesInfo
+                .containsKey(nodeName)) {
                 mappedToscaTemplate = nodeTypesInfo.get(nodeName).getMappedToscaTemplate();
             }
             if (MapUtils.isEmpty(mappedToscaTemplate)) {
@@ -2217,11 +2017,9 @@ public class ServiceImportBusinessLogic {
         try {
             String yamlName = nodesInfo.get(nodeName).getTemplateFileName();
             Map<String, Object> nestedVfcJsonMap = nodesInfo.get(nodeName).getMappedToscaTemplate();
-
             createResourcesFromYamlNodeTypesList(yamlName, service, nestedVfcJsonMap, false, nodesArtifactsToHandle, createdArtifacts, nodesInfo,
                 csarInfo);
             log.debug("************* Finished to create node types from yaml {}", yamlName);
-
             if (nestedVfcJsonMap.containsKey(TypeUtils.ToscaTagNamesEnum.TOPOLOGY_TEMPLATE.getElementName())) {
                 log.debug("************* Going to handle complex VFC from yaml {}", yamlName);
                 return handleComplexVfc(nodesArtifactsToHandle, createdArtifacts, nodesInfo, csarInfo, nodeName, yamlName);
@@ -2235,8 +2033,7 @@ public class ServiceImportBusinessLogic {
 
     protected Resource handleComplexVfc(
         Map<String, EnumMap<ArtifactsBusinessLogic.ArtifactOperationEnum, List<ArtifactDefinition>>> nodesArtifactsToHandle,
-        List<ArtifactDefinition> createdArtifacts, Map<String, NodeTypeInfo> nodesInfo, CsarInfo csarInfo,
-        String nodeName, String yamlName) {
+        List<ArtifactDefinition> createdArtifacts, Map<String, NodeTypeInfo> nodesInfo, CsarInfo csarInfo, String nodeName, String yamlName) {
         try {
             Resource oldComplexVfc = null;
             Resource newComplexVfc = serviceImportParseLogic.buildValidComplexVfc(csarInfo, nodeName, nodesInfo);
@@ -2244,31 +2041,30 @@ public class ServiceImportBusinessLogic {
                 .getFullLatestComponentByToscaResourceName(newComplexVfc.getToscaResourceName());
             if (oldComplexVfcRes.isRight() && oldComplexVfcRes.right().value() == StorageOperationStatus.NOT_FOUND) {
                 oldComplexVfcRes = toscaOperationFacade.getFullLatestComponentByToscaResourceName(
-                    serviceImportParseLogic.buildNestedToscaResourceName(ResourceTypeEnum.VF.name(), csarInfo.getVfResourceName(),
-                        nodeName).getRight());
+                    serviceImportParseLogic.buildNestedToscaResourceName(ResourceTypeEnum.VF.name(), csarInfo.getVfResourceName(), nodeName)
+                        .getRight());
             }
             if (oldComplexVfcRes.isRight() && oldComplexVfcRes.right().value() != StorageOperationStatus.NOT_FOUND) {
-                log.debug("Failed to fetch previous complex VFC by tosca resource name {}. Status is {}. ",
-                    newComplexVfc.getToscaResourceName(), oldComplexVfcRes.right().value());
+                log.debug("Failed to fetch previous complex VFC by tosca resource name {}. Status is {}. ", newComplexVfc.getToscaResourceName(),
+                    oldComplexVfcRes.right().value());
                 throw new ComponentException(ActionStatus.GENERAL_ERROR);
             } else if (oldComplexVfcRes.isLeft()) {
                 log.debug(VALIDATE_DERIVED_BEFORE_UPDATE);
-                Either<Boolean, ResponseFormat> eitherValidation = serviceImportParseLogic.validateNestedDerivedFromDuringUpdate(
-                    oldComplexVfcRes.left().value(), newComplexVfc,
-                    ValidationUtils.hasBeenCertified(oldComplexVfcRes.left().value().getVersion()));
+                Either<Boolean, ResponseFormat> eitherValidation = serviceImportParseLogic
+                    .validateNestedDerivedFromDuringUpdate(oldComplexVfcRes.left().value(), newComplexVfc,
+                        ValidationUtils.hasBeenCertified(oldComplexVfcRes.left().value().getVersion()));
                 if (eitherValidation.isLeft()) {
                     oldComplexVfc = oldComplexVfcRes.left().value();
                 }
             }
-            newComplexVfc = handleComplexVfc(nodesArtifactsToHandle, createdArtifacts, nodesInfo, csarInfo, nodeName, yamlName,
-                oldComplexVfc, newComplexVfc);
+            newComplexVfc = handleComplexVfc(nodesArtifactsToHandle, createdArtifacts, nodesInfo, csarInfo, nodeName, yamlName, oldComplexVfc,
+                newComplexVfc);
             csarInfo.getCreatedNodesToscaResourceNames().put(nodeName, newComplexVfc.getToscaResourceName());
-            LifecycleChangeInfoWithAction lifecycleChangeInfo = new LifecycleChangeInfoWithAction(
-                CERTIFICATION_ON_IMPORT, LifecycleChangeInfoWithAction.LifecycleChanceActionEnum.CREATE_FROM_CSAR);
+            LifecycleChangeInfoWithAction lifecycleChangeInfo = new LifecycleChangeInfoWithAction(CERTIFICATION_ON_IMPORT,
+                LifecycleChangeInfoWithAction.LifecycleChanceActionEnum.CREATE_FROM_CSAR);
             log.debug("Going to certify cvfc {}. ", newComplexVfc.getName());
             final Resource result = serviceImportParseLogic
-                .propagateStateToCertified(csarInfo.getModifier(), newComplexVfc, lifecycleChangeInfo, true, false,
-                    true);
+                .propagateStateToCertified(csarInfo.getModifier(), newComplexVfc, lifecycleChangeInfo, true, false, true);
             csarInfo.getCreatedNodes().put(nodeName, result);
             csarInfo.removeNodeFromQueue();
             return result;
@@ -2280,8 +2076,8 @@ public class ServiceImportBusinessLogic {
 
     protected Resource handleComplexVfc(
         Map<String, EnumMap<ArtifactsBusinessLogic.ArtifactOperationEnum, List<ArtifactDefinition>>> nodesArtifactsToHandle,
-        List<ArtifactDefinition> createdArtifacts, Map<String, NodeTypeInfo> nodesInfo, CsarInfo csarInfo,
-        String nodeName, String yamlName, Resource oldComplexVfc, Resource newComplexVfc) {
+        List<ArtifactDefinition> createdArtifacts, Map<String, NodeTypeInfo> nodesInfo, CsarInfo csarInfo, String nodeName, String yamlName,
+        Resource oldComplexVfc, Resource newComplexVfc) {
         Resource handleComplexVfcRes;
         try {
             Map<String, Object> mappedToscaTemplate = nodesInfo.get(nodeName).getMappedToscaTemplate();
@@ -2290,12 +2086,11 @@ public class ServiceImportBusinessLogic {
                 .collect(toMap(Map.Entry::getKey, e -> e.getValue().getUnmarkedCopy()));
             CsarInfo.markNestedVfc(mappedToscaTemplate, newNodeTypesInfo);
             if (oldComplexVfc == null) {
-                handleComplexVfcRes = createResourceFromYaml(newComplexVfc, yamlContent, yamlName, newNodeTypesInfo,
-                    csarInfo, nodesArtifactsToHandle, false, true, nodeName);
+                handleComplexVfcRes = createResourceFromYaml(newComplexVfc, yamlContent, yamlName, newNodeTypesInfo, csarInfo, nodesArtifactsToHandle,
+                    false, true, nodeName);
             } else {
-                handleComplexVfcRes = updateResourceFromYaml(oldComplexVfc, newComplexVfc,
-                    AuditingActionEnum.UPDATE_RESOURCE_METADATA, createdArtifacts, yamlContent, yamlName, csarInfo,
-                    newNodeTypesInfo, nodesArtifactsToHandle, nodeName, true);
+                handleComplexVfcRes = updateResourceFromYaml(oldComplexVfc, newComplexVfc, AuditingActionEnum.UPDATE_RESOURCE_METADATA,
+                    createdArtifacts, yamlContent, yamlName, csarInfo, newNodeTypesInfo, nodesArtifactsToHandle, nodeName, true);
             }
             return handleComplexVfcRes;
         } catch (Exception e) {
@@ -2304,9 +2099,9 @@ public class ServiceImportBusinessLogic {
         }
     }
 
-    protected Resource updateResourceFromYaml(Resource oldRresource, Resource newRresource,
-                                              AuditingActionEnum actionEnum, List<ArtifactDefinition> createdArtifacts,
-                                              String yamlFileName, String yamlFileContent, CsarInfo csarInfo, Map<String, NodeTypeInfo> nodeTypesInfo,
+    protected Resource updateResourceFromYaml(Resource oldRresource, Resource newRresource, AuditingActionEnum actionEnum,
+                                              List<ArtifactDefinition> createdArtifacts, String yamlFileName, String yamlFileContent,
+                                              CsarInfo csarInfo, Map<String, NodeTypeInfo> nodeTypesInfo,
                                               Map<String, EnumMap<ArtifactsBusinessLogic.ArtifactOperationEnum, List<ArtifactDefinition>>> nodeTypesArtifactsToHandle,
                                               String nodeName, boolean isNested) {
         boolean inTransaction = true;
@@ -2320,14 +2115,13 @@ public class ServiceImportBusinessLogic {
             if (MapUtils.isEmpty(instances) && newRresource.getResourceType() != ResourceTypeEnum.PNF) {
                 throw new ComponentException(ActionStatus.NOT_TOPOLOGY_TOSCA_TEMPLATE, yamlFileName);
             }
-            preparedResource = updateExistingResourceByImport(newRresource, oldRresource, csarInfo.getModifier(),
-                inTransaction, shouldLock, isNested).left;
+            preparedResource = updateExistingResourceByImport(newRresource, oldRresource, csarInfo.getModifier(), inTransaction, shouldLock,
+                isNested).left;
             log.trace("YAML topology file found in CSAR, file name: {}, contents: {}", yamlFileName, yamlFileContent);
             serviceImportParseLogic.handleResourceGenericType(preparedResource);
-            handleNodeTypes(yamlFileName, preparedResource, yamlFileContent,
-                shouldLock, nodeTypesArtifactsToHandle, createdArtifacts, nodeTypesInfo, csarInfo, nodeName);
-            preparedResource = serviceImportParseLogic
-                .createInputsOnResource(preparedResource, uploadComponentInstanceInfoMap.getInputs());
+            handleNodeTypes(yamlFileName, preparedResource, yamlFileContent, shouldLock, nodeTypesArtifactsToHandle, createdArtifacts, nodeTypesInfo,
+                csarInfo, nodeName);
+            preparedResource = serviceImportParseLogic.createInputsOnResource(preparedResource, uploadComponentInstanceInfoMap.getInputs());
             preparedResource = createResourceInstances(yamlFileName, preparedResource, instances, csarInfo.getCreatedNodes());
             preparedResource = createResourceInstancesRelations(csarInfo.getModifier(), yamlFileName, preparedResource, instances);
         } catch (ComponentException e) {
@@ -2346,8 +2140,7 @@ public class ServiceImportBusinessLogic {
             throw e;
         }
         Either<Map<String, GroupDefinition>, ResponseFormat> validateUpdateVfGroupNamesRes = serviceBusinessLogic.groupBusinessLogic
-            .validateUpdateVfGroupNames(uploadComponentInstanceInfoMap.getGroups(),
-                preparedResource.getSystemName());
+            .validateUpdateVfGroupNames(uploadComponentInstanceInfoMap.getGroups(), preparedResource.getSystemName());
         if (validateUpdateVfGroupNamesRes.isRight()) {
             throw new ComponentException(validateUpdateVfGroupNamesRes.right().value());
         }
@@ -2359,30 +2152,25 @@ public class ServiceImportBusinessLogic {
         }
         serviceImportParseLogic.handleGroupsProperties(preparedResource, groups);
         preparedResource = serviceImportParseLogic.updateGroupsOnResource(preparedResource, groups);
-        NodeTypeInfoToUpdateArtifacts nodeTypeInfoToUpdateArtifacts = new NodeTypeInfoToUpdateArtifacts(nodeName,
-            nodeTypesArtifactsToHandle);
-
-        Either<Resource, ResponseFormat> updateArtifactsEither = createOrUpdateArtifacts(
-            ArtifactsBusinessLogic.ArtifactOperationEnum.UPDATE, createdArtifacts, yamlFileName,
-            csarInfo, preparedResource, nodeTypeInfoToUpdateArtifacts, inTransaction, shouldLock);
+        NodeTypeInfoToUpdateArtifacts nodeTypeInfoToUpdateArtifacts = new NodeTypeInfoToUpdateArtifacts(nodeName, nodeTypesArtifactsToHandle);
+        Either<Resource, ResponseFormat> updateArtifactsEither = createOrUpdateArtifacts(ArtifactsBusinessLogic.ArtifactOperationEnum.UPDATE,
+            createdArtifacts, yamlFileName, csarInfo, preparedResource, nodeTypeInfoToUpdateArtifacts, inTransaction, shouldLock);
         if (updateArtifactsEither.isRight()) {
             log.debug("failed to update artifacts {}", updateArtifactsEither.right().value());
             throw new ComponentException(updateArtifactsEither.right().value());
         }
         preparedResource = serviceImportParseLogic.getResourceWithGroups(updateArtifactsEither.left().value().getUniqueId());
-
         ActionStatus mergingPropsAndInputsStatus = resourceDataMergeBusinessLogic.mergeResourceEntities(oldRresource, preparedResource);
         if (mergingPropsAndInputsStatus != ActionStatus.OK) {
-            ResponseFormat responseFormat = componentsUtils.getResponseFormatByResource(mergingPropsAndInputsStatus,
-                preparedResource);
+            ResponseFormat responseFormat = componentsUtils.getResponseFormatByResource(mergingPropsAndInputsStatus, preparedResource);
             throw new ComponentException(responseFormat);
         }
         compositionBusinessLogic.setPositionsForComponentInstances(preparedResource, csarInfo.getModifier().getUserId());
         return preparedResource;
     }
 
-    protected Resource createResourceFromYaml(Resource resource, String topologyTemplateYaml,
-                                              String yamlName, Map<String, NodeTypeInfo> nodeTypesInfo, CsarInfo csarInfo,
+    protected Resource createResourceFromYaml(Resource resource, String topologyTemplateYaml, String yamlName,
+                                              Map<String, NodeTypeInfo> nodeTypesInfo, CsarInfo csarInfo,
                                               Map<String, EnumMap<ArtifactsBusinessLogic.ArtifactOperationEnum, List<ArtifactDefinition>>> nodeTypesArtifactsToCreate,
                                               boolean shouldLock, boolean inTransaction, String nodeName) {
         List<ArtifactDefinition> createdArtifacts = new ArrayList<>();
@@ -2394,9 +2182,8 @@ public class ServiceImportBusinessLogic {
                 throw new ComponentException(ActionStatus.NOT_TOPOLOGY_TOSCA_TEMPLATE, yamlName);
             }
             log.debug("#createResourceFromYaml - Going to create resource {} and RIs ", resource.getName());
-            createdResource = createResourceAndRIsFromYaml(yamlName, resource,
-                parsedToscaYamlInfo, AuditingActionEnum.IMPORT_RESOURCE, false, createdArtifacts, topologyTemplateYaml,
-                nodeTypesInfo, csarInfo, nodeTypesArtifactsToCreate, shouldLock, inTransaction, nodeName);
+            createdResource = createResourceAndRIsFromYaml(yamlName, resource, parsedToscaYamlInfo, AuditingActionEnum.IMPORT_RESOURCE, false,
+                createdArtifacts, topologyTemplateYaml, nodeTypesInfo, csarInfo, nodeTypesArtifactsToCreate, shouldLock, inTransaction, nodeName);
             log.debug("#createResourceFromYaml - The resource {} has been created ", resource.getName());
         } catch (ComponentException e) {
             ResponseFormat responseFormat =
@@ -2412,16 +2199,15 @@ public class ServiceImportBusinessLogic {
         return createdResource;
     }
 
-    protected Resource createResourceAndRIsFromYaml(String yamlName, Resource resource,
-                                                    ParsedToscaYamlInfo parsedToscaYamlInfo, AuditingActionEnum actionEnum, boolean isNormative,
-                                                    List<ArtifactDefinition> createdArtifacts, String topologyTemplateYaml,
-                                                    Map<String, NodeTypeInfo> nodeTypesInfo, CsarInfo csarInfo,
+    protected Resource createResourceAndRIsFromYaml(String yamlName, Resource resource, ParsedToscaYamlInfo parsedToscaYamlInfo,
+                                                    AuditingActionEnum actionEnum, boolean isNormative, List<ArtifactDefinition> createdArtifacts,
+                                                    String topologyTemplateYaml, Map<String, NodeTypeInfo> nodeTypesInfo, CsarInfo csarInfo,
                                                     Map<String, EnumMap<ArtifactsBusinessLogic.ArtifactOperationEnum, List<ArtifactDefinition>>> nodeTypesArtifactsToCreate,
                                                     boolean shouldLock, boolean inTransaction, String nodeName) {
         List<ArtifactDefinition> nodeTypesNewCreatedArtifacts = new ArrayList<>();
         if (shouldLock) {
-            Either<Boolean, ResponseFormat> lockResult = serviceBusinessLogic.lockComponentByName(resource.getSystemName(), resource,
-                CREATE_RESOURCE);
+            Either<Boolean, ResponseFormat> lockResult = serviceBusinessLogic
+                .lockComponentByName(resource.getSystemName(), resource, CREATE_RESOURCE);
             if (lockResult.isRight()) {
                 serviceImportParseLogic.rollback(inTransaction, resource, createdArtifacts, nodeTypesNewCreatedArtifacts);
                 throw new ComponentException(lockResult.right().value());
@@ -2431,10 +2217,8 @@ public class ServiceImportBusinessLogic {
         try {
             log.trace("************* createResourceFromYaml before full create resource {}", yamlName);
             Resource genericResource = serviceBusinessLogic.fetchAndSetDerivedFromGenericType(resource);
-            resource = createResourceTransaction(resource,
-                csarInfo.getModifier(), isNormative);
+            resource = createResourceTransaction(resource, csarInfo.getModifier(), isNormative);
             log.trace("************* Going to add inputs from yaml {}", yamlName);
-
             Map<String, Object> yamlMap = ImportUtils.loadYamlAsStrictMap(csarInfo.getMainTemplateContent());
             Map<String, Object> metadata = (Map<String, Object>) yamlMap.get("metadata");
             String type = (String) metadata.get("type");
@@ -2443,11 +2227,9 @@ public class ServiceImportBusinessLogic {
             }
             Map<String, InputDefinition> inputs = parsedToscaYamlInfo.getInputs();
             resource = serviceImportParseLogic.createInputsOnResource(resource, inputs);
-            Map<String, UploadComponentInstanceInfo> uploadComponentInstanceInfoMap = parsedToscaYamlInfo
-                .getInstances();
-            resource = createRIAndRelationsFromYaml(yamlName, resource, uploadComponentInstanceInfoMap,
-                topologyTemplateYaml, nodeTypesNewCreatedArtifacts, nodeTypesInfo, csarInfo,
-                nodeTypesArtifactsToCreate, nodeName);
+            Map<String, UploadComponentInstanceInfo> uploadComponentInstanceInfoMap = parsedToscaYamlInfo.getInstances();
+            resource = createRIAndRelationsFromYaml(yamlName, resource, uploadComponentInstanceInfoMap, topologyTemplateYaml,
+                nodeTypesNewCreatedArtifacts, nodeTypesInfo, csarInfo, nodeTypesArtifactsToCreate, nodeName);
             log.trace("************* Finished to create nodes, RI and Relation  from yaml {}", yamlName);
             // validate update vf module group names
             Either<Map<String, GroupDefinition>, ResponseFormat> validateUpdateVfGroupNamesRes = serviceBusinessLogic.groupBusinessLogic
@@ -2458,32 +2240,25 @@ public class ServiceImportBusinessLogic {
             }
             Map<String, GroupDefinition> groups;
             log.trace("************* Going to add groups from yaml {}", yamlName);
-
             if (!validateUpdateVfGroupNamesRes.left().value().isEmpty()) {
                 groups = validateUpdateVfGroupNamesRes.left().value();
             } else {
                 groups = parsedToscaYamlInfo.getGroups();
             }
-
-            Either<Resource, ResponseFormat> createGroupsOnResource = createGroupsOnResource(resource,
-                groups);
+            Either<Resource, ResponseFormat> createGroupsOnResource = createGroupsOnResource(resource, groups);
             if (createGroupsOnResource.isRight()) {
                 serviceImportParseLogic.rollback(inTransaction, resource, createdArtifacts, nodeTypesNewCreatedArtifacts);
                 throw new ComponentException(createGroupsOnResource.right().value());
             }
             resource = createGroupsOnResource.left().value();
             log.trace("************* Going to add artifacts from yaml {}", yamlName);
-
             NodeTypeInfoToUpdateArtifacts nodeTypeInfoToUpdateArtifacts = new NodeTypeInfoToUpdateArtifacts(nodeName, nodeTypesArtifactsToCreate);
-
-            Either<Resource, ResponseFormat> createArtifactsEither = createOrUpdateArtifacts(
-                ArtifactsBusinessLogic.ArtifactOperationEnum.CREATE, createdArtifacts, yamlName,
-                csarInfo, resource, nodeTypeInfoToUpdateArtifacts, inTransaction, shouldLock);
+            Either<Resource, ResponseFormat> createArtifactsEither = createOrUpdateArtifacts(ArtifactsBusinessLogic.ArtifactOperationEnum.CREATE,
+                createdArtifacts, yamlName, csarInfo, resource, nodeTypeInfoToUpdateArtifacts, inTransaction, shouldLock);
             if (createArtifactsEither.isRight()) {
                 serviceImportParseLogic.rollback(inTransaction, resource, createdArtifacts, nodeTypesNewCreatedArtifacts);
                 throw new ComponentException(createArtifactsEither.right().value());
             }
-
             resource = serviceImportParseLogic.getResourceWithGroups(createArtifactsEither.left().value().getUniqueId());
             ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.CREATED);
             componentsUtils.auditResource(responseFormat, csarInfo.getModifier(), resource, actionEnum);
@@ -2503,26 +2278,23 @@ public class ServiceImportBusinessLogic {
         }
     }
 
-    protected Either<Resource, ResponseFormat> createGroupsOnResource(Resource resource,
-                                                                      Map<String, GroupDefinition> groups) {
+    protected Either<Resource, ResponseFormat> createGroupsOnResource(Resource resource, Map<String, GroupDefinition> groups) {
         if (groups != null && !groups.isEmpty()) {
-            List<GroupDefinition> groupsAsList = updateGroupsMembersUsingResource(
-                groups, resource);
+            List<GroupDefinition> groupsAsList = updateGroupsMembersUsingResource(groups, resource);
             serviceImportParseLogic.handleGroupsProperties(resource, groups);
             serviceImportParseLogic.fillGroupsFinalFields(groupsAsList);
-            Either<List<GroupDefinition>, ResponseFormat> createGroups = serviceBusinessLogic.groupBusinessLogic.createGroups(resource,
-                groupsAsList, true);
+            Either<List<GroupDefinition>, ResponseFormat> createGroups = serviceBusinessLogic.groupBusinessLogic
+                .createGroups(resource, groupsAsList, true);
             if (createGroups.isRight()) {
                 return Either.right(createGroups.right().value());
             }
         } else {
             return Either.left(resource);
         }
-        Either<Resource, StorageOperationStatus> updatedResource = toscaOperationFacade
-            .getToscaElement(resource.getUniqueId());
+        Either<Resource, StorageOperationStatus> updatedResource = toscaOperationFacade.getToscaElement(resource.getUniqueId());
         if (updatedResource.isRight()) {
-            ResponseFormat responseFormat = componentsUtils.getResponseFormatByResource(
-                componentsUtils.convertFromStorageResponse(updatedResource.right().value()), resource);
+            ResponseFormat responseFormat = componentsUtils
+                .getResponseFormatByResource(componentsUtils.convertFromStorageResponse(updatedResource.right().value()), resource);
             return Either.right(responseFormat);
         }
         return Either.left(updatedResource.left().value());
@@ -2531,7 +2303,6 @@ public class ServiceImportBusinessLogic {
     protected List<GroupDefinition> updateGroupsMembersUsingResource(Map<String, GroupDefinition> groups, Resource component) {
         List<GroupDefinition> result = new ArrayList<>();
         List<ComponentInstance> componentInstances = component.getComponentInstances();
-
         if (groups != null) {
             Either<Boolean, ResponseFormat> validateCyclicGroupsDependencies = serviceImportParseLogic.validateCyclicGroupsDependencies(groups);
             if (validateCyclicGroupsDependencies.isRight()) {
@@ -2557,19 +2328,16 @@ public class ServiceImportBusinessLogic {
         Set<String> compInstancesNames = members.keySet();
         if (CollectionUtils.isEmpty(componentInstances)) {
             String membersAstString = compInstancesNames.stream().collect(joining(","));
-            log.debug("The members: {}, in group: {}, cannot be found in component {}. There are no component instances.",
-                membersAstString, groupName, component.getNormalizedName());
-            throw new ComponentException(componentsUtils.getResponseFormat(
-                ActionStatus.GROUP_INVALID_COMPONENT_INSTANCE, membersAstString, groupName,
-                component.getNormalizedName(), serviceImportParseLogic.getComponentTypeForResponse(component)));
-        }
-        Map<String, String> memberNames = componentInstances.stream()
-            .collect(toMap(ComponentInstance::getName, ComponentInstance::getUniqueId));
+            log.debug("The members: {}, in group: {}, cannot be found in component {}. There are no component instances.", membersAstString,
+                groupName, component.getNormalizedName());
+            throw new ComponentException(componentsUtils
+                .getResponseFormat(ActionStatus.GROUP_INVALID_COMPONENT_INSTANCE, membersAstString, groupName, component.getNormalizedName(),
+                    serviceImportParseLogic.getComponentTypeForResponse(component)));
+        }
+        Map<String, String> memberNames = componentInstances.stream().collect(toMap(ComponentInstance::getName, ComponentInstance::getUniqueId));
         memberNames.putAll(groups.keySet().stream().collect(toMap(g -> g, g -> "")));
-        Map<String, String> relevantInstances = memberNames.entrySet().stream()
-            .filter(n -> compInstancesNames.contains(n.getKey()))
+        Map<String, String> relevantInstances = memberNames.entrySet().stream().filter(n -> compInstancesNames.contains(n.getKey()))
             .collect(toMap(Map.Entry::getKey, Map.Entry::getValue));
-
         if (relevantInstances == null || relevantInstances.size() != compInstancesNames.size()) {
             List<String> foundMembers = new ArrayList<>();
             if (relevantInstances != null) {
@@ -2577,17 +2345,16 @@ public class ServiceImportBusinessLogic {
             }
             compInstancesNames.removeAll(foundMembers);
             String membersAstString = compInstancesNames.stream().collect(joining(","));
-            throw new ComponentException(componentsUtils.getResponseFormat(
-                ActionStatus.GROUP_INVALID_COMPONENT_INSTANCE, membersAstString, groupName,
-                component.getNormalizedName(), serviceImportParseLogic.getComponentTypeForResponse(component)));
+            throw new ComponentException(componentsUtils
+                .getResponseFormat(ActionStatus.GROUP_INVALID_COMPONENT_INSTANCE, membersAstString, groupName, component.getNormalizedName(),
+                    serviceImportParseLogic.getComponentTypeForResponse(component)));
         }
         updatedGroupDefinition.setMembers(relevantInstances);
     }
 
-    protected Resource createResourceTransaction(Resource resource, User user,
-                                                 boolean isNormative) {
-        Either<Boolean, StorageOperationStatus> eitherValidation = toscaOperationFacade.validateComponentNameExists(
-            resource.getName(), resource.getResourceType(), resource.getComponentType());
+    protected Resource createResourceTransaction(Resource resource, User user, boolean isNormative) {
+        Either<Boolean, StorageOperationStatus> eitherValidation = toscaOperationFacade
+            .validateComponentNameExists(resource.getName(), resource.getResourceType(), resource.getComponentType());
         if (eitherValidation.isRight()) {
             ResponseFormat errorResponse = componentsUtils
                 .getResponseFormat(componentsUtils.convertFromStorageResponse(eitherValidation.right().value()));
@@ -2595,8 +2362,8 @@ public class ServiceImportBusinessLogic {
         }
         if (eitherValidation.left().value()) {
             log.debug("resource with name: {}, already exists", resource.getName());
-            ResponseFormat errorResponse = componentsUtils.getResponseFormat(ActionStatus.COMPONENT_NAME_ALREADY_EXIST,
-                ComponentTypeEnum.RESOURCE.getValue(), resource.getName());
+            ResponseFormat errorResponse = componentsUtils
+                .getResponseFormat(ActionStatus.COMPONENT_NAME_ALREADY_EXIST, ComponentTypeEnum.RESOURCE.getValue(), resource.getName());
             throw new ComponentException(errorResponse);
         }
         log.debug("send resource {} to dao for create", resource.getName());
@@ -2610,38 +2377,31 @@ public class ServiceImportBusinessLogic {
                 resource.setAbstract(false);
             }
         }
-        return toscaOperationFacade.createToscaComponent(resource)
-            .left()
+        return toscaOperationFacade.createToscaComponent(resource).left()
             .on(r -> serviceImportParseLogic.throwComponentExceptionByResource(r, resource));
     }
 
-    protected ImmutablePair<Resource, ActionStatus> updateExistingResourceByImport(
-        Resource newResource, Resource oldResource, User user, boolean inTransaction, boolean needLock,
-        boolean isNested) {
+    protected ImmutablePair<Resource, ActionStatus> updateExistingResourceByImport(Resource newResource, Resource oldResource, User user,
+                                                                                   boolean inTransaction, boolean needLock, boolean isNested) {
         String lockedResourceId = oldResource.getUniqueId();
-        log.debug("found resource: name={}, id={}, version={}, state={}", oldResource.getName(), lockedResourceId,
-            oldResource.getVersion(), oldResource.getLifecycleState());
+        log.debug("found resource: name={}, id={}, version={}, state={}", oldResource.getName(), lockedResourceId, oldResource.getVersion(),
+            oldResource.getLifecycleState());
         ImmutablePair<Resource, ActionStatus> resourcePair = null;
         try {
             serviceBusinessLogic.lockComponent(lockedResourceId, oldResource, needLock, "Update Resource by Import");
-            oldResource = serviceImportParseLogic
-                .prepareResourceForUpdate(oldResource, newResource, user, inTransaction, false);
+            oldResource = serviceImportParseLogic.prepareResourceForUpdate(oldResource, newResource, user, inTransaction, false);
             serviceImportParseLogic.mergeOldResourceMetadataWithNew(oldResource, newResource);
             serviceImportParseLogic.validateResourceFieldsBeforeUpdate(oldResource, newResource, inTransaction, isNested);
-            serviceImportParseLogic
-                .validateCapabilityTypesCreate(user, serviceImportParseLogic.getCapabilityTypeOperation(), newResource,
-                    AuditingActionEnum.IMPORT_RESOURCE, inTransaction);
+            serviceImportParseLogic.validateCapabilityTypesCreate(user, serviceImportParseLogic.getCapabilityTypeOperation(), newResource,
+                AuditingActionEnum.IMPORT_RESOURCE, inTransaction);
             createNewResourceToOldResource(newResource, oldResource, user);
-
-            Either<Resource, StorageOperationStatus> overrideResource = toscaOperationFacade
-                .overrideComponent(newResource, oldResource);
+            Either<Resource, StorageOperationStatus> overrideResource = toscaOperationFacade.overrideComponent(newResource, oldResource);
             if (overrideResource.isRight()) {
                 ResponseFormat responseFormat = new ResponseFormat();
                 serviceBusinessLogic.throwComponentException(responseFormat);
             }
             log.debug("Resource updated successfully!!!");
-            resourcePair = new ImmutablePair<>(overrideResource.left().value(),
-                ActionStatus.OK);
+            resourcePair = new ImmutablePair<>(overrideResource.left().value(), ActionStatus.OK);
             return resourcePair;
         } finally {
             if (resourcePair == null) {
@@ -2697,8 +2457,7 @@ public class ServiceImportBusinessLogic {
                                                                          boolean needLock,
                                                                          Map<String, EnumMap<ArtifactsBusinessLogic.ArtifactOperationEnum, List<ArtifactDefinition>>> nodeTypesArtifactsToHandle,
                                                                          List<ArtifactDefinition> nodeTypesNewCreatedArtifacts,
-                                                                         Map<String, NodeTypeInfo> nodeTypesInfo,
-                                                                         CsarInfo csarInfo) {
+                                                                         Map<String, NodeTypeInfo> nodeTypesInfo, CsarInfo csarInfo) {
         try {
             Either<String, ImportUtils.ResultStatusEnum> toscaVersion = findFirstToscaStringElement(mappedToscaTemplate,
                 TypeUtils.ToscaTagNamesEnum.TOSCA_VERSION);
@@ -2725,26 +2484,20 @@ public class ServiceImportBusinessLogic {
         Resource vfcCreated = null;
         while (nodesNameValueIter.hasNext()) {
             Map.Entry<String, Object> nodeType = nodesNameValueIter.next();
-            Map<ArtifactsBusinessLogic.ArtifactOperationEnum, List<ArtifactDefinition>> nodeTypeArtifactsToHandle = nodeTypesArtifactsToHandle == null
-                || nodeTypesArtifactsToHandle.isEmpty() ? null
-                : nodeTypesArtifactsToHandle.get(nodeType.getKey());
-
+            Map<ArtifactsBusinessLogic.ArtifactOperationEnum, List<ArtifactDefinition>> nodeTypeArtifactsToHandle =
+                nodeTypesArtifactsToHandle == null || nodeTypesArtifactsToHandle.isEmpty() ? null : nodeTypesArtifactsToHandle.get(nodeType.getKey());
             if (nodeTypesInfo.containsKey(nodeType.getKey())) {
-                vfcCreated = handleNestedVfc(service,
-                    nodeTypesArtifactsToHandle, nodeTypesNewCreatedArtifacts, nodeTypesInfo, csarInfo,
+                vfcCreated = handleNestedVfc(service, nodeTypesArtifactsToHandle, nodeTypesNewCreatedArtifacts, nodeTypesInfo, csarInfo,
                     nodeType.getKey());
                 log.trace("************* Finished to handle nested vfc {}", nodeType.getKey());
-            } else if (csarInfo.getCreatedNodesToscaResourceNames() != null
-                && !csarInfo.getCreatedNodesToscaResourceNames().containsKey(nodeType.getKey())) {
+            } else if (csarInfo.getCreatedNodesToscaResourceNames() != null && !csarInfo.getCreatedNodesToscaResourceNames()
+                .containsKey(nodeType.getKey())) {
                 ImmutablePair<Resource, ActionStatus> resourceCreated = serviceImportParseLogic
-                    .createNodeTypeResourceFromYaml(yamlName, nodeType, csarInfo.getModifier(), mapToConvert,
-                        service, needLock, nodeTypeArtifactsToHandle, nodeTypesNewCreatedArtifacts, true,
-                        csarInfo, true);
+                    .createNodeTypeResourceFromYaml(yamlName, nodeType, csarInfo.getModifier(), mapToConvert, service, needLock,
+                        nodeTypeArtifactsToHandle, nodeTypesNewCreatedArtifacts, true, csarInfo, true);
                 log.debug("************* Finished to create node {}", nodeType.getKey());
-
                 vfcCreated = resourceCreated.getLeft();
-                csarInfo.getCreatedNodesToscaResourceNames().put(nodeType.getKey(),
-                    vfcCreated.getName());
+                csarInfo.getCreatedNodesToscaResourceNames().put(nodeType.getKey(), vfcCreated.getName());
             }
             if (vfcCreated != null) {
                 csarInfo.getCreatedNodes().put(nodeType.getKey(), vfcCreated);
@@ -2752,5 +2505,4 @@ public class ServiceImportBusinessLogic {
             mapToConvert.remove(TypeUtils.ToscaTagNamesEnum.NODE_TYPES.getElementName());
         }
     }
-
 }
index fa079d2..9fba1c7 100644 (file)
  * limitations under the License.
  * ============LICENSE_END=========================================================
  */
-
 package org.openecomp.sdc.be.components.impl;
 
-
 import javax.servlet.ServletContext;
 import org.openecomp.sdc.be.datatypes.components.ServiceMetadataDataDefinition;
 import org.openecomp.sdc.be.impl.WebAppContextWrapper;
@@ -30,79 +28,72 @@ import org.springframework.beans.factory.annotation.Autowired;
 import org.springframework.stereotype.Component;
 import org.springframework.web.context.WebApplicationContext;
 
-
 //upload Service model by Shiyong1989@hotmail.com
 @Component("ServiceImportManager")
 public class ServiceImportManager {
 
-  private ServletContext servletContext;
-
-  private ResponseFormatManager responseFormatManager;
-
-  @Autowired
-  private ServiceBusinessLogic serviceBusinessLogic;
-
-  public ServiceImportBusinessLogic getServiceImportBusinessLogic() {
-    return serviceImportBusinessLogic;
-  }
-
-  public void setServiceImportBusinessLogic(
-      ServiceImportBusinessLogic serviceImportBusinessLogic) {
-    this.serviceImportBusinessLogic = serviceImportBusinessLogic;
-  }
+    private ServletContext servletContext;
+    private ResponseFormatManager responseFormatManager;
+    @Autowired
+    private ServiceBusinessLogic serviceBusinessLogic;
+    @Autowired
+    private ServiceImportBusinessLogic serviceImportBusinessLogic;
 
-  @Autowired
-  private ServiceImportBusinessLogic serviceImportBusinessLogic;
-
-  public boolean isServiceExist(String serviceName) {
-    return serviceBusinessLogic.isServiceExist(serviceName);
-  }
+    public ServiceImportBusinessLogic getServiceImportBusinessLogic() {
+        return serviceImportBusinessLogic;
+    }
 
+    public void setServiceImportBusinessLogic(ServiceImportBusinessLogic serviceImportBusinessLogic) {
+        this.serviceImportBusinessLogic = serviceImportBusinessLogic;
+    }
 
-  public ServiceBusinessLogic getServiceBusinessLogic() {
-    return serviceBusinessLogic;
-  }
+    public boolean isServiceExist(String serviceName) {
+        return serviceBusinessLogic.isServiceExist(serviceName);
+    }
 
-  public void setServiceBusinessLogic(
-      ServiceBusinessLogic serviceBusinessLogic) {
-    this.serviceBusinessLogic = serviceBusinessLogic;
-  }
+    public ServiceBusinessLogic getServiceBusinessLogic() {
+        return serviceBusinessLogic;
+    }
 
+    public void setServiceBusinessLogic(ServiceBusinessLogic serviceBusinessLogic) {
+        this.serviceBusinessLogic = serviceBusinessLogic;
+    }
 
-  public void populateServiceMetadata(UploadServiceInfo serviceMetaData, Service service) {
-    if (service != null && serviceMetaData != null) {
-      service.setDescription(serviceMetaData.getDescription());
-      service.setTags(serviceMetaData.getTags());
-      service.setCategories(serviceMetaData.getCategories());
-      service.setContactId(serviceMetaData.getContactId());
-      service.setName(serviceMetaData.getName());
-      service.setIcon(serviceMetaData.getServiceIconPath());
-      service.setServiceVendorModelNumber(serviceMetaData.getServiceVendorModelNumber());
-      ServiceMetadataDataDefinition serviceMetadataDataDefinition = (ServiceMetadataDataDefinition) service
-          .getComponentMetadataDefinition().getMetadataDataDefinition();
-      serviceMetadataDataDefinition.getServiceVendorModelNumber();
-      service.setServiceType("");
-      service.setProjectCode(serviceMetaData.getProjectCode());
-      if (serviceMetaData.getVendorName() != null) {
-        service.setVendorName(serviceMetaData.getVendorName());
-      }
-      if (serviceMetaData.getVendorRelease() != null) {
-        service.setVendorRelease(serviceMetaData.getVendorRelease());
-      }
+    public void populateServiceMetadata(UploadServiceInfo serviceMetaData, Service service) {
+        if (service != null && serviceMetaData != null) {
+            service.setDescription(serviceMetaData.getDescription());
+            service.setTags(serviceMetaData.getTags());
+            service.setCategories(serviceMetaData.getCategories());
+            service.setContactId(serviceMetaData.getContactId());
+            service.setName(serviceMetaData.getName());
+            service.setIcon(serviceMetaData.getServiceIconPath());
+            service.setServiceVendorModelNumber(serviceMetaData.getServiceVendorModelNumber());
+            ServiceMetadataDataDefinition serviceMetadataDataDefinition = (ServiceMetadataDataDefinition) service.getComponentMetadataDefinition()
+                .getMetadataDataDefinition();
+            serviceMetadataDataDefinition.getServiceVendorModelNumber();
+            service.setServiceType("");
+            service.setProjectCode(serviceMetaData.getProjectCode());
+            if (serviceMetaData.getVendorName() != null) {
+                service.setVendorName(serviceMetaData.getVendorName());
+            }
+            if (serviceMetaData.getVendorRelease() != null) {
+                service.setVendorRelease(serviceMetaData.getVendorRelease());
+            }
+        }
     }
-  }
 
-  public synchronized void init(ServletContext servletContext) {
-    if (this.servletContext == null) {
-      this.servletContext = servletContext;
-      responseFormatManager = ResponseFormatManager.getInstance();
-      serviceBusinessLogic = getServiceBL(servletContext);
+    public synchronized void init(ServletContext servletContext) {
+        if (this.servletContext == null) {
+            this.servletContext = servletContext;
+            responseFormatManager = ResponseFormatManager.getInstance();
+            serviceBusinessLogic = getServiceBL(servletContext);
+        }
     }
-  }
 
-  private ServiceBusinessLogic getServiceBL(ServletContext context) {
-    WebAppContextWrapper webApplicationContextWrapper = (WebAppContextWrapper) context.getAttribute(org.openecomp.sdc.common.api.Constants.WEB_APPLICATION_CONTEXT_WRAPPER_ATTR);
-    WebApplicationContext webApplicationContext = webApplicationContextWrapper.getWebAppContext(context);
-    return webApplicationContext.getBean(ServiceBusinessLogic.class);
-  }
+    private ServiceBusinessLogic getServiceBL(ServletContext context) {
+        WebAppContextWrapper webApplicationContextWrapper = (WebAppContextWrapper) context
+            .getAttribute(org.openecomp.sdc.common.api.Constants.WEB_APPLICATION_CONTEXT_WRAPPER_ATTR);
+        WebApplicationContext webApplicationContext = webApplicationContextWrapper.getWebAppContext(context);
+        return webApplicationContext.getBean(ServiceBusinessLogic.class);
+    }
 }
index 6a5e531..3404323 100644 (file)
@@ -13,7 +13,6 @@
  * See the License for the specific language governing permissions and
  * limitations under the License.
  */
-
 package org.openecomp.sdc.be.components.impl;
 
 import static java.util.stream.Collectors.joining;
@@ -151,21 +150,17 @@ public class ServiceImportParseLogic {
 
     public Either<Map<String, EnumMap<ArtifactsBusinessLogic.ArtifactOperationEnum, List<ArtifactDefinition>>>, ResponseFormat> findNodeTypesArtifactsToHandle(
         Map<String, NodeTypeInfo> nodeTypesInfo, CsarInfo csarInfo, Service oldResource) {
-
         Map<String, EnumMap<ArtifactsBusinessLogic.ArtifactOperationEnum, List<ArtifactDefinition>>> nodeTypesArtifactsToHandle = new HashMap<>();
-        Either<Map<String, EnumMap<ArtifactsBusinessLogic.ArtifactOperationEnum, List<ArtifactDefinition>>>, ResponseFormat> nodeTypesArtifactsToHandleRes
-            = Either.left(nodeTypesArtifactsToHandle);
-
+        Either<Map<String, EnumMap<ArtifactsBusinessLogic.ArtifactOperationEnum, List<ArtifactDefinition>>>, ResponseFormat> nodeTypesArtifactsToHandleRes = Either
+            .left(nodeTypesArtifactsToHandle);
         try {
             Map<String, List<ArtifactDefinition>> extractedVfcsArtifacts = CsarUtils.extractVfcsArtifactsFromCsar(csarInfo.getCsar());
-            Map<String, ImmutablePair<String, String>> extractedVfcToscaNames =
-                extractVfcToscaNames(nodeTypesInfo, oldResource.getName(), csarInfo);
-            log.debug("Going to fetch node types for resource with name {} during import csar with UUID {}. ",
-                oldResource.getName(), csarInfo.getCsarUUID());
-            extractedVfcToscaNames
-                .forEach((namespace, vfcToscaNames) -> findAddNodeTypeArtifactsToHandle(csarInfo, nodeTypesArtifactsToHandle, oldResource,
-                    extractedVfcsArtifacts,
-                    namespace, vfcToscaNames));
+            Map<String, ImmutablePair<String, String>> extractedVfcToscaNames = extractVfcToscaNames(nodeTypesInfo, oldResource.getName(), csarInfo);
+            log.debug("Going to fetch node types for resource with name {} during import csar with UUID {}. ", oldResource.getName(),
+                csarInfo.getCsarUUID());
+            extractedVfcToscaNames.forEach(
+                (namespace, vfcToscaNames) -> findAddNodeTypeArtifactsToHandle(csarInfo, nodeTypesArtifactsToHandle, oldResource,
+                    extractedVfcsArtifacts, namespace, vfcToscaNames));
         } catch (Exception e) {
             ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR);
             nodeTypesArtifactsToHandleRes = Either.right(responseFormat);
@@ -174,45 +169,41 @@ public class ServiceImportParseLogic {
         return nodeTypesArtifactsToHandleRes;
     }
 
-    private Map<String, ImmutablePair<String, String>> extractVfcToscaNames(Map<String, NodeTypeInfo> nodeTypesInfo,
-                                                                            String vfResourceName, CsarInfo csarInfo) {
+    private Map<String, ImmutablePair<String, String>> extractVfcToscaNames(Map<String, NodeTypeInfo> nodeTypesInfo, String vfResourceName,
+                                                                            CsarInfo csarInfo) {
         Map<String, ImmutablePair<String, String>> vfcToscaNames = new HashMap<>();
-
         Map<String, Object> nodes = extractAllNodes(nodeTypesInfo, csarInfo);
         if (!nodes.isEmpty()) {
             Iterator<Map.Entry<String, Object>> nodesNameEntry = nodes.entrySet().iterator();
             while (nodesNameEntry.hasNext()) {
                 Map.Entry<String, Object> nodeType = nodesNameEntry.next();
-                ImmutablePair<String, String> toscaResourceName = buildNestedToscaResourceName(
-                    ResourceTypeEnum.VFC.name(), vfResourceName, nodeType.getKey());
+                ImmutablePair<String, String> toscaResourceName = buildNestedToscaResourceName(ResourceTypeEnum.VFC.name(), vfResourceName,
+                    nodeType.getKey());
                 vfcToscaNames.put(nodeType.getKey(), toscaResourceName);
             }
         }
         for (NodeTypeInfo cvfc : nodeTypesInfo.values()) {
-            vfcToscaNames.put(cvfc.getType(),
-                buildNestedToscaResourceName(ResourceTypeEnum.VF.name(), vfResourceName, cvfc.getType()));
+            vfcToscaNames.put(cvfc.getType(), buildNestedToscaResourceName(ResourceTypeEnum.VF.name(), vfResourceName, cvfc.getType()));
         }
         return vfcToscaNames;
     }
 
-    public String buildNodeTypeYaml(Map.Entry<String, Object> nodeNameValue, Map<String, Object> mapToConvert,
-                                    String nodeResourceType, CsarInfo csarInfo) {
+    public String buildNodeTypeYaml(Map.Entry<String, Object> nodeNameValue, Map<String, Object> mapToConvert, String nodeResourceType,
+                                    CsarInfo csarInfo) {
         // We need to create a Yaml from each node_types in order to create
+
         // resource from each node type using import normative flow.
         DumperOptions options = new DumperOptions();
         options.setDefaultFlowStyle(DumperOptions.FlowStyle.BLOCK);
         Yaml yaml = new Yaml(options);
-
         Map<String, Object> node = new HashMap<>();
-        node.put(buildNestedToscaResourceName(nodeResourceType, csarInfo.getVfResourceName(), nodeNameValue.getKey())
-            .getLeft(), nodeNameValue.getValue());
+        node.put(buildNestedToscaResourceName(nodeResourceType, csarInfo.getVfResourceName(), nodeNameValue.getKey()).getLeft(),
+            nodeNameValue.getValue());
         mapToConvert.put(TypeUtils.ToscaTagNamesEnum.NODE_TYPES.getElementName(), node);
-
         return yaml.dumpAsMap(mapToConvert);
     }
 
-    ImmutablePair<String, String> buildNestedToscaResourceName(String nodeResourceType, String vfResourceName,
-                                                               String nodeTypeFullName) {
+    ImmutablePair<String, String> buildNestedToscaResourceName(String nodeResourceType, String vfResourceName, String nodeTypeFullName) {
         String actualType;
         String actualVfName;
         if (ResourceTypeEnum.CVFC.name().equals(nodeResourceType)) {
@@ -228,24 +219,19 @@ public class ServiceImportParseLogic {
             if (!nodeTypeFullName.contains(Constants.USER_DEFINED_RESOURCE_NAMESPACE_PREFIX)) {
                 nameWithouNamespacePrefix = nodeTypeFullName;
             } else {
-                nameWithouNamespacePrefix = nodeTypeFullName
-                    .substring(Constants.USER_DEFINED_RESOURCE_NAMESPACE_PREFIX.length());
+                nameWithouNamespacePrefix = nodeTypeFullName.substring(Constants.USER_DEFINED_RESOURCE_NAMESPACE_PREFIX.length());
             }
             String[] findTypes = nameWithouNamespacePrefix.split("\\.");
             String resourceType = findTypes[0];
             String actualName = nameWithouNamespacePrefix.substring(resourceType.length());
-
             if (actualName.startsWith(Constants.ABSTRACT)) {
-                toscaResourceName.append(resourceType.toLowerCase()).append('.')
-                    .append(ValidationUtils.convertToSystemName(actualVfName));
+                toscaResourceName.append(resourceType.toLowerCase()).append('.').append(ValidationUtils.convertToSystemName(actualVfName));
             } else {
                 toscaResourceName.append(actualType.toLowerCase()).append('.').append(ValidationUtils.convertToSystemName(actualVfName));
             }
             StringBuilder previousToscaResourceName = new StringBuilder(toscaResourceName);
             return new ImmutablePair<>(toscaResourceName.append(actualName.toLowerCase()).toString(),
-                previousToscaResourceName
-                    .append(actualName.substring(actualName.split("\\.")[1].length() + 1).toLowerCase())
-                    .toString());
+                previousToscaResourceName.append(actualName.substring(actualName.split("\\.")[1].length() + 1).toLowerCase()).toString());
         } catch (Exception e) {
             componentsUtils.getResponseFormat(ActionStatus.INVALID_TOSCA_TEMPLATE);
             log.debug("Exception occured when buildNestedToscaResourceName, error is:{}", e.getMessage(), e);
@@ -274,7 +260,6 @@ public class ServiceImportParseLogic {
                                                     Map<String, EnumMap<ArtifactsBusinessLogic.ArtifactOperationEnum, List<ArtifactDefinition>>> nodeTypesArtifactsToHandle,
                                                     Service resource, Map<String, List<ArtifactDefinition>> extractedVfcsArtifacts, String namespace,
                                                     ImmutablePair<String, String> vfcToscaNames) {
-
         EnumMap<ArtifactsBusinessLogic.ArtifactOperationEnum, List<ArtifactDefinition>> curNodeTypeArtifactsToHandle = null;
         log.debug("Going to fetch node type with tosca name {}. ", vfcToscaNames.getLeft());
         Resource curNodeType = findVfcResource(csarInfo, resource, vfcToscaNames.getLeft(), vfcToscaNames.getRight(), null);
@@ -286,19 +271,19 @@ public class ServiceImportParseLogic {
             curNodeTypeArtifactsToHandle = findNodeTypeArtifactsToHandle(curNodeType, currArtifacts);
         } else if (curNodeType != null) {
             // delete all artifacts if have not received artifacts from
+
             // csar
             try {
                 curNodeTypeArtifactsToHandle = new EnumMap<>(ArtifactsBusinessLogic.ArtifactOperationEnum.class);
                 List<ArtifactDefinition> artifactsToDelete = new ArrayList<>();
                 // delete all informational artifacts
-                artifactsToDelete.addAll(curNodeType.getArtifacts().values().stream()
-                    .filter(a -> a.getArtifactGroupType() == ArtifactGroupTypeEnum.INFORMATIONAL)
-                    .collect(toList()));
+                artifactsToDelete.addAll(
+                    curNodeType.getArtifacts().values().stream().filter(a -> a.getArtifactGroupType() == ArtifactGroupTypeEnum.INFORMATIONAL)
+                        .collect(toList()));
                 // delete all deployment artifacts
                 artifactsToDelete.addAll(curNodeType.getDeploymentArtifacts().values());
                 if (!artifactsToDelete.isEmpty()) {
-                    curNodeTypeArtifactsToHandle
-                        .put(ArtifactsBusinessLogic.ArtifactOperationEnum.DELETE, artifactsToDelete);
+                    curNodeTypeArtifactsToHandle.put(ArtifactsBusinessLogic.ArtifactOperationEnum.DELETE, artifactsToDelete);
                 }
             } catch (Exception e) {
                 componentsUtils.getResponseFormat(ActionStatus.INVALID_TOSCA_TEMPLATE);
@@ -311,10 +296,8 @@ public class ServiceImportParseLogic {
         }
     }
 
-    protected void handleAndAddExtractedVfcsArtifacts(List<ArtifactDefinition> vfcArtifacts,
-                                                      List<ArtifactDefinition> artifactsToAdd) {
-        List<String> vfcArtifactNames = vfcArtifacts.stream().map(ArtifactDataDefinition::getArtifactName)
-            .collect(toList());
+    protected void handleAndAddExtractedVfcsArtifacts(List<ArtifactDefinition> vfcArtifacts, List<ArtifactDefinition> artifactsToAdd) {
+        List<String> vfcArtifactNames = vfcArtifacts.stream().map(ArtifactDataDefinition::getArtifactName).collect(toList());
         artifactsToAdd.stream().forEach(a -> {
             if (!vfcArtifactNames.contains(a.getArtifactName())) {
                 vfcArtifacts.add(a);
@@ -330,16 +313,14 @@ public class ServiceImportParseLogic {
             log.debug("Error occured during fetching node type with tosca name {}, error: {}", currVfcToscaName, status);
             throw new ComponentException(componentsUtils.convertFromStorageResponse(status), csarInfo.getCsarUUID());
         } else if (org.apache.commons.lang.StringUtils.isNotEmpty(currVfcToscaName)) {
-            return (Resource) toscaOperationFacade.getLatestByToscaResourceName(currVfcToscaName)
-                .left()
+            return (Resource) toscaOperationFacade.getLatestByToscaResourceName(currVfcToscaName).left()
                 .on(st -> findVfcResource(csarInfo, resource, previousVfcToscaName, null, st));
         }
         return null;
     }
 
-    protected EnumMap<ArtifactsBusinessLogic.ArtifactOperationEnum, List<ArtifactDefinition>> findNodeTypeArtifactsToHandle(
-        Resource curNodeType, List<ArtifactDefinition> extractedArtifacts) {
-
+    protected EnumMap<ArtifactsBusinessLogic.ArtifactOperationEnum, List<ArtifactDefinition>> findNodeTypeArtifactsToHandle(Resource curNodeType,
+                                                                                                                            List<ArtifactDefinition> extractedArtifacts) {
         EnumMap<ArtifactsBusinessLogic.ArtifactOperationEnum, List<ArtifactDefinition>> nodeTypeArtifactsToHandle = null;
         try {
             List<ArtifactDefinition> artifactsToUpload = new ArrayList<>(extractedArtifacts);
@@ -364,10 +345,8 @@ public class ServiceImportParseLogic {
             existingArtifacts.putAll(curNodeType.getDeploymentArtifacts());
         }
         if (MapUtils.isNotEmpty(curNodeType.getArtifacts())) {
-            existingArtifacts
-                .putAll(curNodeType.getArtifacts().entrySet()
-                    .stream()
-                    .filter(e -> e.getValue().getArtifactGroupType() == ArtifactGroupTypeEnum.INFORMATIONAL)
+            existingArtifacts.putAll(
+                curNodeType.getArtifacts().entrySet().stream().filter(e -> e.getValue().getArtifactGroupType() == ArtifactGroupTypeEnum.INFORMATIONAL)
                     .collect(toMap(Map.Entry::getKey, Map.Entry::getValue)));
         }
         return existingArtifacts;
@@ -396,23 +375,19 @@ public class ServiceImportParseLogic {
                                                     Map<String, ArtifactDefinition> existingArtifacts) {
         try {
             if (!existingArtifacts.isEmpty()) {
-                extractedArtifacts.stream()
-                    .forEach(a -> processNodeTypeArtifact(artifactsToUpload, artifactsToUpdate, existingArtifacts, a));
+                extractedArtifacts.stream().forEach(a -> processNodeTypeArtifact(artifactsToUpload, artifactsToUpdate, existingArtifacts, a));
                 artifactsToDelete.addAll(existingArtifacts.values());
             }
         } catch (Exception e) {
             log.debug("Exception occured when processExistingNodeTypeArtifacts, error is:{}", e.getMessage(), e);
             throw new ComponentException(ActionStatus.GENERAL_ERROR);
         }
-
     }
 
     protected void processNodeTypeArtifact(List<ArtifactDefinition> artifactsToUpload, List<ArtifactDefinition> artifactsToUpdate,
                                            Map<String, ArtifactDefinition> existingArtifacts, ArtifactDefinition currNewArtifact) {
-        Optional<ArtifactDefinition> foundArtifact = existingArtifacts.values()
-            .stream()
-            .filter(a -> a.getArtifactName().equals(currNewArtifact.getArtifactName()))
-            .findFirst();
+        Optional<ArtifactDefinition> foundArtifact = existingArtifacts.values().stream()
+            .filter(a -> a.getArtifactName().equals(currNewArtifact.getArtifactName())).findFirst();
         if (foundArtifact.isPresent()) {
             if (foundArtifact.get().getArtifactType().equals(currNewArtifact.getArtifactType())) {
                 updateFoundArtifact(artifactsToUpdate, currNewArtifact, foundArtifact.get());
@@ -420,9 +395,8 @@ public class ServiceImportParseLogic {
                 artifactsToUpload.remove(currNewArtifact);
             } else {
                 log.debug("Can't upload two artifact with the same name {}.", currNewArtifact.getArtifactName());
-                throw new ComponentException(ActionStatus.ARTIFACT_ALREADY_EXIST_IN_DIFFERENT_TYPE_IN_CSAR,
-                    currNewArtifact.getArtifactName(), currNewArtifact.getArtifactType(),
-                    foundArtifact.get().getArtifactType());
+                throw new ComponentException(ActionStatus.ARTIFACT_ALREADY_EXIST_IN_DIFFERENT_TYPE_IN_CSAR, currNewArtifact.getArtifactName(),
+                    currNewArtifact.getArtifactType(), foundArtifact.get().getArtifactType());
             }
         }
     }
@@ -431,16 +405,13 @@ public class ServiceImportParseLogic {
                                        ArtifactDefinition foundArtifact) {
         if (!foundArtifact.getArtifactChecksum().equals(currNewArtifact.getArtifactChecksum())) {
             foundArtifact.setPayload(currNewArtifact.getPayloadData());
-            foundArtifact.setPayloadData(
-                Base64.encodeBase64String(currNewArtifact.getPayloadData()));
-            foundArtifact.setArtifactChecksum(GeneralUtility
-                .calculateMD5Base64EncodedByByteArray(currNewArtifact.getPayloadData()));
+            foundArtifact.setPayloadData(Base64.encodeBase64String(currNewArtifact.getPayloadData()));
+            foundArtifact.setArtifactChecksum(GeneralUtility.calculateMD5Base64EncodedByByteArray(currNewArtifact.getPayloadData()));
             artifactsToUpdate.add(foundArtifact);
         }
     }
 
-    public void addNonMetaCreatedArtifactsToSupportRollback(ArtifactOperationInfo operation,
-                                                            List<ArtifactDefinition> createdArtifacts,
+    public void addNonMetaCreatedArtifactsToSupportRollback(ArtifactOperationInfo operation, List<ArtifactDefinition> createdArtifacts,
                                                             Either<Either<ArtifactDefinition, Operation>, ResponseFormat> eitherNonMetaArtifacts) {
         if (ArtifactsBusinessLogic.ArtifactOperationEnum.isCreateOrLink(operation.getArtifactOperationEnum()) && createdArtifacts != null
             && eitherNonMetaArtifacts.isLeft()) {
@@ -472,7 +443,6 @@ public class ServiceImportParseLogic {
 
     protected boolean isfillGroupMemebersRecursivlyStopCondition(String groupName, Map<String, GroupDefinition> allGroups,
                                                                  Set<String> allGroupMembers) {
-
         boolean stop = false;
         // In Case Not Group Stop
         if (!allGroups.containsKey(groupName)) {
@@ -482,7 +452,6 @@ public class ServiceImportParseLogic {
         if (!stop) {
             GroupDefinition groupDefinition = allGroups.get(groupName);
             stop = MapUtils.isEmpty(groupDefinition.getMembers());
-
         }
         // In Case all group members already contained stop
         if (!stop) {
@@ -497,19 +466,15 @@ public class ServiceImportParseLogic {
         return stop;
     }
 
-    public Resource buildValidComplexVfc(Resource resource, CsarInfo csarInfo, String nodeName,
-                                         Map<String, NodeTypeInfo> nodesInfo) {
-
+    public Resource buildValidComplexVfc(Resource resource, CsarInfo csarInfo, String nodeName, Map<String, NodeTypeInfo> nodesInfo) {
         Resource complexVfc = buildComplexVfcMetadata(resource, csarInfo, nodeName, nodesInfo);
         log.debug("************* Going to validate complex VFC from yaml {}", complexVfc.getName());
         csarInfo.addNodeToQueue(nodeName);
-        return validateResourceBeforeCreate(complexVfc, csarInfo.getModifier(),
-            AuditingActionEnum.IMPORT_RESOURCE, true, csarInfo);
+        return validateResourceBeforeCreate(complexVfc, csarInfo.getModifier(), AuditingActionEnum.IMPORT_RESOURCE, true, csarInfo);
     }
 
     public Resource validateResourceBeforeCreate(Resource resource, User user, AuditingActionEnum actionEnum, boolean inTransaction,
                                                  CsarInfo csarInfo) {
-
         validateResourceFieldsBeforeCreate(user, resource, actionEnum, inTransaction);
         validateCapabilityTypesCreate(user, getCapabilityTypeOperation(), resource, actionEnum, inTransaction);
         validateLifecycleTypesCreate(user, resource, actionEnum);
@@ -524,21 +489,20 @@ public class ServiceImportParseLogic {
             } else {
                 resourceSystemName = resource.getSystemName();
             }
-            resource.setToscaResourceName(CommonBeUtils
-                .generateToscaResourceName(resource.getResourceType().name().toLowerCase(), resourceSystemName));
+            resource
+                .setToscaResourceName(CommonBeUtils.generateToscaResourceName(resource.getResourceType().name().toLowerCase(), resourceSystemName));
         }
-
         // Generate invariant UUID - must be here and not in operation since it
+
         // should stay constant during clone
+
         // TODO
         String invariantUUID = UniqueIdBuilder.buildInvariantUUID();
         resource.setInvariantUUID(invariantUUID);
-
         return resource;
     }
 
-    protected Either<Boolean, ResponseFormat> validateResourceType(User user, Resource resource,
-                                                                   AuditingActionEnum actionEnum) {
+    protected Either<Boolean, ResponseFormat> validateResourceType(User user, Resource resource, AuditingActionEnum actionEnum) {
         Either<Boolean, ResponseFormat> eitherResult = Either.left(true);
         if (resource.getResourceType() == null) {
             log.debug("Invalid resource type for resource");
@@ -549,8 +513,7 @@ public class ServiceImportParseLogic {
         return eitherResult;
     }
 
-    protected Either<Boolean, ResponseFormat> validateLifecycleTypesCreate(User user, Resource resource,
-                                                                           AuditingActionEnum actionEnum) {
+    protected Either<Boolean, ResponseFormat> validateLifecycleTypesCreate(User user, Resource resource, AuditingActionEnum actionEnum) {
         Either<Boolean, ResponseFormat> eitherResult = Either.left(true);
         if (resource.getInterfaces() != null && resource.getInterfaces().size() > 0) {
             log.debug("validate interface lifecycle Types Exist");
@@ -558,21 +521,16 @@ public class ServiceImportParseLogic {
             while (intItr.hasNext() && eitherResult.isLeft()) {
                 InterfaceDefinition interfaceDefinition = intItr.next();
                 String intType = interfaceDefinition.getUniqueId();
-                Either<InterfaceDefinition, StorageOperationStatus> eitherCapTypeFound = interfaceTypeOperation
-                    .getInterface(intType);
+                Either<InterfaceDefinition, StorageOperationStatus> eitherCapTypeFound = interfaceTypeOperation.getInterface(intType);
                 if (eitherCapTypeFound.isRight()) {
                     if (eitherCapTypeFound.right().value() == StorageOperationStatus.NOT_FOUND) {
-                        BeEcompErrorManager.getInstance().logBeGraphObjectMissingError(
-                            "Create Resource - validateLifecycleTypesCreate", "Interface", intType);
-                        log.debug("Lifecycle Type: {} is required by resource: {} but does not exist in the DB",
-                            intType, resource.getName());
                         BeEcompErrorManager.getInstance()
-                            .logBeDaoSystemError("Create Resource - validateLifecycleTypesCreate");
-                        log.debug("request to data model failed with error: {}",
-                            eitherCapTypeFound.right().value().name());
+                            .logBeGraphObjectMissingError("Create Resource - validateLifecycleTypesCreate", "Interface", intType);
+                        log.debug("Lifecycle Type: {} is required by resource: {} but does not exist in the DB", intType, resource.getName());
+                        BeEcompErrorManager.getInstance().logBeDaoSystemError("Create Resource - validateLifecycleTypesCreate");
+                        log.debug("request to data model failed with error: {}", eitherCapTypeFound.right().value().name());
                     }
-                    ResponseFormat errorResponse = componentsUtils
-                        .getResponseFormat(ActionStatus.MISSING_LIFECYCLE_TYPE, intType);
+                    ResponseFormat errorResponse = componentsUtils.getResponseFormat(ActionStatus.MISSING_LIFECYCLE_TYPE, intType);
                     eitherResult = Either.right(errorResponse);
                     componentsUtils.auditResource(errorResponse, user, resource, actionEnum);
                 }
@@ -581,19 +539,14 @@ public class ServiceImportParseLogic {
         return eitherResult;
     }
 
-    public Either<Boolean, ResponseFormat> validateCapabilityTypesCreate(User user,
-                                                                         ICapabilityTypeOperation capabilityTypeOperation, Resource resource,
-                                                                         AuditingActionEnum actionEnum,
-                                                                         boolean inTransaction) {
-
+    public Either<Boolean, ResponseFormat> validateCapabilityTypesCreate(User user, ICapabilityTypeOperation capabilityTypeOperation,
+                                                                         Resource resource, AuditingActionEnum actionEnum, boolean inTransaction) {
         Either<Boolean, ResponseFormat> eitherResult = Either.left(true);
         if (resource.getCapabilities() != null && resource.getCapabilities().size() > 0) {
             log.debug("validate capability Types Exist - capabilities section");
-
             for (Map.Entry<String, List<CapabilityDefinition>> typeEntry : resource.getCapabilities().entrySet()) {
-
-                eitherResult = validateCapabilityTypeExists(user, capabilityTypeOperation, resource, actionEnum,
-                    eitherResult, typeEntry, inTransaction);
+                eitherResult = validateCapabilityTypeExists(user, capabilityTypeOperation, resource, actionEnum, eitherResult, typeEntry,
+                    inTransaction);
                 if (eitherResult.isRight()) {
                     return Either.right(eitherResult.right().value());
                 }
@@ -602,8 +555,8 @@ public class ServiceImportParseLogic {
         if (resource.getRequirements() != null && resource.getRequirements().size() > 0) {
             log.debug("validate capability Types Exist - requirements section");
             for (String type : resource.getRequirements().keySet()) {
-                eitherResult = validateCapabilityTypeExists(user, capabilityTypeOperation, resource,
-                    resource.getRequirements().get(type), actionEnum, eitherResult, type, inTransaction);
+                eitherResult = validateCapabilityTypeExists(user, capabilityTypeOperation, resource, resource.getRequirements().get(type), actionEnum,
+                    eitherResult, type, inTransaction);
                 if (eitherResult.isRight()) {
                     return Either.right(eitherResult.right().value());
                 }
@@ -612,9 +565,8 @@ public class ServiceImportParseLogic {
         return eitherResult;
     }
 
-    protected Either<Boolean, ResponseFormat> validateCapabilityTypeExists(User user,
-                                                                           ICapabilityTypeOperation capabilityTypeOperation, Resource resource,
-                                                                           AuditingActionEnum actionEnum,
+    protected Either<Boolean, ResponseFormat> validateCapabilityTypeExists(User user, ICapabilityTypeOperation capabilityTypeOperation,
+                                                                           Resource resource, AuditingActionEnum actionEnum,
                                                                            Either<Boolean, ResponseFormat> eitherResult,
                                                                            Map.Entry<String, List<CapabilityDefinition>> typeEntry,
                                                                            boolean inTransaction) {
@@ -622,17 +574,13 @@ public class ServiceImportParseLogic {
             .getCapabilityType(typeEntry.getKey(), inTransaction);
         if (eitherCapTypeFound.isRight()) {
             if (eitherCapTypeFound.right().value() == StorageOperationStatus.NOT_FOUND) {
-                BeEcompErrorManager.getInstance().logBeGraphObjectMissingError(
-                    CREATE_RESOURCE_VALIDATE_CAPABILITY_TYPES, "Capability Type", typeEntry.getKey());
-                log.debug("Capability Type: {} is required by resource: {} but does not exist in the DB",
-                    typeEntry.getKey(), resource.getName());
                 BeEcompErrorManager.getInstance()
-                    .logBeDaoSystemError(CREATE_RESOURCE_VALIDATE_CAPABILITY_TYPES);
+                    .logBeGraphObjectMissingError(CREATE_RESOURCE_VALIDATE_CAPABILITY_TYPES, "Capability Type", typeEntry.getKey());
+                log.debug("Capability Type: {} is required by resource: {} but does not exist in the DB", typeEntry.getKey(), resource.getName());
+                BeEcompErrorManager.getInstance().logBeDaoSystemError(CREATE_RESOURCE_VALIDATE_CAPABILITY_TYPES);
             }
-            log.debug("Trying to get capability type {} failed with error: {}", typeEntry.getKey(),
-                eitherCapTypeFound.right().value().name());
-            ResponseFormat errorResponse = componentsUtils.getResponseFormat(ActionStatus.MISSING_CAPABILITY_TYPE,
-                typeEntry.getKey());
+            log.debug("Trying to get capability type {} failed with error: {}", typeEntry.getKey(), eitherCapTypeFound.right().value().name());
+            ResponseFormat errorResponse = componentsUtils.getResponseFormat(ActionStatus.MISSING_CAPABILITY_TYPE, typeEntry.getKey());
             eitherResult = Either.right(errorResponse);
             componentsUtils.auditResource(errorResponse, user, resource, actionEnum);
             return Either.right(eitherResult.right().value());
@@ -668,9 +616,8 @@ public class ServiceImportParseLogic {
         return eitherResult;
     }
 
-    protected Either<Boolean, ResponseFormat> validateCapabilityTypeExists(User user,
-                                                                           ICapabilityTypeOperation capabilityTypeOperation, Resource resource,
-                                                                           List<?> validationObjects,
+    protected Either<Boolean, ResponseFormat> validateCapabilityTypeExists(User user, ICapabilityTypeOperation capabilityTypeOperation,
+                                                                           Resource resource, List<?> validationObjects,
                                                                            AuditingActionEnum actionEnum,
                                                                            Either<Boolean, ResponseFormat> eitherResult, String type,
                                                                            boolean inTransaction) {
@@ -679,26 +626,21 @@ public class ServiceImportParseLogic {
                 .getCapabilityType(type, inTransaction);
             if (eitherCapTypeFound.isRight()) {
                 if (eitherCapTypeFound.right().value() == StorageOperationStatus.NOT_FOUND) {
-                    BeEcompErrorManager.getInstance().logBeGraphObjectMissingError(
-                        CREATE_RESOURCE_VALIDATE_CAPABILITY_TYPES, "Capability Type", type);
-                    log.debug("Capability Type: {} is required by resource: {} but does not exist in the DB", type,
-                        resource.getName());
                     BeEcompErrorManager.getInstance()
-                        .logBeDaoSystemError(CREATE_RESOURCE_VALIDATE_CAPABILITY_TYPES);
+                        .logBeGraphObjectMissingError(CREATE_RESOURCE_VALIDATE_CAPABILITY_TYPES, "Capability Type", type);
+                    log.debug("Capability Type: {} is required by resource: {} but does not exist in the DB", type, resource.getName());
+                    BeEcompErrorManager.getInstance().logBeDaoSystemError(CREATE_RESOURCE_VALIDATE_CAPABILITY_TYPES);
                 }
-                log.debug("Trying to get capability type {} failed with error: {}", type,
-                    eitherCapTypeFound.right().value().name());
+                log.debug("Trying to get capability type {} failed with error: {}", type, eitherCapTypeFound.right().value().name());
                 ResponseFormat errorResponse = null;
                 if (type != null) {
                     errorResponse = componentsUtils.getResponseFormat(ActionStatus.MISSING_CAPABILITY_TYPE, type);
                 } else {
-                    errorResponse = componentsUtils.getResponseFormatByElement(ActionStatus.MISSING_CAPABILITY_TYPE,
-                        validationObjects);
+                    errorResponse = componentsUtils.getResponseFormatByElement(ActionStatus.MISSING_CAPABILITY_TYPE, validationObjects);
                 }
                 eitherResult = Either.right(errorResponse);
                 componentsUtils.auditResource(errorResponse, user, resource, actionEnum);
             }
-
         } catch (Exception e) {
             log.debug("Exception occured when validateCapabilityTypeExists, error is:{}", e.getMessage(), e);
             throw new ComponentException(ActionStatus.INVALID_TOSCA_TEMPLATE, resource.getName());
@@ -706,8 +648,8 @@ public class ServiceImportParseLogic {
         return eitherResult;
     }
 
-    protected Either<Boolean, ResponseFormat> validateResourceFieldsBeforeCreate(User user, Resource resource,
-                                                                                 AuditingActionEnum actionEnum, boolean inTransaction) {
+    protected Either<Boolean, ResponseFormat> validateResourceFieldsBeforeCreate(User user, Resource resource, AuditingActionEnum actionEnum,
+                                                                                 boolean inTransaction) {
         serviceBusinessLogic.validateComponentFieldsBeforeCreate(user, resource, actionEnum);
         // validate category
         log.debug("validate category");
@@ -736,22 +678,18 @@ public class ServiceImportParseLogic {
         if (currentCreatorFullName != null) {
             log.debug("Resource Creator fullname is automatically set and cannot be updated");
         }
-
         String currentLastUpdaterFullName = resource.getLastUpdaterFullName();
         if (currentLastUpdaterFullName != null) {
             log.debug("Resource LastUpdater fullname is automatically set and cannot be updated");
         }
-
         Long currentLastUpdateDate = resource.getLastUpdateDate();
         if (currentLastUpdateDate != null) {
             log.debug("Resource last update date is automatically set and cannot be updated");
         }
-
         Boolean currentAbstract = resource.isAbstract();
         if (currentAbstract != null) {
             log.debug("Resource abstract is automatically set and cannot be updated");
         }
-
         return Either.left(true);
     }
 
@@ -760,8 +698,7 @@ public class ServiceImportParseLogic {
             return;
         }
         String templateName = resource.getDerivedFrom().get(0);
-        Either<Boolean, StorageOperationStatus> dataModelResponse = toscaOperationFacade
-            .validateToscaResourceNameExists(templateName);
+        Either<Boolean, StorageOperationStatus> dataModelResponse = toscaOperationFacade.validateToscaResourceNameExists(templateName);
         if (dataModelResponse.isRight()) {
             StorageOperationStatus storageStatus = dataModelResponse.right().value();
             BeEcompErrorManager.getInstance().logBeDaoSystemError("Create Resource - validateDerivedFromExist");
@@ -779,13 +716,11 @@ public class ServiceImportParseLogic {
         }
     }
 
-    protected void validateLicenseType(User user, Resource resource,
-                                       AuditingActionEnum actionEnum) {
+    protected void validateLicenseType(User user, Resource resource, AuditingActionEnum actionEnum) {
         log.debug("validate licenseType");
         String licenseType = resource.getLicenseType();
         if (licenseType != null) {
-            List<String> licenseTypes = ConfigurationManager.getConfigurationManager().getConfiguration()
-                .getLicenseTypes();
+            List<String> licenseTypes = ConfigurationManager.getConfigurationManager().getConfiguration().getLicenseTypes();
             if (!licenseTypes.contains(licenseType)) {
                 log.debug("License type {} isn't configured", licenseType);
                 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.INVALID_CONTENT);
@@ -813,19 +748,18 @@ public class ServiceImportParseLogic {
         if (org.apache.commons.lang.StringUtils.isNotEmpty(resourceVendorModelNumber)) {
             if (!ValidationUtils.validateResourceVendorModelNumberLength(resourceVendorModelNumber)) {
                 log.info("resource vendor model number exceeds limit.");
-                ResponseFormat errorResponse = componentsUtils.getResponseFormat(
-                    ActionStatus.RESOURCE_VENDOR_MODEL_NUMBER_EXCEEDS_LIMIT,
+                ResponseFormat errorResponse = componentsUtils.getResponseFormat(ActionStatus.RESOURCE_VENDOR_MODEL_NUMBER_EXCEEDS_LIMIT,
                     "" + ValidationUtils.RESOURCE_VENDOR_MODEL_NUMBER_MAX_LENGTH);
                 componentsUtils.auditResource(errorResponse, user, resource, actionEnum);
                 throw new ComponentException(ActionStatus.RESOURCE_VENDOR_MODEL_NUMBER_EXCEEDS_LIMIT,
                     "" + ValidationUtils.RESOURCE_VENDOR_MODEL_NUMBER_MAX_LENGTH);
             }
             // resource vendor model number is currently validated as vendor
+
             // name
             if (!ValidationUtils.validateVendorName(resourceVendorModelNumber)) {
                 log.info("resource vendor model number  is not valid.");
-                ResponseFormat errorResponse = componentsUtils
-                    .getResponseFormat(ActionStatus.INVALID_RESOURCE_VENDOR_MODEL_NUMBER);
+                ResponseFormat errorResponse = componentsUtils.getResponseFormat(ActionStatus.INVALID_RESOURCE_VENDOR_MODEL_NUMBER);
                 componentsUtils.auditResource(errorResponse, user, resource, actionEnum);
                 throw new ComponentException(ActionStatus.INVALID_RESOURCE_VENDOR_MODEL_NUMBER);
             }
@@ -841,7 +775,6 @@ public class ServiceImportParseLogic {
             componentsUtils.auditResource(errorResponse, user, resource, actionEnum);
             throw new ComponentException(ActionStatus.MISSING_VENDOR_RELEASE);
         }
-
         validateVendorReleaseName(vendorRelease, user, resource, actionEnum);
     }
 
@@ -849,12 +782,11 @@ public class ServiceImportParseLogic {
         if (vendorRelease != null) {
             if (!ValidationUtils.validateVendorReleaseLength(vendorRelease)) {
                 log.info("vendor release exceds limit.");
-                ResponseFormat errorResponse = componentsUtils.getResponseFormat(
-                    ActionStatus.VENDOR_RELEASE_EXCEEDS_LIMIT, "" + ValidationUtils.VENDOR_RELEASE_MAX_LENGTH);
+                ResponseFormat errorResponse = componentsUtils
+                    .getResponseFormat(ActionStatus.VENDOR_RELEASE_EXCEEDS_LIMIT, "" + ValidationUtils.VENDOR_RELEASE_MAX_LENGTH);
                 componentsUtils.auditResource(errorResponse, user, resource, actionEnum);
                 throw new ComponentException(ActionStatus.VENDOR_RELEASE_EXCEEDS_LIMIT, "" + ValidationUtils.VENDOR_RELEASE_MAX_LENGTH);
             }
-
             if (!ValidationUtils.validateVendorRelease(vendorRelease)) {
                 log.info("vendor release  is not valid.");
                 ResponseFormat errorResponse = componentsUtils.getResponseFormat(ActionStatus.INVALID_VENDOR_RELEASE);
@@ -864,17 +796,14 @@ public class ServiceImportParseLogic {
         }
     }
 
-    protected void validateCategory(User user, Resource resource,
-                                    AuditingActionEnum actionEnum, boolean inTransaction) {
-
+    protected void validateCategory(User user, Resource resource, AuditingActionEnum actionEnum, boolean inTransaction) {
         List<CategoryDefinition> categories = resource.getCategories();
         if (CollectionUtils.isEmpty(categories)) {
             log.debug(CATEGORY_IS_EMPTY);
-            ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.COMPONENT_MISSING_CATEGORY,
-                ComponentTypeEnum.RESOURCE.getValue());
+            ResponseFormat responseFormat = componentsUtils
+                .getResponseFormat(ActionStatus.COMPONENT_MISSING_CATEGORY, ComponentTypeEnum.RESOURCE.getValue());
             componentsUtils.auditResource(responseFormat, user, resource, actionEnum);
-            throw new ComponentException(ActionStatus.COMPONENT_MISSING_CATEGORY,
-                ComponentTypeEnum.RESOURCE.getValue());
+            throw new ComponentException(ActionStatus.COMPONENT_MISSING_CATEGORY, ComponentTypeEnum.RESOURCE.getValue());
         }
         if (categories.size() > 1) {
             log.debug("Must be only one category for resource");
@@ -890,30 +819,26 @@ public class ServiceImportParseLogic {
             log.debug("Must be only one sub category for resource");
             throw new ComponentException(ActionStatus.RESOURCE_TOO_MUCH_SUBCATEGORIES);
         }
-
         SubCategoryDefinition subcategory = subcategories.get(0);
-
         if (!ValidationUtils.validateStringNotEmpty(category.getName())) {
             log.debug(CATEGORY_IS_EMPTY);
-            ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.COMPONENT_MISSING_CATEGORY,
-                ComponentTypeEnum.RESOURCE.getValue());
+            ResponseFormat responseFormat = componentsUtils
+                .getResponseFormat(ActionStatus.COMPONENT_MISSING_CATEGORY, ComponentTypeEnum.RESOURCE.getValue());
             componentsUtils.auditResource(responseFormat, user, resource, actionEnum);
-            throw new ComponentException(ActionStatus.COMPONENT_MISSING_CATEGORY,
-                ComponentTypeEnum.RESOURCE.getValue());
+            throw new ComponentException(ActionStatus.COMPONENT_MISSING_CATEGORY, ComponentTypeEnum.RESOURCE.getValue());
         }
         if (!ValidationUtils.validateStringNotEmpty(subcategory.getName())) {
             log.debug(CATEGORY_IS_EMPTY);
-            ResponseFormat responseFormat = componentsUtils.getResponseFormat(
-                ActionStatus.COMPONENT_MISSING_SUBCATEGORY, ComponentTypeEnum.RESOURCE.getValue());
+            ResponseFormat responseFormat = componentsUtils
+                .getResponseFormat(ActionStatus.COMPONENT_MISSING_SUBCATEGORY, ComponentTypeEnum.RESOURCE.getValue());
             componentsUtils.auditResource(responseFormat, user, resource, actionEnum);
             throw new ComponentException(ActionStatus.COMPONENT_MISSING_SUBCATEGORY, ComponentTypeEnum.RESOURCE.getValue());
         }
-
         validateCategoryListed(category, subcategory, user, resource, actionEnum, inTransaction);
     }
 
-    protected void validateCategoryListed(CategoryDefinition category, SubCategoryDefinition subcategory,
-                                          User user, Resource resource, AuditingActionEnum actionEnum, boolean inTransaction) {
+    protected void validateCategoryListed(CategoryDefinition category, SubCategoryDefinition subcategory, User user, Resource resource,
+                                          AuditingActionEnum actionEnum, boolean inTransaction) {
         ResponseFormat responseFormat;
         if (category != null && subcategory != null) {
             try {
@@ -927,24 +852,17 @@ public class ServiceImportParseLogic {
                     throw new ComponentException(categories.right().value());
                 }
                 List<CategoryDefinition> categoryList = categories.left().value();
-                Optional<CategoryDefinition> foundCategory = categoryList.stream()
-                    .filter(cat -> cat.getName().equals(category.getName()))
+                Optional<CategoryDefinition> foundCategory = categoryList.stream().filter(cat -> cat.getName().equals(category.getName()))
                     .findFirst();
                 if (!foundCategory.isPresent()) {
-                    log.debug(
-                        "Category {} is not part of resource category group. Resource category valid values are {}",
-                        category, categoryList);
+                    log.debug("Category {} is not part of resource category group. Resource category valid values are {}", category, categoryList);
                     failOnInvalidCategory(user, resource, actionEnum);
                 }
-                Optional<SubCategoryDefinition> foundSubcategory = foundCategory.get()
-                    .getSubcategories()
-                    .stream()
-                    .filter(subcat -> subcat.getName().equals(subcategory.getName()))
-                    .findFirst();
+                Optional<SubCategoryDefinition> foundSubcategory = foundCategory.get().getSubcategories().stream()
+                    .filter(subcat -> subcat.getName().equals(subcategory.getName())).findFirst();
                 if (!foundSubcategory.isPresent()) {
-                    log.debug(
-                        "SubCategory {} is not part of resource category group. Resource subcategory valid values are {}",
-                        subcategory, foundCategory.get().getSubcategories());
+                    log.debug("SubCategory {} is not part of resource category group. Resource subcategory valid values are {}", subcategory,
+                        foundCategory.get().getSubcategories());
                     failOnInvalidCategory(user, resource, actionEnum);
                 }
             } catch (Exception e) {
@@ -956,15 +874,12 @@ public class ServiceImportParseLogic {
 
     protected void failOnInvalidCategory(User user, Resource resource, AuditingActionEnum actionEnum) {
         ResponseFormat responseFormat;
-        responseFormat = componentsUtils.getResponseFormat(ActionStatus.COMPONENT_INVALID_CATEGORY,
-            ComponentTypeEnum.RESOURCE.getValue());
+        responseFormat = componentsUtils.getResponseFormat(ActionStatus.COMPONENT_INVALID_CATEGORY, ComponentTypeEnum.RESOURCE.getValue());
         componentsUtils.auditResource(responseFormat, user, resource, actionEnum);
-        throw new ComponentException(ActionStatus.COMPONENT_INVALID_CATEGORY,
-            ComponentTypeEnum.RESOURCE.getValue());
+        throw new ComponentException(ActionStatus.COMPONENT_INVALID_CATEGORY, ComponentTypeEnum.RESOURCE.getValue());
     }
 
-    protected void validateVendorName(User user, Resource resource,
-                                      AuditingActionEnum actionEnum) {
+    protected void validateVendorName(User user, Resource resource, AuditingActionEnum actionEnum) {
         String vendorName = resource.getVendorName();
         if (!ValidationUtils.validateStringNotEmpty(vendorName)) {
             log.info("vendor name is missing.");
@@ -975,18 +890,15 @@ public class ServiceImportParseLogic {
         validateVendorName(vendorName, user, resource, actionEnum);
     }
 
-    protected void validateVendorName(String vendorName, User user, Resource resource,
-                                      AuditingActionEnum actionEnum) {
+    protected void validateVendorName(String vendorName, User user, Resource resource, AuditingActionEnum actionEnum) {
         if (vendorName != null) {
             if (!ValidationUtils.validateVendorNameLength(vendorName)) {
                 log.info("vendor name exceds limit.");
-                ResponseFormat errorResponse = componentsUtils.getResponseFormat(ActionStatus.VENDOR_NAME_EXCEEDS_LIMIT,
-                    "" + ValidationUtils.VENDOR_NAME_MAX_LENGTH);
+                ResponseFormat errorResponse = componentsUtils
+                    .getResponseFormat(ActionStatus.VENDOR_NAME_EXCEEDS_LIMIT, "" + ValidationUtils.VENDOR_NAME_MAX_LENGTH);
                 componentsUtils.auditResource(errorResponse, user, resource, actionEnum);
-                throw new ComponentException(ActionStatus.VENDOR_NAME_EXCEEDS_LIMIT,
-                    "" + ValidationUtils.VENDOR_NAME_MAX_LENGTH);
+                throw new ComponentException(ActionStatus.VENDOR_NAME_EXCEEDS_LIMIT, "" + ValidationUtils.VENDOR_NAME_MAX_LENGTH);
             }
-
             if (!ValidationUtils.validateVendorName(vendorName)) {
                 log.info("vendor name  is not valid.");
                 ResponseFormat errorResponse = componentsUtils.getResponseFormat(ActionStatus.INVALID_VENDOR_NAME);
@@ -996,8 +908,7 @@ public class ServiceImportParseLogic {
         }
     }
 
-    private Resource buildComplexVfcMetadata(Resource resourceVf, CsarInfo csarInfo, String nodeName,
-                                             Map<String, NodeTypeInfo> nodesInfo) {
+    private Resource buildComplexVfcMetadata(Resource resourceVf, CsarInfo csarInfo, String nodeName, Map<String, NodeTypeInfo> nodesInfo) {
         Resource cvfc = new Resource();
         NodeTypeInfo nodeTypeInfo = nodesInfo.get(nodeName);
         cvfc.setName(buildCvfcName(csarInfo.getVfResourceName(), nodeName));
@@ -1013,15 +924,11 @@ public class ServiceImportParseLogic {
         cvfc.setVendorName(resourceVf.getVendorName());
         cvfc.setVendorRelease(resourceVf.getVendorRelease());
         cvfc.setResourceVendorModelNumber(resourceVf.getResourceVendorModelNumber());
-        cvfc.setToscaResourceName(
-            buildNestedToscaResourceName(ResourceTypeEnum.VF.name(), csarInfo.getVfResourceName(), nodeName)
-                .getLeft());
+        cvfc.setToscaResourceName(buildNestedToscaResourceName(ResourceTypeEnum.VF.name(), csarInfo.getVfResourceName(), nodeName).getLeft());
         cvfc.setInvariantUUID(UniqueIdBuilder.buildInvariantUUID());
-
         List<String> tags = new ArrayList<>();
         tags.add(cvfc.getName());
         cvfc.setTags(tags);
-
         CategoryDefinition category = new CategoryDefinition();
         category.setName(ImportUtils.Constants.ABSTRACT_CATEGORY_NAME);
         SubCategoryDefinition subCategory = new SubCategoryDefinition();
@@ -1030,17 +937,14 @@ public class ServiceImportParseLogic {
         List<CategoryDefinition> categories = new ArrayList<>();
         categories.add(category);
         cvfc.setCategories(categories);
-
         cvfc.setVersion(ImportUtils.Constants.FIRST_NON_CERTIFIED_VERSION);
         cvfc.setLifecycleState(ImportUtils.Constants.NORMATIVE_TYPE_LIFE_CYCLE_NOT_CERTIFIED_CHECKOUT);
         cvfc.setHighestVersion(ImportUtils.Constants.NORMATIVE_TYPE_HIGHEST_VERSION);
-
         return cvfc;
     }
 
     private String buildCvfcName(String resourceVfName, String nodeName) {
-        String nameWithouNamespacePrefix = nodeName
-            .substring(Constants.USER_DEFINED_RESOURCE_NAMESPACE_PREFIX.length());
+        String nameWithouNamespacePrefix = nodeName.substring(Constants.USER_DEFINED_RESOURCE_NAMESPACE_PREFIX.length());
         String[] findTypes = nameWithouNamespacePrefix.split("\\.");
         String resourceType = findTypes[0];
         String resourceName = resourceVfName + "-" + nameWithouNamespacePrefix.substring(resourceType.length() + 1);
@@ -1051,54 +955,43 @@ public class ServiceImportParseLogic {
         return resourceName + "VF";
     }
 
-    public UploadResourceInfo fillResourceMetadata(String yamlName, Resource resourceVf,
-                                                   String nodeName, User user) {
+    public UploadResourceInfo fillResourceMetadata(String yamlName, Resource resourceVf, String nodeName, User user) {
         UploadResourceInfo resourceMetaData = new UploadResourceInfo();
-
         // validate nodetype name prefix
         if (!nodeName.startsWith(Constants.USER_DEFINED_RESOURCE_NAMESPACE_PREFIX)) {
-            log.debug("invalid nodeName:{} does not start with {}.", nodeName,
-                Constants.USER_DEFINED_RESOURCE_NAMESPACE_PREFIX);
-            throw new ComponentException(ActionStatus.INVALID_NODE_TEMPLATE,
-                yamlName, resourceMetaData.getName(), nodeName);
+            log.debug("invalid nodeName:{} does not start with {}.", nodeName, Constants.USER_DEFINED_RESOURCE_NAMESPACE_PREFIX);
+            throw new ComponentException(ActionStatus.INVALID_NODE_TEMPLATE, yamlName, resourceMetaData.getName(), nodeName);
         }
-
         String actualName = this.getNodeTypeActualName(nodeName);
         String namePrefix = nodeName.replace(actualName, "");
         String resourceType = namePrefix.substring(Constants.USER_DEFINED_RESOURCE_NAMESPACE_PREFIX.length());
-
         // if we import from csar, the node_type name can be
+
         // org.openecomp.resource.abstract.node_name - in this case we always
+
         // create a vfc
         if (resourceType.equals(Constants.ABSTRACT)) {
             resourceType = ResourceTypeEnum.VFC.name().toLowerCase();
         }
         // validating type
         if (!ResourceTypeEnum.containsName(resourceType.toUpperCase())) {
-            log.debug("invalid resourceType:{} the type is not one of the valide types:{}.", resourceType.toUpperCase(),
-                ResourceTypeEnum.values());
-            throw new ComponentException(ActionStatus.INVALID_NODE_TEMPLATE,
-                yamlName, resourceMetaData.getName(), nodeName);
+            log.debug("invalid resourceType:{} the type is not one of the valide types:{}.", resourceType.toUpperCase(), ResourceTypeEnum.values());
+            throw new ComponentException(ActionStatus.INVALID_NODE_TEMPLATE, yamlName, resourceMetaData.getName(), nodeName);
         }
-
         // Setting name
         resourceMetaData.setName(resourceVf.getSystemName() + actualName);
-
         // Setting type from name
         String type = resourceType.toUpperCase();
         resourceMetaData.setResourceType(type);
-
         resourceMetaData.setDescription(ImportUtils.Constants.INNER_VFC_DESCRIPTION);
         resourceMetaData.setIcon(ImportUtils.Constants.DEFAULT_ICON);
         resourceMetaData.setContactId(user.getUserId());
         resourceMetaData.setVendorName(resourceVf.getVendorName());
         resourceMetaData.setVendorRelease(resourceVf.getVendorRelease());
-
         // Setting tag
         List<String> tags = new ArrayList<>();
         tags.add(resourceMetaData.getName());
         resourceMetaData.setTags(tags);
-
         // Setting category
         CategoryDefinition category = new CategoryDefinition();
         category.setName(ImportUtils.Constants.ABSTRACT_CATEGORY_NAME);
@@ -1108,13 +1001,11 @@ public class ServiceImportParseLogic {
         List<CategoryDefinition> categories = new ArrayList<>();
         categories.add(category);
         resourceMetaData.setCategories(categories);
-
         return resourceMetaData;
     }
 
     protected String getNodeTypeActualName(String fullName) {
-        String nameWithouNamespacePrefix = fullName
-            .substring(Constants.USER_DEFINED_RESOURCE_NAMESPACE_PREFIX.length());
+        String nameWithouNamespacePrefix = fullName.substring(Constants.USER_DEFINED_RESOURCE_NAMESPACE_PREFIX.length());
         String[] findTypes = nameWithouNamespacePrefix.split("\\.");
         String resourceType = findTypes[0];
         return nameWithouNamespacePrefix.substring(resourceType.length());
@@ -1129,8 +1020,7 @@ public class ServiceImportParseLogic {
 
     public Either<RequirementDefinition, ResponseFormat> findAviableRequiremen(String regName, String yamlName,
                                                                                UploadComponentInstanceInfo uploadComponentInstanceInfo,
-                                                                               ComponentInstance currentCompInstance,
-                                                                               String capName) {
+                                                                               ComponentInstance currentCompInstance, String capName) {
         Map<String, List<RequirementDefinition>> comInstRegDefMap = currentCompInstance.getRequirements();
         List<RequirementDefinition> list = comInstRegDefMap.get(capName);
         RequirementDefinition validRegDef = null;
@@ -1138,8 +1028,7 @@ public class ServiceImportParseLogic {
             for (Map.Entry<String, List<RequirementDefinition>> entry : comInstRegDefMap.entrySet()) {
                 for (RequirementDefinition reqDef : entry.getValue()) {
                     if (reqDef.getName().equals(regName)) {
-                        if (reqDef.getMaxOccurrences() != null
-                            && !reqDef.getMaxOccurrences().equals(RequirementDataDefinition.MAX_OCCURRENCES)) {
+                        if (reqDef.getMaxOccurrences() != null && !reqDef.getMaxOccurrences().equals(RequirementDataDefinition.MAX_OCCURRENCES)) {
                             String leftOccurrences = reqDef.getLeftOccurrences();
                             if (leftOccurrences == null) {
                                 leftOccurrences = reqDef.getMaxOccurrences();
@@ -1157,7 +1046,6 @@ public class ServiceImportParseLogic {
                             validRegDef = reqDef;
                             break;
                         }
-
                     }
                 }
                 if (validRegDef != null) {
@@ -1167,8 +1055,7 @@ public class ServiceImportParseLogic {
         } else {
             for (RequirementDefinition reqDef : list) {
                 if (reqDef.getName().equals(regName)) {
-                    if (reqDef.getMaxOccurrences() != null
-                        && !reqDef.getMaxOccurrences().equals(RequirementDataDefinition.MAX_OCCURRENCES)) {
+                    if (reqDef.getMaxOccurrences() != null && !reqDef.getMaxOccurrences().equals(RequirementDataDefinition.MAX_OCCURRENCES)) {
                         String leftOccurrences = reqDef.getLeftOccurrences();
                         if (leftOccurrences == null) {
                             leftOccurrences = reqDef.getMaxOccurrences();
@@ -1190,18 +1077,18 @@ public class ServiceImportParseLogic {
             }
         }
         if (validRegDef == null) {
-            ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.INVALID_NODE_TEMPLATE,
-                yamlName, uploadComponentInstanceInfo.getName(), uploadComponentInstanceInfo.getType());
+            ResponseFormat responseFormat = componentsUtils
+                .getResponseFormat(ActionStatus.INVALID_NODE_TEMPLATE, yamlName, uploadComponentInstanceInfo.getName(),
+                    uploadComponentInstanceInfo.getType());
             return Either.right(responseFormat);
         }
         return Either.left(validRegDef);
     }
 
-    public CapabilityDefinition findAvailableCapabilityByTypeOrName(RequirementDefinition validReq,
-                                                                    ComponentInstance currentCapCompInstance, UploadReqInfo uploadReqInfo) {
+    public CapabilityDefinition findAvailableCapabilityByTypeOrName(RequirementDefinition validReq, ComponentInstance currentCapCompInstance,
+                                                                    UploadReqInfo uploadReqInfo) {
         try {
-            if (null == uploadReqInfo.getCapabilityName()
-                || validReq.getCapability().equals(uploadReqInfo.getCapabilityName())) {
+            if (null == uploadReqInfo.getCapabilityName() || validReq.getCapability().equals(uploadReqInfo.getCapabilityName())) {
                 // get by capability type
                 return findAvailableCapability(validReq, currentCapCompInstance);
             }
@@ -1216,11 +1103,9 @@ public class ServiceImportParseLogic {
         Map<String, List<CapabilityDefinition>> capMap = instance.getCapabilities();
         if (capMap.containsKey(validReq.getCapability())) {
             List<CapabilityDefinition> capList = capMap.get(validReq.getCapability());
-
             for (CapabilityDefinition cap : capList) {
                 if (isBoundedByOccurrences(cap)) {
-                    String leftOccurrences = cap.getLeftOccurrences() != null ?
-                        cap.getLeftOccurrences() : cap.getMaxOccurrences();
+                    String leftOccurrences = cap.getLeftOccurrences() != null ? cap.getLeftOccurrences() : cap.getMaxOccurrences();
                     int left = Integer.parseInt(leftOccurrences);
                     if (left > 0) {
                         --left;
@@ -1235,8 +1120,8 @@ public class ServiceImportParseLogic {
         return null;
     }
 
-    protected CapabilityDefinition findAvailableCapability(RequirementDefinition validReq,
-                                                           ComponentInstance currentCapCompInstance, UploadReqInfo uploadReqInfo) {
+    protected CapabilityDefinition findAvailableCapability(RequirementDefinition validReq, ComponentInstance currentCapCompInstance,
+                                                           UploadReqInfo uploadReqInfo) {
         CapabilityDefinition cap = null;
         Map<String, List<CapabilityDefinition>> capMap = currentCapCompInstance.getCapabilities();
         if (!capMap.containsKey(validReq.getCapability())) {
@@ -1248,16 +1133,13 @@ public class ServiceImportParseLogic {
             return null;
         }
         cap = capByName.get();
-
         if (isBoundedByOccurrences(cap)) {
             String leftOccurrences = cap.getLeftOccurrences();
             int left = Integer.parseInt(leftOccurrences);
             if (left > 0) {
                 --left;
                 cap.setLeftOccurrences(String.valueOf(left));
-
             }
-
         }
         return cap;
     }
@@ -1283,6 +1165,7 @@ public class ServiceImportParseLogic {
         parametersView.setIgnoreComponentInstances(false);
         parametersView.setIgnoreInputs(false);
         // inputs are read when creating
+
         // property values on instances
         parametersView.setIgnoreUsers(false);
         return parametersView;
@@ -1309,13 +1192,10 @@ public class ServiceImportParseLogic {
         if (isNotEmpty(defaultCapabilities.get(capabilityType).get(0).getProperties())) {
             defaultCapability = defaultCapabilities.get(capabilityType).get(0);
         } else {
-            Either<Component, StorageOperationStatus> getFullComponentRes = toscaOperationFacade
-                .getToscaFullElement(resourceId);
+            Either<Component, StorageOperationStatus> getFullComponentRes = toscaOperationFacade.getToscaFullElement(resourceId);
             if (getFullComponentRes.isRight()) {
-                log.debug("Failed to get full component {}. Status is {}. ", resourceId,
-                    getFullComponentRes.right().value());
-                throw new ComponentException(componentsUtils.getResponseFormat(ActionStatus.COMPONENT_NOT_FOUND,
-                    resourceId));
+                log.debug("Failed to get full component {}. Status is {}. ", resourceId, getFullComponentRes.right().value());
+                throw new ComponentException(componentsUtils.getResponseFormat(ActionStatus.COMPONENT_NOT_FOUND, resourceId));
             }
             defaultCapability = getFullComponentRes.left().value().getCapabilities().get(capabilityType).get(0);
         }
@@ -1323,33 +1203,27 @@ public class ServiceImportParseLogic {
     }
 
     protected void validateCapabilityProperties(List<UploadCapInfo> capabilities, String resourceId, CapabilityDefinition defaultCapability) {
-        if (CollectionUtils.isEmpty(defaultCapability.getProperties())
-            && isNotEmpty(capabilities.get(0).getProperties())) {
-            log.debug("Failed to validate capability {} of component {}. Property list is empty. ",
-                defaultCapability.getName(), resourceId);
-            log.debug(
-                "Failed to update capability property values. Property list of fetched capability {} is empty. ",
-                defaultCapability.getName());
+        if (CollectionUtils.isEmpty(defaultCapability.getProperties()) && isNotEmpty(capabilities.get(0).getProperties())) {
+            log.debug("Failed to validate capability {} of component {}. Property list is empty. ", defaultCapability.getName(), resourceId);
+            log.debug("Failed to update capability property values. Property list of fetched capability {} is empty. ", defaultCapability.getName());
             throw new ComponentException(componentsUtils.getResponseFormat(ActionStatus.PROPERTY_NOT_FOUND, resourceId));
         } else if (isNotEmpty(capabilities.get(0).getProperties())) {
             validateUniquenessUpdateUploadedComponentInstanceCapability(defaultCapability, capabilities.get(0));
         }
     }
 
-    protected void validateUniquenessUpdateUploadedComponentInstanceCapability(
-        CapabilityDefinition defaultCapability, UploadCapInfo uploadedCapability) {
+    protected void validateUniquenessUpdateUploadedComponentInstanceCapability(CapabilityDefinition defaultCapability,
+                                                                               UploadCapInfo uploadedCapability) {
         List<ComponentInstanceProperty> validProperties = new ArrayList<>();
         Map<String, PropertyDefinition> defaultProperties = defaultCapability.getProperties().stream()
-            .collect(toMap(PropertyDefinition::getName, Function
-                .identity()));
+            .collect(toMap(PropertyDefinition::getName, Function.identity()));
         List<UploadPropInfo> uploadedProperties = uploadedCapability.getProperties();
         for (UploadPropInfo property : uploadedProperties) {
             String propertyName = property.getName().toLowerCase();
             String propertyType = property.getType();
             ComponentInstanceProperty validProperty;
             if (defaultProperties.containsKey(propertyName) && propertTypeEqualsTo(defaultProperties, propertyName, propertyType)) {
-                throw new ComponentException(componentsUtils.getResponseFormat(ActionStatus.PROPERTY_NAME_ALREADY_EXISTS,
-                    propertyName));
+                throw new ComponentException(componentsUtils.getResponseFormat(ActionStatus.PROPERTY_NAME_ALREADY_EXISTS, propertyName));
             }
             validProperty = new ComponentInstanceProperty();
             validProperty.setName(propertyName);
@@ -1381,15 +1255,14 @@ public class ServiceImportParseLogic {
             if (artifactMap == null) {
                 artifactMap = new HashMap<>();
             }
-            Map<String, Object> deploymentResourceArtifacts = ConfigurationManager.getConfigurationManager()
-                .getConfiguration().getDeploymentResourceArtifacts();
+            Map<String, Object> deploymentResourceArtifacts = ConfigurationManager.getConfigurationManager().getConfiguration()
+                .getDeploymentResourceArtifacts();
             if (deploymentResourceArtifacts != null) {
                 Map<String, ArtifactDefinition> finalArtifactMap = artifactMap;
                 deploymentResourceArtifacts.forEach((k, v) -> processDeploymentResourceArtifacts(user, resource, finalArtifactMap, k, v));
             }
             resource.setDeploymentArtifacts(artifactMap);
         }
-
     }
 
     protected void processDeploymentResourceArtifacts(User user, Resource resource, Map<String, ArtifactDefinition> artifactMap, String k, Object v) {
@@ -1402,16 +1275,13 @@ public class ServiceImportParseLogic {
                 return;
             }
         } else {
-            log.info("resource types for artifact placeholder {} were not defined. default is all resources",
-                k);
+            log.info("resource types for artifact placeholder {} were not defined. default is all resources", k);
         }
         if (shouldCreateArtifact) {
             if (serviceBusinessLogic.artifactsBusinessLogic != null) {
-                ArtifactDefinition artifactDefinition = serviceBusinessLogic.artifactsBusinessLogic.createArtifactPlaceHolderInfo(
-                    resource.getUniqueId(), k, (Map<String, Object>) v,
-                    user, ArtifactGroupTypeEnum.DEPLOYMENT);
-                if (artifactDefinition != null
-                    && !artifactMap.containsKey(artifactDefinition.getArtifactLabel())) {
+                ArtifactDefinition artifactDefinition = serviceBusinessLogic.artifactsBusinessLogic
+                    .createArtifactPlaceHolderInfo(resource.getUniqueId(), k, (Map<String, Object>) v, user, ArtifactGroupTypeEnum.DEPLOYMENT);
+                if (artifactDefinition != null && !artifactMap.containsKey(artifactDefinition.getArtifactLabel())) {
                     artifactMap.put(artifactDefinition.getArtifactLabel(), artifactDefinition);
                 }
             }
@@ -1419,25 +1289,19 @@ public class ServiceImportParseLogic {
     }
 
     public void mergeOldResourceMetadataWithNew(Resource oldResource, Resource newResource) {
-
         if (newResource.getTags() == null || newResource.getTags().isEmpty()) {
             newResource.setTags(oldResource.getTags());
         }
-
         if (newResource.getDescription() == null) {
             newResource.setDescription(oldResource.getDescription());
         }
-
         if (newResource.getContactId() == null) {
             newResource.setContactId(oldResource.getContactId());
         }
-
         newResource.setCategories(oldResource.getCategories());
-
     }
 
-    protected Resource buildComplexVfcMetadata(CsarInfo csarInfo, String nodeName,
-                                               Map<String, NodeTypeInfo> nodesInfo) {
+    protected Resource buildComplexVfcMetadata(CsarInfo csarInfo, String nodeName, Map<String, NodeTypeInfo> nodesInfo) {
         Resource cvfc = new Resource();
         NodeTypeInfo nodeTypeInfo = nodesInfo.get(nodeName);
         cvfc.setName(buildCvfcName(csarInfo.getVfResourceName(), nodeName));
@@ -1453,15 +1317,11 @@ public class ServiceImportParseLogic {
         cvfc.setVendorName("cmri");
         cvfc.setVendorRelease("1.0");
         cvfc.setResourceVendorModelNumber("");
-        cvfc.setToscaResourceName(
-            buildNestedToscaResourceName(ResourceTypeEnum.VF.name(), csarInfo.getVfResourceName(), nodeName)
-                .getLeft());
+        cvfc.setToscaResourceName(buildNestedToscaResourceName(ResourceTypeEnum.VF.name(), csarInfo.getVfResourceName(), nodeName).getLeft());
         cvfc.setInvariantUUID(UniqueIdBuilder.buildInvariantUUID());
-
         List<String> tags = new ArrayList<>();
         tags.add(cvfc.getName());
         cvfc.setTags(tags);
-
         CategoryDefinition category = new CategoryDefinition();
         category.setName(ImportUtils.Constants.ABSTRACT_CATEGORY_NAME);
         SubCategoryDefinition subCategory = new SubCategoryDefinition();
@@ -1470,11 +1330,9 @@ public class ServiceImportParseLogic {
         List<CategoryDefinition> categories = new ArrayList<>();
         categories.add(category);
         cvfc.setCategories(categories);
-
         cvfc.setVersion(ImportUtils.Constants.FIRST_NON_CERTIFIED_VERSION);
         cvfc.setLifecycleState(ImportUtils.Constants.NORMATIVE_TYPE_LIFE_CYCLE_NOT_CERTIFIED_CHECKOUT);
         cvfc.setHighestVersion(ImportUtils.Constants.NORMATIVE_TYPE_HIGHEST_VERSION);
-
         return cvfc;
     }
 
@@ -1485,13 +1343,11 @@ public class ServiceImportParseLogic {
 
     private void validateDerivedFromNotEmpty(User user, Resource resource, AuditingActionEnum actionEnum) {
         log.debug("validate resource derivedFrom field");
-        if ((resource.getDerivedFrom() == null) || (resource.getDerivedFrom().isEmpty())
-            || (resource.getDerivedFrom().get(0)) == null || (resource.getDerivedFrom().get(0).trim().isEmpty())) {
+        if ((resource.getDerivedFrom() == null) || (resource.getDerivedFrom().isEmpty()) || (resource.getDerivedFrom().get(0)) == null || (resource
+            .getDerivedFrom().get(0).trim().isEmpty())) {
             log.info("derived from (template) field is missing for the resource");
-            ResponseFormat responseFormat = componentsUtils
-                .getResponseFormat(ActionStatus.MISSING_DERIVED_FROM_TEMPLATE);
+            ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.MISSING_DERIVED_FROM_TEMPLATE);
             componentsUtils.auditResource(responseFormat, user, resource, actionEnum);
-
             throw new ComponentException(ActionStatus.MISSING_DERIVED_FROM_TEMPLATE);
         }
     }
@@ -1499,46 +1355,40 @@ public class ServiceImportParseLogic {
     public Service createInputsOnService(Service service, Map<String, InputDefinition> inputs) {
         List<InputDefinition> resourceProperties = service.getInputs();
         if (MapUtils.isNotEmpty(inputs) || isNotEmpty(resourceProperties)) {
-
-            Either<List<InputDefinition>, ResponseFormat> createInputs = inputsBusinessLogic.createInputsInGraph(inputs,
-                service);
+            Either<List<InputDefinition>, ResponseFormat> createInputs = inputsBusinessLogic.createInputsInGraph(inputs, service);
             if (createInputs.isRight()) {
                 throw new ComponentException(createInputs.right().value());
             }
         } else {
             return service;
         }
-        Either<Service, StorageOperationStatus> updatedResource = toscaOperationFacade
-            .getToscaElement(service.getUniqueId());
+        Either<Service, StorageOperationStatus> updatedResource = toscaOperationFacade.getToscaElement(service.getUniqueId());
         if (updatedResource.isRight()) {
-            throw new ComponentException(componentsUtils.getResponseFormatByComponent(
-                componentsUtils.convertFromStorageResponse(updatedResource.right().value()), service, ComponentTypeEnum.SERVICE));
+            throw new ComponentException(componentsUtils
+                .getResponseFormatByComponent(componentsUtils.convertFromStorageResponse(updatedResource.right().value()), service,
+                    ComponentTypeEnum.SERVICE));
         }
         return updatedResource.left().value();
     }
 
-
     public Service createServiceTransaction(Service service, User user, boolean isNormative) {
         // validate resource name uniqueness
         log.debug("validate resource name");
-        Either<Boolean, StorageOperationStatus> eitherValidation = toscaOperationFacade.validateComponentNameExists(
-            service.getName(), null, service.getComponentType());
+        Either<Boolean, StorageOperationStatus> eitherValidation = toscaOperationFacade
+            .validateComponentNameExists(service.getName(), null, service.getComponentType());
         if (eitherValidation.isRight()) {
-            log.debug("Failed to validate component name {}. Status is {}. ", service.getName(),
-                eitherValidation.right().value());
+            log.debug("Failed to validate component name {}. Status is {}. ", service.getName(), eitherValidation.right().value());
             ResponseFormat errorResponse = componentsUtils
                 .getResponseFormat(componentsUtils.convertFromStorageResponse(eitherValidation.right().value()));
             throw new ComponentException(errorResponse);
         }
         if (eitherValidation.left().value()) {
             log.debug("resource with name: {}, already exists", service.getName());
-            ResponseFormat errorResponse = componentsUtils.getResponseFormat(ActionStatus.COMPONENT_NAME_ALREADY_EXIST,
-                ComponentTypeEnum.RESOURCE.getValue(), service.getName());
+            ResponseFormat errorResponse = componentsUtils
+                .getResponseFormat(ActionStatus.COMPONENT_NAME_ALREADY_EXIST, ComponentTypeEnum.RESOURCE.getValue(), service.getName());
             throw new ComponentException(errorResponse);
         }
-
         log.debug("send resource {} to dao for create", service.getName());
-
         createArtifactsPlaceHolderData(service, user);
         // enrich object
         if (!isNormative) {
@@ -1547,18 +1397,15 @@ public class ServiceImportParseLogic {
             service.setVersion(INITIAL_VERSION);
             service.setHighestVersion(true);
         }
-        return toscaOperationFacade.createToscaComponent(service)
-            .left()
-            .on(r -> throwComponentExceptionByResource(r, service));
+        return toscaOperationFacade.createToscaComponent(service).left().on(r -> throwComponentExceptionByResource(r, service));
     }
 
     public Service throwComponentExceptionByResource(StorageOperationStatus status, Service service) {
-        ResponseFormat responseFormat = componentsUtils.getResponseFormatByComponent(
-            componentsUtils.convertFromStorageResponse(status), service, ComponentTypeEnum.SERVICE);
+        ResponseFormat responseFormat = componentsUtils
+            .getResponseFormatByComponent(componentsUtils.convertFromStorageResponse(status), service, ComponentTypeEnum.SERVICE);
         throw new ComponentException(responseFormat);
     }
 
-
     protected void createArtifactsPlaceHolderData(Service service, User user) {
         setInformationalArtifactsPlaceHolder(service, user);
         serviceBusinessLogic.setDeploymentArtifactsPlaceHolder(service, user);
@@ -1567,40 +1414,34 @@ public class ServiceImportParseLogic {
 
     @SuppressWarnings("unchecked")
     protected void setInformationalArtifactsPlaceHolder(Service service, User user) {
-
         Map<String, ArtifactDefinition> artifactMap = service.getArtifacts();
         if (artifactMap == null) {
             artifactMap = new HashMap<>();
         }
         String resourceUniqueId = service.getUniqueId();
-        List<String> exludeResourceCategory = ConfigurationManager.getConfigurationManager().getConfiguration()
-            .getExcludeResourceCategory();
-        List<String> exludeResourceType = ConfigurationManager.getConfigurationManager().getConfiguration()
-            .getExcludeResourceType();
-        Map<String, Object> informationalResourceArtifacts = ConfigurationManager.getConfigurationManager()
-            .getConfiguration().getInformationalResourceArtifacts();
+        List<String> exludeResourceCategory = ConfigurationManager.getConfigurationManager().getConfiguration().getExcludeResourceCategory();
+        List<String> exludeResourceType = ConfigurationManager.getConfigurationManager().getConfiguration().getExcludeResourceType();
+        Map<String, Object> informationalResourceArtifacts = ConfigurationManager.getConfigurationManager().getConfiguration()
+            .getInformationalResourceArtifacts();
         List<CategoryDefinition> categories = service.getCategories();
         boolean isCreateArtifact = true;
         if (exludeResourceCategory != null) {
             String category = categories.get(0).getName();
             isCreateArtifact = exludeResourceCategory.stream().noneMatch(e -> e.equalsIgnoreCase(category));
         }
-
         if (informationalResourceArtifacts != null && isCreateArtifact) {
             Set<String> keys = informationalResourceArtifacts.keySet();
             for (String informationalResourceArtifactName : keys) {
-                Map<String, Object> artifactInfoMap = (Map<String, Object>) informationalResourceArtifacts
-                    .get(informationalResourceArtifactName);
+                Map<String, Object> artifactInfoMap = (Map<String, Object>) informationalResourceArtifacts.get(informationalResourceArtifactName);
                 if (serviceBusinessLogic.artifactsBusinessLogic != null) {
-                    ArtifactDefinition artifactDefinition = serviceBusinessLogic.artifactsBusinessLogic.createArtifactPlaceHolderInfo(
-                        resourceUniqueId, informationalResourceArtifactName, artifactInfoMap, user,
-                        ArtifactGroupTypeEnum.INFORMATIONAL);
+                    ArtifactDefinition artifactDefinition = serviceBusinessLogic.artifactsBusinessLogic
+                        .createArtifactPlaceHolderInfo(resourceUniqueId, informationalResourceArtifactName, artifactInfoMap, user,
+                            ArtifactGroupTypeEnum.INFORMATIONAL);
                     artifactMap.put(artifactDefinition.getArtifactLabel(), artifactDefinition);
                 }
             }
         }
         service.setArtifacts(artifactMap);
-
     }
 
     public void rollback(boolean inTransaction, Service service, List<ArtifactDefinition> createdArtifacts,
@@ -1615,48 +1456,40 @@ public class ServiceImportParseLogic {
     }
 
     public Map<String, Object> getNodeTypesFromTemplate(Map<String, Object> mappedToscaTemplate) {
-        return ImportUtils.findFirstToscaMapElement(mappedToscaTemplate, TypeUtils.ToscaTagNamesEnum.NODE_TYPES)
-            .left().orValue(HashMap::new);
+        return ImportUtils.findFirstToscaMapElement(mappedToscaTemplate, TypeUtils.ToscaTagNamesEnum.NODE_TYPES).left().orValue(HashMap::new);
     }
 
-    private Resource nodeForceCertification(Resource resource, User user,
-                                            LifecycleChangeInfoWithAction lifecycleChangeInfo, boolean inTransaction, boolean needLock) {
-        return lifecycleBusinessLogic.forceResourceCertification(resource, user, lifecycleChangeInfo, inTransaction,
-            needLock);
+    private Resource nodeForceCertification(Resource resource, User user, LifecycleChangeInfoWithAction lifecycleChangeInfo, boolean inTransaction,
+                                            boolean needLock) {
+        return lifecycleBusinessLogic.forceResourceCertification(resource, user, lifecycleChangeInfo, inTransaction, needLock);
     }
 
-    private Resource nodeFullCertification(String uniqueId, User user,
-                                           LifecycleChangeInfoWithAction lifecycleChangeInfo, boolean inTransaction, boolean needLock) {
+    private Resource nodeFullCertification(String uniqueId, User user, LifecycleChangeInfoWithAction lifecycleChangeInfo, boolean inTransaction,
+                                           boolean needLock) {
         Either<Resource, ResponseFormat> resourceResponse = lifecycleBusinessLogic
-            .changeState(uniqueId, user, LifeCycleTransitionEnum.CERTIFY, lifecycleChangeInfo,
-                inTransaction, needLock);
+            .changeState(uniqueId, user, LifeCycleTransitionEnum.CERTIFY, lifecycleChangeInfo, inTransaction, needLock);
         if (resourceResponse.isRight()) {
             throw new ByResponseFormatComponentException(resourceResponse.right().value());
         }
         return resourceResponse.left().value();
     }
 
-    public Either<Boolean, ResponseFormat> validateNestedDerivedFromDuringUpdate(Resource currentResource,
-                                                                                 Resource updateInfoResource, boolean hasBeenCertified) {
-
+    public Either<Boolean, ResponseFormat> validateNestedDerivedFromDuringUpdate(Resource currentResource, Resource updateInfoResource,
+                                                                                 boolean hasBeenCertified) {
         List<String> currentDerivedFrom = currentResource.getDerivedFrom();
         List<String> updatedDerivedFrom = updateInfoResource.getDerivedFrom();
-        if (currentDerivedFrom == null || currentDerivedFrom.isEmpty() || updatedDerivedFrom == null
-            || updatedDerivedFrom.isEmpty()) {
+        if (currentDerivedFrom == null || currentDerivedFrom.isEmpty() || updatedDerivedFrom == null || updatedDerivedFrom.isEmpty()) {
             log.trace("Update normative types");
             return Either.left(true);
         }
-
         String derivedFromCurrent = currentDerivedFrom.get(0);
         String derivedFromUpdated = updatedDerivedFrom.get(0);
-
         if (!derivedFromCurrent.equals(derivedFromUpdated)) {
             if (!hasBeenCertified) {
                 validateDerivedFromExist(null, updateInfoResource, null);
             } else {
-                Either<Boolean, ResponseFormat> validateDerivedFromExtending = validateDerivedFromExtending(null,
-                    currentResource, updateInfoResource, null);
-
+                Either<Boolean, ResponseFormat> validateDerivedFromExtending = validateDerivedFromExtending(null, currentResource, updateInfoResource,
+                    null);
                 if (validateDerivedFromExtending.isRight() || !validateDerivedFromExtending.left().value()) {
                     log.debug("Derived from cannot be updated if it doesnt inherits directly or extends inheritance");
                     return validateDerivedFromExtending;
@@ -1666,45 +1499,35 @@ public class ServiceImportParseLogic {
         return Either.left(true);
     }
 
-    protected Either<Boolean, ResponseFormat> validateDerivedFromExtending(User user, Resource currentResource,
-                                                                           Resource updateInfoResource, AuditingActionEnum actionEnum) {
+    protected Either<Boolean, ResponseFormat> validateDerivedFromExtending(User user, Resource currentResource, Resource updateInfoResource,
+                                                                           AuditingActionEnum actionEnum) {
         String currentTemplateName = currentResource.getDerivedFrom().get(0);
         String updatedTemplateName = updateInfoResource.getDerivedFrom().get(0);
-
         Either<Boolean, StorageOperationStatus> dataModelResponse = toscaOperationFacade
             .validateToscaResourceNameExtends(currentTemplateName, updatedTemplateName);
         if (dataModelResponse.isRight()) {
             StorageOperationStatus storageStatus = dataModelResponse.right().value();
-            BeEcompErrorManager.getInstance()
-                .logBeDaoSystemError("Create/Update Resource - validateDerivingFromExtendingType");
-            ResponseFormat responseFormat = componentsUtils.getResponseFormatByResource(
-                componentsUtils.convertFromStorageResponse(storageStatus), currentResource);
+            BeEcompErrorManager.getInstance().logBeDaoSystemError("Create/Update Resource - validateDerivingFromExtendingType");
+            ResponseFormat responseFormat = componentsUtils
+                .getResponseFormatByResource(componentsUtils.convertFromStorageResponse(storageStatus), currentResource);
             log.trace("audit before sending response");
             componentsUtils.auditResource(responseFormat, user, currentResource, actionEnum);
             return Either.right(responseFormat);
         }
-
         if (!dataModelResponse.left().value()) {
-            log.info("resource template with name {} does not inherit as original {}", updatedTemplateName,
-                currentTemplateName);
-            ResponseFormat responseFormat = componentsUtils
-                .getResponseFormat(ActionStatus.PARENT_RESOURCE_DOES_NOT_EXTEND);
+            log.info("resource template with name {} does not inherit as original {}", updatedTemplateName, currentTemplateName);
+            ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.PARENT_RESOURCE_DOES_NOT_EXTEND);
             componentsUtils.auditResource(responseFormat, user, currentResource, actionEnum);
-
             return Either.right(responseFormat);
-
         }
         return Either.left(true);
     }
 
-    public void validateResourceFieldsBeforeUpdate(Resource currentResource, Resource updateInfoResource,
-                                                   boolean inTransaction, boolean isNested) {
+    public void validateResourceFieldsBeforeUpdate(Resource currentResource, Resource updateInfoResource, boolean inTransaction, boolean isNested) {
         validateFields(currentResource, updateInfoResource, inTransaction, isNested);
     }
 
-
     private void validateFields(Resource currentResource, Resource updateInfoResource, boolean inTransaction, boolean isNested) {
-
         boolean hasBeenCertified = ValidationUtils.hasBeenCertified(currentResource.getVersion());
         log.debug("validate resource name before update");
         validateResourceName(currentResource, updateInfoResource, hasBeenCertified, isNested);
@@ -1726,12 +1549,9 @@ public class ServiceImportParseLogic {
         }
         log.debug(VALIDATE_DERIVED_BEFORE_UPDATE);
         log.debug("validate category before update");
-
     }
 
-
-    protected void validateResourceName(Resource currentResource, Resource updateInfoResource,
-                                        boolean hasBeenCertified, boolean isNested) {
+    protected void validateResourceName(Resource currentResource, Resource updateInfoResource, boolean hasBeenCertified, boolean isNested) {
         String resourceNameUpdated = updateInfoResource.getName();
         if (!isResourceNameEquals(currentResource, updateInfoResource)) {
             if (isNested || !hasBeenCertified) {
@@ -1739,10 +1559,8 @@ public class ServiceImportParseLogic {
                 currentResource.setName(resourceNameUpdated);
                 currentResource.setNormalizedName(ValidationUtils.normaliseComponentName(resourceNameUpdated));
                 currentResource.setSystemName(ValidationUtils.convertToSystemName(resourceNameUpdated));
-
             } else {
-                log.info("Resource name: {}, cannot be updated once the resource has been certified once.",
-                    resourceNameUpdated);
+                log.info("Resource name: {}, cannot be updated once the resource has been certified once.", resourceNameUpdated);
                 throw new ComponentException(ActionStatus.RESOURCE_NAME_CANNOT_BE_CHANGED);
             }
         }
@@ -1754,34 +1572,25 @@ public class ServiceImportParseLogic {
         if (resourceNameCurrent.equals(resourceNameUpdated)) {
             return true;
         }
-        return currentResource.getResourceType().equals(ResourceTypeEnum.VF) &&
-            resourceNameUpdated.equals(addCvfcSuffixToResourceName(resourceNameCurrent));
+        return currentResource.getResourceType().equals(ResourceTypeEnum.VF) && resourceNameUpdated
+            .equals(addCvfcSuffixToResourceName(resourceNameCurrent));
     }
 
-    public Resource prepareResourceForUpdate(Resource oldResource, Resource newResource, User user,
-                                             boolean inTransaction, boolean needLock) {
-
+    public Resource prepareResourceForUpdate(Resource oldResource, Resource newResource, User user, boolean inTransaction, boolean needLock) {
         if (!ComponentValidationUtils.canWorkOnResource(oldResource, user.getUserId())) {
             // checkout
-            return lifecycleBusinessLogic.changeState(
-                oldResource.getUniqueId(), user, LifeCycleTransitionEnum.CHECKOUT,
-                new LifecycleChangeInfoWithAction("update by import"), inTransaction, needLock)
-                .left()
-                .on(response -> failOnChangeState(response, user, oldResource, newResource));
+            return lifecycleBusinessLogic
+                .changeState(oldResource.getUniqueId(), user, LifeCycleTransitionEnum.CHECKOUT, new LifecycleChangeInfoWithAction("update by import"),
+                    inTransaction, needLock).left().on(response -> failOnChangeState(response, user, oldResource, newResource));
         }
         return oldResource;
     }
 
     protected Resource failOnChangeState(ResponseFormat response, User user, Resource oldResource, Resource newResource) {
         if (response.getRequestError() != null) {
-            log.info("resource {} cannot be updated. reason={}", oldResource.getUniqueId(),
-                response.getFormattedMessage());
-
+            log.info("resource {} cannot be updated. reason={}", oldResource.getUniqueId(), response.getFormattedMessage());
             componentsUtils.auditResource(response, user, newResource, AuditingActionEnum.IMPORT_RESOURCE,
-                ResourceVersionInfo.newBuilder()
-                    .state(oldResource.getLifecycleState().name())
-                    .version(oldResource.getVersion())
-                    .build());
+                ResourceVersionInfo.newBuilder().state(oldResource.getLifecycleState().name()).version(oldResource.getVersion()).build());
         }
         throw new ComponentException(response);
     }
@@ -1797,20 +1606,17 @@ public class ServiceImportParseLogic {
     public Resource createInputsOnResource(Resource resource, Map<String, InputDefinition> inputs) {
         List<InputDefinition> resourceProperties = resource.getInputs();
         if (MapUtils.isNotEmpty(inputs) || isNotEmpty(resourceProperties)) {
-
-            Either<List<InputDefinition>, ResponseFormat> createInputs = inputsBusinessLogic.createInputsInGraph(inputs,
-                resource);
+            Either<List<InputDefinition>, ResponseFormat> createInputs = inputsBusinessLogic.createInputsInGraph(inputs, resource);
             if (createInputs.isRight()) {
                 throw new ComponentException(createInputs.right().value());
             }
         } else {
             return resource;
         }
-        Either<Resource, StorageOperationStatus> updatedResource = toscaOperationFacade
-            .getToscaElement(resource.getUniqueId());
+        Either<Resource, StorageOperationStatus> updatedResource = toscaOperationFacade.getToscaElement(resource.getUniqueId());
         if (updatedResource.isRight()) {
-            throw new ComponentException(componentsUtils.getResponseFormatByResource(
-                componentsUtils.convertFromStorageResponse(updatedResource.right().value()), resource));
+            throw new ComponentException(
+                componentsUtils.getResponseFormatByResource(componentsUtils.convertFromStorageResponse(updatedResource.right().value()), resource));
         }
         return updatedResource.left().value();
     }
@@ -1830,25 +1636,18 @@ public class ServiceImportParseLogic {
         if (isNotEmpty(groupsToCreate)) {
             fillGroupsFinalFields(groupsToCreate);
             if (isNotEmpty(groupsFromResource)) {
-                serviceBusinessLogic.groupBusinessLogic.addGroups(resource,
-                    groupsToCreate, true)
-                    .left()
+                serviceBusinessLogic.groupBusinessLogic.addGroups(resource, groupsToCreate, true).left()
                     .on(serviceBusinessLogic::throwComponentException);
             } else {
-                serviceBusinessLogic.groupBusinessLogic.createGroups(resource,
-                    groupsToCreate, true)
-                    .left()
+                serviceBusinessLogic.groupBusinessLogic.createGroups(resource, groupsToCreate, true).left()
                     .on(serviceBusinessLogic::throwComponentException);
             }
         }
         if (isNotEmpty(groupsToDelete)) {
-            serviceBusinessLogic.groupBusinessLogic.deleteGroups(resource, groupsToDelete)
-                .left()
-                .on(serviceBusinessLogic::throwComponentException);
+            serviceBusinessLogic.groupBusinessLogic.deleteGroups(resource, groupsToDelete).left().on(serviceBusinessLogic::throwComponentException);
         }
         if (isNotEmpty(groupsToUpdate)) {
-            serviceBusinessLogic.groupBusinessLogic.updateGroups(resource, groupsToUpdate, true)
-                .left()
+            serviceBusinessLogic.groupBusinessLogic.updateGroups(resource, groupsToUpdate, true).left()
                 .on(serviceBusinessLogic::throwComponentException);
         }
     }
@@ -1856,8 +1655,8 @@ public class ServiceImportParseLogic {
     protected void addGroupsToCreateOrUpdate(List<GroupDefinition> groupsFromResource, List<GroupDefinition> groupsAsList,
                                              List<GroupDefinition> groupsToUpdate, List<GroupDefinition> groupsToCreate) {
         for (GroupDefinition group : groupsAsList) {
-            Optional<GroupDefinition> op = groupsFromResource.stream()
-                .filter(p -> p.getInvariantName().equalsIgnoreCase(group.getInvariantName())).findAny();
+            Optional<GroupDefinition> op = groupsFromResource.stream().filter(p -> p.getInvariantName().equalsIgnoreCase(group.getInvariantName()))
+                .findAny();
             if (op.isPresent()) {
                 GroupDefinition groupToUpdate = op.get();
                 groupToUpdate.setMembers(group.getMembers());
@@ -1873,8 +1672,7 @@ public class ServiceImportParseLogic {
     protected void addGroupsToDelete(List<GroupDefinition> groupsFromResource, List<GroupDefinition> groupsAsList,
                                      List<GroupDefinition> groupsToDelete) {
         for (GroupDefinition group : groupsFromResource) {
-            Optional<GroupDefinition> op = groupsAsList.stream()
-                .filter(p -> p.getName().equalsIgnoreCase(group.getName())).findAny();
+            Optional<GroupDefinition> op = groupsAsList.stream().filter(p -> p.getName().equalsIgnoreCase(group.getName())).findAny();
             if (!op.isPresent() && (group.getArtifacts() == null || group.getArtifacts().isEmpty())) {
                 groupsToDelete.add(group);
             }
@@ -1882,10 +1680,8 @@ public class ServiceImportParseLogic {
     }
 
     protected List<GroupDefinition> updateGroupsMembersUsingResource(Map<String, GroupDefinition> groups, Service component) {
-
         List<GroupDefinition> result = new ArrayList<>();
         List<ComponentInstance> componentInstances = component.getComponentInstances();
-
         if (groups != null) {
             Either<Boolean, ResponseFormat> validateCyclicGroupsDependencies = validateCyclicGroupsDependencies(groups);
             if (validateCyclicGroupsDependencies.isRight()) {
@@ -1909,42 +1705,35 @@ public class ServiceImportParseLogic {
     public void updateGroupMembers(Map<String, GroupDefinition> groups, GroupDefinition updatedGroupDefinition, Service component,
                                    List<ComponentInstance> componentInstances, String groupName, Map<String, String> members) {
         Set<String> compInstancesNames = members.keySet();
-
         if (CollectionUtils.isEmpty(componentInstances)) {
             String membersAstString = compInstancesNames.stream().collect(joining(","));
-            log.debug("The members: {}, in group: {}, cannot be found in component {}. There are no component instances.",
-                membersAstString, groupName, component.getNormalizedName());
-            throw new ComponentException(componentsUtils.getResponseFormat(
-                ActionStatus.GROUP_INVALID_COMPONENT_INSTANCE, membersAstString, groupName,
-                component.getNormalizedName(), getComponentTypeForResponse(component)));
+            log.debug("The members: {}, in group: {}, cannot be found in component {}. There are no component instances.", membersAstString,
+                groupName, component.getNormalizedName());
+            throw new ComponentException(componentsUtils
+                .getResponseFormat(ActionStatus.GROUP_INVALID_COMPONENT_INSTANCE, membersAstString, groupName, component.getNormalizedName(),
+                    getComponentTypeForResponse(component)));
         }
         // Find all component instances with the member names
-        Map<String, String> memberNames = componentInstances.stream()
-            .collect(toMap(ComponentInstance::getName, ComponentInstance::getUniqueId));
+        Map<String, String> memberNames = componentInstances.stream().collect(toMap(ComponentInstance::getName, ComponentInstance::getUniqueId));
         memberNames.putAll(groups.keySet().stream().collect(toMap(g -> g, g -> "")));
-        Map<String, String> relevantInstances = memberNames.entrySet().stream()
-            .filter(n -> compInstancesNames.contains(n.getKey()))
+        Map<String, String> relevantInstances = memberNames.entrySet().stream().filter(n -> compInstancesNames.contains(n.getKey()))
             .collect(toMap(Map.Entry::getKey, Map.Entry::getValue));
-
         if (relevantInstances == null || relevantInstances.size() != compInstancesNames.size()) {
-
             List<String> foundMembers = new ArrayList<>();
             if (relevantInstances != null) {
                 foundMembers = relevantInstances.keySet().stream().collect(toList());
             }
             compInstancesNames.removeAll(foundMembers);
             String membersAstString = compInstancesNames.stream().collect(joining(","));
-            log.debug("The members: {}, in group: {}, cannot be found in component: {}", membersAstString,
-                groupName, component.getNormalizedName());
-            throw new ComponentException(componentsUtils.getResponseFormat(
-                ActionStatus.GROUP_INVALID_COMPONENT_INSTANCE, membersAstString, groupName,
-                component.getNormalizedName(), getComponentTypeForResponse(component)));
+            log.debug("The members: {}, in group: {}, cannot be found in component: {}", membersAstString, groupName, component.getNormalizedName());
+            throw new ComponentException(componentsUtils
+                .getResponseFormat(ActionStatus.GROUP_INVALID_COMPONENT_INSTANCE, membersAstString, groupName, component.getNormalizedName(),
+                    getComponentTypeForResponse(component)));
         }
         updatedGroupDefinition.setMembers(relevantInstances);
     }
 
     public Either<Boolean, ResponseFormat> validateCyclicGroupsDependencies(Map<String, GroupDefinition> allGroups) {
-
         Either<Boolean, ResponseFormat> result = Either.left(true);
         try {
             Iterator<Map.Entry<String, GroupDefinition>> allGroupsItr = allGroups.entrySet().iterator();
@@ -1957,8 +1746,7 @@ public class ServiceImportParseLogic {
                 fillAllGroupMemebersRecursivly(groupAEntry.getKey(), allGroups, allGroupAMembersNames);
                 // If A is a group member of itself found cyclic dependency
                 if (allGroupAMembersNames.contains(groupAName)) {
-                    ResponseFormat responseFormat = componentsUtils
-                        .getResponseFormat(ActionStatus.GROUP_HAS_CYCLIC_DEPENDENCY, groupAName);
+                    ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.GROUP_HAS_CYCLIC_DEPENDENCY, groupAName);
                     result = Either.right(responseFormat);
                 }
             }
@@ -1970,9 +1758,7 @@ public class ServiceImportParseLogic {
         return result;
     }
 
-    protected void fillAllGroupMemebersRecursivly(String groupName, Map<String, GroupDefinition> allGroups,
-                                                  Set<String> allGroupMembers) {
-
+    protected void fillAllGroupMemebersRecursivly(String groupName, Map<String, GroupDefinition> allGroups, Set<String> allGroupMembers) {
         // Found Cyclic dependency
         if (isfillGroupMemebersRecursivlyStopCondition(groupName, allGroups, allGroupMembers)) {
             return;
@@ -1981,6 +1767,7 @@ public class ServiceImportParseLogic {
         // All Members Of Current Group Resource Instances & Other Groups
         Set<String> currGroupMembers = groupDefinition.getMembers().keySet();
         // Filtered Members Of Current Group containing only members which
+
         // are groups
         List<String> currGroupFilteredMembers = currGroupMembers.stream().
             // Keep Only Elements of type group and not Resource Instances
@@ -1989,7 +1776,6 @@ public class ServiceImportParseLogic {
                 peek(allGroupMembers::add).
             // Collect results
                 collect(toList());
-
         // Recursively call the method for all the filtered group members
         for (String innerGroupName : currGroupFilteredMembers) {
             fillAllGroupMemebersRecursivly(innerGroupName, allGroups, allGroupMembers);
@@ -2000,83 +1786,65 @@ public class ServiceImportParseLogic {
                                                                             boolean isInTransaction, boolean needLock,
                                                                             Map<ArtifactsBusinessLogic.ArtifactOperationEnum, List<ArtifactDefinition>> nodeTypeArtifactsToHandle,
                                                                             List<ArtifactDefinition> nodeTypesNewCreatedArtifacts,
-                                                                            boolean forceCertificationAllowed, CsarInfo csarInfo,
-                                                                            String nodeName, boolean isNested) {
-
+                                                                            boolean forceCertificationAllowed, CsarInfo csarInfo, String nodeName,
+                                                                            boolean isNested) {
         LifecycleChangeInfoWithAction lifecycleChangeInfo = new LifecycleChangeInfoWithAction(CERTIFICATION_ON_IMPORT,
             LifecycleChangeInfoWithAction.LifecycleChanceActionEnum.CREATE_FROM_CSAR);
-
-        Function<Resource, Boolean> validator = resource -> validateResourceCreationFromNodeType(
-            resource, creator);
-
-        return resourceImportManager.importCertifiedResource(nodeTypeYaml, resourceMetaData, creator, validator,
-            lifecycleChangeInfo, isInTransaction, true, needLock, nodeTypeArtifactsToHandle,
-            nodeTypesNewCreatedArtifacts, forceCertificationAllowed, csarInfo, nodeName, isNested);
-    }
-
-    public ImmutablePair<Resource, ActionStatus> createNodeTypeResourceFromYaml(
-        String yamlName, Map.Entry<String, Object> nodeNameValue, User user, Map<String, Object> mapToConvert,
-        Service resourceVf, boolean needLock,
-        Map<ArtifactsBusinessLogic.ArtifactOperationEnum, List<ArtifactDefinition>> nodeTypeArtifactsToHandle,
-        List<ArtifactDefinition> nodeTypesNewCreatedArtifacts, boolean forceCertificationAllowed, CsarInfo csarInfo,
-        boolean isNested) {
-
+        Function<Resource, Boolean> validator = resource -> validateResourceCreationFromNodeType(resource, creator);
+        return resourceImportManager
+            .importCertifiedResource(nodeTypeYaml, resourceMetaData, creator, validator, lifecycleChangeInfo, isInTransaction, true, needLock,
+                nodeTypeArtifactsToHandle, nodeTypesNewCreatedArtifacts, forceCertificationAllowed, csarInfo, nodeName, isNested);
+    }
+
+    public ImmutablePair<Resource, ActionStatus> createNodeTypeResourceFromYaml(String yamlName, Map.Entry<String, Object> nodeNameValue, User user,
+                                                                                Map<String, Object> mapToConvert, Service resourceVf,
+                                                                                boolean needLock,
+                                                                                Map<ArtifactsBusinessLogic.ArtifactOperationEnum, List<ArtifactDefinition>> nodeTypeArtifactsToHandle,
+                                                                                List<ArtifactDefinition> nodeTypesNewCreatedArtifacts,
+                                                                                boolean forceCertificationAllowed, CsarInfo csarInfo,
+                                                                                boolean isNested) {
         UploadResourceInfo resourceMetaData = fillResourceMetadata(yamlName, resourceVf, nodeNameValue.getKey(), user);
-
-        String singleVfcYaml = buildNodeTypeYaml(nodeNameValue, mapToConvert,
-            resourceMetaData.getResourceType(), csarInfo);
+        String singleVfcYaml = buildNodeTypeYaml(nodeNameValue, mapToConvert, resourceMetaData.getResourceType(), csarInfo);
         user = serviceBusinessLogic.validateUser(user, "CheckIn Resource", resourceVf, AuditingActionEnum.CHECKIN_RESOURCE, true);
-        return createResourceFromNodeType(singleVfcYaml, resourceMetaData, user, true, needLock,
-            nodeTypeArtifactsToHandle, nodeTypesNewCreatedArtifacts, forceCertificationAllowed, csarInfo,
-            nodeNameValue.getKey(), isNested);
+        return createResourceFromNodeType(singleVfcYaml, resourceMetaData, user, true, needLock, nodeTypeArtifactsToHandle,
+            nodeTypesNewCreatedArtifacts, forceCertificationAllowed, csarInfo, nodeNameValue.getKey(), isNested);
     }
 
-    protected UploadResourceInfo fillResourceMetadata(String yamlName, Service resourceVf,
-                                                      String nodeName, User user) {
+    protected UploadResourceInfo fillResourceMetadata(String yamlName, Service resourceVf, String nodeName, User user) {
         UploadResourceInfo resourceMetaData = new UploadResourceInfo();
-
         // validate nodetype name prefix
         if (!nodeName.startsWith(Constants.USER_DEFINED_RESOURCE_NAMESPACE_PREFIX)) {
-            log.debug("invalid nodeName:{} does not start with {}.", nodeName,
-                Constants.USER_DEFINED_RESOURCE_NAMESPACE_PREFIX);
-            throw new ComponentException(ActionStatus.INVALID_NODE_TEMPLATE,
-                yamlName, resourceMetaData.getName(), nodeName);
+            log.debug("invalid nodeName:{} does not start with {}.", nodeName, Constants.USER_DEFINED_RESOURCE_NAMESPACE_PREFIX);
+            throw new ComponentException(ActionStatus.INVALID_NODE_TEMPLATE, yamlName, resourceMetaData.getName(), nodeName);
         }
-
         String actualName = this.getNodeTypeActualName(nodeName);
         String namePrefix = nodeName.replace(actualName, "");
         String resourceType = namePrefix.substring(Constants.USER_DEFINED_RESOURCE_NAMESPACE_PREFIX.length());
-
         // if we import from csar, the node_type name can be
+
         // org.openecomp.resource.abstract.node_name - in this case we always
+
         // create a vfc
         if (resourceType.equals(Constants.ABSTRACT)) {
             resourceType = ResourceTypeEnum.VFC.name().toLowerCase();
         }
         // validating type
         if (!ResourceTypeEnum.containsName(resourceType.toUpperCase())) {
-            log.debug("invalid resourceType:{} the type is not one of the valide types:{}.", resourceType.toUpperCase(),
-                ResourceTypeEnum.values());
-            throw new ComponentException(ActionStatus.INVALID_NODE_TEMPLATE,
-                yamlName, resourceMetaData.getName(), nodeName);
+            log.debug("invalid resourceType:{} the type is not one of the valide types:{}.", resourceType.toUpperCase(), ResourceTypeEnum.values());
+            throw new ComponentException(ActionStatus.INVALID_NODE_TEMPLATE, yamlName, resourceMetaData.getName(), nodeName);
         }
-
         // Setting name
         resourceMetaData.setName(resourceVf.getSystemName() + actualName);
-
         // Setting type from name
         String type = resourceType.toUpperCase();
         resourceMetaData.setResourceType(type);
-
         resourceMetaData.setDescription(ImportUtils.Constants.INNER_VFC_DESCRIPTION);
         resourceMetaData.setIcon(ImportUtils.Constants.DEFAULT_ICON);
         resourceMetaData.setContactId(user.getUserId());
-
         // Setting tag
         List<String> tags = new ArrayList<>();
         tags.add(resourceMetaData.getName());
         resourceMetaData.setTags(tags);
-
         // Setting category
         CategoryDefinition category = new CategoryDefinition();
         category.setName(ImportUtils.Constants.ABSTRACT_CATEGORY_NAME);
@@ -2086,24 +1854,20 @@ public class ServiceImportParseLogic {
         List<CategoryDefinition> categories = new ArrayList<>();
         categories.add(category);
         resourceMetaData.setCategories(categories);
-
         return resourceMetaData;
     }
 
-
-    public Resource propagateStateToCertified(User user, Resource resource,
-                                              LifecycleChangeInfoWithAction lifecycleChangeInfo, boolean inTransaction, boolean needLock,
-                                              boolean forceCertificationAllowed) {
-
+    public Resource propagateStateToCertified(User user, Resource resource, LifecycleChangeInfoWithAction lifecycleChangeInfo, boolean inTransaction,
+                                              boolean needLock, boolean forceCertificationAllowed) {
         Either<Resource, ResponseFormat> result = null;
         try {
-            if (resource.getLifecycleState() != LifecycleStateEnum.CERTIFIED && forceCertificationAllowed
-                && lifecycleBusinessLogic.isFirstCertification(resource.getVersion())) {
+            if (resource.getLifecycleState() != LifecycleStateEnum.CERTIFIED && forceCertificationAllowed && lifecycleBusinessLogic
+                .isFirstCertification(resource.getVersion())) {
                 nodeForceCertification(resource, user, lifecycleChangeInfo, inTransaction, needLock);
             }
             if (resource.getLifecycleState() == LifecycleStateEnum.CERTIFIED) {
-                Either<ArtifactDefinition, Operation> eitherPopulated = serviceBusinessLogic.populateToscaArtifacts(
-                    resource, user, false, inTransaction, needLock);
+                Either<ArtifactDefinition, Operation> eitherPopulated = serviceBusinessLogic
+                    .populateToscaArtifacts(resource, user, false, inTransaction, needLock);
                 return resource;
             }
             return nodeFullCertification(resource.getUniqueId(), user, lifecycleChangeInfo, inTransaction, needLock);
@@ -2122,14 +1886,11 @@ public class ServiceImportParseLogic {
         }
     }
 
-    public Resource buildValidComplexVfc(CsarInfo csarInfo, String nodeName,
-                                         Map<String, NodeTypeInfo> nodesInfo) {
-
+    public Resource buildValidComplexVfc(CsarInfo csarInfo, String nodeName, Map<String, NodeTypeInfo> nodesInfo) {
         Resource complexVfc = buildComplexVfcMetadata(csarInfo, nodeName, nodesInfo);
         log.debug("************* Going to validate complex VFC from yaml {}", complexVfc.getName());
         csarInfo.addNodeToQueue(nodeName);
-        return validateResourceBeforeCreate(complexVfc, csarInfo.getModifier(),
-            AuditingActionEnum.IMPORT_RESOURCE, true, csarInfo);
+        return validateResourceBeforeCreate(complexVfc, csarInfo.getModifier(), AuditingActionEnum.IMPORT_RESOURCE, true, csarInfo);
     }
 
     public Resource updateGroupsOnResource(Resource resource, Map<String, GroupDefinition> groups) {
@@ -2138,28 +1899,24 @@ public class ServiceImportParseLogic {
         } else {
             updateOrCreateGroups(resource, groups);
         }
-        Either<Resource, StorageOperationStatus> updatedResource = toscaOperationFacade
-            .getToscaElement(resource.getUniqueId());
+        Either<Resource, StorageOperationStatus> updatedResource = toscaOperationFacade.getToscaElement(resource.getUniqueId());
         if (updatedResource.isRight()) {
-            throw new ComponentException(componentsUtils.getResponseFormatByResource(
-                componentsUtils.convertFromStorageResponse(updatedResource.right().value()), resource));
+            throw new ComponentException(
+                componentsUtils.getResponseFormatByResource(componentsUtils.convertFromStorageResponse(updatedResource.right().value()), resource));
         }
         return updatedResource.left().value();
     }
 
     protected void setInformationalArtifactsPlaceHolder(Resource resource, User user) {
-
         Map<String, ArtifactDefinition> artifactMap = resource.getArtifacts();
         if (artifactMap == null) {
             artifactMap = new HashMap<>();
         }
         String resourceUniqueId = resource.getUniqueId();
-        List<String> exludeResourceCategory = ConfigurationManager.getConfigurationManager().getConfiguration()
-            .getExcludeResourceCategory();
-        List<String> exludeResourceType = ConfigurationManager.getConfigurationManager().getConfiguration()
-            .getExcludeResourceType();
-        Map<String, Object> informationalResourceArtifacts = ConfigurationManager.getConfigurationManager()
-            .getConfiguration().getInformationalResourceArtifacts();
+        List<String> exludeResourceCategory = ConfigurationManager.getConfigurationManager().getConfiguration().getExcludeResourceCategory();
+        List<String> exludeResourceType = ConfigurationManager.getConfigurationManager().getConfiguration().getExcludeResourceType();
+        Map<String, Object> informationalResourceArtifacts = ConfigurationManager.getConfigurationManager().getConfiguration()
+            .getInformationalResourceArtifacts();
         List<CategoryDefinition> categories = resource.getCategories();
         boolean isCreateArtifact = true;
         if (exludeResourceCategory != null) {
@@ -2173,18 +1930,16 @@ public class ServiceImportParseLogic {
         if (informationalResourceArtifacts != null && isCreateArtifact) {
             Set<String> keys = informationalResourceArtifacts.keySet();
             for (String informationalResourceArtifactName : keys) {
-                Map<String, Object> artifactInfoMap = (Map<String, Object>) informationalResourceArtifacts
-                    .get(informationalResourceArtifactName);
+                Map<String, Object> artifactInfoMap = (Map<String, Object>) informationalResourceArtifacts.get(informationalResourceArtifactName);
                 if (serviceBusinessLogic.artifactsBusinessLogic != null) {
-                    ArtifactDefinition artifactDefinition = serviceBusinessLogic.artifactsBusinessLogic.createArtifactPlaceHolderInfo(
-                        resourceUniqueId, informationalResourceArtifactName, artifactInfoMap, user,
-                        ArtifactGroupTypeEnum.INFORMATIONAL);
+                    ArtifactDefinition artifactDefinition = serviceBusinessLogic.artifactsBusinessLogic
+                        .createArtifactPlaceHolderInfo(resourceUniqueId, informationalResourceArtifactName, artifactInfoMap, user,
+                            ArtifactGroupTypeEnum.INFORMATIONAL);
                     artifactMap.put(artifactDefinition.getArtifactLabel(), artifactDefinition);
                 }
             }
         }
         resource.setArtifacts(artifactMap);
-
     }
 
     public void rollback(boolean inTransaction, Resource resource, List<ArtifactDefinition> createdArtifacts,
@@ -2207,10 +1962,7 @@ public class ServiceImportParseLogic {
     public void handleGroupsProperties(Service service, Map<String, GroupDefinition> groups) {
         List<InputDefinition> inputs = service.getInputs();
         if (MapUtils.isNotEmpty(groups)) {
-            groups.values()
-                .stream()
-                .filter(g -> isNotEmpty(g.getProperties()))
-                .flatMap(g -> g.getProperties().stream())
+            groups.values().stream().filter(g -> isNotEmpty(g.getProperties())).flatMap(g -> g.getProperties().stream())
                 .forEach(p -> handleGetInputs(p, inputs));
         }
     }
@@ -2218,10 +1970,7 @@ public class ServiceImportParseLogic {
     public void handleGroupsProperties(Resource resource, Map<String, GroupDefinition> groups) {
         List<InputDefinition> inputs = resource.getInputs();
         if (MapUtils.isNotEmpty(groups)) {
-            groups.values()
-                .stream()
-                .filter(g -> isNotEmpty(g.getProperties()))
-                .flatMap(g -> g.getProperties().stream())
+            groups.values().stream().filter(g -> isNotEmpty(g.getProperties())).flatMap(g -> g.getProperties().stream())
                 .forEach(p -> handleGetInputs(p, inputs));
         }
     }
@@ -2230,10 +1979,8 @@ public class ServiceImportParseLogic {
         if (isNotEmpty(property.getGetInputValues())) {
             if (inputs == null || inputs.isEmpty()) {
                 log.debug("Failed to add property {} to group. Inputs list is empty ", property);
-                serviceBusinessLogic.rollbackWithException(ActionStatus.INPUTS_NOT_FOUND, property.getGetInputValues()
-                    .stream()
-                    .map(GetInputValueDataDefinition::getInputName)
-                    .collect(toList()).toString());
+                serviceBusinessLogic.rollbackWithException(ActionStatus.INPUTS_NOT_FOUND,
+                    property.getGetInputValues().stream().map(GetInputValueDataDefinition::getInputName).collect(toList()).toString());
             }
             ListIterator<GetInputValueDataDefinition> getInputValuesIter = property.getGetInputValues().listIterator();
             while (getInputValuesIter.hasNext()) {
@@ -2251,9 +1998,7 @@ public class ServiceImportParseLogic {
     }
 
     public InputDefinition findInputByName(List<InputDefinition> inputs, GetInputValueDataDefinition getInput) {
-        Optional<InputDefinition> inputOpt = inputs.stream()
-            .filter(p -> p.getName().equals(getInput.getInputName()))
-            .findFirst();
+        Optional<InputDefinition> inputOpt = inputs.stream().filter(p -> p.getName().equals(getInput.getInputName())).findFirst();
         if (!inputOpt.isPresent()) {
             log.debug("#findInputByName - Failed to find the input {} ", getInput.getInputName());
             serviceBusinessLogic.rollbackWithException(ActionStatus.INPUTS_NOT_FOUND, getInput.getInputName());
@@ -2267,10 +2012,9 @@ public class ServiceImportParseLogic {
             Either<Map<String, List<ComponentInstanceProperty>>, StorageOperationStatus> addPropToInst = toscaOperationFacade
                 .associateComponentInstancePropertiesToComponent(instProperties, resource.getUniqueId());
             if (addPropToInst.isRight()) {
-                log.debug("failed to associate properties of resource {} status is {}", resource.getUniqueId(),
-                    addPropToInst.right().value());
-                throw new ComponentException(componentsUtils.getResponseFormat(
-                    componentsUtils.convertFromStorageResponse(addPropToInst.right().value()), yamlName));
+                log.debug("failed to associate properties of resource {} status is {}", resource.getUniqueId(), addPropToInst.right().value());
+                throw new ComponentException(
+                    componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(addPropToInst.right().value()), yamlName));
             }
         } catch (Exception e) {
             log.debug("Exception occured when findNodeTypeArtifactsToHandle, error is:{}", e.getMessage());
@@ -2284,71 +2028,55 @@ public class ServiceImportParseLogic {
             Either<Map<String, List<ComponentInstanceInput>>, StorageOperationStatus> addInputToInst = toscaOperationFacade
                 .associateComponentInstanceInputsToComponent(instInputs, resource.getUniqueId());
             if (addInputToInst.isRight()) {
-                log.debug("failed to associate inputs value of resource {} status is {}", resource.getUniqueId(),
-                    addInputToInst.right().value());
-                throw new ComponentException(componentsUtils.getResponseFormat(
-                    componentsUtils.convertFromStorageResponse(addInputToInst.right().value()), yamlName));
+                log.debug("failed to associate inputs value of resource {} status is {}", resource.getUniqueId(), addInputToInst.right().value());
+                throw new ComponentException(
+                    componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(addInputToInst.right().value()), yamlName));
             }
         }
     }
 
     public void associateDeploymentArtifactsToInstances(User user, String yamlName, Resource resource,
                                                         Map<String, Map<String, ArtifactDefinition>> instDeploymentArtifacts) {
-        StorageOperationStatus addArtToInst = toscaOperationFacade
-            .associateDeploymentArtifactsToInstances(instDeploymentArtifacts, resource, user);
+        StorageOperationStatus addArtToInst = toscaOperationFacade.associateDeploymentArtifactsToInstances(instDeploymentArtifacts, resource, user);
         if (addArtToInst != StorageOperationStatus.OK && addArtToInst != StorageOperationStatus.NOT_FOUND) {
             log.debug("failed to associate artifact of resource {} status is {}", resource.getUniqueId(), addArtToInst);
-            throw new ComponentException(componentsUtils
-                .getResponseFormat(componentsUtils.convertFromStorageResponse(addArtToInst), yamlName));
+            throw new ComponentException(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(addArtToInst), yamlName));
         }
     }
 
     public void associateArtifactsToInstances(String yamlName, Resource resource, Map<String, Map<String, ArtifactDefinition>> instArtifacts) {
-
         StorageOperationStatus addArtToInst;
-
         addArtToInst = toscaOperationFacade.associateArtifactsToInstances(instArtifacts, resource);
         if (addArtToInst != StorageOperationStatus.OK && addArtToInst != StorageOperationStatus.NOT_FOUND) {
             log.debug("failed to associate artifact of resource {} status is {}", resource.getUniqueId(), addArtToInst);
-            throw new ComponentException(componentsUtils
-                .getResponseFormat(componentsUtils.convertFromStorageResponse(addArtToInst), yamlName));
+            throw new ComponentException(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(addArtToInst), yamlName));
         }
     }
 
     public void associateOrAddCalculatedCapReq(String yamlName, Resource resource,
                                                Map<ComponentInstance, Map<String, List<CapabilityDefinition>>> instCapabilities,
                                                Map<ComponentInstance, Map<String, List<RequirementDefinition>>> instRequirements) {
-
         StorageOperationStatus addArtToInst;
-        addArtToInst = toscaOperationFacade.associateOrAddCalculatedCapReq(instCapabilities, instRequirements,
-            resource);
+        addArtToInst = toscaOperationFacade.associateOrAddCalculatedCapReq(instCapabilities, instRequirements, resource);
         if (addArtToInst != StorageOperationStatus.OK && addArtToInst != StorageOperationStatus.NOT_FOUND) {
-            log.debug("failed to associate cap and req of resource {} status is {}", resource.getUniqueId(),
-                addArtToInst);
-            throw new ComponentException(componentsUtils
-                .getResponseFormat(componentsUtils.convertFromStorageResponse(addArtToInst), yamlName));
+            log.debug("failed to associate cap and req of resource {} status is {}", resource.getUniqueId(), addArtToInst);
+            throw new ComponentException(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(addArtToInst), yamlName));
         }
     }
 
     public void associateInstAttributeToComponentToInstances(String yamlName, Resource resource,
                                                              Map<String, List<AttributeDefinition>> instAttributes) {
-
         StorageOperationStatus addArtToInst;
-        addArtToInst = toscaOperationFacade.associateInstAttributeToComponentToInstances(instAttributes,
-            resource);
+        addArtToInst = toscaOperationFacade.associateInstAttributeToComponentToInstances(instAttributes, resource);
         if (addArtToInst != StorageOperationStatus.OK && addArtToInst != StorageOperationStatus.NOT_FOUND) {
-            log.debug("failed to associate attributes of resource {} status is {}", resource.getUniqueId(),
-                addArtToInst);
-            throw new ComponentException(componentsUtils
-                .getResponseFormat(componentsUtils.convertFromStorageResponse(addArtToInst), yamlName));
+            log.debug("failed to associate attributes of resource {} status is {}", resource.getUniqueId(), addArtToInst);
+            throw new ComponentException(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(addArtToInst), yamlName));
         }
     }
 
     public Resource getResourceAfterCreateRelations(Resource resource) {
         ComponentParametersView parametersView = getComponentFilterAfterCreateRelations();
-        Either<Resource, StorageOperationStatus> eitherGetResource = toscaOperationFacade
-            .getToscaElement(resource.getUniqueId(), parametersView);
-
+        Either<Resource, StorageOperationStatus> eitherGetResource = toscaOperationFacade.getToscaElement(resource.getUniqueId(), parametersView);
         if (eitherGetResource.isRight()) {
             throwComponentExceptionByResource(eitherGetResource.right().value(), resource);
         }
@@ -2356,8 +2084,7 @@ public class ServiceImportParseLogic {
     }
 
     public Resource throwComponentExceptionByResource(StorageOperationStatus status, Resource resource) {
-        ResponseFormat responseFormat = componentsUtils.getResponseFormatByResource(
-            componentsUtils.convertFromStorageResponse(status), resource);
+        ResponseFormat responseFormat = componentsUtils.getResponseFormatByResource(componentsUtils.convertFromStorageResponse(status), resource);
         throw new ComponentException(responseFormat);
     }
 
@@ -2380,10 +2107,9 @@ public class ServiceImportParseLogic {
         }
     }
 
-    public Map<String, List<CapabilityDefinition>> getValidComponentInstanceCapabilities(
-        String resourceId, Map<String, List<CapabilityDefinition>> defaultCapabilities,
-        Map<String, List<UploadCapInfo>> uploadedCapabilities) {
-
+    public Map<String, List<CapabilityDefinition>> getValidComponentInstanceCapabilities(String resourceId,
+                                                                                         Map<String, List<CapabilityDefinition>> defaultCapabilities,
+                                                                                         Map<String, List<UploadCapInfo>> uploadedCapabilities) {
         Map<String, List<CapabilityDefinition>> validCapabilitiesMap = new HashMap<>();
         uploadedCapabilities.forEach((k, v) -> addValidComponentInstanceCapabilities(k, v, resourceId, defaultCapabilities, validCapabilitiesMap));
         return validCapabilitiesMap;
@@ -2394,10 +2120,9 @@ public class ServiceImportParseLogic {
             Either<Map<String, List<ComponentInstanceInput>>, StorageOperationStatus> addInputToInst = toscaOperationFacade
                 .associateComponentInstanceInputsToComponent(instInputs, service.getUniqueId());
             if (addInputToInst.isRight()) {
-                log.debug("failed to associate inputs value of resource {} status is {}", service.getUniqueId(),
-                    addInputToInst.right().value());
-                throw new ComponentException(componentsUtils.getResponseFormat(
-                    componentsUtils.convertFromStorageResponse(addInputToInst.right().value()), yamlName));
+                log.debug("failed to associate inputs value of resource {} status is {}", service.getUniqueId(), addInputToInst.right().value());
+                throw new ComponentException(
+                    componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(addInputToInst.right().value()), yamlName));
             }
         }
     }
@@ -2407,30 +2132,26 @@ public class ServiceImportParseLogic {
         Either<Map<String, List<ComponentInstanceProperty>>, StorageOperationStatus> addPropToInst = toscaOperationFacade
             .associateComponentInstancePropertiesToComponent(instProperties, service.getUniqueId());
         if (addPropToInst.isRight()) {
-            throw new ComponentException(componentsUtils.getResponseFormat(
-                componentsUtils.convertFromStorageResponse(addPropToInst.right().value()), yamlName));
+            throw new ComponentException(
+                componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(addPropToInst.right().value()), yamlName));
         }
     }
 
     public void associateDeploymentArtifactsToInstances(User user, String yamlName, Service resource,
                                                         Map<String, Map<String, ArtifactDefinition>> instDeploymentArtifacts) {
-        StorageOperationStatus addArtToInst = toscaOperationFacade
-            .associateDeploymentArtifactsToInstances(instDeploymentArtifacts, resource, user);
+        StorageOperationStatus addArtToInst = toscaOperationFacade.associateDeploymentArtifactsToInstances(instDeploymentArtifacts, resource, user);
         if (addArtToInst != StorageOperationStatus.OK && addArtToInst != StorageOperationStatus.NOT_FOUND) {
             log.debug("failed to associate artifact of resource {} status is {}", resource.getUniqueId(), addArtToInst);
-            throw new ComponentException(componentsUtils
-                .getResponseFormat(componentsUtils.convertFromStorageResponse(addArtToInst), yamlName));
+            throw new ComponentException(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(addArtToInst), yamlName));
         }
     }
 
     public void associateArtifactsToInstances(String yamlName, Service resource, Map<String, Map<String, ArtifactDefinition>> instArtifacts) {
         StorageOperationStatus addArtToInst;
-
         addArtToInst = toscaOperationFacade.associateArtifactsToInstances(instArtifacts, resource);
         if (addArtToInst != StorageOperationStatus.OK && addArtToInst != StorageOperationStatus.NOT_FOUND) {
             log.debug("failed to associate artifact of resource {} status is {}", resource.getUniqueId(), addArtToInst);
-            throw new ComponentException(componentsUtils
-                .getResponseFormat(componentsUtils.convertFromStorageResponse(addArtToInst), yamlName));
+            throw new ComponentException(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(addArtToInst), yamlName));
         }
     }
 
@@ -2438,86 +2159,66 @@ public class ServiceImportParseLogic {
                                                Map<ComponentInstance, Map<String, List<CapabilityDefinition>>> instCapabilities,
                                                Map<ComponentInstance, Map<String, List<RequirementDefinition>>> instRequirements) {
         StorageOperationStatus addArtToInst;
-        addArtToInst = toscaOperationFacade.associateOrAddCalculatedCapReq(instCapabilities, instRequirements,
-            resource);
-        log.debug("enter associateOrAddCalculatedCapReq,get instCapabilities:{},get instRequirements:{}",
-            instCapabilities, instRequirements);
+        addArtToInst = toscaOperationFacade.associateOrAddCalculatedCapReq(instCapabilities, instRequirements, resource);
+        log.debug("enter associateOrAddCalculatedCapReq,get instCapabilities:{},get instRequirements:{}", instCapabilities, instRequirements);
         if (addArtToInst != StorageOperationStatus.OK && addArtToInst != StorageOperationStatus.NOT_FOUND) {
-            log.debug("failed to associate cap and req of resource {} status is {}", resource.getUniqueId(),
-                addArtToInst);
-            throw new ComponentException(componentsUtils
-                .getResponseFormat(componentsUtils.convertFromStorageResponse(addArtToInst), yamlName));
+            log.debug("failed to associate cap and req of resource {} status is {}", resource.getUniqueId(), addArtToInst);
+            throw new ComponentException(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(addArtToInst), yamlName));
         }
     }
 
     public void associateInstAttributeToComponentToInstances(String yamlName, Service resource,
                                                              Map<String, List<AttributeDefinition>> instAttributes) {
         StorageOperationStatus addArtToInst;
-
-        addArtToInst = toscaOperationFacade.associateInstAttributeToComponentToInstances(instAttributes,
-            resource);
+        addArtToInst = toscaOperationFacade.associateInstAttributeToComponentToInstances(instAttributes, resource);
         if (addArtToInst != StorageOperationStatus.OK && addArtToInst != StorageOperationStatus.NOT_FOUND) {
-            log.debug("failed to associate attributes of resource {} status is {}", resource.getUniqueId(),
-                addArtToInst);
-            throw new ComponentException(componentsUtils
-                .getResponseFormat(componentsUtils.convertFromStorageResponse(addArtToInst), yamlName));
+            log.debug("failed to associate attributes of resource {} status is {}", resource.getUniqueId(), addArtToInst);
+            throw new ComponentException(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(addArtToInst), yamlName));
         }
     }
 
     public void associateRequirementsToService(String yamlName, Service resource, Map<String, ListRequirementDataDefinition> requirements) {
         StorageOperationStatus addReqToService;
-        addReqToService = toscaOperationFacade.associateRequirementsToService(requirements,
-            resource.getUniqueId());
+        addReqToService = toscaOperationFacade.associateRequirementsToService(requirements, resource.getUniqueId());
         if (addReqToService != StorageOperationStatus.OK && addReqToService != StorageOperationStatus.NOT_FOUND) {
-            log.debug("failed to associate attributes of resource {} status is {}", resource.getUniqueId(),
-                addReqToService);
-            throw new ComponentException(componentsUtils
-                .getResponseFormat(componentsUtils.convertFromStorageResponse(addReqToService), yamlName));
+            log.debug("failed to associate attributes of resource {} status is {}", resource.getUniqueId(), addReqToService);
+            throw new ComponentException(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(addReqToService), yamlName));
         }
     }
 
     public void associateCapabilitiesToService(String yamlName, Service resource, Map<String, ListCapabilityDataDefinition> capabilities) {
         StorageOperationStatus addCapToService;
-        addCapToService = toscaOperationFacade.associateCapabilitiesToService(capabilities,
-            resource.getUniqueId());
+        addCapToService = toscaOperationFacade.associateCapabilitiesToService(capabilities, resource.getUniqueId());
         if (addCapToService != StorageOperationStatus.OK && addCapToService != StorageOperationStatus.NOT_FOUND) {
-            log.debug("failed to associate attributes of resource {} status is {}", resource.getUniqueId(),
-                addCapToService);
-            throw new ComponentException(componentsUtils
-                .getResponseFormat(componentsUtils.convertFromStorageResponse(addCapToService), yamlName));
+            log.debug("failed to associate attributes of resource {} status is {}", resource.getUniqueId(), addCapToService);
+            throw new ComponentException(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(addCapToService), yamlName));
         }
     }
 
     public void associateResourceInstances(String yamlName, Service service, List<RequirementCapabilityRelDef> relations) {
         Either<List<RequirementCapabilityRelDef>, StorageOperationStatus> relationsEither = toscaOperationFacade
             .associateResourceInstances(service, service.getUniqueId(), relations);
-
         if (relationsEither.isRight() && relationsEither.right().value() != StorageOperationStatus.NOT_FOUND) {
             StorageOperationStatus status = relationsEither.right().value();
-            log.debug("failed to associate instances of service {} status is {}", service.getUniqueId(),
-                status);
-            throw new ComponentException(componentsUtils
-                .getResponseFormat(componentsUtils.convertFromStorageResponse(status), yamlName));
+            log.debug("failed to associate instances of service {} status is {}", service.getUniqueId(), status);
+            throw new ComponentException(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(status), yamlName));
         }
     }
 
     public void addCapabilities(Map<String, List<CapabilityDefinition>> originCapabilities, String type, List<CapabilityDefinition> capabilities) {
-        List<CapabilityDefinition> list = capabilities.stream().map(CapabilityDefinition::new)
-            .collect(toList());
+        List<CapabilityDefinition> list = capabilities.stream().map(CapabilityDefinition::new).collect(toList());
         originCapabilities.put(type, list);
     }
 
     public void addCapabilitiesProperties(Map<String, Map<String, UploadPropInfo>> newPropertiesMap, List<UploadCapInfo> capabilities) {
         for (UploadCapInfo capability : capabilities) {
             if (isNotEmpty(capability.getProperties())) {
-                newPropertiesMap.put(capability.getName(), capability.getProperties().stream()
-                    .collect(toMap(UploadInfo::getName, p -> p)));
+                newPropertiesMap.put(capability.getName(), capability.getProperties().stream().collect(toMap(UploadInfo::getName, p -> p)));
             }
         }
     }
 
     public Service getServiceWithGroups(String resourceId) {
-
         ComponentParametersView filter = new ComponentParametersView();
         filter.setIgnoreGroups(false);
         Either<Service, StorageOperationStatus> updatedResource = toscaOperationFacade.getToscaElement(resourceId, filter);
@@ -2528,7 +2229,6 @@ public class ServiceImportParseLogic {
     }
 
     public Resource getResourceWithGroups(String resourceId) {
-
         ComponentParametersView filter = new ComponentParametersView();
         filter.setIgnoreGroups(false);
         Either<Resource, StorageOperationStatus> updatedResource = toscaOperationFacade.getToscaElement(resourceId, filter);
@@ -2539,15 +2239,12 @@ public class ServiceImportParseLogic {
     }
 
     public void associateResourceInstances(String yamlName, Resource resource, List<RequirementCapabilityRelDef> relations) {
-
         Either<List<RequirementCapabilityRelDef>, StorageOperationStatus> relationsEither = toscaOperationFacade
             .associateResourceInstances(resource, resource.getUniqueId(), relations);
         if (relationsEither.isRight() && relationsEither.right().value() != StorageOperationStatus.NOT_FOUND) {
             StorageOperationStatus status = relationsEither.right().value();
-            log.debug("failed to associate instances of resource {} status is {}", resource.getUniqueId(),
-                status);
-            throw new ComponentException(componentsUtils
-                .getResponseFormat(componentsUtils.convertFromStorageResponse(status), yamlName));
+            log.debug("failed to associate instances of resource {} status is {}", resource.getUniqueId(), status);
+            throw new ComponentException(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(status), yamlName));
         }
     }
 
@@ -2557,23 +2254,19 @@ public class ServiceImportParseLogic {
             UploadComponentInstanceInfo uploadComponentInstanceInfo = entry.getValue();
             ComponentInstance currentCompInstance = null;
             for (ComponentInstance compInstance : componentInstancesList) {
-
                 if (compInstance.getName().equals(uploadComponentInstanceInfo.getName())) {
                     currentCompInstance = compInstance;
                     break;
                 }
             }
             if (currentCompInstance == null) {
-                log.debug(COMPONENT_INSTANCE_WITH_NAME_IN_RESOURCE, uploadComponentInstanceInfo.getName(),
-                    resource.getUniqueId());
-                BeEcompErrorManager.getInstance().logInternalDataError(
-                    COMPONENT_INSTANCE_WITH_NAME + uploadComponentInstanceInfo.getName() + IN_RESOURCE,
-                    resource.getUniqueId(), BeEcompErrorManager.ErrorSeverity.ERROR);
-                ResponseFormat responseFormat = componentsUtils
-                    .getResponseFormat(ActionStatus.NOT_TOPOLOGY_TOSCA_TEMPLATE, yamlName);
+                log.debug(COMPONENT_INSTANCE_WITH_NAME_IN_RESOURCE, uploadComponentInstanceInfo.getName(), resource.getUniqueId());
+                BeEcompErrorManager.getInstance()
+                    .logInternalDataError(COMPONENT_INSTANCE_WITH_NAME + uploadComponentInstanceInfo.getName() + IN_RESOURCE, resource.getUniqueId(),
+                        BeEcompErrorManager.ErrorSeverity.ERROR);
+                ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.NOT_TOPOLOGY_TOSCA_TEMPLATE, yamlName);
                 throw new ComponentException(responseFormat);
             }
-
             ResponseFormat addRelationToRiRes = addRelationToRI(yamlName, resource, entry.getValue(), relations);
             if (addRelationToRiRes.getStatus() != 200) {
                 throw new ComponentException(addRelationToRiRes);
@@ -2581,30 +2274,25 @@ public class ServiceImportParseLogic {
         }
     }
 
-    protected ResponseFormat addRelationToRI(String yamlName, Resource resource,
-                                             UploadComponentInstanceInfo nodesInfoValue, List<RequirementCapabilityRelDef> relations) {
+    protected ResponseFormat addRelationToRI(String yamlName, Resource resource, UploadComponentInstanceInfo nodesInfoValue,
+                                             List<RequirementCapabilityRelDef> relations) {
         List<ComponentInstance> componentInstancesList = resource.getComponentInstances();
         ComponentInstance currentCompInstance = null;
-
         for (ComponentInstance compInstance : componentInstancesList) {
-
             if (compInstance.getName().equals(nodesInfoValue.getName())) {
                 currentCompInstance = compInstance;
                 break;
             }
         }
         if (currentCompInstance == null) {
-            log.debug(COMPONENT_INSTANCE_WITH_NAME_IN_RESOURCE, nodesInfoValue.getName(),
-                resource.getUniqueId());
-            BeEcompErrorManager.getInstance().logInternalDataError(
-                COMPONENT_INSTANCE_WITH_NAME + nodesInfoValue.getName() + IN_RESOURCE,
-                resource.getUniqueId(), BeEcompErrorManager.ErrorSeverity.ERROR);
-            return componentsUtils.getResponseFormat(ActionStatus.NOT_TOPOLOGY_TOSCA_TEMPLATE,
-                yamlName);
+            log.debug(COMPONENT_INSTANCE_WITH_NAME_IN_RESOURCE, nodesInfoValue.getName(), resource.getUniqueId());
+            BeEcompErrorManager.getInstance()
+                .logInternalDataError(COMPONENT_INSTANCE_WITH_NAME + nodesInfoValue.getName() + IN_RESOURCE, resource.getUniqueId(),
+                    BeEcompErrorManager.ErrorSeverity.ERROR);
+            return componentsUtils.getResponseFormat(ActionStatus.NOT_TOPOLOGY_TOSCA_TEMPLATE, yamlName);
         }
         String resourceInstanceId = currentCompInstance.getUniqueId();
         Map<String, List<UploadReqInfo>> regMap = nodesInfoValue.getRequirements();
-
         if (regMap != null) {
             Iterator<Map.Entry<String, List<UploadReqInfo>>> nodesRegValue = regMap.entrySet().iterator();
             while (nodesRegValue.hasNext()) {
@@ -2616,16 +2304,13 @@ public class ServiceImportParseLogic {
                     RequirementCapabilityRelDef regCapRelDef = new RequirementCapabilityRelDef();
                     regCapRelDef.setFromNode(resourceInstanceId);
                     log.debug("try to find available requirement {} ", regName);
-                    Either<RequirementDefinition, ResponseFormat> eitherReqStatus = findAviableRequiremen(regName,
-                        yamlName, nodesInfoValue, currentCompInstance,
-                        uploadRegInfo.getCapabilityName());
+                    Either<RequirementDefinition, ResponseFormat> eitherReqStatus = findAviableRequiremen(regName, yamlName, nodesInfoValue,
+                        currentCompInstance, uploadRegInfo.getCapabilityName());
                     if (eitherReqStatus.isRight()) {
                         return eitherReqStatus.right().value();
                     }
-
                     RequirementDefinition validReq = eitherReqStatus.left().value();
-                    List<CapabilityRequirementRelationship> reqAndRelationshipPairList = regCapRelDef
-                        .getRelationships();
+                    List<CapabilityRequirementRelationship> reqAndRelationshipPairList = regCapRelDef.getRelationships();
                     if (reqAndRelationshipPairList == null) {
                         reqAndRelationshipPairList = new ArrayList<>();
                     }
@@ -2636,7 +2321,6 @@ public class ServiceImportParseLogic {
                     RelationshipImpl relationship = new RelationshipImpl();
                     relationship.setType(validReq.getCapability());
                     reqAndRelationshipPair.setRelationships(relationship);
-
                     ComponentInstance currentCapCompInstance = null;
                     for (ComponentInstance compInstance : componentInstancesList) {
                         if (compInstance.getName().equals(uploadRegInfo.getNode())) {
@@ -2644,30 +2328,24 @@ public class ServiceImportParseLogic {
                             break;
                         }
                     }
-
                     if (currentCapCompInstance == null) {
-                        log.debug("The component instance  with name {} not found on resource {} ",
-                            uploadRegInfo.getNode(), resource.getUniqueId());
-                        BeEcompErrorManager.getInstance().logInternalDataError(
-                            COMPONENT_INSTANCE_WITH_NAME + uploadRegInfo.getNode() + IN_RESOURCE,
-                            resource.getUniqueId(), BeEcompErrorManager.ErrorSeverity.ERROR);
-                        return componentsUtils
-                            .getResponseFormat(ActionStatus.NOT_TOPOLOGY_TOSCA_TEMPLATE, yamlName);
+                        log.debug("The component instance  with name {} not found on resource {} ", uploadRegInfo.getNode(), resource.getUniqueId());
+                        BeEcompErrorManager.getInstance()
+                            .logInternalDataError(COMPONENT_INSTANCE_WITH_NAME + uploadRegInfo.getNode() + IN_RESOURCE, resource.getUniqueId(),
+                                BeEcompErrorManager.ErrorSeverity.ERROR);
+                        return componentsUtils.getResponseFormat(ActionStatus.NOT_TOPOLOGY_TOSCA_TEMPLATE, yamlName);
                     }
                     regCapRelDef.setToNode(currentCapCompInstance.getUniqueId());
                     log.debug("try to find aviable Capability  req name is {} ", validReq.getName());
-                    CapabilityDefinition aviableCapForRel = findAvailableCapabilityByTypeOrName(validReq,
-                        currentCapCompInstance, uploadRegInfo);
+                    CapabilityDefinition aviableCapForRel = findAvailableCapabilityByTypeOrName(validReq, currentCapCompInstance, uploadRegInfo);
                     reqAndRelationshipPair.setCapability(aviableCapForRel.getName());
                     reqAndRelationshipPair.setCapabilityUid(aviableCapForRel.getUniqueId());
                     reqAndRelationshipPair.setCapabilityOwnerId(aviableCapForRel.getOwnerId());
                     if (aviableCapForRel == null) {
                         BeEcompErrorManager.getInstance().logInternalDataError(
-                            "aviable capability was not found. req name is " + validReq.getName()
-                                + " component instance is " + currentCapCompInstance.getUniqueId(),
-                            resource.getUniqueId(), BeEcompErrorManager.ErrorSeverity.ERROR);
-                        return componentsUtils
-                            .getResponseFormat(ActionStatus.NOT_TOPOLOGY_TOSCA_TEMPLATE, yamlName);
+                            "aviable capability was not found. req name is " + validReq.getName() + " component instance is " + currentCapCompInstance
+                                .getUniqueId(), resource.getUniqueId(), BeEcompErrorManager.ErrorSeverity.ERROR);
+                        return componentsUtils.getResponseFormat(ActionStatus.NOT_TOPOLOGY_TOSCA_TEMPLATE, yamlName);
                     }
                     CapabilityRequirementRelationship capReqRel = new CapabilityRequirementRelationship();
                     capReqRel.setRelation(reqAndRelationshipPair);
@@ -2681,5 +2359,4 @@ public class ServiceImportParseLogic {
         }
         return componentsUtils.getResponseFormat(ActionStatus.OK);
     }
-
 }
index d6b17ca..576dc41 100644 (file)
  *  SPDX-License-Identifier: Apache-2.0
  *  ============LICENSE_END=========================================================
  */
-
 package org.openecomp.sdc.be.components.impl;
 
+import static java.util.stream.Collectors.toList;
+import static org.openecomp.sdc.be.components.impl.ImportUtils.getPropertyJsonStringValue;
+
+import java.util.List;
+import java.util.Optional;
 import org.apache.commons.collections.CollectionUtils;
 import org.openecomp.sdc.be.components.csar.CsarInfo;
 import org.openecomp.sdc.be.components.impl.exceptions.BusinessLogicException;
@@ -33,18 +37,12 @@ import org.openecomp.sdc.be.model.tosca.ToscaPropertyType;
 import org.springframework.beans.factory.annotation.Autowired;
 import org.springframework.stereotype.Component;
 
-import java.util.List;
-import java.util.Optional;
-
-import static java.util.stream.Collectors.toList;
-import static org.openecomp.sdc.be.components.impl.ImportUtils.getPropertyJsonStringValue;
-
 @Component("softwareInformationBusinessLogic")
 public class SoftwareInformationBusinessLogic {
 
-    private final PropertyBusinessLogic propertyBusinessLogic;
     private static final String SOFTWARE_VERSION_PROPERTY_NAME = "software_versions";
     private static final String DEFAULT_SOFTWARE_VERSION_PROPERTY_NAME = "default_software_version";
+    private final PropertyBusinessLogic propertyBusinessLogic;
 
     @Autowired
     public SoftwareInformationBusinessLogic(final PropertyBusinessLogic propertyBusinessLogic) {
@@ -53,17 +51,16 @@ public class SoftwareInformationBusinessLogic {
 
     /**
      * Adds the software information from a csar package to the resource {@link SoftwareInformationBusinessLogic#SOFTWARE_VERSION_PROPERTY_NAME}
-     * property.<br/> The csar package must contain the expected non-mano yaml file with the software information. Also
-     * the resource must have the {@link SoftwareInformationBusinessLogic#SOFTWARE_VERSION_PROPERTY_NAME} property.
+     * property.<br/> The csar package must contain the expected non-mano yaml file with the software information. Also the resource must have the
+     * {@link SoftwareInformationBusinessLogic#SOFTWARE_VERSION_PROPERTY_NAME} property.
      *
      * @param resource the resource to add the software information
      * @param csarInfo the csar package representation
-     * @return if the expected property exists in the resource and the csar package contains the software information
-     * file, an Optional<PropertyDefinition> with the updated property; otherwise Optional.empty().
+     * @return if the expected property exists in the resource and the csar package contains the software information file, an
+     * Optional<PropertyDefinition> with the updated property; otherwise Optional.empty().
      * @throws BusinessLogicException when there was a problem while updating the property
      */
-    public Optional<PropertyDefinition> setSoftwareInformation(final Resource resource,
-                                                               final CsarInfo csarInfo) throws BusinessLogicException {
+    public Optional<PropertyDefinition> setSoftwareInformation(final Resource resource, final CsarInfo csarInfo) throws BusinessLogicException {
         final Optional<String> softwareInformation = csarInfo.getSoftwareInformationPath();
         if (!softwareInformation.isPresent()) {
             return Optional.empty();
@@ -73,26 +70,22 @@ public class SoftwareInformationBusinessLogic {
             return Optional.empty();
         }
         final byte[] softwareInformationYaml = csarInfo.getCsar().get(softwareInformation.get());
-        final PnfSoftwareInformation pnfSoftwareInformation =
-            parseSoftwareInformation(softwareInformationYaml).orElse(null);
+        final PnfSoftwareInformation pnfSoftwareInformation = parseSoftwareInformation(softwareInformationYaml).orElse(null);
         if (pnfSoftwareInformation == null) {
             return Optional.empty();
         }
-
-        final List<String> versionList = pnfSoftwareInformation.getSoftwareVersionSet().stream()
-            .map(PnfSoftwareVersion::getVersion).collect(toList());
-        final String softwareVersionInformation =
-            getPropertyJsonStringValue(versionList, ToscaPropertyType.LIST.getType());
+        final List<String> versionList = pnfSoftwareInformation.getSoftwareVersionSet().stream().map(PnfSoftwareVersion::getVersion)
+            .collect(toList());
+        final String softwareVersionInformation = getPropertyJsonStringValue(versionList, ToscaPropertyType.LIST.getType());
         propertyDefinition.setValue(softwareVersionInformation);
-
-        final PropertyDefinition updatedPropertyDefinition =
-            propertyBusinessLogic.updateComponentProperty(resource.getUniqueId(), propertyDefinition);
-
+        final PropertyDefinition updatedPropertyDefinition = propertyBusinessLogic
+            .updateComponentProperty(resource.getUniqueId(), propertyDefinition);
         // set default-software-version as first entry of software version list for resource type pnf
-        if(resource.getResourceType() == ResourceTypeEnum.PNF && !versionList.isEmpty()){
+        if (resource.getResourceType() == ResourceTypeEnum.PNF && !versionList.isEmpty()) {
             final String sw_version = versionList.get(0);
-            Optional<InputDefinition> default_Sw_Ver_PropertyDefinition = resource.safeGetInputs().stream().filter(s->DEFAULT_SOFTWARE_VERSION_PROPERTY_NAME.equals(s.getName())).findFirst();
-            if(default_Sw_Ver_PropertyDefinition.isPresent()) {
+            Optional<InputDefinition> default_Sw_Ver_PropertyDefinition = resource.safeGetInputs().stream()
+                .filter(s -> DEFAULT_SOFTWARE_VERSION_PROPERTY_NAME.equals(s.getName())).findFirst();
+            if (default_Sw_Ver_PropertyDefinition.isPresent()) {
                 default_Sw_Ver_PropertyDefinition.get().setDefaultValue(sw_version);
             }
         }
@@ -103,8 +96,7 @@ public class SoftwareInformationBusinessLogic {
      * Parses the non-mano software information yaml file.
      *
      * @param softwareInformationYaml the file byte array
-     * @return an {@code Optional<PnfSoftwareInformation>} if the file was successful parsed, otherwise {@code
-     * Optional.empty()}
+     * @return an {@code Optional<PnfSoftwareInformation>} if the file was successful parsed, otherwise {@code Optional.empty()}
      */
     private Optional<PnfSoftwareInformation> parseSoftwareInformation(byte[] softwareInformationYaml) {
         return SoftwareInformationArtifactYamlParser.parse(softwareInformationYaml);
@@ -112,6 +104,7 @@ public class SoftwareInformationBusinessLogic {
 
     /**
      * Finds the {@link SoftwareInformationBusinessLogic#SOFTWARE_VERSION_PROPERTY_NAME} property in a Resource
+     *
      * @param resource the resource to search for the property
      * @return an {@code Optional<PnfSoftwareInformation>} if the property was found, otherwise {@code Optional.empty()}
      */
@@ -119,8 +112,7 @@ public class SoftwareInformationBusinessLogic {
         if (CollectionUtils.isEmpty(resource.getProperties())) {
             return Optional.empty();
         }
-        return resource.getProperties().stream()
-            .filter(propertyDefinition -> propertyDefinition.getName().equals(SOFTWARE_VERSION_PROPERTY_NAME))
+        return resource.getProperties().stream().filter(propertyDefinition -> propertyDefinition.getName().equals(SOFTWARE_VERSION_PROPERTY_NAME))
             .findFirst();
     }
 
@@ -135,7 +127,6 @@ public class SoftwareInformationBusinessLogic {
         if (!softwareInformation.isPresent()) {
             return false;
         }
-
         csarInfo.getCsar().remove(softwareInformation.get());
         return true;
     }
index 538f565..252c58d 100644 (file)
@@ -17,7 +17,6 @@
  * limitations under the License.
  * ============LICENSE_END=========================================================
  */
-
 package org.openecomp.sdc.be.components.impl;
 
 import java.util.Arrays;
@@ -42,17 +41,15 @@ import org.togglz.core.util.NamedFeature;
 public class TogglingBusinessLogic extends BaseBusinessLogic {
 
     @Autowired
-    public TogglingBusinessLogic(IElementOperation elementDao, IGroupOperation groupOperation,
-            IGroupInstanceOperation groupInstanceOperation, IGroupTypeOperation groupTypeOperation,
-            InterfaceOperation interfaceOperation, InterfaceLifecycleOperation interfaceLifecycleTypeOperation,
-            ArtifactsOperations artifactToscaOperation) {
-        super(elementDao, groupOperation, groupInstanceOperation, groupTypeOperation, interfaceOperation,
-                interfaceLifecycleTypeOperation, artifactToscaOperation);
+    public TogglingBusinessLogic(IElementOperation elementDao, IGroupOperation groupOperation, IGroupInstanceOperation groupInstanceOperation,
+                                 IGroupTypeOperation groupTypeOperation, InterfaceOperation interfaceOperation,
+                                 InterfaceLifecycleOperation interfaceLifecycleTypeOperation, ArtifactsOperations artifactToscaOperation) {
+        super(elementDao, groupOperation, groupInstanceOperation, groupTypeOperation, interfaceOperation, interfaceLifecycleTypeOperation,
+            artifactToscaOperation);
     }
 
     public Map<String, Boolean> getAllFeatureStates() {
-        return Arrays.stream(ToggleableFeature.values()).collect(Collectors.toMap(Enum::name,
-                ToggleableFeature::isActive));
+        return Arrays.stream(ToggleableFeature.values()).collect(Collectors.toMap(Enum::name, ToggleableFeature::isActive));
     }
 
     public boolean getFeatureState(String featureName) {
@@ -60,8 +57,7 @@ public class TogglingBusinessLogic extends BaseBusinessLogic {
     }
 
     public void setAllFeatures(boolean state) {
-        Arrays.asList(ToggleableFeature.values())
-                .forEach(toggleableFeature -> updateFeatureState(toggleableFeature.name(), state));
+        Arrays.asList(ToggleableFeature.values()).forEach(toggleableFeature -> updateFeatureState(toggleableFeature.name(), state));
     }
 
     public void updateFeatureState(String featureName, boolean state) {
index 9c95241..4dc8c98 100644 (file)
@@ -17,7 +17,6 @@
  * limitations under the License.
  * ============LICENSE_END=========================================================
  */
-
 package org.openecomp.sdc.be.components.impl.aaf;
 
 import org.openecomp.sdc.be.components.impl.exceptions.ByActionStatusComponentException;
@@ -25,39 +24,35 @@ import org.openecomp.sdc.be.config.ConfigurationManager;
 import org.openecomp.sdc.be.dao.api.ActionStatus;
 
 public enum AafPermission {
-
-    READ(PermNames.READ_VALUE),
-    WRITE(PermNames.WRITE_VALUE),
-    DELETE(PermNames.DELETE_VALUE),
-    INTERNAL_ALL(PermNames.INTERNAL_ALL_VALUE);
-
+    READ(PermNames.READ_VALUE), WRITE(PermNames.WRITE_VALUE), DELETE(PermNames.DELETE_VALUE), INTERNAL_ALL(PermNames.INTERNAL_ALL_VALUE);
     private String permission;
     private String permissionSuffix;
 
     AafPermission(String permissionSuffix) {
         this.permissionSuffix = permissionSuffix;
-        this.permission = String.format("%s.%s",
-                ConfigurationManager.getConfigurationManager().getConfiguration().getAafNamespace(),
-                permissionSuffix);
-    }
-
-    public String getFullPermission() {
-        return permission;
+        this.permission = String
+            .format("%s.%s", ConfigurationManager.getConfigurationManager().getConfiguration().getAafNamespace(), permissionSuffix);
     }
 
     public static AafPermission getEnumByString(String perm) {
         for (AafPermission e : AafPermission.values()) {
-            if (perm.equals(e.getPermissionSuffix()))
+            if (perm.equals(e.getPermissionSuffix())) {
                 return e;
+            }
         }
         throw new ByActionStatusComponentException(ActionStatus.INVALID_PROPERTY, perm);
     }
 
+    public String getFullPermission() {
+        return permission;
+    }
+
     public String getPermissionSuffix() {
         return this.permissionSuffix;
     }
 
     public static class PermNames {
+
         public static final String READ_VALUE = "endpoint.api.access|*|read";
         public static final String WRITE_VALUE = "endpoint.api.access|*|write";
         public static final String DELETE_VALUE = "endpoint.api.access|*|delete";
index 34ca596..95cebca 100644 (file)
  * limitations under the License.
  * ============LICENSE_END=========================================================
  */
-
 package org.openecomp.sdc.be.components.impl.aaf;
 
 import org.openecomp.sdc.be.config.ConfigurationManager;
 
 public enum AafRoles {
+    READ_ONLY("app.readonly"), ALL("app.all");
+    private String role;
 
-        READ_ONLY("app.readonly"),
-        ALL("app.all");
-
-        private String role;
-
-        AafRoles(String roleSuffix) {
-            this.role = ConfigurationManager.getConfigurationManager().getConfiguration().getAafNamespace() + "." + roleSuffix;
-        }
-
-        public String getRole() {
-            return role;
-        }
+    AafRoles(String roleSuffix) {
+        this.role = ConfigurationManager.getConfigurationManager().getConfiguration().getAafNamespace() + "." + roleSuffix;
+    }
 
+    public String getRole() {
+        return role;
+    }
 }
index a963e5e..782e2ea 100644 (file)
@@ -17,7 +17,6 @@
  * limitations under the License.
  * ============LICENSE_END=========================================================
  */
-
 package org.openecomp.sdc.be.components.impl.aaf;
 
 import java.lang.annotation.ElementType;
@@ -28,5 +27,6 @@ import java.lang.annotation.Target;
 @Retention(RetentionPolicy.RUNTIME)
 @Target(ElementType.METHOD)
 public @interface PermissionAllowed {
+
     String[] value();
 }
index b963cf6..bc66a8c 100644 (file)
  * limitations under the License.
  * ============LICENSE_END=========================================================
  */
-
 package org.openecomp.sdc.be.components.impl.aaf;
 
-
+import javax.servlet.http.HttpServletRequest;
 import org.aspectj.lang.JoinPoint;
 import org.aspectj.lang.annotation.Aspect;
 import org.aspectj.lang.annotation.Before;
@@ -31,19 +30,15 @@ import org.openecomp.sdc.be.servlets.BeGenericServlet;
 import org.openecomp.sdc.common.log.wrappers.Logger;
 import org.openecomp.sdc.common.util.ThreadLocalsHolder;
 
-import javax.servlet.http.HttpServletRequest;
-
 // aop id defined via application-context.xml. the annotations are only for test purposes
 @Aspect
 public class RoleAuthorizationHandler {
 
     private static final Logger log = Logger.getLogger(RoleAuthorizationHandler.class);
-
     private final ConfigurationManager configurationManager = ConfigurationManager.getConfigurationManager();
 
     @Before("@annotation(permissions)")
     public void authorizeRole(JoinPoint joinPoint, PermissionAllowed permissions) {
-
         if (isPermissionAuthenticationNeeded()) {
             String methodName = joinPoint.getSignature().toShortString();
             HttpServletRequest request = ((BeGenericServlet) joinPoint.getThis()).getServletRequest();
@@ -58,13 +53,12 @@ public class RoleAuthorizationHandler {
             logAuth(methodName, perms, false, false);
             throw new ByActionStatusComponentException(ActionStatus.AUTH_FAILED);
         }
-
     }
 
     private void logAuth(String methodName, String[] perms, boolean beforeAuth, Boolean success) {
-        if (beforeAuth)
+        if (beforeAuth) {
             log.trace("#{} - authorizing before invoking endpoint {}", methodName);
-        else {
+        else {
             String status = success ? "SUCCESS" : "FAILED";
             log.trace("#{} - authorizing before invoking endpoint {}, Status: {}", methodName, status);
         }
@@ -77,6 +71,8 @@ public class RoleAuthorizationHandler {
     private boolean isPermissionAuthenticationNeeded() {
         if (configurationManager.getConfiguration().getAafAuthNeeded() && ThreadLocalsHolder.isExternalRequest()) {
             return true;
-        } else return false;
+        } else {
+            return false;
+        }
     }
 }
index 84316db..be529fe 100644 (file)
@@ -17,7 +17,6 @@
  * limitations under the License.
  * ============LICENSE_END=========================================================
  */
-
 package org.openecomp.sdc.be.components.impl.artifact;
 
 import static org.openecomp.sdc.be.components.impl.ArtifactsBusinessLogic.ArtifactOperationEnum.CREATE;
@@ -34,8 +33,7 @@ public final class ArtifactOperationInfo {
     private final boolean isExternalApi;
     private final boolean ignoreLifecycleState;
 
-    public ArtifactOperationInfo(boolean isExternalApi, boolean ignoreLifecycleState,
-        ArtifactOperationEnum artifactOperationEnum) {
+    public ArtifactOperationInfo(boolean isExternalApi, boolean ignoreLifecycleState, ArtifactOperationEnum artifactOperationEnum) {
         this.artifactOperationEnum = artifactOperationEnum;
         this.isExternalApi = isExternalApi;
         this.ignoreLifecycleState = ignoreLifecycleState;
index 3e3b9e2..3362686 100644 (file)
  *  * ============LICENSE_END=========================================================
  *
  */
-
 package org.openecomp.sdc.be.components.impl.artifact;
 
-import org.openecomp.sdc.common.api.ArtifactTypeEnum;
-
-import java.util.HashMap;
-import java.util.Map;
-import java.util.Objects;
-
 import static org.openecomp.sdc.be.components.impl.artifact.PayloadTypeEnum.HEAT_YAML;
 import static org.openecomp.sdc.be.components.impl.artifact.PayloadTypeEnum.NOT_DEFINED;
 import static org.openecomp.sdc.common.api.ArtifactTypeEnum.DCAE_INVENTORY_JSON;
@@ -47,6 +40,11 @@ import static org.openecomp.sdc.common.api.ArtifactTypeEnum.VF_LICENSE;
 import static org.openecomp.sdc.common.api.ArtifactTypeEnum.VNF_CATALOG;
 import static org.openecomp.sdc.common.api.ArtifactTypeEnum.YANG_XML;
 
+import java.util.HashMap;
+import java.util.Map;
+import java.util.Objects;
+import org.openecomp.sdc.common.api.ArtifactTypeEnum;
+
 public class ArtifactTypeToPayloadTypeSelector {
 
     private static final Map<ArtifactTypeWithExtension, PayloadTypeEnum> artifactTypeWithExtension2PayloadType = new HashMap<>();
@@ -66,17 +64,14 @@ public class ArtifactTypeToPayloadTypeSelector {
         artifactTypeWithExtension2PayloadType.put(createArtifactTypeWithExtension(DCAE_INVENTORY_JSON, JSON), PayloadTypeEnum.JSON);
         artifactTypeWithExtension2PayloadType.put(createArtifactTypeWithExtension(DCAE_INVENTORY_JSON, YML), PayloadTypeEnum.YAML);
         artifactTypeWithExtension2PayloadType.put(createArtifactTypeWithExtension(DCAE_INVENTORY_JSON, YAML), PayloadTypeEnum.YAML);
-
         artifactTypeWithExtension2PayloadType.put(createArtifactTypeWithExtension(DCAE_INVENTORY_TOSCA, XML), PayloadTypeEnum.XML);
         artifactTypeWithExtension2PayloadType.put(createArtifactTypeWithExtension(DCAE_INVENTORY_TOSCA, JSON), PayloadTypeEnum.JSON);
         artifactTypeWithExtension2PayloadType.put(createArtifactTypeWithExtension(DCAE_INVENTORY_TOSCA, YML), PayloadTypeEnum.YAML);
         artifactTypeWithExtension2PayloadType.put(createArtifactTypeWithExtension(DCAE_INVENTORY_TOSCA, YAML), PayloadTypeEnum.YAML);
-
         artifactTypeWithExtension2PayloadType.put(createArtifactTypeWithExtension(VES_EVENTS, XML), PayloadTypeEnum.XML);
         artifactTypeWithExtension2PayloadType.put(createArtifactTypeWithExtension(VES_EVENTS, JSON), PayloadTypeEnum.JSON);
         artifactTypeWithExtension2PayloadType.put(createArtifactTypeWithExtension(VES_EVENTS, YML), PayloadTypeEnum.YAML);
         artifactTypeWithExtension2PayloadType.put(createArtifactTypeWithExtension(VES_EVENTS, YAML), PayloadTypeEnum.YAML);
-
         artifactTypeWithExtension2PayloadType.put(createArtifactTypeWithExtension(LIFECYCLE_OPERATIONS, XML), PayloadTypeEnum.XML);
         artifactTypeWithExtension2PayloadType.put(createArtifactTypeWithExtension(LIFECYCLE_OPERATIONS, JSON), PayloadTypeEnum.JSON);
         artifactTypeWithExtension2PayloadType.put(createArtifactTypeWithExtension(LIFECYCLE_OPERATIONS, YML), PayloadTypeEnum.YAML);
@@ -88,7 +83,6 @@ public class ArtifactTypeToPayloadTypeSelector {
         artifactType2PayloadType.put(HEAT_VOL.getType().toLowerCase(), HEAT_YAML);
         artifactType2PayloadType.put(HEAT_NET.getType().toLowerCase(), HEAT_YAML);
         artifactType2PayloadType.put(HEAT_ENV.getType().toLowerCase(), PayloadTypeEnum.HEAT_ENV);
-
         artifactType2PayloadType.put(YANG_XML.getType().toLowerCase(), PayloadTypeEnum.XML);
         artifactType2PayloadType.put(VNF_CATALOG.getType().toLowerCase(), PayloadTypeEnum.XML);
         artifactType2PayloadType.put(VF_LICENSE.getType().toLowerCase(), PayloadTypeEnum.XML);
@@ -114,6 +108,7 @@ public class ArtifactTypeToPayloadTypeSelector {
     }
 
     private class ArtifactTypeWithExtension {
+
         private String artifactType;
         private String fileExtension;
 
@@ -136,9 +131,8 @@ public class ArtifactTypeToPayloadTypeSelector {
                 return false;
             }
             ArtifactTypeWithExtension otherArtifactTypeWithExtension = (ArtifactTypeWithExtension) other;
-
-            return isArtifactTypeEqual(otherArtifactTypeWithExtension.getArtifactType()) &&
-                    isFileExtensionEqual(otherArtifactTypeWithExtension.getFileExtension());
+            return isArtifactTypeEqual(otherArtifactTypeWithExtension.getArtifactType()) && isFileExtensionEqual(
+                otherArtifactTypeWithExtension.getFileExtension());
         }
 
         @Override
index 4a71d4b..b94b565 100644 (file)
  *  * ============LICENSE_END=========================================================
  *  * Modifications copyright (c) 2020 Nokia
  */
-
 package org.openecomp.sdc.be.components.impl.artifact;
 
 import com.google.gson.Gson;
 import com.google.gson.GsonBuilder;
 import fj.data.Either;
+import java.io.ByteArrayInputStream;
+import java.io.IOException;
+import javax.xml.XMLConstants;
+import javax.xml.parsers.ParserConfigurationException;
 import javax.xml.parsers.SAXParser;
+import javax.xml.parsers.SAXParserFactory;
 import org.openecomp.sdc.be.config.validation.DeploymentArtifactHeatConfiguration;
 import org.openecomp.sdc.be.dao.api.ActionStatus;
 import org.openecomp.sdc.common.log.wrappers.Logger;
@@ -36,12 +40,6 @@ import org.xml.sax.SAXNotRecognizedException;
 import org.xml.sax.SAXNotSupportedException;
 import org.xml.sax.XMLReader;
 
-import javax.xml.XMLConstants;
-import javax.xml.parsers.ParserConfigurationException;
-import javax.xml.parsers.SAXParserFactory;
-import java.io.ByteArrayInputStream;
-import java.io.IOException;
-
 public enum PayloadTypeEnum {
     HEAT_YAML {
         @Override
@@ -50,9 +48,7 @@ public enum PayloadTypeEnum {
             if (isNotValidYaml(payload, yamlToObjectConverter)) {
                 return Either.right(ActionStatus.INVALID_YAML);
             }
-
-            DeploymentArtifactHeatConfiguration heatConfiguration =
-                    yamlToObjectConverter.convert(payload, DeploymentArtifactHeatConfiguration.class);
+            DeploymentArtifactHeatConfiguration heatConfiguration = yamlToObjectConverter.convert(payload, DeploymentArtifactHeatConfiguration.class);
             if (heatConfiguration == null || heatConfiguration.getHeat_template_version() == null) {
                 log.debug("HEAT doesn't contain required \"heat_template_version\" section.");
                 return Either.right(ActionStatus.INVALID_DEPLOYMENT_ARTIFACT_HEAT);
@@ -68,8 +64,7 @@ public enum PayloadTypeEnum {
         private boolean isNotValidYaml(byte[] payload, YamlToObjectConverter yamlToObjectConverter) {
             return !yamlToObjectConverter.isValidYaml(payload);
         }
-    },
-    HEAT_ENV {
+    }, HEAT_ENV {
         @Override
         public Either<Boolean, ActionStatus> isValid(byte[] payload) {
             return isValidYaml(payload);
@@ -79,8 +74,7 @@ public enum PayloadTypeEnum {
         public boolean isHeatRelated() {
             return true;
         }
-    },
-    XML {
+    }, XML {
         @Override
         public Either<Boolean, ActionStatus> isValid(byte[] payload) {
             try {
@@ -103,11 +97,10 @@ public enum PayloadTypeEnum {
                 reader.setFeature(XMLConstants.FEATURE_SECURE_PROCESSING, true);
             } catch (SAXNotRecognizedException exception) {
                 log.debug("Xml parser couldn't set feature: \"http://apache.org/xml/features/validation/schema\", false",
-                        exception.getMessage(), exception);
+                    exception.getMessage(), exception);
             }
         }
-    },
-    JSON {
+    }, JSON {
         @Override
         public Either<Boolean, ActionStatus> isValid(byte[] payload) {
             try {
@@ -118,29 +111,20 @@ public enum PayloadTypeEnum {
             }
             return Either.left(true);
         }
-    },
-    YAML {
+    }, YAML {
         @Override
         public Either<Boolean, ActionStatus> isValid(byte[] payload) {
             return isValidYaml(payload);
         }
-    },
-    NOT_DEFINED {
+    }, NOT_DEFINED {
         @Override
         public Either<Boolean, ActionStatus> isValid(byte[] payload) {
             return Either.left(true);
         }
     };
-
     private static final Logger log = Logger.getLogger(PayloadTypeEnum.class);
     private static final Gson gson = new GsonBuilder().setPrettyPrinting().create();
 
-    public abstract Either<Boolean, ActionStatus> isValid(byte[] payload);
-
-    public boolean isHeatRelated() {
-        return false;
-    }
-
     private static Either<Boolean, ActionStatus> isValidYaml(byte[] payload) {
         YamlToObjectConverter yamlToObjectConverter = new YamlToObjectConverter();
         if (yamlToObjectConverter.isValidYaml(payload)) {
@@ -150,4 +134,9 @@ public enum PayloadTypeEnum {
         return Either.right(ActionStatus.INVALID_YAML);
     }
 
+    public abstract Either<Boolean, ActionStatus> isValid(byte[] payload);
+
+    public boolean isHeatRelated() {
+        return false;
+    }
 }
index acf80cb..845487b 100644 (file)
@@ -16,7 +16,6 @@
  *  SPDX-License-Identifier: Apache-2.0
  *  ============LICENSE_END=========================================================
  */
-
 package org.openecomp.sdc.be.components.impl.exceptions;
 
 import lombok.AllArgsConstructor;
@@ -28,5 +27,4 @@ public class BusinessLogicException extends Exception {
 
     @Getter
     private final ResponseFormat responseFormat;
-
 }
index 788d638..e973fe4 100644 (file)
  */
 package org.openecomp.sdc.be.components.impl.exceptions;
 
+import java.util.Arrays;
 import org.openecomp.sdc.be.components.impl.ResponseFormatManager;
 import org.openecomp.sdc.be.dao.api.ActionStatus;
 import org.openecomp.sdc.exception.ResponseFormat;
 
-import java.util.Arrays;
-
 public class ByActionStatusComponentException extends ComponentException {
 
     private final ActionStatus actionStatus;
@@ -51,10 +50,6 @@ public class ByActionStatusComponentException extends ComponentException {
 
     @Override
     public String toString() {
-        return "ComponentException{" +
-            "actionStatus=" + actionStatus +
-            ", params=" + Arrays.toString(params) +
-            '}';
+        return "ComponentException{" + "actionStatus=" + actionStatus + ", params=" + Arrays.toString(params) + '}';
     }
-
 }
index 85fe3ec..3577b7a 100644 (file)
@@ -39,7 +39,7 @@ public class ByResponseFormatComponentException extends ComponentException {
         return params.clone();
     }
 
-    public ActionStatus getActionStatus(){
+    public ActionStatus getActionStatus() {
         return actionStatus;
     }
 
@@ -50,9 +50,6 @@ public class ByResponseFormatComponentException extends ComponentException {
 
     @Override
     public String toString() {
-        return "ComponentException{" +
-            "responseFormat=" + responseFormat +
-            '}';
+        return "ComponentException{" + "responseFormat=" + responseFormat + '}';
     }
-
 }
index 1d98098..351d279 100644 (file)
  * limitations under the License.
  * ============LICENSE_END=========================================================
  */
-
 package org.openecomp.sdc.be.components.impl.exceptions;
 
+import javax.annotation.Nullable;
 import org.openecomp.sdc.be.components.impl.ResponseFormatManager;
 import org.openecomp.sdc.be.dao.api.ActionStatus;
 import org.openecomp.sdc.be.model.Resource;
 import org.openecomp.sdc.exception.ResponseFormat;
 
-import javax.annotation.Nullable;
-
 public class ComponentException extends RuntimeException {
 
     /**
      * This class will be initialized either by action status and params or by ResponseFormat
      */
-
     private final transient ResponseFormat responseFormat;
     private final ActionStatus actionStatus;
     private final String[] params;
-
-    public Resource getResource() {
-        return resource;
-    }
-
     private final Resource resource;
 
     public ComponentException(ResponseFormat responseFormat) {
@@ -62,6 +54,10 @@ public class ComponentException extends RuntimeException {
         this.resource = resource;
     }
 
+    public Resource getResource() {
+        return resource;
+    }
+
     @Nullable
     public ResponseFormat getResponseFormat() {
         return responseFormat;
@@ -74,6 +70,4 @@ public class ComponentException extends RuntimeException {
     public String[] getParams() {
         return params.clone();
     }
-
-
 }
index 441e68b..594e3e4 100644 (file)
@@ -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.
  * limitations under the License.
  * ============LICENSE_END=========================================================
  */
-
 package org.openecomp.sdc.be.components.impl.exceptions;
 
 public class SdcResourceNotFoundException extends RuntimeException {
 
-       private static final long serialVersionUID = 4431147390120646573L;
+    private static final long serialVersionUID = 4431147390120646573L;
 
-       public SdcResourceNotFoundException(){}
+    public SdcResourceNotFoundException() {
+    }
 
-       public SdcResourceNotFoundException(String message){
-               super(message);
-       }
+    public SdcResourceNotFoundException(String message) {
+        super(message);
+    }
 }
index 840fd03..a00f44c 100644 (file)
@@ -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.
  * limitations under the License.
  * ============LICENSE_END=========================================================
  */
-
 package org.openecomp.sdc.be.components.impl.generic;
 
 import fj.data.Either;
+import java.util.ArrayList;
+import java.util.List;
+import java.util.stream.Collectors;
 import org.apache.commons.collections.CollectionUtils;
 import org.openecomp.sdc.be.dao.api.ActionStatus;
 import org.openecomp.sdc.be.datatypes.enums.ComponentTypeEnum;
@@ -36,15 +38,10 @@ import org.openecomp.sdc.common.log.wrappers.Logger;
 import org.openecomp.sdc.exception.ResponseFormat;
 import org.springframework.beans.factory.annotation.Autowired;
 
-import java.util.ArrayList;
-import java.util.List;
-import java.util.stream.Collectors;
-
 @org.springframework.stereotype.Component
 public class GenericTypeBusinessLogic {
 
     private final static Logger log = Logger.getLogger(GenericTypeBusinessLogic.class);
-
     private final ComponentsUtils componentsUtils;
     private final ToscaOperationFacade toscaOperationFacade;
 
@@ -58,58 +55,54 @@ public class GenericTypeBusinessLogic {
      * @param component the component of which to fetch its generic type
      * @return the generic node type which corresponds to the given component
      */
-    public Either<Resource, ResponseFormat> fetchDerivedFromGenericType(Component component){
+    public Either<Resource, ResponseFormat> fetchDerivedFromGenericType(Component component) {
         String genericTypeToscaName = getGenericTypeToscaName(component);
         log.debug("Fetching generic tosca name {}", genericTypeToscaName);
-        if(null == genericTypeToscaName) {
+        if (null == genericTypeToscaName) {
             log.debug("Failed to fetch certified generic node type for component {}", component.getName());
             return Either.right(componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR));
         }
-
-        Either<Resource, StorageOperationStatus> findLatestGeneric = toscaOperationFacade.getLatestCertifiedNodeTypeByToscaResourceName(genericTypeToscaName);
-        if(findLatestGeneric.isRight()){
+        Either<Resource, StorageOperationStatus> findLatestGeneric = toscaOperationFacade
+            .getLatestCertifiedNodeTypeByToscaResourceName(genericTypeToscaName);
+        if (findLatestGeneric.isRight()) {
             log.debug("Failed to fetch certified node type by tosca resource name {}", genericTypeToscaName);
             return Either.right(componentsUtils.getResponseFormat(ActionStatus.GENERIC_TYPE_NOT_FOUND, component.assetType(), genericTypeToscaName));
         }
-
         Resource genericTypeResource = findLatestGeneric.left().value();
         return Either.left(genericTypeResource);
     }
 
     /**
-     *
      * @param genericType the generic node type
      * @return the generic type properties as inputs
      */
     public List<InputDefinition> generateInputsFromGenericTypeProperties(Resource genericType) {
         List<PropertyDefinition> genericTypeProps = genericType.getProperties();
-        if(null != genericTypeProps) {
+        if (null != genericTypeProps) {
             return convertGenericTypePropertiesToInputsDefintion(genericTypeProps, genericType.getUniqueId());
         }
         return new ArrayList<>();
     }
 
     public List<InputDefinition> convertGenericTypePropertiesToInputsDefintion(List<PropertyDefinition> genericTypeProps, String genericUniqueId) {
-        return genericTypeProps.stream()
-                .map(p -> setInputDefinitionFromProp(p, genericUniqueId))
-                .collect(Collectors.toList());
+        return genericTypeProps.stream().map(p -> setInputDefinitionFromProp(p, genericUniqueId)).collect(Collectors.toList());
     }
 
-    private InputDefinition setInputDefinitionFromProp(PropertyDefinition prop, String genericUniqueId){
+    private InputDefinition setInputDefinitionFromProp(PropertyDefinition prop, String genericUniqueId) {
         InputDefinition input = new InputDefinition(prop);
         input.setOwnerId(genericUniqueId);
         return input;
     }
 
     private <T extends Component> String getGenericTypeToscaName(T component) {
-        if(component.getDerivedFromGenericType() != null && !component.getDerivedFromGenericType().isEmpty()){
+        if (component.getDerivedFromGenericType() != null && !component.getDerivedFromGenericType().isEmpty()) {
             return component.getDerivedFromGenericType();
         }
-        return isCvfcHasDerivedFrom(component) ? ((Resource)component).getDerivedFrom().get(0) : component.fetchGenericTypeToscaNameFromConfig();
+        return isCvfcHasDerivedFrom(component) ? ((Resource) component).getDerivedFrom().get(0) : component.fetchGenericTypeToscaNameFromConfig();
     }
 
     private <T extends Component> boolean isCvfcHasDerivedFrom(T component) {
-        return component.getComponentType() == ComponentTypeEnum.RESOURCE && ((Resource)component).getResourceType() == ResourceTypeEnum.CVFC && CollectionUtils.isNotEmpty(((Resource)component).getDerivedFrom());
+        return component.getComponentType() == ComponentTypeEnum.RESOURCE && ((Resource) component).getResourceType() == ResourceTypeEnum.CVFC
+            && CollectionUtils.isNotEmpty(((Resource) component).getDerivedFrom());
     }
-
 }
index b4df58b..74e16a1 100644 (file)
@@ -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.
  * limitations under the License.
  * ============LICENSE_END=========================================================
  */
-
 package org.openecomp.sdc.be.components.impl.group;
 
-import org.apache.commons.collections.MapUtils;
-import org.openecomp.sdc.be.model.GroupDefinition;
-import org.springframework.stereotype.Component;
+import static org.apache.commons.collections.MapUtils.isEmpty;
 
 import java.util.List;
 import java.util.Map;
-
-import static org.apache.commons.collections.MapUtils.isEmpty;
+import org.apache.commons.collections.MapUtils;
+import org.openecomp.sdc.be.model.GroupDefinition;
+import org.springframework.stereotype.Component;
 
 /**
  * A Helper class which handles altering the members state of a group
@@ -69,8 +67,4 @@ public class GroupMembersUpdater {
         }
         return invertedMap.get(memberToFind).toString();
     }
-
-
-
-
 }
index 8e9ba7a..29a2d7c 100644 (file)
  * limitations under the License.
  * ============LICENSE_END=========================================================
  */
-
 package org.openecomp.sdc.be.components.impl.group;
 
+import static org.apache.commons.collections.CollectionUtils.isEmpty;
+
 import java.util.Collections;
+import java.util.List;
+import java.util.Map;
+import java.util.function.Consumer;
 import java.util.stream.Collectors;
 import org.openecomp.sdc.be.components.impl.version.OnChangeVersionCommand;
 import org.openecomp.sdc.be.dao.api.ActionStatus;
@@ -35,63 +39,27 @@ import org.openecomp.sdc.be.model.operations.impl.UniqueIdBuilder;
 import org.openecomp.sdc.be.model.utils.GroupUtils;
 import org.openecomp.sdc.common.log.wrappers.Logger;
 
-import java.util.List;
-import java.util.Map;
-import java.util.function.Consumer;
-
-import static org.apache.commons.collections.CollectionUtils.isEmpty;
-
-
 /**
  * A Helper class which handles altering the version of a group
  */
 @org.springframework.stereotype.Component
 public class GroupVersionUpdater implements OnChangeVersionCommand {
-    
+
     private static final Logger log = Logger.getLogger(GroupVersionUpdater.class);
     private final GroupsOperation groupsOperation;
     private final ComponentsUtils componentsUtils;
-    
 
     public GroupVersionUpdater(GroupsOperation groupsOperation, ComponentsUtils componentsUtils) {
         this.groupsOperation = groupsOperation;
         this.componentsUtils = componentsUtils;
-    
-    }
-    
-    
-    @Override
-    public ActionStatus onChangeVersion(Component container) {
-        log.debug("#onChangeVersion - replacing all group members for component instance");
-        Consumer<List<GroupDefinition>> replaceGroupMemberTask = (groups) -> increaseVersion(groups, container);
-        return updateGroupsVersion(container, replaceGroupMemberTask);
-    }
-
-    public void increaseVersion(List<GroupDefinition> groups, Component container) {
-        groups.forEach(group -> increaseMajorVersion(group, container));
-    }
-
-  
-    private void increaseMajorVersion(GroupDefinition group, Component container) {
-        String version = group.getVersion();
-        
-        String newVersion = GroupUtils.updateVersion(PromoteVersionEnum.MAJOR, group.getVersion());
-      
-        if(!version.equals(newVersion) ){
-            if(isGenerateGroupUUID(group, container)) {
-                String groupUUID = UniqueIdBuilder.generateUUID();
-                group.setGroupUUID(groupUUID);
-            }
-            group.setVersion(String.valueOf(newVersion));
-        }
     }
 
     static <T> List<T> emptyIfNull(final List<T> list) {
-        return (list == null? Collections.emptyList() : list);
+        return (list == null ? Collections.emptyList() : list);
     }
 
     static <T, U> Map<T, U> emptyIfNull(final Map<T, U> list) {
-        return (list == null? Collections.emptyMap() : list);
+        return (list == null ? Collections.emptyMap() : list);
     }
 
     static boolean isGenerateGroupUUID(GroupDefinition group, Component container) {
@@ -100,16 +68,11 @@ public class GroupVersionUpdater implements OnChangeVersionCommand {
         } else {
             List<String> artifactsUuid = emptyIfNull(group.getArtifactsUuid());
             Map<String, ArtifactDefinition> deploymentArtifacts = emptyIfNull(container.getDeploymentArtifacts());
-            List<String> heatArtifactUniqueIDs = emptyIfNull(group.getArtifacts()).stream().filter(a -> !a.endsWith("env")).collect(
-                Collectors.toList());
-
+            List<String> heatArtifactUniqueIDs = emptyIfNull(group.getArtifacts()).stream().filter(a -> !a.endsWith("env"))
+                .collect(Collectors.toList());
             for (String heatArtifactUniqueID : heatArtifactUniqueIDs) {
-                ArtifactDefinition artifactDefinition = deploymentArtifacts
-                    .get(heatArtifactUniqueID.split("\\.", -1)[1]);
-
-                if ((artifactDefinition == null
-                    || artifactDefinition.isEmpty())
-                    || !artifactsUuid.contains(artifactDefinition.getArtifactUUID())) {
+                ArtifactDefinition artifactDefinition = deploymentArtifacts.get(heatArtifactUniqueID.split("\\.", -1)[1]);
+                if ((artifactDefinition == null || artifactDefinition.isEmpty()) || !artifactsUuid.contains(artifactDefinition.getArtifactUUID())) {
                     return true;
                 }
             }
@@ -117,6 +80,29 @@ public class GroupVersionUpdater implements OnChangeVersionCommand {
         }
     }
 
+    @Override
+    public ActionStatus onChangeVersion(Component container) {
+        log.debug("#onChangeVersion - replacing all group members for component instance");
+        Consumer<List<GroupDefinition>> replaceGroupMemberTask = (groups) -> increaseVersion(groups, container);
+        return updateGroupsVersion(container, replaceGroupMemberTask);
+    }
+
+    public void increaseVersion(List<GroupDefinition> groups, Component container) {
+        groups.forEach(group -> increaseMajorVersion(group, container));
+    }
+
+    private void increaseMajorVersion(GroupDefinition group, Component container) {
+        String version = group.getVersion();
+        String newVersion = GroupUtils.updateVersion(PromoteVersionEnum.MAJOR, group.getVersion());
+        if (!version.equals(newVersion)) {
+            if (isGenerateGroupUUID(group, container)) {
+                String groupUUID = UniqueIdBuilder.generateUUID();
+                group.setGroupUUID(groupUUID);
+            }
+            group.setVersion(String.valueOf(newVersion));
+        }
+    }
+
     private ActionStatus updateGroupsVersion(Component groupsContainer, Consumer<List<GroupDefinition>> updateGroupVersion) {
         List<GroupDefinition> groups = groupsContainer.getGroups();
         if (isEmpty(groups)) {
@@ -124,14 +110,10 @@ public class GroupVersionUpdater implements OnChangeVersionCommand {
         }
         updateGroupVersion.accept(groups);
         return updateGroups(groupsContainer.getUniqueId(), groups);
-    }  
+    }
 
-    
     private ActionStatus updateGroups(String componentId, List<GroupDefinition> groupsToUpdate) {
         log.debug("#updateGroups - updating {} groups for container {}", groupsToUpdate.size(), componentId);
         return componentsUtils.convertFromStorageResponse(groupsOperation.updateGroupsOnComponent(componentId, groupsToUpdate));
-               
     }
-
 }
-
index e631e9f..fa1211d 100644 (file)
@@ -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.
  * limitations under the License.
  * ============LICENSE_END=========================================================
  */
-
 package org.openecomp.sdc.be.components.impl.instance;
 
+import java.util.Iterator;
+import java.util.List;
+import java.util.function.Function;
 import org.openecomp.sdc.be.dao.api.ActionStatus;
 import org.openecomp.sdc.be.model.Component;
 import org.openecomp.sdc.be.model.ComponentInstance;
 import org.openecomp.sdc.common.log.wrappers.Logger;
 
-import java.util.Iterator;
-import java.util.List;
-import java.util.function.Function;
-
 @org.springframework.stereotype.Component
 public class ComponentInstanceChangeOperationOrchestrator {
 
@@ -40,24 +38,27 @@ public class ComponentInstanceChangeOperationOrchestrator {
     }
 
     public ActionStatus doPostChangeVersionOperations(Component container, ComponentInstance prevVersion, ComponentInstance newVersion) {
-        log.debug("#doPostChangeVersionOperations - starting post change version operations for component {}. from instance {} to instance {}", container.getUniqueId(), prevVersion.getUniqueId(), newVersion.getUniqueId());
-        Function<OnComponentInstanceChangeOperation, ActionStatus> instanceChangeTaskRunner = operation -> operation.onChangeVersion(container, prevVersion, newVersion);
+        log.debug("#doPostChangeVersionOperations - starting post change version operations for component {}. from instance {} to instance {}",
+            container.getUniqueId(), prevVersion.getUniqueId(), newVersion.getUniqueId());
+        Function<OnComponentInstanceChangeOperation, ActionStatus> instanceChangeTaskRunner = operation -> operation
+            .onChangeVersion(container, prevVersion, newVersion);
         return doOnChangeInstanceOperations(instanceChangeTaskRunner);
     }
 
     public ActionStatus doOnDeleteInstanceOperations(Component container, String deletedInstanceId) {
-        log.debug("#doPostChangeVersionOperations - starting on delete instance operations for component {} and instance {}.", container.getUniqueId(), deletedInstanceId);
-        Function<OnComponentInstanceChangeOperation, ActionStatus> instanceChangeTaskRunner = operation -> operation.onDelete(container, deletedInstanceId);
+        log.debug("#doPostChangeVersionOperations - starting on delete instance operations for component {} and instance {}.",
+            container.getUniqueId(), deletedInstanceId);
+        Function<OnComponentInstanceChangeOperation, ActionStatus> instanceChangeTaskRunner = operation -> operation
+            .onDelete(container, deletedInstanceId);
         return doOnChangeInstanceOperations(instanceChangeTaskRunner);
     }
 
     private ActionStatus doOnChangeInstanceOperations(Function<OnComponentInstanceChangeOperation, ActionStatus> instanceChangeTaskRunner) {
         ActionStatus onDeleteInstanceResult = ActionStatus.OK;
         Iterator<OnComponentInstanceChangeOperation> onDeleteInstIter = onInstanceChangeOperations.iterator();
-        while(onDeleteInstIter.hasNext() && onDeleteInstanceResult == ActionStatus.OK) {
+        while (onDeleteInstIter.hasNext() && onDeleteInstanceResult == ActionStatus.OK) {
             onDeleteInstanceResult = instanceChangeTaskRunner.apply(onDeleteInstIter.next());
         }
         return onDeleteInstanceResult;
     }
-
 }
index 656dd2e..7a8f120 100644 (file)
@@ -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.
  * limitations under the License.
  * ============LICENSE_END=========================================================
  */
-
 package org.openecomp.sdc.be.components.impl.instance;
 
+import static org.apache.commons.collections.CollectionUtils.isEmpty;
+
+import java.util.List;
+import java.util.function.Consumer;
 import org.openecomp.sdc.be.components.impl.group.GroupMembersUpdater;
 import org.openecomp.sdc.be.dao.api.ActionStatus;
 import org.openecomp.sdc.be.datatypes.enums.PromoteVersionEnum;
@@ -30,10 +33,6 @@ import org.openecomp.sdc.be.model.GroupDefinition;
 import org.openecomp.sdc.be.model.jsonjanusgraph.operations.GroupsOperation;
 import org.openecomp.sdc.common.log.wrappers.Logger;
 
-import java.util.List;
-import java.util.function.Consumer;
-
-import static org.apache.commons.collections.CollectionUtils.isEmpty;
 @org.springframework.stereotype.Component
 public class GroupMembersUpdateOperation implements OnComponentInstanceChangeOperation {
 
@@ -50,8 +49,10 @@ public class GroupMembersUpdateOperation implements OnComponentInstanceChangeOpe
 
     @Override
     public ActionStatus onChangeVersion(Component container, ComponentInstance prevVersion, ComponentInstance newVersion) {
-        log.debug("#onChangeVersion - replacing all group members for component instance {} with new component instance on component", prevVersion.getUniqueId(), newVersion.getUniqueId(), container.getUniqueId());
-        Consumer<List<GroupDefinition>> replaceGroupMemberTask = (groups) -> groupMembersUpdater.replaceMember(groups, prevVersion.getUniqueId(), newVersion.getUniqueId());
+        log.debug("#onChangeVersion - replacing all group members for component instance {} with new component instance on component",
+            prevVersion.getUniqueId(), newVersion.getUniqueId(), container.getUniqueId());
+        Consumer<List<GroupDefinition>> replaceGroupMemberTask = (groups) -> groupMembersUpdater
+            .replaceMember(groups, prevVersion.getUniqueId(), newVersion.getUniqueId());
         return doUpdateGroupMembers(container, prevVersion.getUniqueId(), replaceGroupMemberTask);
     }
 
@@ -75,9 +76,6 @@ public class GroupMembersUpdateOperation implements OnComponentInstanceChangeOpe
     private ActionStatus updateGroups(Component container, List<GroupDefinition> groupsToUpdate) {
         log.debug("#updateGroups - updating {} groups for container {}", groupsToUpdate.size(), container.getUniqueId());
         return groupsOperation.updateGroups(container, groupsToUpdate, PromoteVersionEnum.MINOR)
-                .either(groupsUpdated -> ActionStatus.OK,
-                        err -> componentsUtils.convertFromStorageResponse(err, container.getComponentType()));
+            .either(groupsUpdated -> ActionStatus.OK, err -> componentsUtils.convertFromStorageResponse(err, container.getComponentType()));
     }
-
-
 }
index 173fb3f..5093a15 100644 (file)
@@ -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.
  * limitations under the License.
  * ============LICENSE_END=========================================================
  */
-
 package org.openecomp.sdc.be.components.impl.instance;
 
 import org.openecomp.sdc.be.dao.api.ActionStatus;
 import org.openecomp.sdc.be.model.Component;
 import org.openecomp.sdc.be.model.ComponentInstance;
+
 @FunctionalInterface
 public interface OnChangeVersionOperation {
 
     /**
      * A side effect operation to execute when a component instance version was changed from {@code prevVersion} to {@code newVersion}
-     * @param container the container which contains the instance which is version was changed
+     *
+     * @param container   the container which contains the instance which is version was changed
      * @param prevVersion the previous version of the component instance.
-     * @param newVersion the new version of the component instance.
+     * @param newVersion  the new version of the component instance.
      * @return the status of the operation
      */
     ActionStatus onChangeVersion(Component container, ComponentInstance prevVersion, ComponentInstance newVersion);
-
 }
index a01421e..f27cf5b 100644 (file)
@@ -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.
@@ -17,7 +17,6 @@
  * limitations under the License.
  * ============LICENSE_END=========================================================
  */
-
 package org.openecomp.sdc.be.components.impl.instance;
 
 import org.openecomp.sdc.be.components.impl.OnDeleteEntityOperation;
@@ -26,4 +25,5 @@ import org.openecomp.sdc.be.components.impl.OnDeleteEntityOperation;
  * An interface which groups all operations to be executed when an action on a component instance has occurred
  */
 public interface OnComponentInstanceChangeOperation extends OnChangeVersionOperation, OnDeleteEntityOperation {
+
 }
index 863be79..7ef9fc7 100644 (file)
@@ -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.
@@ -17,7 +17,6 @@
  * limitations under the License.
  * ============LICENSE_END=========================================================
  */
-
 package org.openecomp.sdc.be.components.impl.instance;
 
 import org.openecomp.sdc.be.components.impl.policy.PolicyTargetsUpdateHandler;
@@ -39,8 +38,10 @@ public class PolicyTargetsUpdateOperation implements OnComponentInstanceChangeOp
 
     @Override
     public ActionStatus onChangeVersion(Component container, ComponentInstance prevVersion, ComponentInstance newVersion) {
-        log.debug("#onChangeVersion - replacing all policy targets referencing component instance {} with component instance {}", prevVersion.getUniqueId(), newVersion.getUniqueId());
-        return policyTargetsUpdateHandler.replacePoliciesTargets(container, prevVersion.getUniqueId(), newVersion.getUniqueId(), PolicyTargetType.COMPONENT_INSTANCES);
+        log.debug("#onChangeVersion - replacing all policy targets referencing component instance {} with component instance {}",
+            prevVersion.getUniqueId(), newVersion.getUniqueId());
+        return policyTargetsUpdateHandler
+            .replacePoliciesTargets(container, prevVersion.getUniqueId(), newVersion.getUniqueId(), PolicyTargetType.COMPONENT_INSTANCES);
     }
 
     @Override
@@ -48,6 +49,4 @@ public class PolicyTargetsUpdateOperation implements OnComponentInstanceChangeOp
         log.debug("#onDelete - removing all component {} policy targets referencing component instance {}", container.getUniqueId(), deletedEntityId);
         return policyTargetsUpdateHandler.removePoliciesTargets(container, deletedEntityId, PolicyTargetType.COMPONENT_INSTANCES);
     }
-
-
 }
index 892ea8c..cfd0675 100644 (file)
@@ -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.
@@ -17,7 +17,6 @@
  * limitations under the License.
  * ============LICENSE_END=========================================================
  */
-
 package org.openecomp.sdc.be.components.impl.lock;
 
 import org.aspectj.lang.ProceedingJoinPoint;
@@ -46,13 +45,10 @@ public class ComponentLockAspect {
             componentLocker.lock(componentId, componentType);
             log.trace("#{} - after locking component {} of type {}", methodName, componentId, componentType);
             return proceedingJoinPoint.proceed();
-        }
-        finally {
+        } finally {
             log.trace("#{} - before unlocking component {} of type {}", methodName, componentId, componentType);
             componentLocker.unlock(componentId, componentType);
             log.trace("#{} - after unlocking component {} of type {}", methodName, componentId, componentType);
         }
     }
-
-
 }
index 44e49eb..9a0d251 100644 (file)
@@ -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.
  * limitations under the License.
  * ============LICENSE_END=========================================================
  */
-
 package org.openecomp.sdc.be.components.impl.lock;
 
-import org.springframework.transaction.annotation.Transactional;
-
 import java.lang.annotation.ElementType;
 import java.lang.annotation.Inherited;
 import java.lang.annotation.Retention;
 import java.lang.annotation.RetentionPolicy;
 import java.lang.annotation.Target;
+import org.springframework.transaction.annotation.Transactional;
 
 @Target({ElementType.METHOD, ElementType.TYPE})
 @Retention(RetentionPolicy.RUNTIME)
index 00f5fd8..a5416dd 100644 (file)
@@ -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.
  * limitations under the License.
  * ============LICENSE_END=========================================================
  */
-
 package org.openecomp.sdc.be.components.impl.model;
 
-import org.openecomp.sdc.be.model.normatives.ToscaTypeMetadata;
-
 import java.util.Map;
+import org.openecomp.sdc.be.model.normatives.ToscaTypeMetadata;
 
 public class ToscaTypeImportData {
 
index 3b3dab3..df2ea21 100644 (file)
@@ -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.
  * limitations under the License.
  * ============LICENSE_END=========================================================
  */
-
 package org.openecomp.sdc.be.components.impl.policy;
 
+import static org.apache.commons.collections.CollectionUtils.isEmpty;
+
+import java.util.List;
+import java.util.function.Consumer;
 import org.openecomp.sdc.be.dao.api.ActionStatus;
 import org.openecomp.sdc.be.datatypes.elements.PolicyTargetType;
 import org.openecomp.sdc.be.impl.ComponentsUtils;
@@ -29,11 +32,6 @@ import org.openecomp.sdc.be.model.jsonjanusgraph.operations.ToscaOperationFacade
 import org.openecomp.sdc.be.model.operations.api.StorageOperationStatus;
 import org.openecomp.sdc.common.log.wrappers.Logger;
 
-import java.util.List;
-import java.util.function.Consumer;
-
-import static org.apache.commons.collections.CollectionUtils.isEmpty;
-
 @org.springframework.stereotype.Component
 public class PolicyTargetsUpdateHandler {
 
@@ -42,7 +40,8 @@ public class PolicyTargetsUpdateHandler {
     private final ComponentsUtils componentsUtils;
     private final PolicyTargetsUpdater policyTargetsUpdater;
 
-    public PolicyTargetsUpdateHandler(ToscaOperationFacade toscaOperationFacade, ComponentsUtils componentsUtils, PolicyTargetsUpdater policyTargetsUpdater) {
+    public PolicyTargetsUpdateHandler(ToscaOperationFacade toscaOperationFacade, ComponentsUtils componentsUtils,
+                                      PolicyTargetsUpdater policyTargetsUpdater) {
         this.toscaOperationFacade = toscaOperationFacade;
         this.componentsUtils = componentsUtils;
         this.policyTargetsUpdater = policyTargetsUpdater;
@@ -56,11 +55,13 @@ public class PolicyTargetsUpdateHandler {
 
     public ActionStatus replacePoliciesTargets(Component container, String prevTargetId, String newTargetId, PolicyTargetType targetType) {
         log.debug("#replacePoliciesTargets - replacing all policy targets referencing target {} with target {}", prevTargetId, newTargetId);
-        Consumer<List<PolicyDefinition>> replaceTarget = policies -> policyTargetsUpdater.replaceTarget(policies, prevTargetId, newTargetId, targetType);
+        Consumer<List<PolicyDefinition>> replaceTarget = policies -> policyTargetsUpdater
+            .replaceTarget(policies, prevTargetId, newTargetId, targetType);
         return updatePolicyTargets(container, prevTargetId, targetType, replaceTarget);
     }
 
-    private ActionStatus updatePolicyTargets(Component container, String targetId, PolicyTargetType targetType, Consumer<List<PolicyDefinition>> updatePolicyTargetTaskRunner) {
+    private ActionStatus updatePolicyTargets(Component container, String targetId, PolicyTargetType targetType,
+                                             Consumer<List<PolicyDefinition>> updatePolicyTargetTaskRunner) {
         List<PolicyDefinition> policiesWithPrevInstanceAsTarget = container.resolvePoliciesContainingTarget(targetId, targetType);
         if (isEmpty(policiesWithPrevInstanceAsTarget)) {
             return ActionStatus.OK;
@@ -74,5 +75,4 @@ public class PolicyTargetsUpdateHandler {
         StorageOperationStatus updatePolicyResult = toscaOperationFacade.updatePoliciesOfComponent(policiesContainer.getUniqueId(), policiesToUpdate);
         return componentsUtils.convertFromStorageResponse(updatePolicyResult, policiesContainer.getComponentType());
     }
-
 }
index adf9271..e2d5f54 100644 (file)
@@ -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.
  * limitations under the License.
  * ============LICENSE_END=========================================================
  */
-
 package org.openecomp.sdc.be.components.impl.policy;
 
+import static java.util.Collections.emptyList;
+import static org.apache.commons.collections.CollectionUtils.isEmpty;
+
+import java.util.List;
+import java.util.Map;
+import java.util.function.UnaryOperator;
 import org.apache.commons.collections.MapUtils;
 import org.openecomp.sdc.be.datatypes.elements.PolicyTargetType;
 import org.openecomp.sdc.be.datatypes.enums.PromoteVersionEnum;
@@ -27,13 +32,6 @@ import org.openecomp.sdc.be.model.PolicyDefinition;
 import org.openecomp.sdc.be.model.utils.GroupUtils;
 import org.springframework.stereotype.Component;
 
-import java.util.List;
-import java.util.Map;
-import java.util.function.UnaryOperator;
-
-import static java.util.Collections.emptyList;
-import static org.apache.commons.collections.CollectionUtils.isEmpty;
-
 /**
  * A Helper class which handles altering the targets state of a policy
  */
@@ -41,7 +39,7 @@ import static org.apache.commons.collections.CollectionUtils.isEmpty;
 public class PolicyTargetsUpdater {
 
     public void removeTarget(List<PolicyDefinition> policies, String targetId, PolicyTargetType targetType) {
-        policies.forEach(policy ->removePolicyTarget(policy, targetId, targetType));
+        policies.forEach(policy -> removePolicyTarget(policy, targetId, targetType));
     }
 
     public void replaceTarget(List<PolicyDefinition> policies, String oldTargetId, String newTargetId, PolicyTargetType targetType) {
@@ -62,21 +60,19 @@ public class PolicyTargetsUpdater {
         if (isEmpty(policyTargets)) {
             return;
         }
-        
         policyTargets.remove(targetId);
         policy.setVersion(GroupUtils.updateVersion(PromoteVersionEnum.MINOR, policy.getVersion()));
     }
 
     private List<String> getTargetsList(PolicyDefinition policyDefinition, PolicyTargetType targetType) {
         Map<PolicyTargetType, List<String>> targets = policyDefinition.getTargets();
-        if(MapUtils.isEmpty(targets) || isEmpty(targets.get(targetType))) {
+        if (MapUtils.isEmpty(targets) || isEmpty(targets.get(targetType))) {
             return emptyList();
         }
         return targets.get(targetType);
     }
 
     private UnaryOperator<String> prevInstanceIdByNewInstanceId(String prevInstanceId, String newInstanceId) {
-        return instId -> instId.equals(prevInstanceId) ? newInstanceId: instId;
+        return instId -> instId.equals(prevInstanceId) ? newInstanceId : instId;
     }
-
 }
index ef2f8cb..ac6e89d 100644 (file)
  * limitations under the License.
  * ============LICENSE_END=========================================================
  */
-
 package org.openecomp.sdc.be.components.impl.policy;
 
+import static org.apache.commons.collections.CollectionUtils.isEmpty;
 
+import java.util.List;
+import java.util.function.Consumer;
 import org.openecomp.sdc.be.components.impl.version.OnChangeVersionCommand;
 import org.openecomp.sdc.be.dao.api.ActionStatus;
 import org.openecomp.sdc.be.datatypes.enums.PromoteVersionEnum;
@@ -33,30 +35,21 @@ import org.openecomp.sdc.be.model.operations.impl.UniqueIdBuilder;
 import org.openecomp.sdc.be.model.utils.GroupUtils;
 import org.openecomp.sdc.common.log.wrappers.Logger;
 
-import java.util.List;
-import java.util.function.Consumer;
-
-import static org.apache.commons.collections.CollectionUtils.isEmpty;
-
-
 /**
  * A Helper class which handles altering the version of a group
  */
 @org.springframework.stereotype.Component
 public class PolicyVersionUpdater implements OnChangeVersionCommand {
-    
+
     private static final Logger log = Logger.getLogger(PolicyVersionUpdater.class);
     private final ToscaOperationFacade toscaOperationFacade;
     private final ComponentsUtils componentsUtils;
-    
 
     public PolicyVersionUpdater(ToscaOperationFacade toscaOperationFacade, ComponentsUtils componentsUtils) {
         this.toscaOperationFacade = toscaOperationFacade;
         this.componentsUtils = componentsUtils;
-    
     }
-    
-    
+
     @Override
     public ActionStatus onChangeVersion(Component container) {
         log.debug("#onChangeVersion - replacing all group members for component instance");
@@ -68,21 +61,16 @@ public class PolicyVersionUpdater implements OnChangeVersionCommand {
         policies.forEach(policy -> increaseMajorVersion(policy));
     }
 
-  
     private void increaseMajorVersion(PolicyDefinition policy) {
         String version = policy.getVersion();
-        
         String newVersion = GroupUtils.updateVersion(PromoteVersionEnum.MAJOR, policy.getVersion());
-      
-        if(!version.equals(newVersion) ){           
+        if (!version.equals(newVersion)) {
             String groupUUID = UniqueIdBuilder.generateUUID();
             policy.setPolicyUUID(groupUUID);
             policy.setVersion(String.valueOf(newVersion));
         }
+    }
 
-    }    
-   
-    
     private ActionStatus updatePoliciesVersion(Component container, Consumer<List<PolicyDefinition>> updatePoliciesVersion) {
         List<PolicyDefinition> policies = container.resolvePoliciesList();
         if (isEmpty(policies)) {
@@ -90,15 +78,11 @@ public class PolicyVersionUpdater implements OnChangeVersionCommand {
         }
         updatePoliciesVersion.accept(policies);
         return updatePolicies(container, policies);
-    }  
+    }
 
-    
     private ActionStatus updatePolicies(Component policiesContainer, List<PolicyDefinition> policiesToUpdate) {
         log.debug("#updatePolicies - updating {} policies for container {}", policiesToUpdate.size(), policiesContainer.getUniqueId());
         StorageOperationStatus updatePolicyResult = toscaOperationFacade.updatePoliciesOfComponent(policiesContainer.getUniqueId(), policiesToUpdate);
         return componentsUtils.convertFromStorageResponse(updatePolicyResult, policiesContainer.getComponentType());
     }
-
 }
-
-
index 36c1e58..a7dd5af 100644 (file)
  * See the License for the specific language governing permissions and
  * limitations under the License.
  */
-
 package org.openecomp.sdc.be.components.impl.utils;
 
+import java.util.List;
+import java.util.Map;
+import java.util.stream.Collectors;
 import org.openecomp.sdc.be.datatypes.elements.CINodeFilterDataDefinition;
 import org.openecomp.sdc.be.datatypes.elements.ListDataDefinition;
 import org.openecomp.sdc.be.datatypes.elements.RequirementNodeFilterCapabilityDataDefinition;
@@ -25,22 +27,15 @@ import org.openecomp.sdc.be.model.UploadNodeFilterInfo;
 import org.openecomp.sdc.be.model.UploadNodeFilterPropertyInfo;
 import org.openecomp.sdc.common.log.wrappers.Logger;
 
-import java.util.List;
-import java.util.Map;
-import java.util.stream.Collectors;
-
 public class CINodeFilterUtils {
 
     Logger log = Logger.getLogger(CINodeFilterUtils.class);
 
-
-    public CINodeFilterDataDefinition getNodeFilterDataDefinition(
-            UploadNodeFilterInfo uploadNodeFilterInfo, String uniqueId) {
-        CINodeFilterDataDefinition nodeFilterDataDefinition =
-                new CINodeFilterDataDefinition();
+    public CINodeFilterDataDefinition getNodeFilterDataDefinition(UploadNodeFilterInfo uploadNodeFilterInfo, String uniqueId) {
+        CINodeFilterDataDefinition nodeFilterDataDefinition = new CINodeFilterDataDefinition();
         nodeFilterDataDefinition.setName(uploadNodeFilterInfo.getName());
-        List<RequirementNodeFilterPropertyDataDefinition> collect =
-                uploadNodeFilterInfo.getProperties().stream().map(this::buildProperty).collect(Collectors.toList());
+        List<RequirementNodeFilterPropertyDataDefinition> collect = uploadNodeFilterInfo.getProperties().stream().map(this::buildProperty)
+            .collect(Collectors.toList());
         ListDataDefinition<RequirementNodeFilterPropertyDataDefinition> listDataDefinition = new ListDataDefinition<>();
         listDataDefinition.getListToscaDataDefinition().addAll(collect);
         nodeFilterDataDefinition.setProperties(listDataDefinition);
@@ -51,38 +46,31 @@ public class CINodeFilterUtils {
     }
 
     private ListDataDefinition<RequirementNodeFilterCapabilityDataDefinition> converCapabilties(
-            Map<String, UploadNodeFilterCapabilitiesInfo> capabilities) {
-        ListDataDefinition<RequirementNodeFilterCapabilityDataDefinition> listDataDefinition =
-                new ListDataDefinition<>();
+        Map<String, UploadNodeFilterCapabilitiesInfo> capabilities) {
+        ListDataDefinition<RequirementNodeFilterCapabilityDataDefinition> listDataDefinition = new ListDataDefinition<>();
         for (UploadNodeFilterCapabilitiesInfo capability : capabilities.values()) {
-            RequirementNodeFilterCapabilityDataDefinition requirementNodeFilterCapabilityDataDefinition =
-                    convertCapability(capability);
+            RequirementNodeFilterCapabilityDataDefinition requirementNodeFilterCapabilityDataDefinition = convertCapability(capability);
             listDataDefinition.add(requirementNodeFilterCapabilityDataDefinition);
         }
         return listDataDefinition;
     }
 
-    private RequirementNodeFilterCapabilityDataDefinition convertCapability(
-            UploadNodeFilterCapabilitiesInfo capability) {
+    private RequirementNodeFilterCapabilityDataDefinition convertCapability(UploadNodeFilterCapabilitiesInfo capability) {
         RequirementNodeFilterCapabilityDataDefinition retVal = new RequirementNodeFilterCapabilityDataDefinition();
         retVal.setName(capability.getName());
-        List<RequirementNodeFilterPropertyDataDefinition> props =
-                capability.getProperties().stream().map(this::buildProperty).collect(Collectors.toList());
+        List<RequirementNodeFilterPropertyDataDefinition> props = capability.getProperties().stream().map(this::buildProperty)
+            .collect(Collectors.toList());
         ListDataDefinition<RequirementNodeFilterPropertyDataDefinition> propsList = new ListDataDefinition<>();
         propsList.getListToscaDataDefinition().addAll(props);
         retVal.setProperties(propsList);
         return retVal;
     }
 
-
-    private RequirementNodeFilterPropertyDataDefinition buildProperty(
-            UploadNodeFilterPropertyInfo uploadNodeFilterPropertyInfo) {
+    private RequirementNodeFilterPropertyDataDefinition buildProperty(UploadNodeFilterPropertyInfo uploadNodeFilterPropertyInfo) {
         RequirementNodeFilterPropertyDataDefinition retVal = new RequirementNodeFilterPropertyDataDefinition();
         retVal.setName(uploadNodeFilterPropertyInfo.getName());
         List<String> propertyConstraints = uploadNodeFilterPropertyInfo.getValues();
         retVal.setConstraints(propertyConstraints);
         return retVal;
     }
-
-
 }
index 20a294c..8deebb6 100644 (file)
@@ -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.
  * limitations under the License.
  * ============LICENSE_END=========================================================
  */
-
 package org.openecomp.sdc.be.components.impl.utils;
 
-import org.openecomp.sdc.be.model.CapabilityTypeDefinition;
-
 import java.util.Objects;
+import org.openecomp.sdc.be.model.CapabilityTypeDefinition;
 
 public class CapabilityTypeImportUtils {
 
@@ -33,16 +31,14 @@ public class CapabilityTypeImportUtils {
         if (capabilityType1 == capabilityType2) {
             return true;
         }
-        
         if (capabilityType1 == null || capabilityType2 == null) {
             return false;
         }
-        
-        return Objects.equals(capabilityType1.getType(), capabilityType2.getType()) &&
-                Objects.equals(capabilityType1.getVersion(), capabilityType2.getVersion()) &&
-                Objects.equals(capabilityType1.getDerivedFrom(), capabilityType2.getDerivedFrom()) &&
-                Objects.equals(capabilityType1.getValidSourceTypes(), capabilityType2.getValidSourceTypes()) &&
-                Objects.equals(capabilityType1.getDescription(), capabilityType2.getDescription()) &&
-                Objects.equals(capabilityType1.getProperties(), capabilityType2.getProperties());
+        return Objects.equals(capabilityType1.getType(), capabilityType2.getType()) && Objects
+            .equals(capabilityType1.getVersion(), capabilityType2.getVersion()) && Objects
+            .equals(capabilityType1.getDerivedFrom(), capabilityType2.getDerivedFrom()) && Objects
+            .equals(capabilityType1.getValidSourceTypes(), capabilityType2.getValidSourceTypes()) && Objects
+            .equals(capabilityType1.getDescription(), capabilityType2.getDescription()) && Objects
+            .equals(capabilityType1.getProperties(), capabilityType2.getProperties());
     }
 }
index 02176d9..038df27 100644 (file)
@@ -17,7 +17,6 @@
  * limitations under the License.
  * ============LICENSE_END=========================================================
  */
-
 package org.openecomp.sdc.be.components.impl.utils;
 
 import java.util.List;
@@ -37,46 +36,28 @@ public final class ComponentUtils {
     private ComponentUtils() {
     }
 
-    public static boolean checkArtifactInComponent(
-        Component component, String artifactId
-    ) {
-        Predicate<ArtifactDefinition> hasSameArtifactId =
-            ad -> ad != null && ad.getUniqueId().equals(artifactId);
-
-        return exists(component.getArtifacts(), hasSameArtifactId) ||
-            exists(component.getDeploymentArtifacts(), hasSameArtifactId) ||
-            exists(component.getToscaArtifacts(), hasSameArtifactId) ||
-            hasOperationImplementationWithUniqueId(component, artifactId) ||
-            isServiceAndHasApiArtifactWithUniqueId(component, hasSameArtifactId);
+    public static boolean checkArtifactInComponent(Component component, String artifactId) {
+        Predicate<ArtifactDefinition> hasSameArtifactId = ad -> ad != null && ad.getUniqueId().equals(artifactId);
+        return exists(component.getArtifacts(), hasSameArtifactId) || exists(component.getDeploymentArtifacts(), hasSameArtifactId) || exists(
+            component.getToscaArtifacts(), hasSameArtifactId) || hasOperationImplementationWithUniqueId(component, artifactId)
+            || isServiceAndHasApiArtifactWithUniqueId(component, hasSameArtifactId);
     }
 
-    private static boolean isServiceAndHasApiArtifactWithUniqueId(Component component,
-        Predicate<ArtifactDefinition> hasSameArtifactId) {
-        return component.getComponentType() == ComponentTypeEnum.SERVICE && exists(
-            ((Service) component).getServiceApiArtifacts(), hasSameArtifactId);
+    private static boolean isServiceAndHasApiArtifactWithUniqueId(Component component, Predicate<ArtifactDefinition> hasSameArtifactId) {
+        return component.getComponentType() == ComponentTypeEnum.SERVICE && exists(((Service) component).getServiceApiArtifacts(), hasSameArtifactId);
     }
 
     private static boolean hasOperationImplementationWithUniqueId(Component component, String artifactId) {
-        return findFirst(valueStream(component.getInterfaces())
-                .flatMap(v -> valueStream(v.getOperationsMap()))
-                .map(OperationDataDefinition::getImplementation),
-            e -> e != null && e.getUniqueId().equals(artifactId)
-        ).isPresent();
+        return findFirst(
+            valueStream(component.getInterfaces()).flatMap(v -> valueStream(v.getOperationsMap())).map(OperationDataDefinition::getImplementation),
+            e -> e != null && e.getUniqueId().equals(artifactId)).isPresent();
     }
 
-    public static boolean checkArtifactInResourceInstance(
-        Component component, String resourceInstanceId, String artifactId
-    ) {
-        Predicate<ComponentInstance> hasSameResourceId =
-            ri -> ri != null && ri.getUniqueId().equals(resourceInstanceId);
-
-        Predicate<ArtifactDefinition> hasSameArtifactId =
-            ad -> ad != null && ad.getUniqueId().equals(artifactId);
-
-        return findFirst(component.getComponentInstances(), hasSameResourceId).map(ri ->
-            exists(ri.getDeploymentArtifacts(), hasSameArtifactId) ||
-                exists(ri.getArtifacts(), hasSameArtifactId)
-        ).isPresent();
+    public static boolean checkArtifactInResourceInstance(Component component, String resourceInstanceId, String artifactId) {
+        Predicate<ComponentInstance> hasSameResourceId = ri -> ri != null && ri.getUniqueId().equals(resourceInstanceId);
+        Predicate<ArtifactDefinition> hasSameArtifactId = ad -> ad != null && ad.getUniqueId().equals(artifactId);
+        return findFirst(component.getComponentInstances(), hasSameResourceId)
+            .map(ri -> exists(ri.getDeploymentArtifacts(), hasSameArtifactId) || exists(ri.getArtifacts(), hasSameArtifactId)).isPresent();
     }
 
     private static <V> Optional<V> findFirst(List<V> ovs, Predicate<V> p) {
@@ -84,9 +65,7 @@ public final class ComponentUtils {
     }
 
     private static <K, V> boolean exists(Map<K, V> okvs, Predicate<V> p) {
-        return Optional.ofNullable(okvs)
-            .flatMap(kvs -> findFirst(kvs.values().stream(), p))
-            .isPresent();
+        return Optional.ofNullable(okvs).flatMap(kvs -> findFirst(kvs.values().stream(), p)).isPresent();
     }
 
     private static <V> Optional<V> findFirst(Stream<V> vs, Predicate<V> p) {
index 5d2f26a..b0ad5ef 100644 (file)
  * See the License for the specific language governing permissions and
  * limitations under the License.
  */
-
 package org.openecomp.sdc.be.components.impl.utils;
 
+import java.util.List;
+import java.util.Map;
 import lombok.Getter;
 import lombok.Setter;
 import org.openecomp.sdc.be.components.csar.CsarInfo;
@@ -23,11 +24,10 @@ import org.openecomp.sdc.be.model.ArtifactDefinition;
 import org.openecomp.sdc.be.model.NodeTypeInfo;
 import org.openecomp.sdc.be.model.ParsedToscaYamlInfo;
 
-import java.util.List;
-import java.util.Map;
 @Getter
 @Setter
 public class CreateServiceFromYamlParameter {
+
     private String yamlName;
     private ParsedToscaYamlInfo parsedToscaYamlInfo;
     private List<ArtifactDefinition> createdArtifacts;
index eb7e6ba..c759440 100644 (file)
@@ -16,7 +16,6 @@
  *  SPDX-License-Identifier: Apache-2.0
  *  ============LICENSE_END=========================================================
  */
-
 package org.openecomp.sdc.be.components.impl.utils;
 
 import java.util.List;
@@ -29,9 +28,7 @@ public class DirectivesUtil {
     private static Optional<String> getDirective(final String directiveValue) {
         final List<String> directives = ConfigurationManager.getConfigurationManager().getConfiguration().getDirectives();
         if (CollectionUtils.isNotEmpty(directives)) {
-            return directives.stream()
-                .filter(directiveValues -> directiveValues.equalsIgnoreCase(directiveValue))
-                .findFirst();
+            return directives.stream().filter(directiveValues -> directiveValues.equalsIgnoreCase(directiveValue)).findFirst();
         }
         return Optional.empty();
     }
@@ -42,5 +39,4 @@ public class DirectivesUtil {
         }
         return inDirectives.stream().allMatch(directive -> getDirective(directive).isPresent());
     }
-
 }
index ec4192c..316b82b 100644 (file)
@@ -40,27 +40,23 @@ public class ExceptionUtils {
         this.janusGraphDao = janusGraphDao;
     }
 
-    public <T> T rollBackAndThrow(ActionStatus actionStatus, String ... params) {
-         janusGraphDao.rollback();
-         throw new ByActionStatusComponentException(actionStatus, params);
-     }
+    public <T> T rollBackAndThrow(ActionStatus actionStatus, String... params) {
+        janusGraphDao.rollback();
+        throw new ByActionStatusComponentException(actionStatus, params);
+    }
 
     public <T> T rollBackAndThrow(ResponseFormat responseFormat) {
         janusGraphDao.rollback();
         throw new ByResponseFormatComponentException(responseFormat);
     }
 
-    public <T> T rollBackAndThrow(StorageOperationStatus status, String ... params) {
+    public <T> T rollBackAndThrow(StorageOperationStatus status, String... params) {
         janusGraphDao.rollback();
         throw new StorageException(status, params);
     }
 
-    public <T> T rollBackAndThrow(JanusGraphOperationStatus status, String ... params) {
+    public <T> T rollBackAndThrow(JanusGraphOperationStatus status, String... params) {
         janusGraphDao.rollback();
         throw new StorageException(status, params);
     }
-
-
-
-
 }
index 4516a22..e8ba2d1 100644 (file)
@@ -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.
  * limitations under the License.
  * ============LICENSE_END=========================================================
  */
-
 package org.openecomp.sdc.be.components.impl.utils;
 
-import org.openecomp.sdc.be.dao.utils.MapUtil;
-import org.openecomp.sdc.be.model.PolicyTypeDefinition;
-import org.openecomp.sdc.be.model.PropertyDefinition;
+import static org.apache.commons.collections.CollectionUtils.isNotEmpty;
+import static org.springframework.util.CollectionUtils.isEmpty;
 
 import java.util.List;
 import java.util.Map;
 import java.util.Objects;
-
-import static org.apache.commons.collections.CollectionUtils.isNotEmpty;
-import static org.springframework.util.CollectionUtils.isEmpty;
+import org.openecomp.sdc.be.dao.utils.MapUtil;
+import org.openecomp.sdc.be.model.PolicyTypeDefinition;
+import org.openecomp.sdc.be.model.PropertyDefinition;
 
 public class PolicyTypeImportUtils {
 
@@ -43,22 +41,15 @@ public class PolicyTypeImportUtils {
         if (pt1 == null || pt2 == null) {
             return false;
         }
-        return Objects.equals(pt1.getType(), pt2.getType()) &&
-                Objects.equals(pt1.getName(), pt2.getName()) &&
-                Objects.equals(pt1.getIcon(), pt2.getIcon()) &&
-                Objects.equals(pt1.getVersion(), pt2.getVersion()) &&
-                Objects.equals(pt1.getDerivedFrom(), pt2.getDerivedFrom()) &&
-                Objects.equals(pt1.getTargets(), pt2.getTargets()) &&
-                Objects.equals(pt1.getMetadata(), pt2.getMetadata()) &&
-                Objects.equals(pt1.getDescription(), pt2.getDescription()) &&
-                PolicyTypeImportUtils.isPolicyPropertiesEquals(pt1.getProperties(), pt2.getProperties());
+        return Objects.equals(pt1.getType(), pt2.getType()) && Objects.equals(pt1.getName(), pt2.getName()) && Objects
+            .equals(pt1.getIcon(), pt2.getIcon()) && Objects.equals(pt1.getVersion(), pt2.getVersion()) && Objects
+            .equals(pt1.getDerivedFrom(), pt2.getDerivedFrom()) && Objects.equals(pt1.getTargets(), pt2.getTargets()) && Objects
+            .equals(pt1.getMetadata(), pt2.getMetadata()) && Objects.equals(pt1.getDescription(), pt2.getDescription()) && PolicyTypeImportUtils
+            .isPolicyPropertiesEquals(pt1.getProperties(), pt2.getProperties());
     }
 
-    private static boolean isPolicyPropertiesEquals(List<PropertyDefinition> pt1Props,
-        List<PropertyDefinition> pt2Props) {
-        if ((pt1Props == pt2Props)
-            || pt1Props == null && isEmpty(pt2Props)
-            || pt2Props == null && isEmpty(pt1Props)) {
+    private static boolean isPolicyPropertiesEquals(List<PropertyDefinition> pt1Props, List<PropertyDefinition> pt2Props) {
+        if ((pt1Props == pt2Props) || pt1Props == null && isEmpty(pt2Props) || pt2Props == null && isEmpty(pt1Props)) {
             return true;
         } else if (!isPropertiesListSizesEquals(pt1Props, pt2Props)) {
             return false;
@@ -66,8 +57,8 @@ public class PolicyTypeImportUtils {
             // The two cases tested by these assertions should have been taken care of by the previous two tests
             assert (pt1Props != null && pt2Props != null);
             Map<String, PropertyDefinition> pt1PropsByName = MapUtil.toMap(pt1Props, PropertyDefinition::getName);
-            long numberOfEqualsProperties = pt2Props.stream()
-                .filter(pt2Prop -> policyPropertyEquals(pt1PropsByName.get(pt2Prop.getName()), pt2Prop)).count();
+            long numberOfEqualsProperties = pt2Props.stream().filter(pt2Prop -> policyPropertyEquals(pt1PropsByName.get(pt2Prop.getName()), pt2Prop))
+                .count();
             return numberOfEqualsProperties == pt1Props.size();
         }
     }
@@ -79,17 +70,13 @@ public class PolicyTypeImportUtils {
         if (pt1Prop == null || pt2Prop == null) {
             return false;
         }
-        return Objects.equals(pt1Prop.getDefaultValue(), pt2Prop.getDefaultValue()) &&
-               Objects.equals(pt1Prop.isDefinition(), pt2Prop.isDefinition()) &&
-               Objects.equals(pt1Prop.getDescription(), pt2Prop.getDescription()) &&
-               Objects.equals(pt1Prop.isPassword(), pt2Prop.isPassword()) &&
-               Objects.equals(pt1Prop.isRequired(), pt2Prop.isRequired()) &&
-               Objects.equals(pt1Prop.getSchemaType(), pt2Prop.getSchemaType()) &&
-               Objects.equals(pt1Prop.getType(), pt2Prop.getType());
+        return Objects.equals(pt1Prop.getDefaultValue(), pt2Prop.getDefaultValue()) && Objects.equals(pt1Prop.isDefinition(), pt2Prop.isDefinition())
+            && Objects.equals(pt1Prop.getDescription(), pt2Prop.getDescription()) && Objects.equals(pt1Prop.isPassword(), pt2Prop.isPassword())
+            && Objects.equals(pt1Prop.isRequired(), pt2Prop.isRequired()) && Objects.equals(pt1Prop.getSchemaType(), pt2Prop.getSchemaType())
+            && Objects.equals(pt1Prop.getType(), pt2Prop.getType());
     }
 
     private static boolean isPropertiesListSizesEquals(List<PropertyDefinition> pt1Props, List<PropertyDefinition> pt2Props) {
-        return (isEmpty(pt1Props) && isEmpty(pt2Props))
-            || (isNotEmpty(pt1Props) && isNotEmpty(pt2Props) && pt1Props.size() == pt2Props.size());
+        return (isEmpty(pt1Props) && isEmpty(pt2Props)) || (isNotEmpty(pt1Props) && isNotEmpty(pt2Props) && pt1Props.size() == pt2Props.size());
     }
 }
index eee84bb..d7f9292 100644 (file)
@@ -40,8 +40,7 @@ public class PMDictionaryValidator {
 
     public Optional<String> validateIfPmDictionary(String artifactType, byte[] decodedPayload) {
         if (isPmDictionary(artifactType)) {
-            return validate(decodedPayload).stream()
-                .reduce((a, b) -> a + "; " + b);
+            return validate(decodedPayload).stream().reduce((a, b) -> a + "; " + b);
         }
         return Optional.empty();
     }
@@ -54,9 +53,7 @@ public class PMDictionaryValidator {
         List<String> errors = new ArrayList<>();
         try {
             List<YamlDocumentValidationError> validationErrors = yamlContentValidator.validate(fileContent);
-            validationErrors.stream()
-                .map(this::formatErrorMessage)
-                .forEach(errors::add);
+            validationErrors.stream().map(this::formatErrorMessage).forEach(errors::add);
         } catch (Exception e) {
             errors.add(e.getMessage());
         }
@@ -64,10 +61,6 @@ public class PMDictionaryValidator {
     }
 
     private String formatErrorMessage(YamlDocumentValidationError error) {
-        return String.format("Document number: %d, Path: %s, Message: %s",
-            error.getYamlDocumentNumber(),
-            error.getPath(),
-            error.getMessage());
+        return String.format("Document number: %d, Path: %s, Message: %s", error.getYamlDocumentNumber(), error.getPath(), error.getMessage());
     }
-
 }
index de115b5..19cc14e 100644 (file)
  * limitations under the License.
  * ============LICENSE_END=========================================================
  */
-
 package org.openecomp.sdc.be.components.impl.version;
 
 import org.openecomp.sdc.be.dao.api.ActionStatus;
 import org.openecomp.sdc.be.model.Component;
 
-
 @FunctionalInterface
 public interface OnChangeVersionCommand {
-    
+
     /**
      * A side effect operation to execute when a component instance version was changed from {@code prevVersion} to {@code newVersion}
-     * @param container the container which contains the instance which is version was changed
+     *
+     * @param container   the container which contains the instance which is version was changed
      * @param prevVersion the previous version of the component instance.
-     * @param newVersion the new version of the component instance.
+     * @param newVersion  the new version of the component instance.
      * @return the status of the operation
      */
     ActionStatus onChangeVersion(Component container);
-
 }
index 13086c7..a6bc4d0 100644 (file)
  * limitations under the License.
  * ============LICENSE_END=========================================================
  */
-
 package org.openecomp.sdc.be.components.impl.version;
 
-import org.openecomp.sdc.be.dao.api.ActionStatus;
-import org.openecomp.sdc.be.model.Component;
-import org.openecomp.sdc.common.log.wrappers.Logger;
-
 import java.util.Iterator;
 import java.util.List;
 import java.util.function.Function;
-
-
-
+import org.openecomp.sdc.be.dao.api.ActionStatus;
+import org.openecomp.sdc.be.model.Component;
+import org.openecomp.sdc.common.log.wrappers.Logger;
 
 @org.springframework.stereotype.Component
 public class VesionUpdateHandler {
-    
-    private static final Logger log = Logger.getLogger(VesionUpdateHandler.class);
 
+    private static final Logger log = Logger.getLogger(VesionUpdateHandler.class);
     private final List<OnChangeVersionCommand> onChangeVersionOperations;
-    
-    public VesionUpdateHandler( List<OnChangeVersionCommand> onChangeVersionOperations) {
+
+    public VesionUpdateHandler(List<OnChangeVersionCommand> onChangeVersionOperations) {
         this.onChangeVersionOperations = onChangeVersionOperations;
     }
-    
-    
+
     public ActionStatus doPostChangeVersionCommand(Component container) {
-        log.debug("#doPostChangeVersionOperations - starting post change version operations for component {}. from instance {} to instance {}", container.getUniqueId());
+        log.debug("#doPostChangeVersionOperations - starting post change version operations for component {}. from instance {} to instance {}",
+            container.getUniqueId());
         Function<OnChangeVersionCommand, ActionStatus> vesionChangeTaskRunner = operation -> operation.onChangeVersion(container);
         return doOnChangeVesionOperations(vesionChangeTaskRunner);
     }
-    
+
     private ActionStatus doOnChangeVesionOperations(Function<OnChangeVersionCommand, ActionStatus> vesionChangeTaskRunner) {
         ActionStatus onVesionChangeResult = ActionStatus.OK;
         Iterator<OnChangeVersionCommand> onChangeVesionIter = onChangeVersionOperations.iterator();
-        while(onChangeVesionIter.hasNext() && onVesionChangeResult == ActionStatus.OK) {
+        while (onChangeVesionIter.hasNext() && onVesionChangeResult == ActionStatus.OK) {
             onVesionChangeResult = vesionChangeTaskRunner.apply(onChangeVesionIter.next());
         }
         return onVesionChangeResult;
     }
-    
-    
-  
-    
-
 }
index 7adc77f..757c789 100644 (file)
@@ -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.
  * limitations under the License.
  * ============LICENSE_END=========================================================
  */
-
 package org.openecomp.sdc.be.components.lifecycle;
 
 import fj.data.Either;
+import java.util.Arrays;
+import java.util.List;
+import java.util.Map;
+import java.util.Optional;
 import org.openecomp.sdc.be.components.impl.ComponentBusinessLogic;
 import org.openecomp.sdc.be.components.impl.ServiceBusinessLogic;
 import org.openecomp.sdc.be.components.impl.exceptions.ByResponseFormatComponentException;
@@ -52,38 +55,31 @@ import org.openecomp.sdc.common.log.wrappers.Logger;
 import org.openecomp.sdc.common.util.ValidationUtils;
 import org.openecomp.sdc.exception.ResponseFormat;
 
-import java.util.Arrays;
-import java.util.List;
-import java.util.Map;
-import java.util.Optional;
-
 public class CertificationChangeTransition extends LifeCycleTransition {
-    private static final  String ALLOTTED_CATEGORY = "Allotted Resource";
-    private static final  String DEPENDING_SRV_NAME = "depending_service_name";
-    private static final  String PROVIDING_SRV_NAME = "providing_service_name";
-    private static final  String PROVIDING_SRV_UUID = "providing_service_uuid";
-    private static final  String DEPENDING_SRV_UUID = "depending_service_uuid";
 
+    private static final String ALLOTTED_CATEGORY = "Allotted Resource";
+    private static final String DEPENDING_SRV_NAME = "depending_service_name";
+    private static final String PROVIDING_SRV_NAME = "providing_service_name";
+    private static final String PROVIDING_SRV_UUID = "providing_service_uuid";
+    private static final String DEPENDING_SRV_UUID = "depending_service_uuid";
     private static final Logger log = Logger.getLogger(CertificationChangeTransition.class);
-
     private LifecycleStateEnum nextState;
     private LifeCycleTransitionEnum name;
     private AuditingActionEnum auditingAction;
     private NodeTemplateOperation nodeTemplateOperation;
     private ServiceBusinessLogic serviceBusinessLogic;
 
-    public CertificationChangeTransition(ServiceBusinessLogic serviceBusinessLogic, LifeCycleTransitionEnum name, ComponentsUtils componentUtils, ToscaElementLifecycleOperation lifecycleOperation, ToscaOperationFacade toscaOperationFacade, JanusGraphDao janusGraphDao) {
+    public CertificationChangeTransition(ServiceBusinessLogic serviceBusinessLogic, LifeCycleTransitionEnum name, ComponentsUtils componentUtils,
+                                         ToscaElementLifecycleOperation lifecycleOperation, ToscaOperationFacade toscaOperationFacade,
+                                         JanusGraphDao janusGraphDao) {
         super(componentUtils, lifecycleOperation, toscaOperationFacade, janusGraphDao);
-
         this.name = name;
         this.serviceBusinessLogic = serviceBusinessLogic;
-
         // authorized roles
-        Role[] certificationChangeRoles = { Role.ADMIN, Role.DESIGNER };
-        Role[] resourceRoles = { Role.ADMIN, Role.DESIGNER};
+        Role[] certificationChangeRoles = {Role.ADMIN, Role.DESIGNER};
+        Role[] resourceRoles = {Role.ADMIN, Role.DESIGNER};
         addAuthorizedRoles(ComponentTypeEnum.RESOURCE, Arrays.asList(resourceRoles));
         addAuthorizedRoles(ComponentTypeEnum.SERVICE, Arrays.asList(certificationChangeRoles));
-
         this.auditingAction = AuditingActionEnum.CERTIFICATION_SUCCESS_RESOURCE;
         this.nextState = LifecycleStateEnum.CERTIFIED;
     }
@@ -109,57 +105,50 @@ public class CertificationChangeTransition extends LifeCycleTransition {
     private ResponseFormat formatCertificationError(Component component, StorageOperationStatus response, ComponentTypeEnum componentType) {
         BeEcompErrorManager.getInstance().logBeDaoSystemError("Change LifecycleState - Certify failed on graph");
         log.debug("certification change failed on graph");
-
         return componentUtils.getResponseFormatByComponent(componentUtils.convertFromStorageResponse(response), component, componentType);
     }
 
     @Override
-    public Either<Boolean, ResponseFormat> validateBeforeTransition(Component component, ComponentTypeEnum componentType, User modifier, User owner, LifecycleStateEnum oldState, LifecycleChangeInfoWithAction lifecycleChangeInfo) {
+    public Either<Boolean, ResponseFormat> validateBeforeTransition(Component component, ComponentTypeEnum componentType, User modifier, User owner,
+                                                                    LifecycleStateEnum oldState, LifecycleChangeInfoWithAction lifecycleChangeInfo) {
         String componentName = component.getComponentMetadataDefinition().getMetadataDataDefinition().getName();
         log.info("validate before certification change. resource name={}, oldState={}, owner userId={}", componentName, oldState, owner.getUserId());
-
         // validate user
-        Either<Boolean, ResponseFormat> userValidationResponse = userRoleValidation(modifier,component, componentType, lifecycleChangeInfo);
+        Either<Boolean, ResponseFormat> userValidationResponse = userRoleValidation(modifier, component, componentType, lifecycleChangeInfo);
         if (userValidationResponse.isRight()) {
             log.debug("userRoleValidation failed");
             return userValidationResponse;
         }
-
         if (oldState != LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT && oldState != LifecycleStateEnum.NOT_CERTIFIED_CHECKIN) {
             log.debug("Valid states for certification are NOT_CERTIFIED_CHECKIN and NOT_CERTIFIED_CHECKOUT. {} is invalid state", oldState);
-            ResponseFormat error = componentUtils.getResponseFormat(ActionStatus.ILLEGAL_COMPONENT_STATE, componentName, componentType.name().toLowerCase(), oldState.name());
+            ResponseFormat error = componentUtils
+                .getResponseFormat(ActionStatus.ILLEGAL_COMPONENT_STATE, componentName, componentType.name().toLowerCase(), oldState.name());
             return Either.right(error);
         }
         return Either.left(true);
     }
 
     @Override
-    public <T extends Component> Either<T, ResponseFormat> changeState(
-        ComponentTypeEnum componentType,
-        Component component,
-        ComponentBusinessLogic componentBl, User modifier, User owner, boolean shouldLock, boolean inTransaction
-    ) {
-
+    public <T extends Component> Either<T, ResponseFormat> changeState(ComponentTypeEnum componentType, Component component,
+                                                                       ComponentBusinessLogic componentBl, User modifier, User owner,
+                                                                       boolean shouldLock, boolean inTransaction) {
         log.info("start performing certification change for resource {}", component.getUniqueId());
         Either<T, ResponseFormat> result = null;
-
         try {
             handleValidationsAndArtifactsGenerationBeforeCertifying(componentType, component, componentBl, modifier, shouldLock, inTransaction);
-            Either<ToscaElement, StorageOperationStatus> certificationChangeResult =
-                    lifeCycleOperation.certifyToscaElement(component.getUniqueId(), modifier.getUserId(), owner.getUserId());
-
+            Either<ToscaElement, StorageOperationStatus> certificationChangeResult = lifeCycleOperation
+                .certifyToscaElement(component.getUniqueId(), modifier.getUserId(), owner.getUserId());
             if (certificationChangeResult.isRight()) {
                 ResponseFormat responseFormat = formatCertificationError(component, certificationChangeResult.right().value(), componentType);
                 result = Either.right(responseFormat);
                 return result;
             }
-
             ToscaElement certificationResult = certificationChangeResult.left().value();
             T componentAfterCertification = ModelConverter.convertFromToscaElement(certificationResult);
-            if ( result == null || result.isLeft() ){
+            if (result == null || result.isLeft()) {
                 //update edges for allotted resource 
                 StorageOperationStatus status = handleConnectionsForAllotted(componentAfterCertification);
-                if ( status != StorageOperationStatus.OK){
+                if (status != StorageOperationStatus.OK) {
                     ResponseFormat responseFormat = formatCertificationError(componentAfterCertification, status, componentType);
                     result = Either.right(responseFormat);
                 }
@@ -171,59 +160,55 @@ public class CertificationChangeTransition extends LifeCycleTransition {
         } finally {
             if (result == null || result.isRight()) {
                 BeEcompErrorManager.getInstance().logBeDaoSystemError("Change LifecycleState");
-                if ( !inTransaction ) {
+                if (!inTransaction) {
                     log.debug("operation failed. do rollback");
                     janusGraphDao.rollback();
                 }
             } else {
-                if ( !inTransaction ) {
+                if (!inTransaction) {
                     log.debug("operation success. do commit");
                     janusGraphDao.commit();
                 }
             }
         }
-
     }
 
     private void updateCapReqPropertiesOwnerId(Component component) {
-        if(component.isTopologyTemplate() && ToscaUtils.isNotComplexVfc(component)) {
+        if (component.isTopologyTemplate() && ToscaUtils.isNotComplexVfc(component)) {
             toscaOperationFacade.updateCapReqPropertiesOwnerId(component.getUniqueId());
         }
     }
 
     Either<Boolean, ResponseFormat> validateAllResourceInstanceCertified(Component component) {
         Either<Boolean, ResponseFormat> eitherResult = Either.left(true);
-
-        if (component.isVspArchived()){
-            return Either.right(componentUtils.getResponseFormat(ActionStatus.ARCHIVED_ORIGINS_FOUND, component.getComponentType().name(), component.getName()));
+        if (component.isVspArchived()) {
+            return Either.right(
+                componentUtils.getResponseFormat(ActionStatus.ARCHIVED_ORIGINS_FOUND, component.getComponentType().name(), component.getName()));
         }
-
         List<ComponentInstance> resourceInstance = component.getComponentInstances();
         if (resourceInstance != null) {
-
             //Filter components instances with archived origins
-            Optional<ComponentInstance> archivedRIOptional = resourceInstance.stream().filter(ComponentInstanceDataDefinition::isOriginArchived).findAny();
-
+            Optional<ComponentInstance> archivedRIOptional = resourceInstance.stream().filter(ComponentInstanceDataDefinition::isOriginArchived)
+                .findAny();
             //RIs with archived origins found, return relevant error
-            if (archivedRIOptional.isPresent()){
-                return Either.right(componentUtils.getResponseFormat(ActionStatus.ARCHIVED_ORIGINS_FOUND, component.getComponentType().name(), component.getName()));
+            if (archivedRIOptional.isPresent()) {
+                return Either.right(
+                    componentUtils.getResponseFormat(ActionStatus.ARCHIVED_ORIGINS_FOUND, component.getComponentType().name(), component.getName()));
             }
-
             //Continue with searching for non certified RIs
-            Optional<ComponentInstance> nonCertifiedRIOptional = resourceInstance.stream().filter(p -> !ValidationUtils.validateCertifiedVersion(p.getComponentVersion())).findAny();
+            Optional<ComponentInstance> nonCertifiedRIOptional = resourceInstance.stream()
+                .filter(p -> !ValidationUtils.validateCertifiedVersion(p.getComponentVersion())).findAny();
             // Uncertified Resource Found
             if (nonCertifiedRIOptional.isPresent()) {
                 ComponentInstance nonCertifiedRI = nonCertifiedRIOptional.get();
                 ResponseFormat resFormat = getRelevantResponseFormatUncertifiedRI(nonCertifiedRI, component.getComponentType());
                 eitherResult = Either.right(resFormat);
             }
-
         }
         return eitherResult;
     }
 
     private ResponseFormat getRelevantResponseFormatUncertifiedRI(ComponentInstance nonCertifiedRI, ComponentTypeEnum componentType) {
-
         Either<Resource, StorageOperationStatus> eitherResource = toscaOperationFacade.getToscaElement(nonCertifiedRI.getComponentUid());
         if (eitherResource.isRight()) {
             return componentUtils.getResponseFormat(ActionStatus.GENERAL_ERROR);
@@ -231,7 +216,6 @@ public class CertificationChangeTransition extends LifeCycleTransition {
         ActionStatus actionStatus;
         Resource resource = eitherResource.left().value();
         Either<Resource, StorageOperationStatus> status = toscaOperationFacade.findLastCertifiedToscaElementByUUID(resource);
-
         if (ValidationUtils.validateMinorVersion(nonCertifiedRI.getComponentVersion())) {
             if (status.isRight() || status.left().value() == null) {
                 actionStatus = ActionStatus.VALIDATED_RESOURCE_NOT_FOUND;
@@ -248,7 +232,9 @@ public class CertificationChangeTransition extends LifeCycleTransition {
         return componentUtils.getResponseFormat(actionStatus, componentType == ComponentTypeEnum.RESOURCE ? "VF" : "service", resource.getName());
     }
 
-    private void handleValidationsAndArtifactsGenerationBeforeCertifying(ComponentTypeEnum componentType, Component component, ComponentBusinessLogic componentBl, User modifier, boolean shouldLock, boolean inTransaction) {
+    private void handleValidationsAndArtifactsGenerationBeforeCertifying(ComponentTypeEnum componentType, Component component,
+                                                                         ComponentBusinessLogic componentBl, User modifier, boolean shouldLock,
+                                                                         boolean inTransaction) {
         if (component.isTopologyTemplate()) {
             Either<Boolean, ResponseFormat> statusCert = validateAllResourceInstanceCertified(component);
             if (statusCert.isRight()) {
@@ -256,37 +242,35 @@ public class CertificationChangeTransition extends LifeCycleTransition {
             }
         }
         if (componentType == ComponentTypeEnum.SERVICE) {
-
-            Either<Service, ResponseFormat> generateHeatEnvResult = serviceBusinessLogic.generateHeatEnvArtifacts((Service) component, modifier, shouldLock, inTransaction);
-
+            Either<Service, ResponseFormat> generateHeatEnvResult = serviceBusinessLogic
+                .generateHeatEnvArtifacts((Service) component, modifier, shouldLock, inTransaction);
             if (generateHeatEnvResult.isRight()) {
                 throw new ByResponseFormatComponentException(generateHeatEnvResult.right().value());
             }
-            Either<Service, ResponseFormat> generateVfModuleResult = serviceBusinessLogic.generateVfModuleArtifacts(generateHeatEnvResult.left().value(), modifier, shouldLock, inTransaction);
+            Either<Service, ResponseFormat> generateVfModuleResult = serviceBusinessLogic
+                .generateVfModuleArtifacts(generateHeatEnvResult.left().value(), modifier, shouldLock, inTransaction);
             if (generateVfModuleResult.isRight()) {
                 throw new ByResponseFormatComponentException(generateVfModuleResult.right().value());
             }
             component = generateVfModuleResult.left().value();
         }
-
         componentBl.populateToscaArtifacts(component, modifier, true, inTransaction, shouldLock);
     }
 
-
     private void updateCalculatedCapabilitiesRequirements(Component certifiedComponent) {
-        if(certifiedComponent.getComponentType() == ComponentTypeEnum.SERVICE){
+        if (certifiedComponent.getComponentType() == ComponentTypeEnum.SERVICE) {
             toscaOperationFacade.updateNamesOfCalculatedCapabilitiesRequirements(certifiedComponent.getUniqueId());
         }
     }
 
-    private StorageOperationStatus handleConnectionsForAllotted(Component component){
+    private StorageOperationStatus handleConnectionsForAllotted(Component component) {
         StorageOperationStatus status = StorageOperationStatus.OK;
-        if (component.getComponentType() == ComponentTypeEnum.RESOURCE && component.isTopologyTemplate()  ){
+        if (component.getComponentType() == ComponentTypeEnum.RESOURCE && component.isTopologyTemplate(){
             List<CategoryDefinition> categories = component.getCategories();
-            Optional<CategoryDefinition> findFirst = categories.stream().filter(c->c.getName().equals(ALLOTTED_CATEGORY)).findFirst();
-            if ( findFirst.isPresent() ){
+            Optional<CategoryDefinition> findFirst = categories.stream().filter(c -> c.getName().equals(ALLOTTED_CATEGORY)).findFirst();
+            if (findFirst.isPresent()) {
                 findInstanceByAllottedProperties(component);
-            }else{
+            } else {
                 log.debug("Component isn't from allotted category.");
             }
         }
@@ -297,27 +281,29 @@ public class CertificationChangeTransition extends LifeCycleTransition {
         log.debug("Component is from alloted category. Remove all previous ALLOTTED_OF connections for all instances");
         nodeTemplateOperation.removeAllAllotedEdges(component.getUniqueId());
         Map<String, List<ComponentInstanceProperty>> componentInstancesProperties = component.getComponentInstancesProperties();
-        if ( componentInstancesProperties != null ){
-            componentInstancesProperties.entrySet().forEach(e->{
+        if (componentInstancesProperties != null) {
+            componentInstancesProperties.entrySet().forEach(e -> {
                 List<ComponentInstanceProperty> props = e.getValue();
-                Optional<ComponentInstanceProperty> findProp = props.stream().filter(p -> p.getName().equals(DEPENDING_SRV_NAME) ||  p.getName().equals(PROVIDING_SRV_NAME)).findFirst();
-                if ( findProp.isPresent() ){
-                    log.debug("Find specific properties [{} or {}]on instance {} ", DEPENDING_SRV_NAME,PROVIDING_SRV_NAME, e.getKey()  );
-                    handleAllotedInstance(component.getUniqueId(), e.getKey(), e.getValue() );
-                }else{
-                    log.debug("Not defined specific properties [{} or {}]on instance {} ", DEPENDING_SRV_NAME,PROVIDING_SRV_NAME, e.getKey()  );
+                Optional<ComponentInstanceProperty> findProp = props.stream()
+                    .filter(p -> p.getName().equals(DEPENDING_SRV_NAME) || p.getName().equals(PROVIDING_SRV_NAME)).findFirst();
+                if (findProp.isPresent()) {
+                    log.debug("Find specific properties [{} or {}]on instance {} ", DEPENDING_SRV_NAME, PROVIDING_SRV_NAME, e.getKey());
+                    handleAllotedInstance(component.getUniqueId(), e.getKey(), e.getValue());
+                } else {
+                    log.debug("Not defined specific properties [{} or {}]on instance {} ", DEPENDING_SRV_NAME, PROVIDING_SRV_NAME, e.getKey());
                 }
             });
         }
     }
 
     private StorageOperationStatus handleAllotedInstance(String componentId, String instanceId, List<ComponentInstanceProperty> props) {
-        ComponentInstanceProperty serviceUUIDProp = props.stream().filter(p -> p.getName().equals(PROVIDING_SRV_UUID) ||  p.getName().equals(DEPENDING_SRV_UUID)).findFirst().get();
-        if ( serviceUUIDProp.getValue() != null && !serviceUUIDProp.getValue().contains("get_input")){
-            log.debug("Handle Allotted edge on instance {} for service UUID {} ", instanceId,  serviceUUIDProp.getValue() );
-            return  nodeTemplateOperation.createAllottedOfEdge(componentId, instanceId, serviceUUIDProp.getValue());
-        }else{
-            log.debug("An incorrectly defined service UUID for Allotted instance {} . Skip instance", instanceId,  serviceUUIDProp.getValue() );
+        ComponentInstanceProperty serviceUUIDProp = props.stream()
+            .filter(p -> p.getName().equals(PROVIDING_SRV_UUID) || p.getName().equals(DEPENDING_SRV_UUID)).findFirst().get();
+        if (serviceUUIDProp.getValue() != null && !serviceUUIDProp.getValue().contains("get_input")) {
+            log.debug("Handle Allotted edge on instance {} for service UUID {} ", instanceId, serviceUUIDProp.getValue());
+            return nodeTemplateOperation.createAllottedOfEdge(componentId, instanceId, serviceUUIDProp.getValue());
+        } else {
+            log.debug("An incorrectly defined service UUID for Allotted instance {} . Skip instance", instanceId, serviceUUIDProp.getValue());
             return StorageOperationStatus.OK;
         }
     }
index db4bef4..71c41ca 100644 (file)
@@ -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.
  * limitations under the License.
  * ============LICENSE_END=========================================================
  */
-
 package org.openecomp.sdc.be.components.lifecycle;
 
 import fj.data.Either;
+import java.util.Arrays;
 import org.openecomp.sdc.be.components.impl.ComponentBusinessLogic;
 import org.openecomp.sdc.be.components.impl.version.VesionUpdateHandler;
 import org.openecomp.sdc.be.config.BeEcompErrorManager;
@@ -44,24 +44,21 @@ import org.openecomp.sdc.be.user.Role;
 import org.openecomp.sdc.common.log.wrappers.Logger;
 import org.openecomp.sdc.exception.ResponseFormat;
 
-import java.util.Arrays;
-
 public class CheckinTransition extends LifeCycleTransition {
 
     private static final Logger log = Logger.getLogger(CheckinTransition.class);
-
     private VesionUpdateHandler vesionUpdateHandler;
 
-    public CheckinTransition(ComponentsUtils componentUtils, ToscaElementLifecycleOperation lifecycleOperation, ToscaOperationFacade toscaOperationFacade, JanusGraphDao janusGraphDao,  VesionUpdateHandler groupUpdateHandler) {
+    public CheckinTransition(ComponentsUtils componentUtils, ToscaElementLifecycleOperation lifecycleOperation,
+                             ToscaOperationFacade toscaOperationFacade, JanusGraphDao janusGraphDao, VesionUpdateHandler groupUpdateHandler) {
         super(componentUtils, lifecycleOperation, toscaOperationFacade, janusGraphDao);
         this.vesionUpdateHandler = groupUpdateHandler;
         // authorized roles
-        Role[] resourceServiceCheckoutRoles = { Role.ADMIN, Role.DESIGNER };
-        Role[] productCheckoutRoles = { Role.ADMIN, Role.PRODUCT_MANAGER };
+        Role[] resourceServiceCheckoutRoles = {Role.ADMIN, Role.DESIGNER};
+        Role[] productCheckoutRoles = {Role.ADMIN, Role.PRODUCT_MANAGER};
         addAuthorizedRoles(ComponentTypeEnum.RESOURCE, Arrays.asList(resourceServiceCheckoutRoles));
         addAuthorizedRoles(ComponentTypeEnum.SERVICE, Arrays.asList(resourceServiceCheckoutRoles));
         addAuthorizedRoles(ComponentTypeEnum.PRODUCT, Arrays.asList(productCheckoutRoles));
-
     }
 
     @Override
@@ -75,32 +72,28 @@ public class CheckinTransition extends LifeCycleTransition {
     }
 
     @Override
-    public Either<? extends Component, ResponseFormat> changeState(ComponentTypeEnum componentType, Component component, ComponentBusinessLogic componentBl, User modifier, User owner, boolean shouldLock, boolean inTransaction) {
+    public Either<? extends Component, ResponseFormat> changeState(ComponentTypeEnum componentType, Component component,
+                                                                   ComponentBusinessLogic componentBl, User modifier, User owner, boolean shouldLock,
+                                                                   boolean inTransaction) {
         log.debug("start performing checkin for {} {}", componentType, component.getUniqueId());
-
         Either<? extends Component, ResponseFormat> result = null;
-        try{
-            Either<ToscaElement, StorageOperationStatus> checkinResourceResult = lifeCycleOperation.
-                    checkinToscaELement(component.getLifecycleState(), component.getUniqueId(), modifier.getUserId(), owner.getUserId());
-
+        try {
+            Either<ToscaElement, StorageOperationStatus> checkinResourceResult = lifeCycleOperation
+                .checkinToscaELement(component.getLifecycleState(), component.getUniqueId(), modifier.getUserId(), owner.getUserId());
             if (checkinResourceResult.isRight()) {
                 log.debug("checkout failed on graph");
                 StorageOperationStatus response = checkinResourceResult.right().value();
                 ActionStatus actionStatus = componentUtils.convertFromStorageResponse(response);
-
                 if (response.equals(StorageOperationStatus.ENTITY_ALREADY_EXISTS)) {
                     actionStatus = ActionStatus.COMPONENT_VERSION_ALREADY_EXIST;
                 }
                 ResponseFormat responseFormat = componentUtils.getResponseFormatByComponent(actionStatus, component, componentType);
-                result =  Either.right(responseFormat);
-            }
-            else {
+                result = Either.right(responseFormat);
+            } else {
                 updateCalculatedCapabilitiesRequirements(checkinResourceResult.left().value());
                 Component r = ModelConverter.convertFromToscaElement(checkinResourceResult.left().value());
                 updateGroupsAndPolicesVersion(r);
-                result =  Either.left(r);
-
-
+                result = Either.left(r);
             }
         } finally {
             if (result == null || result.isRight()) {
@@ -124,35 +117,37 @@ public class CheckinTransition extends LifeCycleTransition {
     }
 
     @Override
-    public Either<Boolean, ResponseFormat> validateBeforeTransition(Component component, ComponentTypeEnum componentType, User modifier, User owner, LifecycleStateEnum oldState, LifecycleChangeInfoWithAction lifecycleChangeInfo) {
+    public Either<Boolean, ResponseFormat> validateBeforeTransition(Component component, ComponentTypeEnum componentType, User modifier, User owner,
+                                                                    LifecycleStateEnum oldState, LifecycleChangeInfoWithAction lifecycleChangeInfo) {
         String componentName = component.getComponentMetadataDefinition().getMetadataDataDefinition().getName();
         log.debug("validate before checkin. component name={}, oldState={}, owner userId={}", componentName, oldState, owner.getUserId());
-
         // validate user
-        Either<Boolean, ResponseFormat> userValidationResponse = userRoleValidation(modifier,component, componentType, lifecycleChangeInfo);
+        Either<Boolean, ResponseFormat> userValidationResponse = userRoleValidation(modifier, component, componentType, lifecycleChangeInfo);
         if (userValidationResponse.isRight()) {
             return userValidationResponse;
         }
-
         if (!oldState.equals(LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT)) {
             ActionStatus action = ActionStatus.COMPONENT_ALREADY_CHECKED_IN;
-            if (oldState.equals(LifecycleStateEnum.CERTIFIED)){
+            if (oldState.equals(LifecycleStateEnum.CERTIFIED)) {
                 action = ActionStatus.COMPONENT_ALREADY_CERTIFIED;
             }
-            ResponseFormat error = componentUtils.getResponseFormat(action, componentName, componentType.name().toLowerCase(), owner.getFirstName(), owner.getLastName(), owner.getUserId());
+            ResponseFormat error = componentUtils
+                .getResponseFormat(action, componentName, componentType.name().toLowerCase(), owner.getFirstName(), owner.getLastName(),
+                    owner.getUserId());
             return Either.right(error);
         }
-
-        if (oldState.equals(LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT) && !modifier.getUserId().equals(owner.getUserId()) && !modifier.getRole().equals(Role.ADMIN.name())) {
-            ResponseFormat error = componentUtils.getResponseFormat(ActionStatus.COMPONENT_CHECKOUT_BY_ANOTHER_USER, componentName, componentType.name().toLowerCase(), owner.getFirstName(), owner.getLastName(), owner.getUserId());
+        if (oldState.equals(LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT) && !modifier.getUserId().equals(owner.getUserId()) && !modifier.getRole()
+            .equals(Role.ADMIN.name())) {
+            ResponseFormat error = componentUtils
+                .getResponseFormat(ActionStatus.COMPONENT_CHECKOUT_BY_ANOTHER_USER, componentName, componentType.name().toLowerCase(),
+                    owner.getFirstName(), owner.getLastName(), owner.getUserId());
             return Either.right(error);
         }
-
         return Either.left(true);
     }
 
     private void updateCalculatedCapabilitiesRequirements(ToscaElement toscaElement) {
-        if(toscaElement.getToscaType() == ToscaElementTypeEnum.TOPOLOGY_TEMPLATE && toscaElement.getResourceType() != ResourceTypeEnum.CVFC){
+        if (toscaElement.getToscaType() == ToscaElementTypeEnum.TOPOLOGY_TEMPLATE && toscaElement.getResourceType() != ResourceTypeEnum.CVFC) {
             toscaOperationFacade.updateNamesOfCalculatedCapabilitiesRequirements(toscaElement.getUniqueId());
         }
     }
index 352371c..44505ec 100644 (file)
@@ -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.
  * limitations under the License.
  * ============LICENSE_END=========================================================
  */
-
 package org.openecomp.sdc.be.components.lifecycle;
 
 import fj.data.Either;
+import java.util.Arrays;
+import java.util.List;
 import org.openecomp.sdc.be.components.impl.ComponentBusinessLogic;
 import org.openecomp.sdc.be.config.BeEcompErrorManager;
 import org.openecomp.sdc.be.dao.api.ActionStatus;
@@ -48,23 +49,19 @@ import org.openecomp.sdc.be.user.Role;
 import org.openecomp.sdc.common.log.wrappers.Logger;
 import org.openecomp.sdc.exception.ResponseFormat;
 
-import java.util.Arrays;
-import java.util.List;
-
 public class CheckoutTransition extends LifeCycleTransition {
 
     private static final Logger log = Logger.getLogger(CheckoutTransition.class);
 
-    CheckoutTransition(ComponentsUtils componentUtils, ToscaElementLifecycleOperation lifecycleOperation, ToscaOperationFacade toscaOperationFacade, JanusGraphDao janusGraphDao) {
+    CheckoutTransition(ComponentsUtils componentUtils, ToscaElementLifecycleOperation lifecycleOperation, ToscaOperationFacade toscaOperationFacade,
+                       JanusGraphDao janusGraphDao) {
         super(componentUtils, lifecycleOperation, toscaOperationFacade, janusGraphDao);
-
         // authorized roles
-        Role[] resourceServiceCheckoutRoles = { Role.ADMIN, Role.DESIGNER };
-        Role[] productCheckoutRoles = { Role.ADMIN, Role.PRODUCT_MANAGER };
+        Role[] resourceServiceCheckoutRoles = {Role.ADMIN, Role.DESIGNER};
+        Role[] productCheckoutRoles = {Role.ADMIN, Role.PRODUCT_MANAGER};
         addAuthorizedRoles(ComponentTypeEnum.RESOURCE, Arrays.asList(resourceServiceCheckoutRoles));
         addAuthorizedRoles(ComponentTypeEnum.SERVICE, Arrays.asList(resourceServiceCheckoutRoles));
         addAuthorizedRoles(ComponentTypeEnum.PRODUCT, Arrays.asList(productCheckoutRoles));
-
     }
 
     @Override
@@ -78,39 +75,36 @@ public class CheckoutTransition extends LifeCycleTransition {
     }
 
     @Override
-    public Either<? extends Component, ResponseFormat> changeState(ComponentTypeEnum componentType, Component component, ComponentBusinessLogic componentBl, User modifier, User owner, boolean shouldLock, boolean inTransaction) {
-
+    public Either<? extends Component, ResponseFormat> changeState(ComponentTypeEnum componentType, Component component,
+                                                                   ComponentBusinessLogic componentBl, User modifier, User owner, boolean shouldLock,
+                                                                   boolean inTransaction) {
         log.debug("start performing {} for resource {}", getName(), component.getUniqueId());
-
         Either<? extends Component, ResponseFormat> result = null;
         try {
-
-            Either<ToscaElement, StorageOperationStatus> checkoutResourceResult = lifeCycleOperation.checkoutToscaElement(component.getUniqueId(), modifier.getUserId(), owner.getUserId());
-
+            Either<ToscaElement, StorageOperationStatus> checkoutResourceResult = lifeCycleOperation
+                .checkoutToscaElement(component.getUniqueId(), modifier.getUserId(), owner.getUserId());
             if (checkoutResourceResult.isRight()) {
                 log.debug("checkout failed on graph");
                 StorageOperationStatus response = checkoutResourceResult.right().value();
                 ActionStatus actionStatus = componentUtils.convertFromStorageResponse(response);
-
                 if (response.equals(StorageOperationStatus.ENTITY_ALREADY_EXISTS)) {
                     actionStatus = ActionStatus.COMPONENT_VERSION_ALREADY_EXIST;
                 }
                 ResponseFormat responseFormat = componentUtils.getResponseFormatByComponent(actionStatus, component, componentType);
                 result = Either.right(responseFormat);
             } else {
-
                 Component clonedComponent = ModelConverter.convertFromToscaElement(checkoutResourceResult.left().value());
-                if(componentType == ComponentTypeEnum.SERVICE) {
-                    Service service = (Service)clonedComponent;
+                if (componentType == ComponentTypeEnum.SERVICE) {
+                    Service service = (Service) clonedComponent;
                     service.validateAndSetInstantiationType();
                 }
-                if ( checkoutResourceResult.left().value().getToscaType() == ToscaElementTypeEnum.NODE_TYPE ){
+                if (checkoutResourceResult.left().value().getToscaType() == ToscaElementTypeEnum.NODE_TYPE) {
                     Either<Component, ActionStatus> upgradeToLatestDerived = componentBl.shouldUpgradeToLatestDerived(clonedComponent);
-                    if (upgradeToLatestDerived.isRight() && ActionStatus.OK != upgradeToLatestDerived.right().value()){
+                    if (upgradeToLatestDerived.isRight() && ActionStatus.OK != upgradeToLatestDerived.right().value()) {
                         result = Either.right(componentUtils.getResponseFormat(upgradeToLatestDerived.right().value()));
                         return result;
                     }
-                    if ( upgradeToLatestDerived.isLeft() ){
+                    if (upgradeToLatestDerived.isLeft()) {
                         //get resource after update derived
                         clonedComponent = upgradeToLatestDerived.left().value();
                     }
@@ -119,7 +113,7 @@ public class CheckoutTransition extends LifeCycleTransition {
                 Either<Boolean, ResponseFormat> upgradeToLatestGeneric = componentBl.shouldUpgradeToLatestGeneric(clonedComponent);
                 if (upgradeToLatestGeneric.isRight()) {
                     result = Either.right(upgradeToLatestGeneric.right().value());
-                } else if (upgradeToLatestGeneric.left().value()  ) {
+                } else if (upgradeToLatestGeneric.left().value()) {
                     StorageOperationStatus response = upgradeToLatestGenericData(clonedComponent);
                     if (StorageOperationStatus.OK != response) {
                         ActionStatus actionStatus = componentUtils.convertFromStorageResponse(response);
@@ -128,9 +122,8 @@ public class CheckoutTransition extends LifeCycleTransition {
                     }
                 }
                 handleCalculatedCapabilitiesRequirements(clonedComponent);
-               updateCapReqPropertiesOwnerId(clonedComponent);
+                updateCapReqPropertiesOwnerId(clonedComponent);
             }
-
         } finally {
             if (result == null || result.isRight()) {
                 BeEcompErrorManager.getInstance().logBeDaoSystemError("Change LifecycleState");
@@ -149,34 +142,36 @@ public class CheckoutTransition extends LifeCycleTransition {
     }
 
     private void handleCalculatedCapabilitiesRequirements(Component clonedComponent) {
-        if(clonedComponent.isTopologyTemplate() && ToscaUtils.isNotComplexVfc(clonedComponent)){
+        if (clonedComponent.isTopologyTemplate() && ToscaUtils.isNotComplexVfc(clonedComponent)) {
             toscaOperationFacade.revertNamesOfCalculatedCapabilitiesRequirements(clonedComponent.getUniqueId());
         }
     }
 
     private void updateCapReqPropertiesOwnerId(Component component) {
-        if(component.isTopologyTemplate() && ToscaUtils.isNotComplexVfc(component)) {
+        if (component.isTopologyTemplate() && ToscaUtils.isNotComplexVfc(component)) {
             toscaOperationFacade.updateCapReqPropertiesOwnerId(component.getUniqueId());
         }
     }
-    private StorageOperationStatus upgradeToLatestGenericData(Component clonedComponent) {
 
+    private StorageOperationStatus upgradeToLatestGenericData(Component clonedComponent) {
         StorageOperationStatus updateStatus = StorageOperationStatus.OK;
         Either<Component, StorageOperationStatus> updateEither = toscaOperationFacade.updateToscaElement(clonedComponent);
         if (updateEither.isRight()) {
             updateStatus = updateEither.right().value();
         } else if (clonedComponent.shouldGenerateInputs()) {
             List<InputDefinition> newInputs = clonedComponent.getInputs();
-            updateStatus = lifeCycleOperation.updateToscaDataOfToscaElement(clonedComponent.getUniqueId(), EdgeLabelEnum.INPUTS, VertexTypeEnum.INPUTS, newInputs, JsonPresentationFields.NAME);
+            updateStatus = lifeCycleOperation
+                .updateToscaDataOfToscaElement(clonedComponent.getUniqueId(), EdgeLabelEnum.INPUTS, VertexTypeEnum.INPUTS, newInputs,
+                    JsonPresentationFields.NAME);
         }
         return updateStatus;
     }
 
     @Override
-    public Either<Boolean, ResponseFormat> validateBeforeTransition(Component component, ComponentTypeEnum componentType, User modifier, User owner, LifecycleStateEnum oldState, LifecycleChangeInfoWithAction lifecycleChangeInfo) {
+    public Either<Boolean, ResponseFormat> validateBeforeTransition(Component component, ComponentTypeEnum componentType, User modifier, User owner,
+                                                                    LifecycleStateEnum oldState, LifecycleChangeInfoWithAction lifecycleChangeInfo) {
         String componentName = component.getComponentMetadataDefinition().getMetadataDataDefinition().getName();
         log.debug("validate before checkout. resource name={}, oldState={}, owner userId={}", componentName, oldState, owner.getUserId());
-
         // validate user
         Either<Boolean, ResponseFormat> userValidationResponse = userRoleValidation(modifier, component, componentType, lifecycleChangeInfo);
         if (userValidationResponse.isRight()) {
@@ -184,10 +179,11 @@ public class CheckoutTransition extends LifeCycleTransition {
         }
         // check resource is not locked by another user
         if (oldState.equals(LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT)) {
-            ResponseFormat error = componentUtils.getResponseFormat(ActionStatus.COMPONENT_IN_CHECKOUT_STATE, componentName, componentType.name().toLowerCase(), owner.getFirstName(), owner.getLastName(), owner.getUserId());
+            ResponseFormat error = componentUtils
+                .getResponseFormat(ActionStatus.COMPONENT_IN_CHECKOUT_STATE, componentName, componentType.name().toLowerCase(), owner.getFirstName(),
+                    owner.getLastName(), owner.getUserId());
             return Either.right(error);
         }
         return Either.left(true);
     }
-
 }
index 65fd1b8..bd3923e 100644 (file)
@@ -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.
  * limitations under the License.
  * ============LICENSE_END=========================================================
  */
-
 package org.openecomp.sdc.be.components.lifecycle;
 
 import fj.data.Either;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
 import org.openecomp.sdc.be.components.impl.ComponentBusinessLogic;
 import org.openecomp.sdc.be.components.lifecycle.LifecycleChangeInfoWithAction.LifecycleChanceActionEnum;
 import org.openecomp.sdc.be.config.ConfigurationManager;
@@ -42,10 +44,6 @@ import org.openecomp.sdc.be.user.Role;
 import org.openecomp.sdc.exception.ResponseFormat;
 import org.springframework.beans.factory.annotation.Autowired;
 
-import java.util.HashMap;
-import java.util.List;
-import java.util.Map;
-
 public abstract class LifeCycleTransition {
 
     protected ConfigurationManager configurationManager;
@@ -54,14 +52,12 @@ public abstract class LifeCycleTransition {
     @Autowired
     protected JanusGraphDao janusGraphDao;
     protected ComponentsUtils componentUtils;
-
     protected Map<ComponentTypeEnum, List<Role>> authorizedRoles;
     protected Map<ResourceTypeEnum, List<Role>> resourceAuthorizedRoles;
-
     ToscaOperationFacade toscaOperationFacade;
 
-    protected LifeCycleTransition(ComponentsUtils componentUtils, ToscaElementLifecycleOperation lifecycleOperation2, ToscaOperationFacade toscaOperationFacade, JanusGraphDao janusGraphDao) {
-
+    protected LifeCycleTransition(ComponentsUtils componentUtils, ToscaElementLifecycleOperation lifecycleOperation2,
+                                  ToscaOperationFacade toscaOperationFacade, JanusGraphDao janusGraphDao) {
         this.configurationManager = ConfigurationManager.getConfigurationManager();
         this.lifeCycleOperation = lifecycleOperation2;
         this.componentUtils = componentUtils;
@@ -107,58 +103,66 @@ public abstract class LifeCycleTransition {
         this.resourceAuthorizedRoles.put(resourceType, authorizedRoles);
     }
 
-    public abstract <T extends Component> Either<T, ResponseFormat> changeState(
-        ComponentTypeEnum componentType,
-        Component component,
-        ComponentBusinessLogic componentBl,
-        User modifier, User owner, boolean needLock, boolean inTransaction
-    );
+    public abstract <T extends Component> Either<T, ResponseFormat> changeState(ComponentTypeEnum componentType, Component component,
+                                                                                ComponentBusinessLogic componentBl, User modifier, User owner,
+                                                                                boolean needLock, boolean inTransaction);
 
-    public abstract Either<Boolean, ResponseFormat> validateBeforeTransition(Component component, ComponentTypeEnum componentType, User modifier, User owner, LifecycleStateEnum oldState, LifecycleChangeInfoWithAction lifecycleChangeInfo);
-
-    public Either<Boolean, ResponseFormat> validateBeforeTransition(Component component, ComponentTypeEnum componentType, User modifier, User owner, LifecycleStateEnum oldState) {
+    public abstract Either<Boolean, ResponseFormat> validateBeforeTransition(Component component, ComponentTypeEnum componentType, User modifier,
+                                                                             User owner, LifecycleStateEnum oldState,
+                                                                             LifecycleChangeInfoWithAction lifecycleChangeInfo);
 
+    public Either<Boolean, ResponseFormat> validateBeforeTransition(Component component, ComponentTypeEnum componentType, User modifier, User owner,
+                                                                    LifecycleStateEnum oldState) {
         return this.validateBeforeTransition(component, componentType, modifier, owner, oldState, null);
     }
 
     protected Either<User, ResponseFormat> getComponentOwner(Component component, ComponentTypeEnum componentType) {
-
         Either<User, StorageOperationStatus> resourceOwnerResult = getLifeCycleOperation().getToscaElementOwner(component.getUniqueId());
         if (resourceOwnerResult.isRight()) {
-            ResponseFormat responseFormat = componentUtils.getResponseFormatByComponent(componentUtils.convertFromStorageResponse(resourceOwnerResult.right().value()), component, componentType);
+            ResponseFormat responseFormat = componentUtils
+                .getResponseFormatByComponent(componentUtils.convertFromStorageResponse(resourceOwnerResult.right().value()), component,
+                    componentType);
             return Either.right(responseFormat);
         }
         return Either.left(resourceOwnerResult.left().value());
     }
 
-    protected Either<Boolean, ResponseFormat> userRoleValidation(User modifier,Component component, ComponentTypeEnum componentType, LifecycleChangeInfoWithAction lifecycleChangeInfo) {
-
+    protected Either<Boolean, ResponseFormat> userRoleValidation(User modifier, Component component, ComponentTypeEnum componentType,
+                                                                 LifecycleChangeInfoWithAction lifecycleChangeInfo) {
         // validate user
+
         //first check the user for the component and then for the resource
-        if (getAuthorizedRoles(componentType).contains(Role.valueOf(modifier.getRole())) || userResourceRoleValidation(component,componentType,modifier)) {
+        if (getAuthorizedRoles(componentType).contains(Role.valueOf(modifier.getRole())) || userResourceRoleValidation(component, componentType,
+            modifier)) {
             return Either.left(true);
         }
         // this is only used in 2 cases
+
         //1. when creating vfc/cp when import vf from csar - when we
+
         // create resources from node type, we create need to change the state
+
         // to certified
+
         //2. certification flow upno upgrade migration
-        if (lifecycleChangeInfo != null && lifecycleChangeInfo.getAction() != null && (lifecycleChangeInfo.getAction() == LifecycleChanceActionEnum.CREATE_FROM_CSAR|| lifecycleChangeInfo.getAction() == LifecycleChanceActionEnum.UPGRADE_MIGRATION)) {
+        if (lifecycleChangeInfo != null && lifecycleChangeInfo.getAction() != null && (
+            lifecycleChangeInfo.getAction() == LifecycleChanceActionEnum.CREATE_FROM_CSAR
+                || lifecycleChangeInfo.getAction() == LifecycleChanceActionEnum.UPGRADE_MIGRATION)) {
             return Either.left(true);
         }
-
         ResponseFormat responseFormat = componentUtils.getResponseFormat(ActionStatus.RESTRICTED_OPERATION);
         return Either.right(responseFormat);
     }
 
     protected boolean userResourceRoleValidation(Component component, ComponentTypeEnum componentType, User modifier) {
-        if (componentType.equals(ComponentTypeEnum.RESOURCE)){
-            ResourceTypeEnum resourceType = ((ResourceMetadataDataDefinition)component.getComponentMetadataDefinition().getMetadataDataDefinition()).getResourceType();
-            if (getResourceAuthorizedRoles(resourceType)!=null && getResourceAuthorizedRoles(resourceType).contains(Role.valueOf(modifier.getRole()))) {
+        if (componentType.equals(ComponentTypeEnum.RESOURCE)) {
+            ResourceTypeEnum resourceType = ((ResourceMetadataDataDefinition) component.getComponentMetadataDefinition().getMetadataDataDefinition())
+                .getResourceType();
+            if (getResourceAuthorizedRoles(resourceType) != null && getResourceAuthorizedRoles(resourceType)
+                .contains(Role.valueOf(modifier.getRole()))) {
                 return true;
             }
         }
         return false;
     }
-
 }
index 43714f2..6f4c641 100644 (file)
@@ -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,7 +19,6 @@
  * Modifications copyright (c) 2019 Nokia
  * ================================================================================
  */
-
 package org.openecomp.sdc.be.components.lifecycle;
 
 import com.google.common.annotations.VisibleForTesting;
@@ -69,67 +68,51 @@ import org.springframework.context.annotation.Lazy;
 public class LifecycleBusinessLogic {
 
     private static final String COMMENT = "comment";
-
+    private static final Logger log = Logger.getLogger(LifecycleBusinessLogic.class);
+    @Autowired
+    ToscaOperationFacade toscaOperationFacade;
+    @Autowired
+    NodeTemplateOperation nodeTemplateOperation;
+    @Autowired
+    CatalogOperation catalogOperations;
+    @Autowired
+    VesionUpdateHandler groupUpdateHandler;
     @Autowired
     private IGraphLockOperation graphLockOperation = null;
-
     @Autowired
     private JanusGraphDao janusGraphDao;
-
-    private static final Logger log = Logger.getLogger(LifecycleBusinessLogic.class);
-
     @javax.annotation.Resource
     private ComponentsUtils componentUtils;
-
     @javax.annotation.Resource
     private ToscaElementLifecycleOperation lifecycleOperation;
-
     @Autowired
     @Lazy
     private ServiceBusinessLogic serviceBusinessLogic;
-
     @Autowired
     @Lazy
     private ResourceBusinessLogic resourceBusinessLogic;
-
     @Autowired
     @Lazy
     private ProductBusinessLogic productBusinessLogic;
-
-    @Autowired
-    ToscaOperationFacade toscaOperationFacade;
-    
-    @Autowired
-    NodeTemplateOperation nodeTemplateOperation;
-
-    @Autowired
-    CatalogOperation catalogOperations;
-
-    @Autowired
-    VesionUpdateHandler groupUpdateHandler;
-
     private Map<String, LifeCycleTransition> stateTransitions;
 
     @PostConstruct
     public void init() {
-       initStateOperations();
+        initStateOperations();
     }
 
     private void initStateOperations() {
         stateTransitions = new HashMap<>();
-
-        LifeCycleTransition checkoutOp = new CheckoutTransition(componentUtils, lifecycleOperation, toscaOperationFacade,
-            janusGraphDao);
+        LifeCycleTransition checkoutOp = new CheckoutTransition(componentUtils, lifecycleOperation, toscaOperationFacade, janusGraphDao);
         stateTransitions.put(checkoutOp.getName().name(), checkoutOp);
-
         UndoCheckoutTransition undoCheckoutOp = new UndoCheckoutTransition(componentUtils, lifecycleOperation, toscaOperationFacade, janusGraphDao);
         undoCheckoutOp.setCatalogOperations(catalogOperations);
         stateTransitions.put(undoCheckoutOp.getName().name(), undoCheckoutOp);
-
-        LifeCycleTransition checkinOp = new CheckinTransition(componentUtils, lifecycleOperation, toscaOperationFacade, janusGraphDao, groupUpdateHandler);
+        LifeCycleTransition checkinOp = new CheckinTransition(componentUtils, lifecycleOperation, toscaOperationFacade, janusGraphDao,
+            groupUpdateHandler);
         stateTransitions.put(checkinOp.getName().name(), checkinOp);
-
-        CertificationChangeTransition successCertification = new CertificationChangeTransition(serviceBusinessLogic, LifeCycleTransitionEnum.CERTIFY, componentUtils, lifecycleOperation, toscaOperationFacade, janusGraphDao);
+        CertificationChangeTransition successCertification = new CertificationChangeTransition(serviceBusinessLogic, LifeCycleTransitionEnum.CERTIFY,
+            componentUtils, lifecycleOperation, toscaOperationFacade, janusGraphDao);
         successCertification.setNodeTemplateOperation(nodeTemplateOperation);
         stateTransitions.put(successCertification.getName().name(), successCertification);
     }
@@ -140,19 +123,15 @@ public class LifecycleBusinessLogic {
     }
 
     // TODO: rhalili - should use changeComponentState when possible
-    public Either<Resource, ResponseFormat> changeState(String resourceId, User modifier, LifeCycleTransitionEnum transitionEnum, LifecycleChangeInfoWithAction changeInfo, boolean inTransaction, boolean needLock) {
+    public Either<Resource, ResponseFormat> changeState(String resourceId, User modifier, LifeCycleTransitionEnum transitionEnum,
+                                                        LifecycleChangeInfoWithAction changeInfo, boolean inTransaction, boolean needLock) {
         return changeComponentState(ComponentTypeEnum.RESOURCE, resourceId, modifier, transitionEnum, changeInfo, inTransaction, needLock);
     }
 
-    public <T extends Component> Either<T, ResponseFormat> changeComponentState(
-        ComponentTypeEnum componentType,
-        String componentId,
-        User modifier,
-        LifeCycleTransitionEnum transitionEnum,
-        LifecycleChangeInfoWithAction changeInfo,
-        boolean inTransaction,
-        boolean needLock) {
-
+    public <T extends Component> Either<T, ResponseFormat> changeComponentState(ComponentTypeEnum componentType, String componentId, User modifier,
+                                                                                LifeCycleTransitionEnum transitionEnum,
+                                                                                LifecycleChangeInfoWithAction changeInfo, boolean inTransaction,
+                                                                                boolean needLock) {
         LifeCycleTransition lifeCycleTransition = stateTransitions.get(transitionEnum.name());
         if (lifeCycleTransition == null) {
             log.debug("state operation is not valid. operations allowed are: {}", LifeCycleTransitionEnum.valuesAsString());
@@ -161,32 +140,24 @@ public class LifecycleBusinessLogic {
         }
         log.debug("get resource from graph");
         ResponseFormat errorResponse;
-
-        Either<T, ResponseFormat> eitherResourceResponse = getComponentForChange(
-            componentType, componentId, modifier, lifeCycleTransition, changeInfo
-        );
+        Either<T, ResponseFormat> eitherResourceResponse = getComponentForChange(componentType, componentId, modifier, lifeCycleTransition,
+            changeInfo);
         if (eitherResourceResponse.isRight()) {
             return eitherResourceResponse;
         }
         T component = eitherResourceResponse.left().value();
         String resourceCurrVersion = component.getVersion();
         LifecycleStateEnum resourceCurrState = component.getLifecycleState();
-
         // lock resource
         if (!inTransaction && needLock) {
             log.debug("lock component {}", componentId);
             try {
                 lockComponent(componentType, component);
-            }catch (ComponentException e){
+            } catch (ComponentException e) {
                 errorResponse = e.getResponseFormat();
                 componentUtils.auditComponent(errorResponse, modifier, component, lifeCycleTransition.getAuditingAction(),
-                        new ResourceCommonInfo(componentType.getValue()),
-                        ResourceVersionInfo.newBuilder()
-                                .state(resourceCurrState.name())
-                                .version(resourceCurrVersion)
-                                .build());
-
-
+                    new ResourceCommonInfo(componentType.getValue()),
+                    ResourceVersionInfo.newBuilder().state(resourceCurrState.name()).version(resourceCurrVersion).build());
                 log.error("lock component {} failed", componentId);
                 return Either.right(errorResponse);
             }
@@ -197,34 +168,28 @@ public class LifecycleBusinessLogic {
             if (commentValidationResult.isRight()) {
                 errorResponse = commentValidationResult.right().value();
                 componentUtils.auditComponent(errorResponse, modifier, component, lifeCycleTransition.getAuditingAction(),
-                        new ResourceCommonInfo(componentType.getValue()),
-                        ResourceVersionInfo.newBuilder()
-                                .state(resourceCurrState.name())
-                                .version(resourceCurrVersion)
-                                .build(),
-                        changeInfo.getUserRemarks());
+                    new ResourceCommonInfo(componentType.getValue()),
+                    ResourceVersionInfo.newBuilder().state(resourceCurrState.name()).version(resourceCurrVersion).build(),
+                    changeInfo.getUserRemarks());
                 return Either.right(errorResponse);
             }
             changeInfo.setUserRemarks(commentValidationResult.left().value());
             log.debug("after validate component");
-            Either<Boolean, ResponseFormat> validateHighestVersion = validateHighestVersion(modifier, lifeCycleTransition, component, resourceCurrVersion, componentType);
+            Either<Boolean, ResponseFormat> validateHighestVersion = validateHighestVersion(modifier, lifeCycleTransition, component,
+                resourceCurrVersion, componentType);
             if (validateHighestVersion.isRight()) {
                 return Either.right(validateHighestVersion.right().value());
             }
             log.debug("after validate Highest Version");
             final T oldComponent = component;
-            Either<T, ResponseFormat> checkedInComponentEither =
-                checkInBeforeCertifyIfNeeded(componentType, modifier, transitionEnum, changeInfo, inTransaction,
-                    component);
-            if(checkedInComponentEither.isRight()) {
+            Either<T, ResponseFormat> checkedInComponentEither = checkInBeforeCertifyIfNeeded(componentType, modifier, transitionEnum, changeInfo,
+                inTransaction, component);
+            if (checkedInComponentEither.isRight()) {
                 return Either.right(checkedInComponentEither.right().value());
             }
             component = checkedInComponentEither.left().value();
-            return changeState(component, lifeCycleTransition, componentType, modifier, changeInfo, inTransaction)
-                                        .left()
-                                        .bind(c -> updateCatalog(c, oldComponent, ChangeTypeEnum.LIFECYCLE));
-
-
+            return changeState(component, lifeCycleTransition, componentType, modifier, changeInfo, inTransaction).left()
+                .bind(c -> updateCatalog(c, oldComponent, ChangeTypeEnum.LIFECYCLE));
         } finally {
             component.setUniqueId(componentId);
             if (!inTransaction && needLock) {
@@ -232,152 +197,106 @@ public class LifecycleBusinessLogic {
                 NodeTypeEnum nodeType = componentType.getNodeType();
                 log.info("During change state, another component {} has been created/updated", componentId);
                 graphLockOperation.unlockComponent(componentId, nodeType);
-
             }
         }
-
     }
 
-    private <T extends Component> Either<T, ResponseFormat>  updateCatalog(
-        T component,
-        T oldComponent,
-        ChangeTypeEnum changeStatus
-    ){
-
+    private <T extends Component> Either<T, ResponseFormat> updateCatalog(T component, T oldComponent, ChangeTypeEnum changeStatus) {
         log.debug("updateCatalog start");
-        T result = component == null? oldComponent : component;
-            if(component != null){
-                ActionStatus status =  catalogOperations.updateCatalog(changeStatus,component);
-                if(status != ActionStatus.OK){
-                    return Either.right(componentUtils.getResponseFormat(status));
-                }
+        T result = component == null ? oldComponent : component;
+        if (component != null) {
+            ActionStatus status = catalogOperations.updateCatalog(changeStatus, component);
+            if (status != ActionStatus.OK) {
+                return Either.right(componentUtils.getResponseFormat(status));
+            }
         }
-
-       return Either.left(result);
+        return Either.left(result);
     }
 
-    private <T extends Component> Either<T, ResponseFormat> checkInBeforeCertifyIfNeeded(
-        ComponentTypeEnum componentType,
-        User modifier,
-        LifeCycleTransitionEnum transitionEnum,
-        LifecycleChangeInfoWithAction changeInfo,
-        boolean inTransaction,
-        T component
-    ) {
-
+    private <T extends Component> Either<T, ResponseFormat> checkInBeforeCertifyIfNeeded(ComponentTypeEnum componentType, User modifier,
+                                                                                         LifeCycleTransitionEnum transitionEnum,
+                                                                                         LifecycleChangeInfoWithAction changeInfo,
+                                                                                         boolean inTransaction, T component) {
         LifecycleStateEnum oldState = component.getLifecycleState();
         log.debug("Certification request for resource {} ", component.getUniqueId());
         if (oldState == LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT && transitionEnum == LifeCycleTransitionEnum.CERTIFY) {
             log.debug("Resource {} is in Checkout state perform checkin", component.getUniqueId());
-            Either<T, ResponseFormat> actionResponse = changeState(
-                component,
-                stateTransitions.get(LifeCycleTransitionEnum.CHECKIN.name()),
+            Either<T, ResponseFormat> actionResponse = changeState(component, stateTransitions.get(LifeCycleTransitionEnum.CHECKIN.name()),
                 componentType, modifier, changeInfo, inTransaction);
             if (actionResponse.isRight()) {
                 log.debug("Failed to check in Resource {} error {}", component.getUniqueId(), actionResponse.right().value());
             }
             return actionResponse;
         }
-
         return Either.left(component);
     }
 
-    private <T extends Component> Either<T, ResponseFormat> changeState(
-        T component,
-        LifeCycleTransition lifeCycleTransition,
-        ComponentTypeEnum componentType,
-        User modifier,
-        LifecycleChangeInfoWithAction changeInfo,
-        boolean inTransaction
-    ) {
+    private <T extends Component> Either<T, ResponseFormat> changeState(T component, LifeCycleTransition lifeCycleTransition,
+                                                                        ComponentTypeEnum componentType, User modifier,
+                                                                        LifecycleChangeInfoWithAction changeInfo, boolean inTransaction) {
         ResponseFormat errorResponse;
-
         LifecycleStateEnum oldState = component.getLifecycleState();
         String resourceCurrVersion = component.getVersion();
         ComponentBusinessLogic bl = getComponentBL(componentType);
-
         Either<User, ResponseFormat> ownerResult = lifeCycleTransition.getComponentOwner(component, componentType);
         if (ownerResult.isRight()) {
             return Either.right(ownerResult.right().value());
         }
         User owner = ownerResult.left().value();
         log.info("owner of resource {} is {}", component.getUniqueId(), owner.getUserId());
-
-        Either<Boolean, ResponseFormat> stateValidationResult = lifeCycleTransition.validateBeforeTransition(component, componentType, modifier, owner, oldState, changeInfo);
+        Either<Boolean, ResponseFormat> stateValidationResult = lifeCycleTransition
+            .validateBeforeTransition(component, componentType, modifier, owner, oldState, changeInfo);
         if (stateValidationResult.isRight()) {
             log.error("Failed to validateBeforeTransition");
             errorResponse = stateValidationResult.right().value();
             componentUtils.auditComponent(errorResponse, modifier, component, lifeCycleTransition.getAuditingAction(),
-                    new ResourceCommonInfo(componentType.getValue()),
-                    ResourceVersionInfo.newBuilder()
-                            .version(resourceCurrVersion)
-                            .state(oldState.name())
-                            .build(),
-                    changeInfo.getUserRemarks());
+                new ResourceCommonInfo(componentType.getValue()),
+                ResourceVersionInfo.newBuilder().version(resourceCurrVersion).state(oldState.name()).build(), changeInfo.getUserRemarks());
             return Either.right(errorResponse);
         }
-        
-        Either<T, ResponseFormat> operationResult = lifeCycleTransition.changeState(
-            componentType, component, bl, modifier, owner, false, inTransaction);
-
+        Either<T, ResponseFormat> operationResult = lifeCycleTransition
+            .changeState(componentType, component, bl, modifier, owner, false, inTransaction);
         if (operationResult.isRight()) {
             errorResponse = operationResult.right().value();
             log.info("audit before sending error response");
             componentUtils.auditComponentAdmin(errorResponse, modifier, component, lifeCycleTransition.getAuditingAction(), componentType,
-                     ResourceVersionInfo.newBuilder()
-                             .state(oldState.name())
-                             .version(resourceCurrVersion)
-                             .build());
-
+                ResourceVersionInfo.newBuilder().state(oldState.name()).version(resourceCurrVersion).build());
             return Either.right(errorResponse);
         }
-        Component resourceAfterOperation = operationResult.left().value() == null? component: operationResult.left().value() ;
+        Component resourceAfterOperation = operationResult.left().value() == null ? component : operationResult.left().value();
         componentUtils.auditComponent(componentUtils.getResponseFormat(ActionStatus.OK), modifier, resourceAfterOperation,
-                lifeCycleTransition.getAuditingAction(), new ResourceCommonInfo(componentType.getValue()),
-                ResourceVersionInfo.newBuilder()
-                        .state(oldState.name())
-                        .version(resourceCurrVersion)
-                        .build(),
-                changeInfo.getUserRemarks());
+            lifeCycleTransition.getAuditingAction(), new ResourceCommonInfo(componentType.getValue()),
+            ResourceVersionInfo.newBuilder().state(oldState.name()).version(resourceCurrVersion).build(), changeInfo.getUserRemarks());
         return operationResult;
-
     }
 
-
-       private <T extends Component> Either<T, ResponseFormat> getComponentForChange(
-           ComponentTypeEnum componentType,
-      String componentId,
-      User modifier,
-      LifeCycleTransition lifeCycleTransition,
-      LifecycleChangeInfoWithAction changeInfo
-  ) {
-
+    private <T extends Component> Either<T, ResponseFormat> getComponentForChange(ComponentTypeEnum componentType, String componentId, User modifier,
+                                                                                  LifeCycleTransition lifeCycleTransition,
+                                                                                  LifecycleChangeInfoWithAction changeInfo) {
         Either<T, StorageOperationStatus> eitherResourceResponse = toscaOperationFacade.getToscaElement(componentId);
-
         ResponseFormat errorResponse;
         if (eitherResourceResponse.isRight()) {
             ActionStatus actionStatus = componentUtils.convertFromStorageResponse(eitherResourceResponse.right().value(), componentType);
             errorResponse = componentUtils.getResponseFormat(actionStatus, Constants.EMPTY_STRING);
             log.debug("audit before sending response");
             componentUtils.auditComponent(errorResponse, modifier, lifeCycleTransition.getAuditingAction(),
-                    new ResourceCommonInfo(componentId, componentType.getValue()), changeInfo.getUserRemarks());
-
+                new ResourceCommonInfo(componentId, componentType.getValue()), changeInfo.getUserRemarks());
             return Either.right(errorResponse);
         }
         return Either.left(eitherResourceResponse.left().value());
     }
 
-    private Either<Boolean, ResponseFormat> validateHighestVersion(User modifier, LifeCycleTransition lifeCycleTransition, Component component, String resourceCurrVersion, ComponentTypeEnum componentType) {
+    private Either<Boolean, ResponseFormat> validateHighestVersion(User modifier, LifeCycleTransition lifeCycleTransition, Component component,
+                                                                   String resourceCurrVersion, ComponentTypeEnum componentType) {
         ResponseFormat errorResponse;
         if (!component.isHighestVersion()) {
-            log.debug("Component version {} is not the last version of component {}", component.getComponentMetadataDefinition().getMetadataDataDefinition().getVersion(),
-                    component.getComponentMetadataDefinition().getMetadataDataDefinition().getName());
-            errorResponse = componentUtils.getResponseFormat(ActionStatus.COMPONENT_HAS_NEWER_VERSION, component.getComponentMetadataDefinition().getMetadataDataDefinition().getName(), componentType.getValue().toLowerCase());
+            log.debug("Component version {} is not the last version of component {}",
+                component.getComponentMetadataDefinition().getMetadataDataDefinition().getVersion(),
+                component.getComponentMetadataDefinition().getMetadataDataDefinition().getName());
+            errorResponse = componentUtils.getResponseFormat(ActionStatus.COMPONENT_HAS_NEWER_VERSION,
+                component.getComponentMetadataDefinition().getMetadataDataDefinition().getName(), componentType.getValue().toLowerCase());
             componentUtils.auditComponentAdmin(errorResponse, modifier, component, lifeCycleTransition.getAuditingAction(), componentType,
-                    ResourceVersionInfo.newBuilder()
-                            .state(component.getLifecycleState().name())
-                            .version(resourceCurrVersion)
-                            .build());
+                ResourceVersionInfo.newBuilder().state(component.getLifecycleState().name()).version(resourceCurrVersion).build());
             return Either.right(errorResponse);
         }
         return Either.left(true);
@@ -386,35 +305,33 @@ public class LifecycleBusinessLogic {
     private Boolean lockComponent(ComponentTypeEnum componentType, Component component) {
         NodeTypeEnum nodeType = componentType.getNodeType();
         StorageOperationStatus lockResourceStatus = graphLockOperation.lockComponent(component.getUniqueId(), nodeType);
-
         if (lockResourceStatus.equals(StorageOperationStatus.OK)) {
             return true;
         } else {
             ActionStatus actionStatus = componentUtils.convertFromStorageResponse(lockResourceStatus);
-            throw new ByActionStatusComponentException(actionStatus, component.getComponentMetadataDefinition().getMetadataDataDefinition().getName());
+            throw new ByActionStatusComponentException(actionStatus,
+                component.getComponentMetadataDefinition().getMetadataDataDefinition().getName());
         }
     }
 
     private Either<String, ResponseFormat> validateComment(LifecycleChangeInfoWithAction changeInfo, LifeCycleTransitionEnum transitionEnum) {
         String comment = changeInfo.getUserRemarks();
         if (LifeCycleTransitionEnum.CERTIFY == transitionEnum || LifeCycleTransitionEnum.CHECKIN == transitionEnum
-        // import?
+            // import?
         ) {
-
             if (!ValidationUtils.validateStringNotEmpty(comment)) {
                 log.debug("user comment cannot be empty or null.");
                 ResponseFormat errorResponse = componentUtils.getResponseFormat(ActionStatus.MISSING_DATA, COMMENT);
                 return Either.right(errorResponse);
             }
-
             comment = ValidationUtils.removeNoneUtf8Chars(comment);
             comment = ValidationUtils.removeHtmlTags(comment);
             comment = ValidationUtils.normaliseWhitespace(comment);
             comment = ValidationUtils.stripOctets(comment);
-
             if (!ValidationUtils.validateLength(comment, ValidationUtils.COMMENT_MAX_LENGTH)) {
                 log.debug("user comment exceeds limit.");
-                return Either.right(componentUtils.getResponseFormat(ActionStatus.EXCEEDS_LIMIT, COMMENT, String.valueOf(ValidationUtils.COMMENT_MAX_LENGTH)));
+                return Either
+                    .right(componentUtils.getResponseFormat(ActionStatus.EXCEEDS_LIMIT, COMMENT, String.valueOf(ValidationUtils.COMMENT_MAX_LENGTH)));
             }
             if (!ValidationUtils.validateIsEnglish(comment)) {
                 return Either.right(componentUtils.getResponseFormat(ActionStatus.INVALID_CONTENT));
@@ -426,39 +343,35 @@ public class LifecycleBusinessLogic {
     private ComponentBusinessLogic getComponentBL(ComponentTypeEnum componentTypeEnum) {
         ComponentBusinessLogic businessLogic;
         switch (componentTypeEnum) {
-        case RESOURCE:
-            businessLogic = this.resourceBusinessLogic;
-            break;
-        case SERVICE:
-            businessLogic = this.serviceBusinessLogic;
-            break;
-        case PRODUCT:
-            businessLogic = this.productBusinessLogic;
-            break;
-        default:
-            throw new IllegalArgumentException("Illegal component type:" + componentTypeEnum.getValue());
+            case RESOURCE:
+                businessLogic = this.resourceBusinessLogic;
+                break;
+            case SERVICE:
+                businessLogic = this.serviceBusinessLogic;
+                break;
+            case PRODUCT:
+                businessLogic = this.productBusinessLogic;
+                break;
+            default:
+                throw new IllegalArgumentException("Illegal component type:" + componentTypeEnum.getValue());
         }
         return businessLogic;
     }
 
     public Either<Component, ResponseFormat> getLatestComponentByUuid(ComponentTypeEnum componentTypeEnum, String uuid) {
-
         Either<Component, StorageOperationStatus> latestVersionEither = toscaOperationFacade.getLatestComponentByUuid(uuid);
-
         if (latestVersionEither.isRight()) {
-
-            return Either.right(componentUtils.getResponseFormat(componentUtils.convertFromStorageResponse(latestVersionEither.right().value(), componentTypeEnum), uuid));
+            return Either.right(componentUtils
+                .getResponseFormat(componentUtils.convertFromStorageResponse(latestVersionEither.right().value(), componentTypeEnum), uuid));
         }
-
         Component latestComponent = latestVersionEither.left().value();
-
         return Either.left(latestComponent);
     }
 
     /**
-     * Performs Force certification. Note that a Force certification is allowed for the first certification only, as only a state and a version is promoted due a Force certification, skipping other actions required if a previous certified version
-     * exists.
-     * 
+     * Performs Force certification. Note that a Force certification is allowed for the first certification only, as only a state and a version is
+     * promoted due a Force certification, skipping other actions required if a previous certified version exists.
+     *
      * @param resource
      * @param user
      * @param lifecycleChangeInfo
@@ -466,7 +379,8 @@ public class LifecycleBusinessLogic {
      * @param needLock
      * @return
      */
-    public Resource forceResourceCertification(Resource resource, User user, LifecycleChangeInfoWithAction lifecycleChangeInfo, boolean inTransaction, boolean needLock) {
+    public Resource forceResourceCertification(Resource resource, User user, LifecycleChangeInfoWithAction lifecycleChangeInfo, boolean inTransaction,
+                                               boolean needLock) {
         Resource result = null;
         Either<ToscaElement, StorageOperationStatus> certifyResourceRes = null;
         if (lifecycleChangeInfo.getAction() != LifecycleChanceActionEnum.CREATE_FROM_CSAR) {
@@ -474,7 +388,8 @@ public class LifecycleBusinessLogic {
             throw new ByActionStatusComponentException(ActionStatus.NOT_ALLOWED);
         }
         if (!isFirstCertification(resource.getVersion())) {
-            log.debug("Failed to perform a force certification of resource{}. Force certification is allowed for the first certification only. ", resource.getName());
+            log.debug("Failed to perform a force certification of resource{}. Force certification is allowed for the first certification only. ",
+                resource.getName());
             throw new ByActionStatusComponentException(ActionStatus.NOT_ALLOWED);
         }
         // lock resource
@@ -484,11 +399,13 @@ public class LifecycleBusinessLogic {
             log.info("after lock component {}", resource.getUniqueId());
         }
         try {
-            certifyResourceRes = lifecycleOperation.forceCerificationOfToscaElement(resource.getUniqueId(), user.getUserId(), user.getUserId(), resource.getVersion());
+            certifyResourceRes = lifecycleOperation
+                .forceCerificationOfToscaElement(resource.getUniqueId(), user.getUserId(), user.getUserId(), resource.getVersion());
             if (certifyResourceRes.isRight()) {
                 StorageOperationStatus status = certifyResourceRes.right().value();
                 log.debug("Failed to perform a force certification of resource {}. The status is {}. ", resource.getName(), status);
-                throw new ByResponseFormatComponentException(componentUtils.getResponseFormatByResource(componentUtils.convertFromStorageResponse(status), resource));
+                throw new ByResponseFormatComponentException(
+                    componentUtils.getResponseFormatByResource(componentUtils.convertFromStorageResponse(status), resource));
             }
             result = ModelConverter.convertFromToscaElement(certifyResourceRes.left().value());
             resource.setComponentMetadataDefinition(result.getComponentMetadataDefinition());
@@ -513,5 +430,4 @@ public class LifecycleBusinessLogic {
     public boolean isFirstCertification(String previousVersion) {
         return previousVersion.split("\\.")[0].equals("0");
     }
-
 }
index 239f15a..bde13f6 100644 (file)
@@ -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.
  * limitations under the License.
  * ============LICENSE_END=========================================================
  */
-
 package org.openecomp.sdc.be.components.lifecycle;
 
 import com.fasterxml.jackson.annotation.JsonInclude;
 
 public class LifecycleChangeInfoBase {
 
+    @JsonInclude
+    private String userRemarks;
+
     public LifecycleChangeInfoBase() {
     }
 
@@ -32,9 +34,6 @@ public class LifecycleChangeInfoBase {
         this.userRemarks = userRemarks;
     }
 
-    @JsonInclude
-    private String userRemarks;
-
     public String getUserRemarks() {
         return userRemarks;
     }
index 3df42e4..cdec764 100644 (file)
@@ -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.
  * limitations under the License.
  * ============LICENSE_END=========================================================
  */
-
 package org.openecomp.sdc.be.components.lifecycle;
 
 import com.fasterxml.jackson.annotation.JsonInclude;
 
 public class LifecycleChangeInfoWithAction extends LifecycleChangeInfoBase {
 
-    public enum LifecycleChanceActionEnum {
-        CREATE_FROM_CSAR, UPDATE_FROM_EXTERNAL_API, UPGRADE_MIGRATION
-    };
-
     @JsonInclude
     private LifecycleChanceActionEnum action;
 
@@ -50,4 +45,6 @@ public class LifecycleChangeInfoWithAction extends LifecycleChangeInfoBase {
     public void setAction(LifecycleChanceActionEnum action) {
         this.action = action;
     }
+
+    public enum LifecycleChanceActionEnum {CREATE_FROM_CSAR, UPDATE_FROM_EXTERNAL_API, UPGRADE_MIGRATION}
 }
index c66f7ea..0502741 100644 (file)
@@ -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.
  * limitations under the License.
  * ============LICENSE_END=========================================================
  */
-
 package org.openecomp.sdc.be.components.lifecycle;
 
 import fj.data.Either;
+import java.util.Arrays;
 import org.openecomp.sdc.be.catalog.enums.ChangeTypeEnum;
 import org.openecomp.sdc.be.components.impl.ComponentBusinessLogic;
 import org.openecomp.sdc.be.config.BeEcompErrorManager;
@@ -43,23 +43,20 @@ import org.openecomp.sdc.be.user.Role;
 import org.openecomp.sdc.common.log.wrappers.Logger;
 import org.openecomp.sdc.exception.ResponseFormat;
 
-import java.util.Arrays;
-
 public class UndoCheckoutTransition extends LifeCycleTransition {
-    private static final Logger log = Logger.getLogger(CheckoutTransition.class);
 
+    private static final Logger log = Logger.getLogger(CheckoutTransition.class);
     private CatalogOperation catalogOperations;
 
-    public UndoCheckoutTransition(ComponentsUtils componentUtils, ToscaElementLifecycleOperation lifecycleOperation, ToscaOperationFacade toscaOperationFacade, JanusGraphDao janusGraphDao) {
+    public UndoCheckoutTransition(ComponentsUtils componentUtils, ToscaElementLifecycleOperation lifecycleOperation,
+                                  ToscaOperationFacade toscaOperationFacade, JanusGraphDao janusGraphDao) {
         super(componentUtils, lifecycleOperation, toscaOperationFacade, janusGraphDao);
-
         // authorized roles
-        Role[] resourceServiceCheckoutRoles = { Role.ADMIN, Role.DESIGNER };
-        Role[] productCheckoutRoles = { Role.ADMIN, Role.PRODUCT_MANAGER };
+        Role[] resourceServiceCheckoutRoles = {Role.ADMIN, Role.DESIGNER};
+        Role[] productCheckoutRoles = {Role.ADMIN, Role.PRODUCT_MANAGER};
         addAuthorizedRoles(ComponentTypeEnum.RESOURCE, Arrays.asList(resourceServiceCheckoutRoles));
         addAuthorizedRoles(ComponentTypeEnum.SERVICE, Arrays.asList(resourceServiceCheckoutRoles));
         addAuthorizedRoles(ComponentTypeEnum.PRODUCT, Arrays.asList(productCheckoutRoles));
-
     }
 
     @Override
@@ -77,54 +74,52 @@ public class UndoCheckoutTransition extends LifeCycleTransition {
     }
 
     @Override
-    public Either<Boolean, ResponseFormat> validateBeforeTransition(Component component, ComponentTypeEnum componentType, User modifier, User owner, LifecycleStateEnum oldState, LifecycleChangeInfoWithAction lifecycleChangeInfo) {
+    public Either<Boolean, ResponseFormat> validateBeforeTransition(Component component, ComponentTypeEnum componentType, User modifier, User owner,
+                                                                    LifecycleStateEnum oldState, LifecycleChangeInfoWithAction lifecycleChangeInfo) {
         String componentName = component.getComponentMetadataDefinition().getMetadataDataDefinition().getName();
         log.debug("validate before undo checkout. resource name={}, oldState={}, owner userId={}", componentName, oldState, owner.getUserId());
-
         // validate user
-        Either<Boolean, ResponseFormat> userValidationResponse = userRoleValidation(modifier,component, componentType, lifecycleChangeInfo);
+        Either<Boolean, ResponseFormat> userValidationResponse = userRoleValidation(modifier, component, componentType, lifecycleChangeInfo);
         if (userValidationResponse.isRight()) {
             return userValidationResponse;
         }
-
         // check resource is not locked by another user
         if (!oldState.equals(LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT)) {
-            ResponseFormat error = componentUtils.getResponseFormat(ActionStatus.COMPONENT_ALREADY_CHECKED_IN, componentName, componentType.name().toLowerCase(), owner.getFirstName(), owner.getLastName(), owner.getUserId());
+            ResponseFormat error = componentUtils
+                .getResponseFormat(ActionStatus.COMPONENT_ALREADY_CHECKED_IN, componentName, componentType.name().toLowerCase(), owner.getFirstName(),
+                    owner.getLastName(), owner.getUserId());
             return Either.right(error);
         }
-
         if (!modifier.equals(owner) && !modifier.getRole().equals(Role.ADMIN.name())) {
-            ResponseFormat error = componentUtils.getResponseFormat(ActionStatus.COMPONENT_CHECKOUT_BY_ANOTHER_USER, componentName, componentType.name().toLowerCase(), owner.getFirstName(), owner.getLastName(), owner.getUserId());
+            ResponseFormat error = componentUtils
+                .getResponseFormat(ActionStatus.COMPONENT_CHECKOUT_BY_ANOTHER_USER, componentName, componentType.name().toLowerCase(),
+                    owner.getFirstName(), owner.getLastName(), owner.getUserId());
             return Either.right(error);
         }
-
         return Either.left(true);
     }
 
     @Override
-    public Either<? extends Component, ResponseFormat> changeState(ComponentTypeEnum componentType, Component component, ComponentBusinessLogic componentBl, User modifier, User owner, boolean shouldLock, boolean inTransaction) {
-
+    public Either<? extends Component, ResponseFormat> changeState(ComponentTypeEnum componentType, Component component,
+                                                                   ComponentBusinessLogic componentBl, User modifier, User owner, boolean shouldLock,
+                                                                   boolean inTransaction) {
         Either<? extends Component, ResponseFormat> result = null;
         log.debug("start performing undo-checkout for resource {}", component.getUniqueId());
-
         try {
             Either<ToscaElement, StorageOperationStatus> undoCheckoutResourceResult = lifeCycleOperation.undoCheckout(component.getUniqueId());
-
             if (undoCheckoutResourceResult.isRight()) {
                 log.debug("checkout failed on graph");
                 StorageOperationStatus response = undoCheckoutResourceResult.right().value();
                 ActionStatus actionStatus = componentUtils.convertFromStorageResponse(response);
                 ResponseFormat responseFormat = componentUtils.getResponseFormatByComponent(actionStatus, component, componentType);
-                result =  Either.right(responseFormat);
-            }
-            else {
+                result = Either.right(responseFormat);
+            } else {
                 ToscaElement element = undoCheckoutResourceResult.left().value();
-                if(element == null){ 
+                if (element == null) {
                     catalogOperations.updateCatalog(ChangeTypeEnum.DELETE, component);
                     result = Either.left(null);
-                }
-                else{
-                    result =  Either.left(ModelConverter.convertFromToscaElement(element));
+                } else {
+                    result = Either.left(ModelConverter.convertFromToscaElement(element));
                 }
             }
         } finally {
@@ -139,6 +134,4 @@ public class UndoCheckoutTransition extends LifeCycleTransition {
         }
         return result;
     }
-    
-
 }
index df5c0c6..e361f58 100644 (file)
@@ -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.
  * limitations under the License.
  * ============LICENSE_END=========================================================
  */
-
 package org.openecomp.sdc.be.components.merge;
 
 /**
  * A command to be executed upon csar update in case new csar topology was changed with respect to previous csar
  */
 public interface ComponentsGlobalMergeCommand extends ComponentsMergeCommand {
+
 }
index 16b75ff..ad2d3a2 100644 (file)
@@ -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.
@@ -17,7 +17,6 @@
  * limitations under the License.
  * ============LICENSE_END=========================================================
  */
-
 package org.openecomp.sdc.be.components.merge;
 
 import org.openecomp.sdc.be.dao.api.ActionStatus;
@@ -27,16 +26,15 @@ public interface ComponentsMergeCommand {
 
     /**
      * encapsulates the logic of merging component inner entities from the previous component into the currently updated component
-     * @param prevComponent the old component, whose entities need to be merged
+     *
+     * @param prevComponent    the old component, whose entities need to be merged
      * @param currentComponent the new component, whose entities need to be merged
      * @return the status of the merge process
      */
     ActionStatus mergeComponents(Component prevComponent, Component currentComponent);
 
     /**
-     *
      * @return short description of the command for logging purposes
      */
     String description();
-
 }
index c4f128f..66f237b 100644 (file)
@@ -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.
  * limitations under the License.
  * ============LICENSE_END=========================================================
  */
-
 package org.openecomp.sdc.be.components.merge;
 
 import fj.data.Either;
+import java.util.List;
+import java.util.Set;
+import java.util.stream.Collectors;
 import org.openecomp.sdc.be.components.impl.generic.GenericTypeBusinessLogic;
 import org.openecomp.sdc.be.dao.api.ActionStatus;
 import org.openecomp.sdc.be.impl.ComponentsUtils;
@@ -30,10 +32,6 @@ import org.openecomp.sdc.be.model.Resource;
 import org.openecomp.sdc.be.model.jsonjanusgraph.operations.ToscaOperationFacade;
 import org.openecomp.sdc.be.model.operations.api.StorageOperationStatus;
 
-import java.util.List;
-import java.util.Set;
-import java.util.stream.Collectors;
-
 @org.springframework.stereotype.Component
 public class GlobalInputsFilteringBusinessLogic {
 
@@ -41,16 +39,18 @@ public class GlobalInputsFilteringBusinessLogic {
     private ToscaOperationFacade toscaOperationFacade;
     private ComponentsUtils componentsUtils;
 
-    public GlobalInputsFilteringBusinessLogic(GenericTypeBusinessLogic genericTypeBusinessLogic, ToscaOperationFacade toscaOperationFacade, ComponentsUtils componentsUtils) {
+    public GlobalInputsFilteringBusinessLogic(GenericTypeBusinessLogic genericTypeBusinessLogic, ToscaOperationFacade toscaOperationFacade,
+                                              ComponentsUtils componentsUtils) {
         this.genericTypeBusinessLogic = genericTypeBusinessLogic;
         this.toscaOperationFacade = toscaOperationFacade;
         this.componentsUtils = componentsUtils;
     }
 
     public Either<List<InputDefinition>, ActionStatus> filterGlobalInputs(Component newResource) {
-            Either<Resource, StorageOperationStatus> genericComp = toscaOperationFacade.getLatestCertifiedNodeTypeByToscaResourceName(newResource.fetchGenericTypeToscaNameFromConfig());
-            return genericComp.bimap(genericResource -> findCommonInputs(genericResource, newResource),
-                                     storageOperationStatus -> componentsUtils.convertFromStorageResponse(storageOperationStatus));
+        Either<Resource, StorageOperationStatus> genericComp = toscaOperationFacade
+            .getLatestCertifiedNodeTypeByToscaResourceName(newResource.fetchGenericTypeToscaNameFromConfig());
+        return genericComp.bimap(genericResource -> findCommonInputs(genericResource, newResource),
+            storageOperationStatus -> componentsUtils.convertFromStorageResponse(storageOperationStatus));
     }
 
     private List<InputDefinition> findCommonInputs(Resource genericResource, Component resource) {
@@ -59,5 +59,4 @@ public class GlobalInputsFilteringBusinessLogic {
         Set<String> genericInputsNames = genericInputs.stream().map(InputDefinition::getName).collect(Collectors.toSet());
         return resourceInputs.stream().filter(input -> genericInputsNames.contains(input.getName())).collect(Collectors.toList());
     }
-
 }
index 47f71cb..0c64538 100644 (file)
@@ -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.
  * limitations under the License.
  * ============LICENSE_END=========================================================
  */
-
 package org.openecomp.sdc.be.components.merge;
 
+import java.util.List;
+import java.util.Map;
+import java.util.Optional;
 import org.openecomp.sdc.be.model.ComponentInstance;
 import org.openecomp.sdc.be.model.RelationshipInfo;
 import org.openecomp.sdc.be.model.RequirementCapabilityRelDef;
 import org.openecomp.sdc.be.model.Resource;
 import org.springframework.stereotype.Component;
 
-import java.util.List;
-import java.util.Map;
-import java.util.Optional;
-
 @Component
 public class RelationsComparator {
 
     /**
-     *
      * @param oldResource the old resource
      * @param newResource the new resource
-     * @return true if there was a change in one of the relations between the old and new resource
-     * a change in relation is determine by comparing the relations type, node, capability and requirement name
+     * @return true if there was a change in one of the relations between the old and new resource a change in relation is determine by comparing the
+     * relations type, node, capability and requirement name
      */
-    public boolean isRelationsChanged(Resource oldResource,  Resource newResource) {
+    public boolean isRelationsChanged(Resource oldResource, Resource newResource) {
         Map<String, List<RequirementCapabilityRelDef>> oldRelationsByInstance = oldResource.groupRelationsFromCsarByInstanceName(oldResource);
         Map<String, List<RequirementCapabilityRelDef>> newRelationsByInstance = newResource.groupRelationsFromCsarByInstanceName(newResource);
         for (Map.Entry<String, List<RequirementCapabilityRelDef>> relationByInst : newRelationsByInstance.entrySet()) {
@@ -51,48 +48,48 @@ public class RelationsComparator {
             }
         }
         return false;
-
     }
 
-    private boolean isInstanceRelationsChanged(Resource oldResource, List<RequirementCapabilityRelDef> oldRelations, Resource newResource, List<RequirementCapabilityRelDef> newRelations) {
-        if (oldRelations == null || oldRelations.size() != newRelations.size()){
+    private boolean isInstanceRelationsChanged(Resource oldResource, List<RequirementCapabilityRelDef> oldRelations, Resource newResource,
+                                               List<RequirementCapabilityRelDef> newRelations) {
+        if (oldRelations == null || oldRelations.size() != newRelations.size()) {
             return true;
         }
         return newRelations.stream().anyMatch(newRelation -> !findRelation(oldResource, oldRelations, newResource, newRelation));
     }
 
-
-
-    private boolean findRelation(Resource oldResource, List<RequirementCapabilityRelDef> oldRelations, Resource newResource, RequirementCapabilityRelDef newRelation) {
+    private boolean findRelation(Resource oldResource, List<RequirementCapabilityRelDef> oldRelations, Resource newResource,
+                                 RequirementCapabilityRelDef newRelation) {
         for (RequirementCapabilityRelDef oldRelation : oldRelations) {
             RelationshipInfo oldRelationship = oldRelation.resolveSingleRelationship().getRelation();
             RelationshipInfo newRelationship = newRelation.resolveSingleRelationship().getRelation();
-            if (oldRelationship != null && newRelationship != null && isRelationEqual(oldRelationship, newRelationship) && isRelationToNodeEquals(oldResource, oldRelation, newResource, newRelation)) {
+            if (oldRelationship != null && newRelationship != null && isRelationEqual(oldRelationship, newRelationship) && isRelationToNodeEquals(
+                oldResource, oldRelation, newResource, newRelation)) {
                 return true;
             }
         }
         return false;
     }
 
-    private boolean isRelationToNodeEquals(Resource oldResource, RequirementCapabilityRelDef oldRelation, Resource newResource, RequirementCapabilityRelDef newRelation) {
+    private boolean isRelationToNodeEquals(Resource oldResource, RequirementCapabilityRelDef oldRelation, Resource newResource,
+                                           RequirementCapabilityRelDef newRelation) {
         String oldToNodeId = oldRelation.getToNode();
         String newToNodeId = newRelation.getToNode();
         Optional<ComponentInstance> oldRelationToNode = oldResource.getComponentInstanceById(oldToNodeId);
         Optional<ComponentInstance> newRelationToNode = newResource.getComponentInstanceById(newToNodeId);
-        return oldRelationToNode.isPresent() && newRelationToNode.isPresent() && oldRelationToNode.get().getInvariantName().equals(newRelationToNode.get().getInvariantName());
+        return oldRelationToNode.isPresent() && newRelationToNode.isPresent() && oldRelationToNode.get().getInvariantName()
+            .equals(newRelationToNode.get().getInvariantName());
     }
 
     private boolean isRelationEqual(RelationshipInfo oldRelationship, RelationshipInfo newRelationship) {
-        return isRelationshipTypeEquals(oldRelationship, newRelationship) &&
-               isRelationshipCapabilityEquals(oldRelationship, newRelationship) &&
-               isRelationshipReqNameEquals(oldRelationship, newRelationship);
+        return isRelationshipTypeEquals(oldRelationship, newRelationship) && isRelationshipCapabilityEquals(oldRelationship, newRelationship)
+            && isRelationshipReqNameEquals(oldRelationship, newRelationship);
     }
 
     private boolean isRelationshipCapabilityEquals(RelationshipInfo oldRelationship, RelationshipInfo newRelationship) {
-        if(oldRelationship.getCapabilityUid() !=null && newRelationship.getCapabilityUid() != null){
+        if (oldRelationship.getCapabilityUid() != null && newRelationship.getCapabilityUid() != null) {
             return oldRelationship.getCapabilityUid().equals(newRelationship.getCapabilityUid());
-        }
-        else if(oldRelationship.getCapabilityUid() == null && newRelationship.getCapabilityUid() == null){
+        } else if (oldRelationship.getCapabilityUid() == null && newRelationship.getCapabilityUid() == null) {
             return true;
         }
         return false;
@@ -103,13 +100,11 @@ public class RelationsComparator {
     }
 
     private boolean isRelationshipReqNameEquals(RelationshipInfo oldRelationship, RelationshipInfo newRelationship) {
-        if(oldRelationship.getRequirement() != null && newRelationship.getRequirement() != null){
+        if (oldRelationship.getRequirement() != null && newRelationship.getRequirement() != null) {
             return oldRelationship.getRequirement().equals(newRelationship.getRequirement());
-        }
-        else if(oldRelationship.getRequirement() == null && newRelationship.getRequirement() == null){
+        } else if (oldRelationship.getRequirement() == null && newRelationship.getRequirement() == null) {
             return true;
         }
         return false;
     }
-
 }
index 24e669a..bb84a57 100644 (file)
@@ -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.
  * limitations under the License.
  * ============LICENSE_END=========================================================
  */
-
 package org.openecomp.sdc.be.components.merge;
 
 import fj.data.Either;
+import java.util.List;
+import java.util.Map;
 import org.openecomp.sdc.be.dao.api.ActionStatus;
 import org.openecomp.sdc.be.dao.utils.MapUtil;
 import org.openecomp.sdc.be.exception.SdcActionException;
@@ -32,29 +33,22 @@ import org.openecomp.sdc.be.model.jsonjanusgraph.operations.ToscaOperationFacade
 import org.openecomp.sdc.be.model.operations.api.StorageOperationStatus;
 import org.openecomp.sdc.common.log.wrappers.Logger;
 
-import java.util.List;
-import java.util.Map;
-
 @org.springframework.stereotype.Component
 public class TopologyComparator {
 
     public static final Logger log = Logger.getLogger(TopologyComparator.class);
-
     @javax.annotation.Resource
     private RelationsComparator relationsComparator;
-
     @javax.annotation.Resource
     private ToscaOperationFacade toscaOperationFacade;
-
     @javax.annotation.Resource
     private ComponentsUtils componentsUtils;
 
     /**
-     *
      * @param oldResource the old version of the resource of which to check for topology change
      * @param newResource the new version of the resource of which to check for topology change
-     * @return true if there was a topology change between the old resource and new resource or false otherwise
-     * in case the action to find topology change failed, an appropriate {@link ActionStatus} will be returned
+     * @return true if there was a topology change between the old resource and new resource or false otherwise in case the action to find topology
+     * change failed, an appropriate {@link ActionStatus} will be returned
      */
     public Either<Boolean, ActionStatus> isTopologyChanged(Resource oldResource, Resource newResource) {
         List<ComponentInstance> oldInstances = oldResource.getComponentInstances();
@@ -70,14 +64,17 @@ public class TopologyComparator {
         return isTopologyInstancesChanged(oldResource, newResource, oldInstancesByName, newInstancesByName);
     }
 
-    private Either<Boolean, ActionStatus> isTopologyInstancesChanged(Resource oldResource, Resource newResource, Map<String, ComponentInstance> oldInstancesByName, Map<String, ComponentInstance> newInstancesByName) {
+    private Either<Boolean, ActionStatus> isTopologyInstancesChanged(Resource oldResource, Resource newResource,
+                                                                     Map<String, ComponentInstance> oldInstancesByName,
+                                                                     Map<String, ComponentInstance> newInstancesByName) {
         try {
-            boolean isTopologyChanged = isInstanceNamesChanged(oldInstancesByName, newInstancesByName) ||
-                                        isInstanceTypesChanged(oldInstancesByName, newInstancesByName) ||
-                                        relationsComparator.isRelationsChanged(oldResource, newResource);
+            boolean isTopologyChanged =
+                isInstanceNamesChanged(oldInstancesByName, newInstancesByName) || isInstanceTypesChanged(oldInstancesByName, newInstancesByName)
+                    || relationsComparator.isRelationsChanged(oldResource, newResource);
             return Either.left(isTopologyChanged);
         } catch (SdcActionException e) {
-            log.error("failed to merge entities of previous resource %s to current resource %s. reason: %s", oldResource.getUniqueId(), newResource.getUniqueId(), e.getActionStatus(), e);
+            log.error("failed to merge entities of previous resource %s to current resource %s. reason: %s", oldResource.getUniqueId(),
+                newResource.getUniqueId(), e.getActionStatus(), e);
             return Either.right(e.getActionStatus());
         }
     }
@@ -97,8 +94,7 @@ public class TopologyComparator {
     }
 
     private boolean isSameToscaTypeOrOriginComponent(ComponentInstance oldInstance, ComponentInstance newInstance) {
-        return isSameToscaType(oldInstance, newInstance) ||
-               isSameOriginComponent(oldInstance, newInstance);
+        return isSameToscaType(oldInstance, newInstance) || isSameOriginComponent(oldInstance, newInstance);
     }
 
     private boolean isSameToscaType(ComponentInstance oldInstance, ComponentInstance newInstance) {
@@ -109,8 +105,10 @@ public class TopologyComparator {
         if (oldInstance.getComponentUid().equals(newInstance.getComponentUid())) {
             return true;
         }
-        Component oldOriginCmpt = toscaOperationFacade.getToscaElement(oldInstance.getComponentUid()).left().on(storageStatus -> throwSdcActionException(storageStatus, oldInstance));
-        Component newOriginCmpt = toscaOperationFacade.getToscaElement(newInstance.getComponentUid()).left().on(storageStatus -> throwSdcActionException(storageStatus, newInstance));
+        Component oldOriginCmpt = toscaOperationFacade.getToscaElement(oldInstance.getComponentUid()).left()
+            .on(storageStatus -> throwSdcActionException(storageStatus, oldInstance));
+        Component newOriginCmpt = toscaOperationFacade.getToscaElement(newInstance.getComponentUid()).left()
+            .on(storageStatus -> throwSdcActionException(storageStatus, newInstance));
         return oldOriginCmpt.getInvariantUUID().equals(newOriginCmpt.getInvariantUUID());
     }
 
@@ -118,6 +116,4 @@ public class TopologyComparator {
         log.error("failed to fetch origin node type %s for instance %s", cmptInstance.getUniqueId(), cmptInstance.getComponentUid());
         throw new SdcActionException(componentsUtils.convertFromStorageResponse(storageOperationStatus));
     }
-
-
 }
index 44fbc9a..1cfc53e 100644 (file)
@@ -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.
@@ -17,7 +17,6 @@
  * limitations under the License.
  * ============LICENSE_END=========================================================
  */
-
 package org.openecomp.sdc.be.components.merge;
 
 /**
@@ -25,5 +24,4 @@ package org.openecomp.sdc.be.components.merge;
  */
 public interface VspComponentsMergeCommand extends ComponentsMergeCommand {
 
-
 }
index 9ec7104..4b5efbe 100644 (file)
@@ -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.
  * limitations under the License.
  * ============LICENSE_END=========================================================
  */
-
 package org.openecomp.sdc.be.components.merge.capability;
 
+import java.util.List;
+import java.util.Map;
 import org.openecomp.sdc.be.model.CapabilityDefinition;
 import org.openecomp.sdc.be.model.Component;
 import org.openecomp.sdc.be.model.ComponentInstance;
 
-import java.util.List;
-import java.util.Map;
-
 public interface CapabilityResolver {
 
     /**
-     *
-     * @param container the instance container
+     * @param container            the instance container
      * @param prevInstanceOrigNode the prev instance's original node type
-     * @param cmptInstanceId the current instance id
-     * @param prevCapabilities list of previous capabilities for which to find their corresponding new capabilities
+     * @param cmptInstanceId       the current instance id
+     * @param prevCapabilities     list of previous capabilities for which to find their corresponding new capabilities
      * @return a mapping between the prev capability to its corresponding new capability (if exists)
      */
-    Map<CapabilityDefinition, CapabilityDefinition> resolvePrevCapToNewCapability(Component container, Component prevInstanceOrigNode, String cmptInstanceId, List<CapabilityDefinition> prevCapabilities);
+    Map<CapabilityDefinition, CapabilityDefinition> resolvePrevCapToNewCapability(Component container, Component prevInstanceOrigNode,
+                                                                                  String cmptInstanceId, List<CapabilityDefinition> prevCapabilities);
 
     /**
-     *
-     * @param oldInstance the old instance of which its capabilities are to be mapped as the key
+     * @param oldInstance  the old instance of which its capabilities are to be mapped as the key
      * @param currInstance the curr instance of which its capabilities are to be mapped as the value
      * @return a mapping between the prev capability to its corresponding new capability (if exists)
      */
index 3f6ed7d..85fe692 100644 (file)
@@ -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.
  * limitations under the License.
  * ============LICENSE_END=========================================================
  */
-
 package org.openecomp.sdc.be.components.merge.capability;
 
-import org.openecomp.sdc.be.components.merge.utils.MergeInstanceUtils;
-import org.openecomp.sdc.be.dao.utils.MapUtil;
-import org.openecomp.sdc.be.model.CapabilityDefinition;
-import org.openecomp.sdc.be.model.Component;
-import org.openecomp.sdc.be.model.ComponentInstance;
+import static java.util.stream.Collectors.toList;
+import static org.openecomp.sdc.be.dao.utils.MapUtil.flattenMapValues;
 
 import java.util.ArrayList;
 import java.util.HashMap;
 import java.util.List;
 import java.util.Map;
 import java.util.Objects;
+import org.openecomp.sdc.be.components.merge.utils.MergeInstanceUtils;
+import org.openecomp.sdc.be.dao.utils.MapUtil;
+import org.openecomp.sdc.be.model.CapabilityDefinition;
+import org.openecomp.sdc.be.model.Component;
+import org.openecomp.sdc.be.model.ComponentInstance;
 
-import static java.util.stream.Collectors.toList;
-import static org.openecomp.sdc.be.dao.utils.MapUtil.flattenMapValues;
 @org.springframework.stereotype.Component
 public class SimpleCapabilityResolver implements CapabilityResolver {
 
@@ -44,27 +43,36 @@ public class SimpleCapabilityResolver implements CapabilityResolver {
     }
 
     @Override
-    public Map<CapabilityDefinition, CapabilityDefinition> resolvePrevCapToNewCapability(Component container, Component prevInstanceOrigNode, String cmptInstanceId, List<CapabilityDefinition> prevCapabilities) {
+    public Map<CapabilityDefinition, CapabilityDefinition> resolvePrevCapToNewCapability(Component container, Component prevInstanceOrigNode,
+                                                                                         String cmptInstanceId,
+                                                                                         List<CapabilityDefinition> prevCapabilities) {
         List<CapabilityDefinition> newCapabilities = resolveInstanceCapabilities(container, cmptInstanceId);
-        Map<String, String> oldCapOwnerToNewOwner = mapOldToNewCapabilitiesOwnerIds(container, prevInstanceOrigNode, cmptInstanceId, prevCapabilities);
+        Map<String, String> oldCapOwnerToNewOwner = mapOldToNewCapabilitiesOwnerIds(container, prevInstanceOrigNode, cmptInstanceId,
+            prevCapabilities);
         return mapOldToNewCapabilities(prevCapabilities, newCapabilities, oldCapOwnerToNewOwner);
     }
 
     @Override
-    public Map<CapabilityDefinition, CapabilityDefinition> resolvePrevCapIdToNewCapability(ComponentInstance oldInstance, ComponentInstance currInstance) {
+    public Map<CapabilityDefinition, CapabilityDefinition> resolvePrevCapIdToNewCapability(ComponentInstance oldInstance,
+                                                                                           ComponentInstance currInstance) {
         List<CapabilityDefinition> newCapabilities = flattenMapValues(currInstance.getCapabilities());
         List<CapabilityDefinition> prevCapabilities = flattenMapValues(oldInstance.getCapabilities());
         Map<String, String> oldCapOwnerToNewOwner = mergeInstanceUtils.mapOldToNewCapabilitiesOwnerIds(oldInstance, currInstance);
         return mapOldToNewCapabilities(prevCapabilities, newCapabilities, oldCapOwnerToNewOwner);
     }
 
-    private Map<CapabilityDefinition, CapabilityDefinition> mapOldToNewCapabilities(List<CapabilityDefinition> prevCapabilities, List<CapabilityDefinition> newCapabilities, Map<String, String> oldCapOwnerToNewOwner) {
-        Map<CapabilityDefinition, CapabilityDefinition> oldToNewCapability = findNewCapByPrevCapabilityNameTypeAndOwner(prevCapabilities, newCapabilities, oldCapOwnerToNewOwner);
+    private Map<CapabilityDefinition, CapabilityDefinition> mapOldToNewCapabilities(List<CapabilityDefinition> prevCapabilities,
+                                                                                    List<CapabilityDefinition> newCapabilities,
+                                                                                    Map<String, String> oldCapOwnerToNewOwner) {
+        Map<CapabilityDefinition, CapabilityDefinition> oldToNewCapability = findNewCapByPrevCapabilityNameTypeAndOwner(prevCapabilities,
+            newCapabilities, oldCapOwnerToNewOwner);
         removeNotFoundNewCapabilities(oldToNewCapability);
         return oldToNewCapability;
     }
 
-    private Map<CapabilityDefinition, CapabilityDefinition> findNewCapByPrevCapabilityNameTypeAndOwner(List<CapabilityDefinition> prevCapabilities, List<CapabilityDefinition> newCapabilities, Map<String, String> oldCapOwnerToNewOwner) {
+    private Map<CapabilityDefinition, CapabilityDefinition> findNewCapByPrevCapabilityNameTypeAndOwner(List<CapabilityDefinition> prevCapabilities,
+                                                                                                       List<CapabilityDefinition> newCapabilities,
+                                                                                                       Map<String, String> oldCapOwnerToNewOwner) {
         Map<CapabilityDefinition, CapabilityDefinition> prevToNewCapabilityMapping = new HashMap<>();
         prevCapabilities.forEach(prevCap -> {
             CapabilityDefinition newCapability = mapOldToNewCapability(prevCap, newCapabilities, oldCapOwnerToNewOwner);
@@ -73,18 +81,16 @@ public class SimpleCapabilityResolver implements CapabilityResolver {
         return prevToNewCapabilityMapping;
     }
 
-    private CapabilityDefinition mapOldToNewCapability(CapabilityDefinition prevCap, List<CapabilityDefinition> newCapabilities, Map<String, String> oldCapOwnerToNewOwner) {
+    private CapabilityDefinition mapOldToNewCapability(CapabilityDefinition prevCap, List<CapabilityDefinition> newCapabilities,
+                                                       Map<String, String> oldCapOwnerToNewOwner) {
         String newOwnerId = oldCapOwnerToNewOwner.get(prevCap.getOwnerId());
-        return newCapabilities.stream()
-                       .filter(newCap -> newCap.getName().equals(prevCap.getName()))
-                       .filter(newCap -> newCap.getType().equals(prevCap.getType()))
-                       .filter(newCap -> newCap.getOwnerId().equals(newOwnerId))
-                       .findFirst()
-                       .orElse(null);
+        return newCapabilities.stream().filter(newCap -> newCap.getName().equals(prevCap.getName()))
+            .filter(newCap -> newCap.getType().equals(prevCap.getType())).filter(newCap -> newCap.getOwnerId().equals(newOwnerId)).findFirst()
+            .orElse(null);
     }
 
-
-    private Map<String, String> mapOldToNewCapabilitiesOwnerIds(Component container, Component origInstanceNode, String cmptInstanceId, List<CapabilityDefinition> prevCapabilities) {
+    private Map<String, String> mapOldToNewCapabilitiesOwnerIds(Component container, Component origInstanceNode, String cmptInstanceId,
+                                                                List<CapabilityDefinition> prevCapabilities) {
         List<String> prevCapOwnerIds = prevCapabilities.stream().map(CapabilityDefinition::getOwnerId).distinct().collect(toList());
         return mergeInstanceUtils.mapOldToNewCapabilitiesOwnerIds(container, origInstanceNode, cmptInstanceId, prevCapOwnerIds);
     }
@@ -94,14 +100,7 @@ public class SimpleCapabilityResolver implements CapabilityResolver {
     }
 
     private List<CapabilityDefinition> resolveInstanceCapabilities(Component capabilityOwnerContainer, String cmptInstanceId) {
-        return capabilityOwnerContainer.getComponentInstanceById(cmptInstanceId)
-                .map(ComponentInstance::getCapabilities)
-                .map(MapUtil::flattenMapValues)
-                .orElse(new ArrayList<>());
+        return capabilityOwnerContainer.getComponentInstanceById(cmptInstanceId).map(ComponentInstance::getCapabilities)
+            .map(MapUtil::flattenMapValues).orElse(new ArrayList<>());
     }
-
-
-
-
-
 }
index dc3f205..560d17d 100644 (file)
@@ -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.
  * limitations under the License.
  * ============LICENSE_END=========================================================
  */
-
 package org.openecomp.sdc.be.components.merge.group;
 
+import static java.util.stream.Collectors.toList;
+import static java.util.stream.Collectors.toMap;
+import static org.apache.commons.collections.CollectionUtils.isEmpty;
+import static org.apache.commons.collections.MapUtils.isEmpty;
+import static org.openecomp.sdc.be.components.merge.resource.ResourceDataMergeBusinessLogic.FIRST_COMMAND;
+
+import java.util.List;
+import java.util.Map;
+import java.util.Optional;
 import org.openecomp.sdc.be.components.merge.ComponentsGlobalMergeCommand;
 import org.openecomp.sdc.be.components.merge.VspComponentsMergeCommand;
 import org.openecomp.sdc.be.dao.api.ActionStatus;
@@ -31,16 +39,6 @@ import org.openecomp.sdc.be.model.jsonjanusgraph.operations.GroupsOperation;
 import org.openecomp.sdc.common.log.wrappers.Logger;
 import org.springframework.core.annotation.Order;
 
-import java.util.List;
-import java.util.Map;
-import java.util.Optional;
-
-import static java.util.stream.Collectors.toList;
-import static java.util.stream.Collectors.toMap;
-import static org.apache.commons.collections.CollectionUtils.isEmpty;
-import static org.apache.commons.collections.MapUtils.isEmpty;
-import static org.openecomp.sdc.be.components.merge.resource.ResourceDataMergeBusinessLogic.FIRST_COMMAND;
-
 @org.springframework.stereotype.Component
 @Order(FIRST_COMMAND)//must run before policies merge command
 public class ComponentGroupMergeCommand implements VspComponentsMergeCommand, ComponentsGlobalMergeCommand {
@@ -71,15 +69,11 @@ public class ComponentGroupMergeCommand implements VspComponentsMergeCommand, Co
         }
         updateGroupsMembers(prevUserDefinedGroups, prevComponent, currentComponent);
         return associateGroupsToComponent(currentComponent, prevUserDefinedGroups);
-
     }
 
     private List<GroupDefinition> getAllPreviouslyUserDefinedGroups(Component prevComponent, Component currCmpt) {
-        return prevComponent.getGroups()
-                .stream()
-                .filter(GroupDefinition::isUserDefined)
-                .filter(group -> !currCmpt.containsGroupWithInvariantName(group.getInvariantName()))
-                .collect(toList());
+        return prevComponent.getGroups().stream().filter(GroupDefinition::isUserDefined)
+            .filter(group -> !currCmpt.containsGroupWithInvariantName(group.getInvariantName())).collect(toList());
     }
 
     private void updateGroupsMembers(List<GroupDefinition> prevUserDefinedGroups, Component prevComponent, Component currentComponent) {
@@ -96,26 +90,16 @@ public class ComponentGroupMergeCommand implements VspComponentsMergeCommand, Co
         return findNewInstancesByPrevInstancesNames(prevComponent, currentComponent, prevGroupMembers);
     }
 
-    private Map<String, String> findNewInstancesByPrevInstancesNames(Component prevComponent, Component currentComponent, Map<String, String> prevGroupMembers) {
-        return prevGroupMembers.values()
-                .stream()
-                .map(prevComponent::getComponentInstanceById)
-                .filter(Optional::isPresent)
-                .map(Optional::get)
-                .map(prevInstance -> currentComponent.getComponentInstanceByName(prevInstance.getName()))
-                .filter(Optional::isPresent)
-                .map(Optional::get)
-                .collect(toMap(ComponentInstance::getName, ComponentInstance::getUniqueId));
+    private Map<String, String> findNewInstancesByPrevInstancesNames(Component prevComponent, Component currentComponent,
+                                                                     Map<String, String> prevGroupMembers) {
+        return prevGroupMembers.values().stream().map(prevComponent::getComponentInstanceById).filter(Optional::isPresent).map(Optional::get)
+            .map(prevInstance -> currentComponent.getComponentInstanceByName(prevInstance.getName())).filter(Optional::isPresent).map(Optional::get)
+            .collect(toMap(ComponentInstance::getName, ComponentInstance::getUniqueId));
     }
 
     private ActionStatus associateGroupsToComponent(Component currentComponent, List<GroupDefinition> prevUserDefinedGroups) {
         currentComponent.addGroups(prevUserDefinedGroups);
         return groupsOperation.addGroups(currentComponent, prevUserDefinedGroups)
-                .either(addedGroups -> ActionStatus.OK,
-                        componentsUtils::convertFromStorageResponse);
+            .either(addedGroups -> ActionStatus.OK, componentsUtils::convertFromStorageResponse);
     }
-
-
-
-
 }
index 00276a9..c9621c3 100644 (file)
@@ -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.
  * limitations under the License.
  * ============LICENSE_END=========================================================
  */
-
 package org.openecomp.sdc.be.components.merge.group;
 
+import static java.util.Collections.emptyList;
+import static java.util.stream.Collectors.toList;
+import static java.util.stream.Collectors.toMap;
+import static org.apache.commons.collections.CollectionUtils.isEmpty;
+import static org.apache.commons.collections.CollectionUtils.isNotEmpty;
+import static org.openecomp.sdc.be.components.merge.resource.ResourceDataMergeBusinessLogic.ANY_ORDER_COMMAND;
+
+import java.util.List;
+import java.util.Map;
 import org.openecomp.sdc.be.components.merge.ComponentsGlobalMergeCommand;
 import org.openecomp.sdc.be.components.merge.VspComponentsMergeCommand;
 import org.openecomp.sdc.be.components.merge.property.DataDefinitionsValuesMergingBusinessLogic;
@@ -33,16 +41,6 @@ import org.openecomp.sdc.be.model.InputDefinition;
 import org.openecomp.sdc.be.model.jsonjanusgraph.operations.GroupsOperation;
 import org.springframework.core.annotation.Order;
 
-import java.util.List;
-import java.util.Map;
-
-import static java.util.Collections.emptyList;
-import static java.util.stream.Collectors.toList;
-import static java.util.stream.Collectors.toMap;
-import static org.apache.commons.collections.CollectionUtils.isEmpty;
-import static org.apache.commons.collections.CollectionUtils.isNotEmpty;
-import static org.openecomp.sdc.be.components.merge.resource.ResourceDataMergeBusinessLogic.ANY_ORDER_COMMAND;
-
 @org.springframework.stereotype.Component
 @Order(ANY_ORDER_COMMAND)
 public class GroupPropertiesMergeCommand implements VspComponentsMergeCommand, ComponentsGlobalMergeCommand {
@@ -51,7 +49,8 @@ public class GroupPropertiesMergeCommand implements VspComponentsMergeCommand, C
     private final ComponentsUtils componentsUtils;
     private final DataDefinitionsValuesMergingBusinessLogic propertyValuesMergingBusinessLogic;
 
-    public GroupPropertiesMergeCommand(GroupsOperation groupsOperation, ComponentsUtils componentsUtils, DataDefinitionsValuesMergingBusinessLogic propertyValuesMergingBusinessLogic) {
+    public GroupPropertiesMergeCommand(GroupsOperation groupsOperation, ComponentsUtils componentsUtils,
+                                       DataDefinitionsValuesMergingBusinessLogic propertyValuesMergingBusinessLogic) {
         this.groupsOperation = groupsOperation;
         this.componentsUtils = componentsUtils;
         this.propertyValuesMergingBusinessLogic = propertyValuesMergingBusinessLogic;
@@ -64,9 +63,10 @@ public class GroupPropertiesMergeCommand implements VspComponentsMergeCommand, C
 
     /**
      * merge user defined group properties values from previous version into vsp defined groups in new version
-     * @param prevComponent the old component, whose group properties need to be merged from
-     * @param currentComponent the new component, whose group properties need to be merged into
-     * old and new component inputs are needed in order to determine if a "get_input" property value should be merged
+     *
+     * @param prevComponent    the old component, whose group properties need to be merged from
+     * @param currentComponent the new component, whose group properties need to be merged into old and new component inputs are needed in order to
+     *                         determine if a "get_input" property value should be merged
      * @return the status of the merge operation
      */
     @Override
@@ -84,7 +84,8 @@ public class GroupPropertiesMergeCommand implements VspComponentsMergeCommand, C
         return mergeGroupPropertiesValues(prevComponent, currentComponent, prevGroups, newGroups);
     }
 
-    private List<GroupDefinition> mergeGroupPropertiesValues(Component prevComponent, Component currentComponent, List<GroupDefinition> prevGroups, List<GroupDefinition> newGroups) {
+    private List<GroupDefinition> mergeGroupPropertiesValues(Component prevComponent, Component currentComponent, List<GroupDefinition> prevGroups,
+                                                             List<GroupDefinition> newGroups) {
         Map<String, GroupDefinition> prevGroupsByInvariantName = getVspGroupsMappedByInvariantName(prevGroups);
         List<GroupDefinition> newGroupsExistInPrevVersion = getNewGroupsExistInPrevComponent(prevGroupsByInvariantName, newGroups);
         newGroupsExistInPrevVersion.forEach(newGroup -> {
@@ -94,23 +95,20 @@ public class GroupPropertiesMergeCommand implements VspComponentsMergeCommand, C
         return newGroupsExistInPrevVersion;
     }
 
-    private void mergeGroupProperties(GroupDefinition prevGroup, List<InputDefinition> prevInputs, GroupDefinition newGroup, List<InputDefinition> currInputs) {
+    private void mergeGroupProperties(GroupDefinition prevGroup, List<InputDefinition> prevInputs, GroupDefinition newGroup,
+                                      List<InputDefinition> currInputs) {
         propertyValuesMergingBusinessLogic.mergeInstanceDataDefinitions(prevGroup.getProperties(), prevInputs, newGroup.getProperties(), currInputs);
     }
 
-    private List<GroupDefinition> getNewGroupsExistInPrevComponent(Map<String, GroupDefinition> prevGroupsByInvariantName, List<GroupDefinition> newGroups) {
-        return newGroups.stream()
-                .filter(newGroup -> prevGroupsByInvariantName.containsKey(newGroup.getInvariantName()))
-                .filter(newGroup -> isNotEmpty(newGroup.getProperties()))
-                .collect(toList());
+    private List<GroupDefinition> getNewGroupsExistInPrevComponent(Map<String, GroupDefinition> prevGroupsByInvariantName,
+                                                                   List<GroupDefinition> newGroups) {
+        return newGroups.stream().filter(newGroup -> prevGroupsByInvariantName.containsKey(newGroup.getInvariantName()))
+            .filter(newGroup -> isNotEmpty(newGroup.getProperties())).collect(toList());
     }
 
     private Map<String, GroupDefinition> getVspGroupsMappedByInvariantName(List<GroupDefinition> newGroups) {
-        return newGroups.stream()
-                .filter(GroupDataDefinition::isVspOriginated)
-                .filter(grp -> isNotEmpty(grp.getProperties()))
-                .collect(toMap(GroupDataDefinition::getInvariantName,
-                               group -> group));
+        return newGroups.stream().filter(GroupDataDefinition::isVspOriginated).filter(grp -> isNotEmpty(grp.getProperties()))
+            .collect(toMap(GroupDataDefinition::getInvariantName, group -> group));
     }
 
     private ActionStatus updateGroups(Component currentComponent, List<GroupDefinition> groupsToUpdate) {
@@ -118,8 +116,6 @@ public class GroupPropertiesMergeCommand implements VspComponentsMergeCommand, C
             return ActionStatus.OK;
         }
         return groupsOperation.updateGroups(currentComponent, groupsToUpdate, PromoteVersionEnum.MINOR)
-                .either(updatedGroups -> ActionStatus.OK,
-                        err -> componentsUtils.convertFromStorageResponse(err, currentComponent.getComponentType()));
+            .either(updatedGroups -> ActionStatus.OK, err -> componentsUtils.convertFromStorageResponse(err, currentComponent.getComponentType()));
     }
-
 }
index 20e3db0..2b1df01 100644 (file)
@@ -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.
  * limitations under the License.
  * ============LICENSE_END=========================================================
  */
-
 package org.openecomp.sdc.be.components.merge.heat;
 
+import java.util.ArrayList;
+import java.util.List;
+import java.util.Map;
 import org.openecomp.sdc.be.dao.utils.MapUtil;
 import org.openecomp.sdc.be.model.ArtifactDefinition;
 import org.openecomp.sdc.be.model.HeatParameterDefinition;
 import org.springframework.stereotype.Component;
 import org.springframework.util.CollectionUtils;
 
-import java.util.ArrayList;
-import java.util.List;
-import java.util.Map;
-
 /**
  * Created by chaya on 9/14/2017.
  */
 @Component
 public class HeatEnvArtifactsMergeBusinessLogic {
 
-    public List<ArtifactDefinition> mergeInstanceHeatEnvArtifacts(List<ArtifactDefinition> origHeatEnvArtifacts, List<ArtifactDefinition> newHeatEnvArtifacts) {
+    public List<ArtifactDefinition> mergeInstanceHeatEnvArtifacts(List<ArtifactDefinition> origHeatEnvArtifacts,
+                                                                  List<ArtifactDefinition> newHeatEnvArtifacts) {
         Map<String, ArtifactDefinition> origArtifactDefinitionByLabel = MapUtil.toMap(origHeatEnvArtifacts, ArtifactDefinition::getArtifactLabel);
         List<ArtifactDefinition> artifactsToUpdate = new ArrayList<>();
-        newHeatEnvArtifacts.stream()
-                .filter(heatEnvArtifact -> origArtifactDefinitionByLabel.containsKey(heatEnvArtifact.getArtifactLabel()))
-                .forEach(heatEnvArtifact -> {
-                    ArtifactDefinition origHeatEnvArtifact = origArtifactDefinitionByLabel.get(heatEnvArtifact.getArtifactLabel());
-                    Boolean wasMergedHeatEnvArtifact = mergeHeatEnvArtifactsParameters(heatEnvArtifact, origHeatEnvArtifact);
-                    if (wasMergedHeatEnvArtifact) {
-                        artifactsToUpdate.add(heatEnvArtifact);
-                    }
-                });
+        newHeatEnvArtifacts.stream().filter(heatEnvArtifact -> origArtifactDefinitionByLabel.containsKey(heatEnvArtifact.getArtifactLabel()))
+            .forEach(heatEnvArtifact -> {
+                ArtifactDefinition origHeatEnvArtifact = origArtifactDefinitionByLabel.get(heatEnvArtifact.getArtifactLabel());
+                Boolean wasMergedHeatEnvArtifact = mergeHeatEnvArtifactsParameters(heatEnvArtifact, origHeatEnvArtifact);
+                if (wasMergedHeatEnvArtifact) {
+                    artifactsToUpdate.add(heatEnvArtifact);
+                }
+            });
         return artifactsToUpdate;
     }
 
@@ -55,13 +53,10 @@ public class HeatEnvArtifactsMergeBusinessLogic {
         List<HeatParameterDefinition> currentHeatEnvParams = currArtifact.getListHeatParameters();
         List<HeatParameterDefinition> origHeatEnvParams = origArtifact.getListHeatParameters();
         boolean wasChanged = false;
-
         if (CollectionUtils.isEmpty(origHeatEnvParams) || CollectionUtils.isEmpty(currentHeatEnvParams)) {
             return false;
         }
-
         Map<String, HeatParameterDefinition> origHeatParametersByName = MapUtil.toMap(origHeatEnvParams, HeatParameterDefinition::getName);
-
         for (HeatParameterDefinition currHeatParam : currentHeatEnvParams) {
             String paramName = currHeatParam.getName();
             HeatParameterDefinition origHeatParam = origHeatParametersByName.get(paramName);
@@ -75,10 +70,7 @@ public class HeatEnvArtifactsMergeBusinessLogic {
     }
 
     private boolean isSameHeatWithDiffValue(HeatParameterDefinition origHeatParam, HeatParameterDefinition newHeatParam) {
-        return origHeatParam != null &&
-               origHeatParam.getCurrentValue() != null &&
-               origHeatParam.getType().equals(newHeatParam.getType()) &&
-              !origHeatParam.getCurrentValue().equals(newHeatParam.getCurrentValue());
+        return origHeatParam != null && origHeatParam.getCurrentValue() != null && origHeatParam.getType().equals(newHeatParam.getType())
+            && !origHeatParam.getCurrentValue().equals(newHeatParam.getCurrentValue());
     }
-
 }
index 0e88c8f..6089bd2 100644 (file)
@@ -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.
  * limitations under the License.
  * ============LICENSE_END=========================================================
  */
-
 package org.openecomp.sdc.be.components.merge.input;
 
+import static java.util.stream.Collectors.toMap;
+import static org.openecomp.sdc.be.components.merge.resource.ResourceDataMergeBusinessLogic.PENULTIMATE_COMMAND;
+import static org.openecomp.sdc.be.utils.PropertyDefinitionUtils.convertListOfProperties;
+
+import java.util.List;
+import java.util.Map;
+import java.util.Map.Entry;
+import java.util.stream.Stream;
 import org.openecomp.sdc.be.components.merge.VspComponentsMergeCommand;
 import org.openecomp.sdc.be.dao.api.ActionStatus;
 import org.openecomp.sdc.be.datatypes.elements.PropertyDataDefinition;
@@ -29,20 +36,12 @@ import org.openecomp.sdc.be.model.InputDefinition;
 import org.openecomp.sdc.be.model.jsonjanusgraph.operations.ToscaOperationFacade;
 import org.springframework.core.annotation.Order;
 
-import java.util.List;
-import java.util.Map;
-import java.util.Map.Entry;
-import java.util.stream.Stream;
-
-import static java.util.stream.Collectors.toMap;
-import static org.openecomp.sdc.be.components.merge.resource.ResourceDataMergeBusinessLogic.PENULTIMATE_COMMAND;
-import static org.openecomp.sdc.be.utils.PropertyDefinitionUtils.convertListOfProperties;
-
 @org.springframework.stereotype.Component
 @Order(PENULTIMATE_COMMAND)//must run after all properties values were merged but before component instance relations merge
 public class ComponentInputsMergeBL extends InputsMergeCommand implements VspComponentsMergeCommand {
 
-    public ComponentInputsMergeBL(InputsValuesMergingBusinessLogic inputsValuesMergingBusinessLogic, DeclaredInputsResolver declaredInputsResolver, ToscaOperationFacade toscaOperationFacade, ComponentsUtils componentsUtils) {
+    public ComponentInputsMergeBL(InputsValuesMergingBusinessLogic inputsValuesMergingBusinessLogic, DeclaredInputsResolver declaredInputsResolver,
+                                  ToscaOperationFacade toscaOperationFacade, ComponentsUtils componentsUtils) {
         super(inputsValuesMergingBusinessLogic, declaredInputsResolver, toscaOperationFacade, componentsUtils);
     }
 
@@ -63,12 +62,9 @@ public class ComponentInputsMergeBL extends InputsMergeCommand implements VspCom
 
     @Override
     Map<String, List<PropertyDataDefinition>> getProperties(Component component) {
-        return Stream.of(component.safeGetComponentInstancesProperties(),
-                         component.safeGetComponentInstancesInputs(),
-                         component.safeGetGroupsProperties(),
-                         component.safeGetPolicyProperties())
-                .flatMap(map -> map.entrySet().stream())
-                .collect(toMap(Entry::getKey, entry -> convertListOfProperties(entry.getValue())));
+        return Stream
+            .of(component.safeGetComponentInstancesProperties(), component.safeGetComponentInstancesInputs(), component.safeGetGroupsProperties(),
+                component.safeGetPolicyProperties()).flatMap(map -> map.entrySet().stream())
+            .collect(toMap(Entry::getKey, entry -> convertListOfProperties(entry.getValue())));
     }
-
 }
index 0d3d294..2da3ade 100644 (file)
@@ -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.
  * limitations under the License.
  * ============LICENSE_END=========================================================
  */
-
 package org.openecomp.sdc.be.components.merge.input;
 
+import static org.openecomp.sdc.be.utils.PropertyDefinitionUtils.resolveGetInputProperties;
 
 import com.google.common.base.Strings;
-import org.openecomp.sdc.be.dao.utils.MapUtil;
-import org.openecomp.sdc.be.datatypes.elements.GetInputValueDataDefinition;
-import org.openecomp.sdc.be.datatypes.elements.PropertyDataDefinition;
-import org.openecomp.sdc.be.model.Component;
-import org.openecomp.sdc.be.model.InputDefinition;
-
 import java.util.ArrayList;
 import java.util.List;
 import java.util.Map;
 import java.util.Objects;
 import java.util.stream.Collectors;
-
-import static org.openecomp.sdc.be.utils.PropertyDefinitionUtils.resolveGetInputProperties;
+import org.openecomp.sdc.be.dao.utils.MapUtil;
+import org.openecomp.sdc.be.datatypes.elements.GetInputValueDataDefinition;
+import org.openecomp.sdc.be.datatypes.elements.PropertyDataDefinition;
+import org.openecomp.sdc.be.model.Component;
+import org.openecomp.sdc.be.model.InputDefinition;
 
 @org.springframework.stereotype.Component
 public class DeclaredInputsResolver {
+
     /**
      * @param oldComponent the old state of {@link Component} that is being updated
      * @param newComponent the new state of {@link Component} that is being updated
-     * @param properties a list of properties
-     * @return a list of all inputs that were previously declared and need to be merged to the updating component
-     * An input needs to merged if a property was declared as an input (by the user) in previous component version and the declared input not exist in new version
+     * @param properties   a list of properties
+     * @return a list of all inputs that were previously declared and need to be merged to the updating component An input needs to merged if a
+     * property was declared as an input (by the user) in previous component version and the declared input not exist in new version
      */
-    List<InputDefinition> getPreviouslyDeclaredInputsToMerge(Component oldComponent, Component newComponent, Map<String, List<PropertyDataDefinition>> properties) {
+    List<InputDefinition> getPreviouslyDeclaredInputsToMerge(Component oldComponent, Component newComponent,
+                                                             Map<String, List<PropertyDataDefinition>> properties) {
         List<InputDefinition> oldInputs = oldComponent.safeGetInputs();
         return getPreviouslyDeclaredInputsToMerge(oldInputs, newComponent, properties);
     }
 
-    public List<InputDefinition> getPreviouslyDeclaredInputsToMerge(List<InputDefinition> oldInputs, Component newComponent, Map<String, List<PropertyDataDefinition>> properties) {
+    public List<InputDefinition> getPreviouslyDeclaredInputsToMerge(List<InputDefinition> oldInputs, Component newComponent,
+                                                                    Map<String, List<PropertyDataDefinition>> properties) {
         Map<String, List<PropertyDataDefinition>> getInputProperties = resolveGetInputProperties(properties);
         List<RedeclareInputData> inputsToRedeclareData = buildRedeclareInputData(newComponent, getInputProperties);
         return findPrevDeclaredInputs(oldInputs, inputsToRedeclareData);
@@ -59,9 +59,9 @@ public class DeclaredInputsResolver {
     private List<RedeclareInputData> buildRedeclareInputData(Component newComponent, Map<String, List<PropertyDataDefinition>> getInputProperties) {
         Map<String, InputDefinition> inputsById = MapUtil.toMap(newComponent.getInputs(), InputDefinition::getUniqueId);
         List<RedeclareInputData> redeclareInputData = new ArrayList<>();
-        getInputProperties.forEach((instanceId, getInputProps) -> redeclareInputData.addAll(findInputsToRedeclare(inputsById, instanceId, getInputProps)));
+        getInputProperties
+            .forEach((instanceId, getInputProps) -> redeclareInputData.addAll(findInputsToRedeclare(inputsById, instanceId, getInputProps)));
         return redeclareInputData;
-
     }
 
     private List<InputDefinition> findPrevDeclaredInputs(List<InputDefinition> oldInputs, List<RedeclareInputData> inputsToRedeclareData) {
@@ -74,29 +74,25 @@ public class DeclaredInputsResolver {
         return inputsToRedeclare;
     }
 
-    private List<RedeclareInputData> findInputsToRedeclare(Map<String, InputDefinition> inputsById, String instanceId, List<PropertyDataDefinition> getInputProps) {
+    private List<RedeclareInputData> findInputsToRedeclare(Map<String, InputDefinition> inputsById, String instanceId,
+                                                           List<PropertyDataDefinition> getInputProps) {
         List<RedeclareInputData> redeclareInputDataList = new ArrayList<>();
         getInputProps.forEach(property -> {
             List<String> inputsToRedeclareIds = findInputsToRedeclareIds(inputsById, property);
-            RedeclareInputData redeclareInputData = new RedeclareInputData(property.getUniqueId(), inputsToRedeclareIds, instanceId, property.getDefaultValue());
+            RedeclareInputData redeclareInputData = new RedeclareInputData(property.getUniqueId(), inputsToRedeclareIds, instanceId,
+                property.getDefaultValue());
             redeclareInputDataList.add(redeclareInputData);
         });
         return redeclareInputDataList;
     }
 
     private List<InputDefinition> prepareInputsForRedeclaration(Map<String, InputDefinition> oldInputsById, RedeclareInputData redeclareInputData) {
-        List<InputDefinition> inputsForRedeclaration = redeclareInputData.declaredInputIds.stream()
-                                            .filter(oldInputsById::containsKey)
-                                            .map(oldInputsById::get)
-                                            .filter(Objects::nonNull)
-                                            .map(InputDefinition::new)
-                                            .collect(Collectors.toList());
-        
+        List<InputDefinition> inputsForRedeclaration = redeclareInputData.declaredInputIds.stream().filter(oldInputsById::containsKey)
+            .map(oldInputsById::get).filter(Objects::nonNull).map(InputDefinition::new).collect(Collectors.toList());
         inputsForRedeclaration.forEach(input -> {
             input.setPropertyId(redeclareInputData.propertyId);
             input.setInstanceUniqueId(redeclareInputData.propertyOwnerId);
-            
-            if(!Strings.isNullOrEmpty(redeclareInputData.value)) {
+            if (!Strings.isNullOrEmpty(redeclareInputData.value)) {
                 input.setValue(redeclareInputData.value);
                 input.setDefaultValue(redeclareInputData.value);
             }
@@ -106,10 +102,8 @@ public class DeclaredInputsResolver {
 
     private List<String> findInputsToRedeclareIds(Map<String, InputDefinition> inputsById, PropertyDataDefinition property) {
         List<GetInputValueDataDefinition> getInputValues = property.getGetInputValues();
-        return getInputValues.stream()
-                .filter(getInputVal -> isGetInputValueHasNoCorrespondingInput(getInputVal, inputsById))
-                .map(GetInputValueDataDefinition::getInputId)
-                .collect(Collectors.toList());
+        return getInputValues.stream().filter(getInputVal -> isGetInputValueHasNoCorrespondingInput(getInputVal, inputsById))
+            .map(GetInputValueDataDefinition::getInputId).collect(Collectors.toList());
     }
 
     private boolean isGetInputValueHasNoCorrespondingInput(GetInputValueDataDefinition getInputVal, Map<String, InputDefinition> inputsById) {
@@ -117,6 +111,7 @@ public class DeclaredInputsResolver {
     }
 
     private class RedeclareInputData {
+
         private String propertyId;
         private List<String> declaredInputIds;
         private String propertyOwnerId;
@@ -128,6 +123,5 @@ public class DeclaredInputsResolver {
             this.propertyOwnerId = propertyOwnerId;
             this.value = value;
         }
-
     }
 }
index 91c6ff0..4f63dd4 100644 (file)
@@ -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.
  * limitations under the License.
  * ============LICENSE_END=========================================================
  */
-
 package org.openecomp.sdc.be.components.merge.input;
 
+import static java.util.stream.Collectors.toMap;
+import static org.openecomp.sdc.be.components.merge.resource.ResourceDataMergeBusinessLogic.LAST_COMMAND;
+import static org.openecomp.sdc.be.utils.PropertyDefinitionUtils.convertListOfProperties;
+
+import java.util.List;
+import java.util.Map;
+import java.util.stream.Stream;
 import org.openecomp.sdc.be.components.impl.utils.ExceptionUtils;
 import org.openecomp.sdc.be.components.merge.ComponentsGlobalMergeCommand;
 import org.openecomp.sdc.be.components.merge.GlobalInputsFilteringBusinessLogic;
@@ -31,14 +37,6 @@ import org.openecomp.sdc.be.model.InputDefinition;
 import org.openecomp.sdc.be.model.jsonjanusgraph.operations.ToscaOperationFacade;
 import org.springframework.core.annotation.Order;
 
-import java.util.List;
-import java.util.Map;
-import java.util.stream.Stream;
-
-import static java.util.stream.Collectors.toMap;
-import static org.openecomp.sdc.be.components.merge.resource.ResourceDataMergeBusinessLogic.LAST_COMMAND;
-import static org.openecomp.sdc.be.utils.PropertyDefinitionUtils.convertListOfProperties;
-
 @org.springframework.stereotype.Component
 @Order(LAST_COMMAND)
 public class GlobalInputsMergeCommand extends InputsMergeCommand implements ComponentsGlobalMergeCommand {
@@ -46,7 +44,9 @@ public class GlobalInputsMergeCommand extends InputsMergeCommand implements Comp
     private GlobalInputsFilteringBusinessLogic globalInputsFilteringBusinessLogic;
     private ExceptionUtils exceptionUtils;
 
-    public GlobalInputsMergeCommand(InputsValuesMergingBusinessLogic inputsValuesMergingBusinessLogic, DeclaredInputsResolver declaredInputsResolver, ToscaOperationFacade toscaOperationFacade, ComponentsUtils componentsUtils, GlobalInputsFilteringBusinessLogic globalInputsFilteringBusinessLogic, ExceptionUtils exceptionUtils) {
+    public GlobalInputsMergeCommand(InputsValuesMergingBusinessLogic inputsValuesMergingBusinessLogic, DeclaredInputsResolver declaredInputsResolver,
+                                    ToscaOperationFacade toscaOperationFacade, ComponentsUtils componentsUtils,
+                                    GlobalInputsFilteringBusinessLogic globalInputsFilteringBusinessLogic, ExceptionUtils exceptionUtils) {
         super(inputsValuesMergingBusinessLogic, declaredInputsResolver, toscaOperationFacade, componentsUtils);
         this.globalInputsFilteringBusinessLogic = globalInputsFilteringBusinessLogic;
         this.exceptionUtils = exceptionUtils;
@@ -69,12 +69,9 @@ public class GlobalInputsMergeCommand extends InputsMergeCommand implements Comp
 
     @Override
     Map<String, List<PropertyDataDefinition>> getProperties(Component component) {
-        return Stream.of(component.safeGetUiComponentInstancesProperties(),
-                         component.safeGetUiComponentInstancesInputs(),
-                         component.safeGetGroupsProperties(),
-                         component.safeGetPolicyProperties())
-                .flatMap(map -> map.entrySet().stream())
-                .collect(toMap(Map.Entry::getKey, entry -> convertListOfProperties(entry.getValue())));
+        return Stream
+            .of(component.safeGetUiComponentInstancesProperties(), component.safeGetUiComponentInstancesInputs(), component.safeGetGroupsProperties(),
+                component.safeGetPolicyProperties()).flatMap(map -> map.entrySet().stream())
+            .collect(toMap(Map.Entry::getKey, entry -> convertListOfProperties(entry.getValue())));
     }
-
 }
index 0f6c89a..ba3e600 100644 (file)
@@ -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.
  * limitations under the License.
  * ============LICENSE_END=========================================================
  */
-
 package org.openecomp.sdc.be.components.merge.input;
 
+import static java.util.Collections.emptyList;
+import static org.apache.commons.collections.CollectionUtils.isEmpty;
+
+import java.util.List;
+import java.util.Map;
+import java.util.stream.Collectors;
 import org.openecomp.sdc.be.dao.api.ActionStatus;
 import org.openecomp.sdc.be.datatypes.elements.PropertyDataDefinition;
 import org.openecomp.sdc.be.impl.ComponentsUtils;
@@ -28,23 +33,16 @@ import org.openecomp.sdc.be.model.InputDefinition;
 import org.openecomp.sdc.be.model.jsonjanusgraph.operations.ToscaOperationFacade;
 import org.openecomp.sdc.common.log.wrappers.Logger;
 
-import java.util.List;
-import java.util.Map;
-import java.util.stream.Collectors;
-
-import static java.util.Collections.emptyList;
-import static org.apache.commons.collections.CollectionUtils.isEmpty;
-
 public abstract class InputsMergeCommand {
 
     private static final Logger log = Logger.getLogger(InputsMergeCommand.class);
-
     private InputsValuesMergingBusinessLogic inputsValuesMergingBusinessLogic;
     private DeclaredInputsResolver declaredInputsResolver;
     private ToscaOperationFacade toscaOperationFacade;
     private ComponentsUtils componentsUtils;
 
-    public InputsMergeCommand(InputsValuesMergingBusinessLogic inputsValuesMergingBusinessLogic, DeclaredInputsResolver declaredInputsResolver, ToscaOperationFacade toscaOperationFacade, ComponentsUtils componentsUtils) {
+    public InputsMergeCommand(InputsValuesMergingBusinessLogic inputsValuesMergingBusinessLogic, DeclaredInputsResolver declaredInputsResolver,
+                              ToscaOperationFacade toscaOperationFacade, ComponentsUtils componentsUtils) {
         this.inputsValuesMergingBusinessLogic = inputsValuesMergingBusinessLogic;
         this.declaredInputsResolver = declaredInputsResolver;
         this.toscaOperationFacade = toscaOperationFacade;
@@ -65,26 +63,26 @@ public abstract class InputsMergeCommand {
         return updateInputs(currComponent.getUniqueId(), mergedInputs);
     }
 
-
-
     private List<InputDefinition> mergeInputsValues(Component prevComponent, Component currComponent) {
-        log.debug("#mergeInputsValues - merge inputs values from previous component {} to current component {}", prevComponent.getUniqueId(), currComponent.getUniqueId());
+        log.debug("#mergeInputsValues - merge inputs values from previous component {} to current component {}", prevComponent.getUniqueId(),
+            currComponent.getUniqueId());
         List<InputDefinition> inputsToMerge = getInputsToMerge(currComponent);
         List<InputDefinition> prevInputs = prevComponent.safeGetInputs();
         inputsValuesMergingBusinessLogic.mergeComponentInputs(prevInputs, inputsToMerge);
         return inputsToMerge;
     }
 
-    private List<InputDefinition> getUniquePreviouslyDeclaredInputsToMerge(Component prevComponent, Component currComponent, List<InputDefinition> mergedInputs) {
+    private List<InputDefinition> getUniquePreviouslyDeclaredInputsToMerge(Component prevComponent, Component currComponent,
+                                                                           List<InputDefinition> mergedInputs) {
         List<InputDefinition> previouslyDeclaredInputsToMerge = getPreviouslyDeclaredInputsToMerge(prevComponent, currComponent);
         return previouslyDeclaredInputsToMerge.stream()
-                .filter(prev -> mergedInputs.stream()
-                        .noneMatch(merged -> merged.getName().equals(prev.getName()))).collect(Collectors.toList());
+            .filter(prev -> mergedInputs.stream().noneMatch(merged -> merged.getName().equals(prev.getName()))).collect(Collectors.toList());
     }
 
-
     private List<InputDefinition> getPreviouslyDeclaredInputsToMerge(Component prevComponent, Component currComponent) {
-        log.debug("#getPreviouslyDeclaredInputsToMerge - getting inputs that were previously declared from previous component {} and setting on current component {}", prevComponent.getUniqueId(), currComponent.getUniqueId());
+        log.debug(
+            "#getPreviouslyDeclaredInputsToMerge - getting inputs that were previously declared from previous component {} and setting on current component {}",
+            prevComponent.getUniqueId(), currComponent.getUniqueId());
         if (isEmpty(prevComponent.getInputs())) {
             return emptyList();
         }
@@ -95,8 +93,6 @@ public abstract class InputsMergeCommand {
     private ActionStatus updateInputs(String containerId, List<InputDefinition> inputsToUpdate) {
         log.debug("#updateInputs - updating inputs for container {}", containerId);
         return toscaOperationFacade.updateInputsToComponent(inputsToUpdate, containerId)
-                .either(updatedInputs -> ActionStatus.OK,
-                        componentsUtils::convertFromStorageResponse);
+            .either(updatedInputs -> ActionStatus.OK, componentsUtils::convertFromStorageResponse);
     }
-
 }
index d3214fb..83a2934 100644 (file)
@@ -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.
  * limitations under the License.
  * ============LICENSE_END=========================================================
  */
-
 package org.openecomp.sdc.be.components.merge.input;
 
+import java.util.List;
+import java.util.Map;
 import org.apache.commons.lang.StringUtils;
 import org.openecomp.sdc.be.dao.utils.MapUtil;
 import org.openecomp.sdc.be.model.InputDefinition;
 
-import java.util.List;
-import java.util.Map;
 @org.springframework.stereotype.Component
 public class InputsValuesMergingBusinessLogic {
 
@@ -33,15 +32,16 @@ public class InputsValuesMergingBusinessLogic {
      * Merge old inputs values into the updated inputs
      */
     public void mergeComponentInputs(List<InputDefinition> oldInputs, List<InputDefinition> inputsToMerge) {
-        Map<String, InputDefinition> oldInputsByName =  MapUtil.toMap(oldInputs, InputDefinition::getName);
+        Map<String, InputDefinition> oldInputsByName = MapUtil.toMap(oldInputs, InputDefinition::getName);
         Map<String, InputDefinition> inputsToMergeByName = MapUtil.toMap(inputsToMerge, InputDefinition::getName);
         mergeComponentInputs(oldInputsByName, inputsToMergeByName);
     }
-    
+
     /**
-     * Merge old inputs values into the updated inputs
-     * An input value is merged if the input previous version had a user defined value and its value is empty in current version
-     * @param oldInputs the currently persisted inputs mapped by their names
+     * Merge old inputs values into the updated inputs An input value is merged if the input previous version had a user defined value and its value
+     * is empty in current version
+     *
+     * @param oldInputs     the currently persisted inputs mapped by their names
      * @param updatedInputs the currently being update inputs mapped by their names
      */
     public void mergeComponentInputs(Map<String, InputDefinition> oldInputs, Map<String, InputDefinition> updatedInputs) {
@@ -69,6 +69,4 @@ public class InputsValuesMergingBusinessLogic {
     private boolean isNonEmptyDefaultValue(InputDefinition input) {
         return input != null && !isEmptyDefaultValue(input);
     }
-
-
 }
index daf20f8..912cb42 100644 (file)
@@ -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.
  * limitations under the License.
  * ============LICENSE_END=========================================================
  */
-
 package org.openecomp.sdc.be.components.merge.instance;
 
+import static org.openecomp.sdc.be.components.merge.resource.ResourceDataMergeBusinessLogic.ANY_ORDER_COMMAND;
+
 import fj.data.Either;
+import java.util.List;
+import java.util.Map;
 import org.apache.commons.collections.CollectionUtils;
 import org.openecomp.sdc.be.components.merge.VspComponentsMergeCommand;
 import org.openecomp.sdc.be.components.merge.capability.CapabilityResolver;
@@ -37,23 +40,19 @@ import org.openecomp.sdc.be.model.operations.api.StorageOperationStatus;
 import org.openecomp.sdc.common.log.wrappers.Logger;
 import org.springframework.core.annotation.Order;
 
-import java.util.List;
-import java.util.Map;
-
-import static org.openecomp.sdc.be.components.merge.resource.ResourceDataMergeBusinessLogic.ANY_ORDER_COMMAND;
-
 @org.springframework.stereotype.Component
 @Order(ANY_ORDER_COMMAND)
 public class ComponentCapabilitiesPropertiesMergeBL implements VspComponentsMergeCommand {
 
     private static final Logger log = Logger.getLogger(ComponentCapabilitiesPropertiesMergeBL.class);
-
     private final DataDefinitionsValuesMergingBusinessLogic dataDefinitionsValuesMergingBusinessLogic;
     private final ToscaOperationFacade toscaOperationFacade;
     private final ComponentsUtils componentsUtils;
     private final CapabilityResolver capabilityResolver;
 
-    public ComponentCapabilitiesPropertiesMergeBL(DataDefinitionsValuesMergingBusinessLogic dataDefinitionsValuesMergingBusinessLogic, ToscaOperationFacade toscaOperationFacade, ComponentsUtils componentsUtils, CapabilityResolver capabilityResolver) {
+    public ComponentCapabilitiesPropertiesMergeBL(DataDefinitionsValuesMergingBusinessLogic dataDefinitionsValuesMergingBusinessLogic,
+                                                  ToscaOperationFacade toscaOperationFacade, ComponentsUtils componentsUtils,
+                                                  CapabilityResolver capabilityResolver) {
         this.dataDefinitionsValuesMergingBusinessLogic = dataDefinitionsValuesMergingBusinessLogic;
         this.toscaOperationFacade = toscaOperationFacade;
         this.componentsUtils = componentsUtils;
@@ -68,16 +67,17 @@ public class ComponentCapabilitiesPropertiesMergeBL implements VspComponentsMerg
     @Override
     public ActionStatus mergeComponents(Component prevComponent, Component currentComponent) {
         StorageOperationStatus mergeStatus = getCmptWithCapabilitiesProps(currentComponent.getUniqueId())
-                .either(currCmptWithCap -> mergeCmptCalculatedCapabilitiesProperties(prevComponent, currCmptWithCap),
-                        err -> err);
+            .either(currCmptWithCap -> mergeCmptCalculatedCapabilitiesProperties(prevComponent, currCmptWithCap), err -> err);
         return componentsUtils.convertFromStorageResponse(mergeStatus);
     }
 
-    public ActionStatus mergeComponentInstanceCapabilities(Component currentComponent, Component origInstanceCmpt, String instanceId, List<CapabilityDefinition> prevInstanceCapabilities) {
+    public ActionStatus mergeComponentInstanceCapabilities(Component currentComponent, Component origInstanceCmpt, String instanceId,
+                                                           List<CapabilityDefinition> prevInstanceCapabilities) {
         if (CollectionUtils.isEmpty(prevInstanceCapabilities)) {
             return ActionStatus.OK;
         }
-        Map<CapabilityDefinition, CapabilityDefinition> oldToNewCap = capabilityResolver.resolvePrevCapToNewCapability(currentComponent, origInstanceCmpt, instanceId, prevInstanceCapabilities);
+        Map<CapabilityDefinition, CapabilityDefinition> oldToNewCap = capabilityResolver
+            .resolvePrevCapToNewCapability(currentComponent, origInstanceCmpt, instanceId, prevInstanceCapabilities);
         oldToNewCap.forEach(this::mergeCapabilityProperties);
         StorageOperationStatus updateStatus = updateInstanceCapabilitiesProperties(currentComponent, instanceId);
         return componentsUtils.convertFromStorageResponse(updateStatus);
@@ -94,7 +94,8 @@ public class ComponentCapabilitiesPropertiesMergeBL implements VspComponentsMerg
 
     private void mergeInstanceCapabilities(ComponentInstance prevInstance, Component currComponent) {
         ComponentInstance currInstance = MapUtil.toMap(currComponent.getComponentInstances(), ComponentInstance::getName).get(prevInstance.getName());
-        Map<CapabilityDefinition, CapabilityDefinition> oldToNewCapabilities = capabilityResolver.resolvePrevCapIdToNewCapability(prevInstance, currInstance);
+        Map<CapabilityDefinition, CapabilityDefinition> oldToNewCapabilities = capabilityResolver
+            .resolvePrevCapIdToNewCapability(prevInstance, currInstance);
         oldToNewCapabilities.forEach(this::mergeCapabilityProperties);
     }
 
@@ -116,13 +117,9 @@ public class ComponentCapabilitiesPropertiesMergeBL implements VspComponentsMerg
         propertiesCapabilitiesFilter.setIgnoreComponentInstances(false);
         propertiesCapabilitiesFilter.setIgnoreCapabilities(false);
         propertiesCapabilitiesFilter.setIgnoreGroups(false);
-        return toscaOperationFacade.getToscaElement(cmptId, propertiesCapabilitiesFilter)
-                .right()
-                .map(err -> {
-                   log.debug("failed to fetch cmpt {} with properties capabilities. status: {}", cmptId, err);
-                   return err;
-                });
-
+        return toscaOperationFacade.getToscaElement(cmptId, propertiesCapabilitiesFilter).right().map(err -> {
+            log.debug("failed to fetch cmpt {} with properties capabilities. status: {}", cmptId, err);
+            return err;
+        });
     }
-
 }
index f68019c..4d88518 100644 (file)
@@ -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.
  * limitations under the License.
  * ============LICENSE_END=========================================================
  */
-
 package org.openecomp.sdc.be.components.merge.instance;
 
+import java.util.HashMap;
+import java.util.Map;
+import java.util.Objects;
+import java.util.Optional;
+import java.util.stream.Collectors;
 import org.openecomp.sdc.be.components.impl.ArtifactsBusinessLogic;
 import org.openecomp.sdc.be.components.impl.artifact.ArtifactOperationInfo;
 import org.openecomp.sdc.be.model.ArtifactDefinition;
@@ -31,12 +35,6 @@ import org.openecomp.sdc.common.api.ArtifactTypeEnum;
 import org.openecomp.sdc.common.api.Constants;
 import org.springframework.beans.factory.annotation.Autowired;
 
-import java.util.HashMap;
-import java.util.Map;
-import java.util.Objects;
-import java.util.Optional;
-import java.util.stream.Collectors;
-
 /**
  * Created by chaya on 9/20/2017.
  */
@@ -45,31 +43,29 @@ public class ComponentInstanceArtifactsMerge implements ComponentInstanceMergeIn
 
     @Autowired
     ToscaOperationFacade toscaOperationFacade;
-
     @Autowired
     ArtifactsBusinessLogic artifactsBusinessLogic;
 
     @Override
-    public void saveDataBeforeMerge(DataForMergeHolder dataHolder, Component containerComponent, ComponentInstance currentResourceInstance, Component originComponent) {
+    public void saveDataBeforeMerge(DataForMergeHolder dataHolder, Component containerComponent, ComponentInstance currentResourceInstance,
+                                    Component originComponent) {
         Map<String, ArtifactDefinition> componentInstancesDeploymentArtifacts = currentResourceInstance.safeGetDeploymentArtifacts();
         Map<String, ArtifactDefinition> originalComponentDeploymentArtifacts = originComponent.getDeploymentArtifacts();
-        Map<String, ArtifactDefinition> deploymentArtifactsCreatedOnTheInstance = componentInstancesDeploymentArtifacts.entrySet()
-                .stream()
-                .filter(i -> !originalComponentDeploymentArtifacts.containsKey(i.getKey()))
-                .filter(i -> !ArtifactTypeEnum.VF_MODULES_METADATA.getType().equals(i.getValue().getArtifactType()))
-                .collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue));
-
+        Map<String, ArtifactDefinition> deploymentArtifactsCreatedOnTheInstance = componentInstancesDeploymentArtifacts.entrySet().stream()
+            .filter(i -> !originalComponentDeploymentArtifacts.containsKey(i.getKey()))
+            .filter(i -> !ArtifactTypeEnum.VF_MODULES_METADATA.getType().equals(i.getValue().getArtifactType()))
+            .collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue));
         dataHolder.setOrigComponentDeploymentArtifactsCreatedOnTheInstance(deploymentArtifactsCreatedOnTheInstance);
 //        dataHolder.setComponentInstanceDeploymentArtifactsTimeOut(componentInstancesDeploymentArtifacts.entrySet().stream()
+
 //                .collect(Collectors.toMap(Map.Entry::getKey, artifact -> artifact.getValue().getTimeout())));
         dataHolder.setComponentInstanceDeploymentArtifactsTimeOut(componentInstancesDeploymentArtifacts.entrySet().stream()
-                .collect(HashMap::new, (map,entry) -> map.put(entry.getKey(), entry.getValue().getTimeout()) ,HashMap::putAll));
+            .collect(HashMap::new, (map, entry) -> map.put(entry.getKey(), entry.getValue().getTimeout()), HashMap::putAll));
         Map<String, ArtifactDefinition> componentInstancesInformationalArtifacts = currentResourceInstance.safeGetArtifacts();
         Map<String, ArtifactDefinition> originalComponentInformationalArtifacts = originComponent.getArtifacts();
-        Map<String, ArtifactDefinition> informationalArtifactsCreatedOnTheInstance = componentInstancesInformationalArtifacts.entrySet()
-                .stream()
-                .filter(i -> !originalComponentInformationalArtifacts.containsKey(i.getKey()))
-                .collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue));
+        Map<String, ArtifactDefinition> informationalArtifactsCreatedOnTheInstance = componentInstancesInformationalArtifacts.entrySet().stream()
+            .filter(i -> !originalComponentInformationalArtifacts.containsKey(i.getKey()))
+            .collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue));
         dataHolder.setOrigComponentInformationalArtifactsCreatedOnTheInstance(informationalArtifactsCreatedOnTheInstance);
     }
 
@@ -79,47 +75,49 @@ public class ComponentInstanceArtifactsMerge implements ComponentInstanceMergeIn
 
     @Override
     public Component mergeDataAfterCreate(User user, DataForMergeHolder dataHolder, Component updatedContainerComponent, String newInstanceId) {
-        Map<String, ArtifactDefinition> origInstanceDeploymentArtifactsCreatedOnTheInstance = dataHolder.getOrigComponentDeploymentArtifactsCreatedOnTheInstance();
-        Map<String, ArtifactDefinition> currentInstanceDeploymentArtifacts = updatedContainerComponent.safeGetComponentInstanceDeploymentArtifacts(newInstanceId);
-        Map<String, ArtifactDefinition> filteredDeploymentArtifactsToAdd = Optional.ofNullable(origInstanceDeploymentArtifactsCreatedOnTheInstance).orElse(new HashMap<>()).entrySet().stream()
-                .filter(artifact -> noArtifactWithTheSameLabel(artifact.getValue().getArtifactLabel(), currentInstanceDeploymentArtifacts))
-                .collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue));
-        Map<String, ArtifactDefinition> updatedTimeOutDeploymentArtifacts = getUpdatedTimeOutDeploymentArtifacts(dataHolder, currentInstanceDeploymentArtifacts);
-        Map<String, ArtifactDefinition> origInstanceInformationalArtifactsCreatedOnTheInstance = dataHolder.getOrigComponentInformationalArtifactsCreatedOnTheInstance();
-        Map<String, ArtifactDefinition> currentInstanceInformationalArtifacts = updatedContainerComponent.safeGetComponentInstanceInformationalArtifacts(newInstanceId);
-        Map<String, ArtifactDefinition> filteredInformationalArtifactsToAdd = Optional.ofNullable(origInstanceInformationalArtifactsCreatedOnTheInstance).orElse(new HashMap<>()).entrySet().stream()
-                .filter(artifact -> noArtifactWithTheSameLabel(artifact.getValue().getArtifactLabel(), currentInstanceInformationalArtifacts))
-                .collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue));
+        Map<String, ArtifactDefinition> origInstanceDeploymentArtifactsCreatedOnTheInstance = dataHolder
+            .getOrigComponentDeploymentArtifactsCreatedOnTheInstance();
+        Map<String, ArtifactDefinition> currentInstanceDeploymentArtifacts = updatedContainerComponent
+            .safeGetComponentInstanceDeploymentArtifacts(newInstanceId);
+        Map<String, ArtifactDefinition> filteredDeploymentArtifactsToAdd = Optional.ofNullable(origInstanceDeploymentArtifactsCreatedOnTheInstance)
+            .orElse(new HashMap<>()).entrySet().stream()
+            .filter(artifact -> noArtifactWithTheSameLabel(artifact.getValue().getArtifactLabel(), currentInstanceDeploymentArtifacts))
+            .collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue));
+        Map<String, ArtifactDefinition> updatedTimeOutDeploymentArtifacts = getUpdatedTimeOutDeploymentArtifacts(dataHolder,
+            currentInstanceDeploymentArtifacts);
+        Map<String, ArtifactDefinition> origInstanceInformationalArtifactsCreatedOnTheInstance = dataHolder
+            .getOrigComponentInformationalArtifactsCreatedOnTheInstance();
+        Map<String, ArtifactDefinition> currentInstanceInformationalArtifacts = updatedContainerComponent
+            .safeGetComponentInstanceInformationalArtifacts(newInstanceId);
+        Map<String, ArtifactDefinition> filteredInformationalArtifactsToAdd = Optional
+            .ofNullable(origInstanceInformationalArtifactsCreatedOnTheInstance).orElse(new HashMap<>()).entrySet().stream()
+            .filter(artifact -> noArtifactWithTheSameLabel(artifact.getValue().getArtifactLabel(), currentInstanceInformationalArtifacts))
+            .collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue));
         Map<String, ArtifactDefinition> allFilteredArtifactsToAdd = new HashMap<>();
         allFilteredArtifactsToAdd.putAll(filteredDeploymentArtifactsToAdd);
         allFilteredArtifactsToAdd.putAll(updatedTimeOutDeploymentArtifacts);
         allFilteredArtifactsToAdd.putAll(filteredInformationalArtifactsToAdd);
-
-        for (Map.Entry<String, ArtifactDefinition> currentArtifactDefinition :  allFilteredArtifactsToAdd.entrySet()) {
-            Map<String, Object> jsonForUpdateArtifact = artifactsBusinessLogic.buildJsonForUpdateArtifact(
-                    currentArtifactDefinition.getValue().getUniqueId(), 
-                    currentArtifactDefinition.getValue().getArtifactName(),
-                    currentArtifactDefinition.getValue().getArtifactType(), 
-                    currentArtifactDefinition.getValue().getArtifactGroupType(),
-                    currentArtifactDefinition.getValue().getArtifactLabel(), 
-                    currentArtifactDefinition.getValue().getArtifactDisplayName(),
-                    currentArtifactDefinition.getValue().getDescription(), 
-                    currentArtifactDefinition.getValue().getPayloadData(),
-                    null, currentArtifactDefinition.getValue().getListHeatParameters());
+        for (Map.Entry<String, ArtifactDefinition> currentArtifactDefinition : allFilteredArtifactsToAdd.entrySet()) {
+            Map<String, Object> jsonForUpdateArtifact = artifactsBusinessLogic
+                .buildJsonForUpdateArtifact(currentArtifactDefinition.getValue().getUniqueId(),
+                    currentArtifactDefinition.getValue().getArtifactName(), currentArtifactDefinition.getValue().getArtifactType(),
+                    currentArtifactDefinition.getValue().getArtifactGroupType(), currentArtifactDefinition.getValue().getArtifactLabel(),
+                    currentArtifactDefinition.getValue().getArtifactDisplayName(), currentArtifactDefinition.getValue().getDescription(),
+                    currentArtifactDefinition.getValue().getPayloadData(), null, currentArtifactDefinition.getValue().getListHeatParameters());
             addEsIdToArtifactJson(jsonForUpdateArtifact, currentArtifactDefinition.getValue().getEsId());
-            artifactsBusinessLogic.updateResourceInstanceArtifactNoContent(newInstanceId, updatedContainerComponent,
-                            user, jsonForUpdateArtifact, new ArtifactOperationInfo(
-                                    false, false, ArtifactsBusinessLogic.ArtifactOperationEnum.LINK), currentArtifactDefinition.getValue());
+            artifactsBusinessLogic.updateResourceInstanceArtifactNoContent(newInstanceId, updatedContainerComponent, user, jsonForUpdateArtifact,
+                new ArtifactOperationInfo(false, false, ArtifactsBusinessLogic.ArtifactOperationEnum.LINK), currentArtifactDefinition.getValue());
         }
         return updatedContainerComponent;
     }
 
-    private Map<String, ArtifactDefinition> getUpdatedTimeOutDeploymentArtifacts(DataForMergeHolder dataHolder, Map<String, ArtifactDefinition> currentInstanceDeploymentArtifacts) {
-        return currentInstanceDeploymentArtifacts.entrySet().stream()
-                .filter(artifact -> Objects.isNull(artifact.getValue().getTimeout()) || !artifact.getValue().getTimeout()
-                        .equals(dataHolder.getComponentInstanceDeploymentArtifactsTimeOut().get(artifact.getKey())))
-                .collect(Collectors.toMap(Map.Entry::getKey, artifact -> mergeTimeOut(artifact.getValue(), dataHolder
-                        .getComponentInstanceDeploymentArtifactsTimeOut().get(artifact.getKey()))));
+    private Map<String, ArtifactDefinition> getUpdatedTimeOutDeploymentArtifacts(DataForMergeHolder dataHolder,
+                                                                                 Map<String, ArtifactDefinition> currentInstanceDeploymentArtifacts) {
+        return currentInstanceDeploymentArtifacts.entrySet().stream().filter(
+            artifact -> Objects.isNull(artifact.getValue().getTimeout()) || !artifact.getValue().getTimeout()
+                .equals(dataHolder.getComponentInstanceDeploymentArtifactsTimeOut().get(artifact.getKey()))).collect(Collectors
+            .toMap(Map.Entry::getKey,
+                artifact -> mergeTimeOut(artifact.getValue(), dataHolder.getComponentInstanceDeploymentArtifactsTimeOut().get(artifact.getKey()))));
     }
 
     private ArtifactDefinition mergeTimeOut(ArtifactDefinition artifact, Integer updatedTimeOut) {
index 9c84504..bc1aa0d 100644 (file)
@@ -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.
  * limitations under the License.
  * ============LICENSE_END=========================================================
  */
-
 package org.openecomp.sdc.be.components.merge.instance;
 
+import static org.apache.commons.collections.MapUtils.isNotEmpty;
+
+import java.util.ArrayList;
+import java.util.Collection;
+import java.util.List;
+import java.util.stream.Collectors;
 import org.openecomp.sdc.be.components.impl.exceptions.ByActionStatusComponentException;
 import org.openecomp.sdc.be.dao.api.ActionStatus;
 import org.openecomp.sdc.be.impl.ComponentsUtils;
@@ -28,26 +33,21 @@ import org.openecomp.sdc.be.model.Component;
 import org.openecomp.sdc.be.model.ComponentInstance;
 import org.openecomp.sdc.be.model.User;
 
-import java.util.ArrayList;
-import java.util.Collection;
-import java.util.List;
-import java.util.stream.Collectors;
-
-import static org.apache.commons.collections.MapUtils.isNotEmpty;
-
 @org.springframework.stereotype.Component
 public class ComponentInstanceCapabilitiesPropertiesMerge implements ComponentInstanceMergeInterface {
 
     private ComponentCapabilitiesPropertiesMergeBL capabilitiesPropertiesMergeBL;
     private ComponentsUtils componentsUtils;
 
-    public ComponentInstanceCapabilitiesPropertiesMerge(ComponentCapabilitiesPropertiesMergeBL capabilitiesPropertiesMergeBL, ComponentsUtils componentsUtils) {
+    public ComponentInstanceCapabilitiesPropertiesMerge(ComponentCapabilitiesPropertiesMergeBL capabilitiesPropertiesMergeBL,
+                                                        ComponentsUtils componentsUtils) {
         this.capabilitiesPropertiesMergeBL = capabilitiesPropertiesMergeBL;
         this.componentsUtils = componentsUtils;
     }
 
     @Override
-    public void saveDataBeforeMerge(DataForMergeHolder dataHolder, Component containerComponent, ComponentInstance currentResourceInstance, Component originComponent) {
+    public void saveDataBeforeMerge(DataForMergeHolder dataHolder, Component containerComponent, ComponentInstance currentResourceInstance,
+                                    Component originComponent) {
         dataHolder.setOrigInstanceCapabilities(getAllInstanceCapabilities(currentResourceInstance));
         dataHolder.setOrigInstanceNode(originComponent);
     }
@@ -56,14 +56,16 @@ public class ComponentInstanceCapabilitiesPropertiesMerge implements ComponentIn
     public Component mergeDataAfterCreate(User user, DataForMergeHolder dataHolder, Component updatedContainerComponent, String newInstanceId) {
         Component origInstanceNode = dataHolder.getOrigInstanceNode();
         List<CapabilityDefinition> origInstanceCapabilities = dataHolder.getOrigInstanceCapabilities();
-        ActionStatus mergeStatus = capabilitiesPropertiesMergeBL.mergeComponentInstanceCapabilities(updatedContainerComponent, origInstanceNode, newInstanceId, origInstanceCapabilities);
-        if(!ActionStatus.OK.equals(mergeStatus)){
+        ActionStatus mergeStatus = capabilitiesPropertiesMergeBL
+            .mergeComponentInstanceCapabilities(updatedContainerComponent, origInstanceNode, newInstanceId, origInstanceCapabilities);
+        if (!ActionStatus.OK.equals(mergeStatus)) {
             throw new ByActionStatusComponentException(mergeStatus);
         }
-        return  updatedContainerComponent;
+        return updatedContainerComponent;
     }
 
     private List<CapabilityDefinition> getAllInstanceCapabilities(ComponentInstance currentResourceInstance) {
-        return isNotEmpty( currentResourceInstance.getCapabilities() )  ? currentResourceInstance.getCapabilities().values().stream().flatMap(Collection::stream).collect(Collectors.toList()) :  new ArrayList<>() ;
+        return isNotEmpty(currentResourceInstance.getCapabilities()) ? currentResourceInstance.getCapabilities().values().stream()
+            .flatMap(Collection::stream).collect(Collectors.toList()) : new ArrayList<>();
     }
 }
index 68851b1..b99178d 100644 (file)
@@ -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.
  * limitations under the License.
  * ============LICENSE_END=========================================================
  */
-
 package org.openecomp.sdc.be.components.merge.instance;
 
 import fj.data.Either;
+import java.util.Collection;
+import java.util.Collections;
+import java.util.HashSet;
+import java.util.List;
+import java.util.Map;
+import java.util.Set;
+import java.util.stream.Collectors;
 import org.javatuples.Pair;
 import org.openecomp.sdc.be.components.impl.ServiceBusinessLogic;
 import org.openecomp.sdc.be.components.impl.exceptions.ByActionStatusComponentException;
@@ -38,56 +44,42 @@ import org.openecomp.sdc.be.model.operations.api.StorageOperationStatus;
 import org.openecomp.sdc.common.log.wrappers.Logger;
 import org.springframework.beans.factory.annotation.Autowired;
 
-import java.util.Collection;
-import java.util.Collections;
-import java.util.HashSet;
-import java.util.List;
-import java.util.Map;
-import java.util.Set;
-import java.util.stream.Collectors;
-
 @org.springframework.stereotype.Component
 public class ComponentInstanceForwardingPathMerge implements ComponentInstanceMergeInterface {
 
     private static Logger log = Logger.getLogger(ComponentInstanceForwardingPathMerge.class);
-
     @Autowired
     private ServiceBusinessLogic serviceBusinessLogic;
-
     @Autowired
     private ToscaOperationFacade toscaOperationFacade;
-
     @Autowired
     private ComponentsUtils componentsUtils;
 
     @Override
-    public void saveDataBeforeMerge(DataForMergeHolder dataHolder, Component containerComponent,
-        ComponentInstance currentResourceInstance, Component originComponent) {
+    public void saveDataBeforeMerge(DataForMergeHolder dataHolder, Component containerComponent, ComponentInstance currentResourceInstance,
+                                    Component originComponent) {
         dataHolder.setOrigInstanceCapabilities(getAllInstanceCapabilities(currentResourceInstance));
         dataHolder.setOrigInstanceNode(originComponent);
         dataHolder.setOrigComponentInstId(currentResourceInstance.getName());
     }
 
     @Override
-    public Component mergeDataAfterCreate(User user, DataForMergeHolder dataHolder,
-                                          Component updatedContainerComponent, String newInstanceId) {
+    public Component mergeDataAfterCreate(User user, DataForMergeHolder dataHolder, Component updatedContainerComponent, String newInstanceId) {
         if (!(updatedContainerComponent instanceof Service)) {
             // no need to handle forwarding paths
             return updatedContainerComponent;
         }
         Service service = (Service) updatedContainerComponent;
         ComponentInstance ci = service.getComponentInstanceById(newInstanceId).orElse(null);
-        if (ci == null){
+        if (ci == null) {
             throw new ByActionStatusComponentException(ActionStatus.COMPONENT_INSTANCE_NOT_FOUND_ON_CONTAINER, newInstanceId);
         }
         Either<Component, StorageOperationStatus> resourceEither = toscaOperationFacade.getToscaFullElement(ci.getComponentUid());
-        if (resourceEither.isRight() ) {
-            log.debug("Failed to fetch resource with id {} for instance {}",ci.getComponentUid() ,ci.getUniqueId());
+        if (resourceEither.isRight()) {
+            log.debug("Failed to fetch resource with id {} for instance {}", ci.getComponentUid(), ci.getUniqueId());
             throw new ByActionStatusComponentException(componentsUtils.convertFromStorageResponse(resourceEither.right().value()));
         }
-
         Component fetchedComponent = resourceEither.left().value();
-
         Pair<Map<String, ForwardingPathDataDefinition>, Map<String, ForwardingPathDataDefinition>> pair = new ForwardingPathUtils()
             .updateForwardingPathOnVersionChange(service, dataHolder, fetchedComponent, newInstanceId);
         Map<String, ForwardingPathDataDefinition> updated = pair.getValue0();
@@ -100,19 +92,16 @@ public class ComponentInstanceForwardingPathMerge implements ComponentInstanceMe
         if (updated != null && !updated.isEmpty()) {
             Service updateFPService = new Service();
             updateFPService.setForwardingPaths(updated);
-            Service updateFPEither = serviceBusinessLogic
-                .updateForwardingPath(service.getUniqueId(), updateFPService, user, false);
-            updated.forEach((key, forwardingPathDataDefinition) -> service.getForwardingPaths().put(key,forwardingPathDataDefinition));
+            Service updateFPEither = serviceBusinessLogic.updateForwardingPath(service.getUniqueId(), updateFPService, user, false);
+            updated.forEach((key, forwardingPathDataDefinition) -> service.getForwardingPaths().put(key, forwardingPathDataDefinition));
         }
         return updatedContainerComponent;
     }
 
-
     private List<CapabilityDefinition> getAllInstanceCapabilities(ComponentInstance currentResourceInstance) {
-        if(currentResourceInstance.getCapabilities() == null || currentResourceInstance.getCapabilities().isEmpty()){
+        if (currentResourceInstance.getCapabilities() == null || currentResourceInstance.getCapabilities().isEmpty()) {
             return Collections.EMPTY_LIST;
         }
-        return currentResourceInstance.getCapabilities().values().stream().flatMap(Collection::stream)
-            .collect(Collectors.toList());
+        return currentResourceInstance.getCapabilities().values().stream().flatMap(Collection::stream).collect(Collectors.toList());
     }
 }
index 2f99439..309c0a9 100644 (file)
@@ -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.
  * limitations under the License.
  * ============LICENSE_END=========================================================
  */
-
 package org.openecomp.sdc.be.components.merge.instance;
 
 import fj.data.Either;
+import java.util.List;
+import java.util.Map;
 import org.openecomp.sdc.be.components.impl.ArtifactsBusinessLogic;
 import org.openecomp.sdc.be.components.impl.artifact.ArtifactOperationInfo;
 import org.openecomp.sdc.be.components.merge.heat.HeatEnvArtifactsMergeBusinessLogic;
@@ -34,9 +35,6 @@ import org.openecomp.sdc.common.api.ArtifactGroupTypeEnum;
 import org.openecomp.sdc.common.log.wrappers.Logger;
 import org.springframework.beans.factory.annotation.Autowired;
 
-import java.util.List;
-import java.util.Map;
-
 /**
  * Created by chaya on 9/20/2017.
  */
@@ -44,32 +42,30 @@ import java.util.Map;
 public class ComponentInstanceHeatEnvMerge implements ComponentInstanceMergeInterface {
 
     private static final Logger log = Logger.getLogger(ComponentInstanceHeatEnvMerge.class);
-
+    @Autowired
+    protected ComponentsUtils componentsUtils;
     @Autowired
     private ArtifactsBusinessLogic artifactsBusinessLogic;
-
     @Autowired
     private HeatEnvArtifactsMergeBusinessLogic heatEnvArtifactsMergeBusinessLogic;
 
-    @Autowired
-    protected ComponentsUtils componentsUtils;
-
-
     @Override
-    public void saveDataBeforeMerge(DataForMergeHolder dataHolder, Component containerComponent, ComponentInstance currentResourceInstance, Component originComponent) {
-        dataHolder.setOrigComponentInstanceHeatEnvArtifacts(containerComponent.safeGetComponentInstanceHeatArtifacts(currentResourceInstance.getUniqueId()));
+    public void saveDataBeforeMerge(DataForMergeHolder dataHolder, Component containerComponent, ComponentInstance currentResourceInstance,
+                                    Component originComponent) {
+        dataHolder.setOrigComponentInstanceHeatEnvArtifacts(
+            containerComponent.safeGetComponentInstanceHeatArtifacts(currentResourceInstance.getUniqueId()));
     }
 
     @Override
     public Component mergeDataAfterCreate(User user, DataForMergeHolder dataHolder, Component updatedContainerComponent, String newInstanceId) {
         List<ArtifactDefinition> origCompInstHeatEnvArtifacts = dataHolder.getOrigComponentInstanceHeatEnvArtifacts();
         List<ArtifactDefinition> newCompInstHeatEnvArtifacts = updatedContainerComponent.safeGetComponentInstanceHeatArtifacts(newInstanceId);
-        List<ArtifactDefinition> artifactsToUpdate = heatEnvArtifactsMergeBusinessLogic.mergeInstanceHeatEnvArtifacts(origCompInstHeatEnvArtifacts, newCompInstHeatEnvArtifacts);
-
+        List<ArtifactDefinition> artifactsToUpdate = heatEnvArtifactsMergeBusinessLogic
+            .mergeInstanceHeatEnvArtifacts(origCompInstHeatEnvArtifacts, newCompInstHeatEnvArtifacts);
         for (ArtifactDefinition artifactInfo : artifactsToUpdate) {
-            Map<String, Object> json = artifactsBusinessLogic.buildJsonForUpdateArtifact(artifactInfo, ArtifactGroupTypeEnum.DEPLOYMENT,  null);
-
-            Either<ArtifactDefinition, Operation> uploadArtifactToService = artifactsBusinessLogic.updateResourceInstanceArtifactNoContent(newInstanceId, updatedContainerComponent, user, json,
+            Map<String, Object> json = artifactsBusinessLogic.buildJsonForUpdateArtifact(artifactInfo, ArtifactGroupTypeEnum.DEPLOYMENT, null);
+            Either<ArtifactDefinition, Operation> uploadArtifactToService = artifactsBusinessLogic
+                .updateResourceInstanceArtifactNoContent(newInstanceId, updatedContainerComponent, user, json,
                     new ArtifactOperationInfo(false, false, ArtifactsBusinessLogic.ArtifactOperationEnum.UPDATE), null);
         }
         return updatedContainerComponent;
index 3058835..d8b5020 100644 (file)
@@ -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.
  * limitations under the License.
  * ============LICENSE_END=========================================================
  */
-
 package org.openecomp.sdc.be.components.merge.instance;
 
+import static org.openecomp.sdc.be.components.merge.resource.ResourceDataMergeBusinessLogic.ANY_ORDER_COMMAND;
+
 import fj.data.Either;
+import java.util.Collections;
+import java.util.List;
+import java.util.Map;
+import java.util.stream.Collectors;
 import org.openecomp.sdc.be.components.merge.VspComponentsMergeCommand;
 import org.openecomp.sdc.be.components.merge.property.DataDefinitionsValuesMergingBusinessLogic;
 import org.openecomp.sdc.be.dao.api.ActionStatus;
@@ -33,13 +38,6 @@ import org.openecomp.sdc.be.model.jsonjanusgraph.operations.ToscaOperationFacade
 import org.openecomp.sdc.be.model.operations.api.StorageOperationStatus;
 import org.springframework.core.annotation.Order;
 
-import java.util.Collections;
-import java.util.List;
-import java.util.Map;
-import java.util.stream.Collectors;
-
-import static org.openecomp.sdc.be.components.merge.resource.ResourceDataMergeBusinessLogic.ANY_ORDER_COMMAND;
-
 @org.springframework.stereotype.Component
 @Order(ANY_ORDER_COMMAND)
 public class ComponentInstanceInputsMergeBL implements VspComponentsMergeCommand {
@@ -48,7 +46,8 @@ public class ComponentInstanceInputsMergeBL implements VspComponentsMergeCommand
     private final ComponentsUtils componentsUtils;
     private final DataDefinitionsValuesMergingBusinessLogic propertyValuesMergingBusinessLogic;
 
-    public ComponentInstanceInputsMergeBL(ToscaOperationFacade toscaOperationFacade, ComponentsUtils componentsUtils, DataDefinitionsValuesMergingBusinessLogic propertyValuesMergingBusinessLogic) {
+    public ComponentInstanceInputsMergeBL(ToscaOperationFacade toscaOperationFacade, ComponentsUtils componentsUtils,
+                                          DataDefinitionsValuesMergingBusinessLogic propertyValuesMergingBusinessLogic) {
         this.toscaOperationFacade = toscaOperationFacade;
         this.componentsUtils = componentsUtils;
         this.propertyValuesMergingBusinessLogic = propertyValuesMergingBusinessLogic;
@@ -60,7 +59,8 @@ public class ComponentInstanceInputsMergeBL implements VspComponentsMergeCommand
         if (componentInstancesInputs == null) {
             return ActionStatus.OK;
         }
-        componentInstancesInputs.forEach((instanceId, instInputs) -> mergeOldInstanceInputsValues(prevComponent, currentComponent, instanceId, instInputs));
+        componentInstancesInputs
+            .forEach((instanceId, instInputs) -> mergeOldInstanceInputsValues(prevComponent, currentComponent, instanceId, instInputs));
         return updateComponentInstancesInputs(currentComponent, componentInstancesInputs);
     }
 
@@ -69,31 +69,27 @@ public class ComponentInstanceInputsMergeBL implements VspComponentsMergeCommand
         return "merge component instance inputs";
     }
 
-    public ActionStatus mergeComponentInstanceInputs(List<ComponentInstanceInput> oldInstProps, List<InputDefinition> oldInputs, Component newComponent, String instanceId) {
+    public ActionStatus mergeComponentInstanceInputs(List<ComponentInstanceInput> oldInstProps, List<InputDefinition> oldInputs,
+                                                     Component newComponent, String instanceId) {
         List<ComponentInstanceInput> newInstInputs = newComponent.safeGetComponentInstanceInput(instanceId);
         if (newInstInputs == null) {
             return ActionStatus.OK;
         }
-        
         List<ComponentInstanceInput> oldRedeclaredInputs = findComponentInputs(oldInstProps);
-        oldRedeclaredInputs.forEach(oldInput -> newInstInputs.stream()
-                                                              .filter(newInstInput -> oldInput.getName().equals(newInstInput.getName()))
-                                                              .forEach(this::switchValues));
-        
+        oldRedeclaredInputs.forEach(
+            oldInput -> newInstInputs.stream().filter(newInstInput -> oldInput.getName().equals(newInstInput.getName())).forEach(this::switchValues));
         propertyValuesMergingBusinessLogic.mergeInstanceDataDefinitions(oldInstProps, oldInputs, newInstInputs, newComponent.getInputs());
         return updateComponentInstanceInputs(newComponent, instanceId, newInstInputs);
     }
-    
+
     private void switchValues(ComponentInstanceInput input) {
         String tempDefaultValue = input.getDefaultValue();
         input.setDefaultValue(input.getValue());
         input.setValue(tempDefaultValue);
     }
-    
+
     private List<ComponentInstanceInput> findComponentInputs(List<ComponentInstanceInput> oldInstProps) {
-        return oldInstProps.stream()
-                           .filter(ComponentInstanceInput::isGetInputProperty)
-                           .collect(Collectors.toList());
+        return oldInstProps.stream().filter(ComponentInstanceInput::isGetInputProperty).collect(Collectors.toList());
     }
 
     private ActionStatus updateComponentInstanceInputs(Component newComponent, String instanceId, List<ComponentInstanceInput> newInstInput) {
@@ -105,18 +101,20 @@ public class ComponentInstanceInputsMergeBL implements VspComponentsMergeCommand
     }
 
     private ActionStatus updateComponentInstancesInputs(Component component, Map<String, List<ComponentInstanceInput>> componentInstancesInputs) {
-        Either<Map<String, List<ComponentInstanceInput>>, StorageOperationStatus> mapStorageOperationStatusEither = toscaOperationFacade.updateComponentInstanceInputsToComponent(componentInstancesInputs, component.getUniqueId());
+        Either<Map<String, List<ComponentInstanceInput>>, StorageOperationStatus> mapStorageOperationStatusEither = toscaOperationFacade
+            .updateComponentInstanceInputsToComponent(componentInstancesInputs, component.getUniqueId());
         if (mapStorageOperationStatusEither.isRight()) {
             return componentsUtils.convertFromStorageResponse(mapStorageOperationStatusEither.right().value());
         }
         return ActionStatus.OK;
     }
 
-    private void mergeOldInstanceInputsValues(Component oldComponent, Component newComponent, String instanceId, List<ComponentInstanceInput> instInputs) {
+    private void mergeOldInstanceInputsValues(Component oldComponent, Component newComponent, String instanceId,
+                                              List<ComponentInstanceInput> instInputs) {
         ComponentInstance currentCompInstance = newComponent.getComponentInstanceById(instanceId).get();
-        List<ComponentInstanceInput> oldInstInputs = oldComponent == null ? Collections.emptyList() : oldComponent.safeGetComponentInstanceInputsByName(currentCompInstance.getName());
+        List<ComponentInstanceInput> oldInstInputs =
+            oldComponent == null ? Collections.emptyList() : oldComponent.safeGetComponentInstanceInputsByName(currentCompInstance.getName());
         List<InputDefinition> oldInputs = oldComponent == null ? Collections.emptyList() : oldComponent.getInputs();
         propertyValuesMergingBusinessLogic.mergeInstanceDataDefinitions(oldInstInputs, oldInputs, instInputs, newComponent.getInputs());
     }
-
 }
index 14c1ad2..a026f18 100644 (file)
@@ -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.
  * limitations under the License.
  * ============LICENSE_END=========================================================
  */
-
 package org.openecomp.sdc.be.components.merge.instance;
 
+import static java.util.Collections.singletonMap;
+import static java.util.stream.Collectors.toList;
+import static org.apache.commons.collections.CollectionUtils.isEmpty;
+import static org.openecomp.sdc.be.dao.utils.MapUtil.toMap;
+import static org.openecomp.sdc.be.utils.PropertyDefinitionUtils.resolveGetInputProperties;
+
+import java.util.Collection;
+import java.util.List;
+import java.util.Map;
+import java.util.stream.Stream;
 import org.openecomp.sdc.be.components.merge.input.DeclaredInputsResolver;
 import org.openecomp.sdc.be.components.merge.input.InputsValuesMergingBusinessLogic;
 import org.openecomp.sdc.be.dao.api.ActionStatus;
@@ -32,17 +41,6 @@ import org.openecomp.sdc.be.model.jsonjanusgraph.operations.ToscaOperationFacade
 import org.openecomp.sdc.be.model.utils.ComponentUtilities;
 import org.openecomp.sdc.common.log.wrappers.Logger;
 
-import java.util.Collection;
-import java.util.List;
-import java.util.Map;
-import java.util.stream.Stream;
-
-import static java.util.Collections.singletonMap;
-import static java.util.stream.Collectors.toList;
-import static org.apache.commons.collections.CollectionUtils.isEmpty;
-import static org.openecomp.sdc.be.dao.utils.MapUtil.toMap;
-import static org.openecomp.sdc.be.utils.PropertyDefinitionUtils.resolveGetInputProperties;
-
 @org.springframework.stereotype.Component
 public class ComponentInstanceInputsRedeclareHandler {
 
@@ -51,55 +49,59 @@ public class ComponentInstanceInputsRedeclareHandler {
     private final ToscaOperationFacade toscaOperationFacade;
     private final ComponentsUtils componentsUtils;
     private final InputsValuesMergingBusinessLogic inputsValuesMergingBusinessLogic;
-    
-    public ComponentInstanceInputsRedeclareHandler(DeclaredInputsResolver declaredInputsResolver, ToscaOperationFacade toscaOperationFacade, ComponentsUtils componentsUtils, InputsValuesMergingBusinessLogic inputsValuesMergingBusinessLogic) {
+
+    public ComponentInstanceInputsRedeclareHandler(DeclaredInputsResolver declaredInputsResolver, ToscaOperationFacade toscaOperationFacade,
+                                                   ComponentsUtils componentsUtils,
+                                                   InputsValuesMergingBusinessLogic inputsValuesMergingBusinessLogic) {
         this.declaredInputsResolver = declaredInputsResolver;
         this.toscaOperationFacade = toscaOperationFacade;
         this.componentsUtils = componentsUtils;
         this.inputsValuesMergingBusinessLogic = inputsValuesMergingBusinessLogic;
     }
 
-    ActionStatus redeclareComponentInputsForInstance(Component container, String newInstanceId, Component newInstanceOriginType, List<InputDefinition> oldInputs) {
-        log.debug("#redeclareComponentInputsForInstance - getting inputs that were previously declared from instance {} and setting on current component {}", newInstanceId, container.getUniqueId());
+    ActionStatus redeclareComponentInputsForInstance(Component container, String newInstanceId, Component newInstanceOriginType,
+                                                     List<InputDefinition> oldInputs) {
+        log.debug(
+            "#redeclareComponentInputsForInstance - getting inputs that were previously declared from instance {} and setting on current component {}",
+            newInstanceId, container.getUniqueId());
         Map<String, List<PropertyDataDefinition>> allPropertiesForInstance = getAllGetPropertiesForInstance(container, newInstanceId);
-        List<InputDefinition> previouslyDeclaredInputs = declaredInputsResolver.getPreviouslyDeclaredInputsToMerge(oldInputs, container, allPropertiesForInstance);
+        List<InputDefinition> previouslyDeclaredInputs = declaredInputsResolver
+            .getPreviouslyDeclaredInputsToMerge(oldInputs, container, allPropertiesForInstance);
         inputsValuesMergingBusinessLogic.mergeComponentInputs(oldInputs, previouslyDeclaredInputs);
         Map<String, List<PropertyDataDefinition>> getInputProperties = resolveGetInputProperties(allPropertiesForInstance);
         updateInputsAnnotations(getInputProperties.get(newInstanceId), newInstanceOriginType, previouslyDeclaredInputs);
-
         return updateInputs(container.getUniqueId(), previouslyDeclaredInputs);
     }
 
-    private void updateInputsAnnotations(List<PropertyDataDefinition> instanceProps, Component newInstanceOriginType, List<InputDefinition> previouslyDeclaredInputs) {
+    private void updateInputsAnnotations(List<PropertyDataDefinition> instanceProps, Component newInstanceOriginType,
+                                         List<InputDefinition> previouslyDeclaredInputs) {
         Map<String, PropertyDataDefinition> instancePropsById = toMap(instanceProps, PropertyDataDefinition::getUniqueId);
         for (InputDefinition input : previouslyDeclaredInputs) {
-            List<Annotation> originPropInputAnnotations = getAnnotationsFromOriginType(newInstanceOriginType, input.getPropertyId(), instancePropsById);
-            if(!isEmpty(originPropInputAnnotations)){
+            List<Annotation> originPropInputAnnotations = getAnnotationsFromOriginType(newInstanceOriginType, input.getPropertyId(),
+                instancePropsById);
+            if (!isEmpty(originPropInputAnnotations)) {
                 input.setAnnotations(originPropInputAnnotations);
             }
         }
     }
 
-    private List<Annotation> getAnnotationsFromOriginType(Component originType, String propertyId, Map<String, PropertyDataDefinition> instancePropsById) {
+    private List<Annotation> getAnnotationsFromOriginType(Component originType, String propertyId,
+                                                          Map<String, PropertyDataDefinition> instancePropsById) {
         PropertyDataDefinition instanceProp = instancePropsById.get(propertyId);
         String originPropInputName = instanceProp.getName();
         return ComponentUtilities.getInputAnnotations(originType, originPropInputName);
     }
 
     private Map<String, List<PropertyDataDefinition>> getAllGetPropertiesForInstance(Component newComponent, String instanceId) {
-        List<PropertyDataDefinition> allInstanceProps = Stream.of(newComponent.safeGetComponentInstanceProperties(instanceId),
-                newComponent.safeGetComponentInstanceInput(instanceId))
-                .flatMap(Collection::stream)
-                .map(PropertyDataDefinition::new)
-                .collect(toList());
+        List<PropertyDataDefinition> allInstanceProps = Stream
+            .of(newComponent.safeGetComponentInstanceProperties(instanceId), newComponent.safeGetComponentInstanceInput(instanceId))
+            .flatMap(Collection::stream).map(PropertyDataDefinition::new).collect(toList());
         return singletonMap(instanceId, allInstanceProps);
     }
 
     private ActionStatus updateInputs(String containerId, List<InputDefinition> inputsToUpdate) {
         log.debug("#updateInputs - updating inputs for container {}", containerId);
         return toscaOperationFacade.updateInputsToComponent(inputsToUpdate, containerId)
-                .either(updatedInputs -> ActionStatus.OK,
-                        componentsUtils::convertFromStorageResponse);
+            .either(updatedInputs -> ActionStatus.OK, componentsUtils::convertFromStorageResponse);
     }
-
 }
index b2579b7..2d49eae 100644 (file)
@@ -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.
@@ -17,9 +17,9 @@
  * limitations under the License.
  * ============LICENSE_END=========================================================
  */
-
 package org.openecomp.sdc.be.components.merge.instance;
 
+import java.util.List;
 import org.apache.commons.collections.CollectionUtils;
 import org.apache.commons.collections.MapUtils;
 import org.openecomp.sdc.be.components.impl.exceptions.ByResponseFormatComponentException;
@@ -35,19 +35,17 @@ import org.openecomp.sdc.be.model.jsonjanusgraph.operations.ToscaOperationFacade
 import org.openecomp.sdc.be.model.operations.api.StorageOperationStatus;
 import org.springframework.beans.factory.annotation.Autowired;
 
-import java.util.List;
-
 @org.springframework.stereotype.Component("ComponentInstanceInterfacesMerge")
 public class ComponentInstanceInterfacesMerge implements ComponentInstanceMergeInterface {
 
     @Autowired
     private ComponentsUtils componentsUtils;
-
     @Autowired
     private ToscaOperationFacade toscaOperationFacade;
 
     @Override
-    public void saveDataBeforeMerge(DataForMergeHolder dataHolder, Component containerComponent, ComponentInstance currentResourceInstance, Component originComponent) {
+    public void saveDataBeforeMerge(DataForMergeHolder dataHolder, Component containerComponent, ComponentInstance currentResourceInstance,
+                                    Component originComponent) {
         dataHolder.setOrigInstanceNode(originComponent);
         dataHolder.setOrigComponentInstanceInterfaces(containerComponent.safeGetComponentInstanceInterfaces(currentResourceInstance.getUniqueId()));
     }
@@ -56,42 +54,38 @@ public class ComponentInstanceInterfacesMerge implements ComponentInstanceMergeI
     public Component mergeDataAfterCreate(User user, DataForMergeHolder dataHolder, Component updatedContainerComponent, String newInstanceId) {
         List<ComponentInstanceInterface> origInstanceInterfaces = dataHolder.getOrigComponentInstanceInterfaces();
         ActionStatus mergeStatus = mergeComponentInstanceInterfaces(updatedContainerComponent, newInstanceId, origInstanceInterfaces);
-        if (!ActionStatus.OK.equals(mergeStatus)){
+        if (!ActionStatus.OK.equals(mergeStatus)) {
             throw new ByResponseFormatComponentException(componentsUtils.getResponseFormat(mergeStatus));
-        }
-        else {
+        } else {
             return updatedContainerComponent;
         }
     }
 
-    private ActionStatus mergeComponentInstanceInterfaces(Component currentComponent, String instanceId, List<ComponentInstanceInterface> prevInstanceInterfaces) {
+    private ActionStatus mergeComponentInstanceInterfaces(Component currentComponent, String instanceId,
+                                                          List<ComponentInstanceInterface> prevInstanceInterfaces) {
         if (CollectionUtils.isEmpty(prevInstanceInterfaces) || MapUtils.isEmpty(currentComponent.getComponentInstancesInterfaces())) {
             return ActionStatus.OK;
         }
-
-        if(CollectionUtils.isEmpty(currentComponent.getComponentInstancesInterfaces().get(instanceId))){
+        if (CollectionUtils.isEmpty(currentComponent.getComponentInstancesInterfaces().get(instanceId))) {
             return ActionStatus.OK;
         }
-
-        currentComponent.getComponentInstancesInterfaces().get(instanceId).stream()
-            .forEach(newInterfaceDef -> newInterfaceDef.getOperationsMap().values()
-                .forEach(newOperationDef -> prevInstanceInterfaces.stream().filter(in -> in.getUniqueId().equals(newInterfaceDef.getUniqueId()))
-                    .forEach(prevInterfaceDef -> prevInterfaceDef.getOperationsMap().values().stream().filter(in1 -> in1.getUniqueId().equals(newOperationDef.getUniqueId()))
+        currentComponent.getComponentInstancesInterfaces().get(instanceId).stream().forEach(
+            newInterfaceDef -> newInterfaceDef.getOperationsMap().values().forEach(
+                newOperationDef -> prevInstanceInterfaces.stream().filter(in -> in.getUniqueId().equals(newInterfaceDef.getUniqueId())).forEach(
+                    prevInterfaceDef -> prevInterfaceDef.getOperationsMap().values().stream()
+                        .filter(in1 -> in1.getUniqueId().equals(newOperationDef.getUniqueId()))
                         .forEach(oldOperationDef -> mergeOperationInputDefinitions(oldOperationDef.getInputs(), newOperationDef.getInputs())))));
-
         StorageOperationStatus updateStatus = toscaOperationFacade.updateComponentInstanceInterfaces(currentComponent, instanceId);
         return componentsUtils.convertFromStorageResponse(updateStatus);
     }
 
-
-    private void mergeOperationInputDefinitions(ListDataDefinition<OperationInputDefinition> origInputs, ListDataDefinition<OperationInputDefinition> newInputs){
+    private void mergeOperationInputDefinitions(ListDataDefinition<OperationInputDefinition> origInputs,
+                                                ListDataDefinition<OperationInputDefinition> newInputs) {
         newInputs.getListToscaDataDefinition()
-            .forEach(inp -> origInputs.getListToscaDataDefinition().stream().filter(in -> in.getInputId().equals(inp.getInputId()))
-                .forEach(in -> {
-                    inp.setSourceProperty(in.getSourceProperty());
-                    inp.setSource(in.getSource());
-                    inp.setValue(in.getValue());
-                }));
+            .forEach(inp -> origInputs.getListToscaDataDefinition().stream().filter(in -> in.getInputId().equals(inp.getInputId())).forEach(in -> {
+                inp.setSourceProperty(in.getSourceProperty());
+                inp.setSource(in.getSource());
+                inp.setValue(in.getValue());
+            }));
     }
-
 }
index 888ad2b..7353a12 100644 (file)
@@ -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.
  * limitations under the License.
  * ============LICENSE_END=========================================================
  */
-
 package org.openecomp.sdc.be.components.merge.instance;
 
 import fj.data.Either;
+import java.util.List;
 import org.openecomp.sdc.be.components.impl.exceptions.ByActionStatusComponentException;
 import org.openecomp.sdc.be.dao.api.ActionStatus;
 import org.openecomp.sdc.be.impl.ComponentsUtils;
@@ -34,8 +34,6 @@ import org.openecomp.sdc.common.log.wrappers.Logger;
 import org.springframework.beans.factory.annotation.Autowired;
 import org.springframework.context.annotation.Lazy;
 
-import java.util.List;
-
 /**
  * Created by chaya on 9/12/2017.
  */
@@ -43,14 +41,11 @@ import java.util.List;
 public class ComponentInstanceMergeDataBusinessLogic {
 
     private static final Logger log = Logger.getLogger(ComponentInstanceMergeDataBusinessLogic.class);
-
     @Autowired
     @Lazy
     private List<ComponentInstanceMergeInterface> componentInstancesMergeBLs;
-
     @Autowired
     private ToscaOperationFacade toscaOperationFacade;
-
     @Autowired
     private ComponentsUtils componentsUtils;
 
@@ -61,10 +56,12 @@ public class ComponentInstanceMergeDataBusinessLogic {
 
     /**
      * Saves all containerComponents data before deleting, in order to merge once creating a new instance
+     *
      * @param containerComponent
      * @param currentResourceInstance
      */
-    public DataForMergeHolder saveAllDataBeforeDeleting(org.openecomp.sdc.be.model.Component containerComponent, ComponentInstance currentResourceInstance, Component originComponent) {
+    public DataForMergeHolder saveAllDataBeforeDeleting(org.openecomp.sdc.be.model.Component containerComponent,
+                                                        ComponentInstance currentResourceInstance, Component originComponent) {
         DataForMergeHolder dataHolder = new DataForMergeHolder();
         for (ComponentInstanceMergeInterface compInstMergeBL : componentInstancesMergeBLs) {
             compInstMergeBL.saveDataBeforeMerge(dataHolder, containerComponent, currentResourceInstance, originComponent);
@@ -74,14 +71,16 @@ public class ComponentInstanceMergeDataBusinessLogic {
 
     /**
      * Merges inputs and instance inputs/props of the new Container component with the old container component data (before deleting)
+     *
      * @param containerComponent
      * @param newContainerComponentId
      * @param newInstanceId
      * @return
      */
-    public Component mergeComponentUserOrigData(User user, DataForMergeHolder dataHolder, org.openecomp.sdc.be.model.Component containerComponent, String newContainerComponentId, String newInstanceId) {
-
-        Either<Component, StorageOperationStatus> componentWithInstancesInputsAndProperties = getComponentWithInstancesMergeEntities(newContainerComponentId);
+    public Component mergeComponentUserOrigData(User user, DataForMergeHolder dataHolder, org.openecomp.sdc.be.model.Component containerComponent,
+                                                String newContainerComponentId, String newInstanceId) {
+        Either<Component, StorageOperationStatus> componentWithInstancesInputsAndProperties = getComponentWithInstancesMergeEntities(
+            newContainerComponentId);
         if (componentWithInstancesInputsAndProperties.isRight()) {
             log.error("Component with id {} was not found", newContainerComponentId);
             StorageOperationStatus storageOperationStatus = componentWithInstancesInputsAndProperties.right().value();
@@ -89,7 +88,7 @@ public class ComponentInstanceMergeDataBusinessLogic {
             throw new ByActionStatusComponentException(actionStatus);
         }
         Component updatedContainerComponent = componentWithInstancesInputsAndProperties.left().value();
-        componentInstancesMergeBLs.forEach(c-> c.mergeDataAfterCreate(user, dataHolder, updatedContainerComponent, newInstanceId));
+        componentInstancesMergeBLs.forEach(c -> c.mergeDataAfterCreate(user, dataHolder, updatedContainerComponent, newInstanceId));
         return updatedContainerComponent;
     }
 
index 29ce663..3cac656 100644 (file)
@@ -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.
@@ -17,7 +17,6 @@
  * limitations under the License.
  * ============LICENSE_END=========================================================
  */
-
 package org.openecomp.sdc.be.components.merge.instance;
 
 import org.openecomp.sdc.be.model.Component;
@@ -29,7 +28,8 @@ import org.openecomp.sdc.be.model.User;
  */
 public interface ComponentInstanceMergeInterface {
 
-    void saveDataBeforeMerge(DataForMergeHolder dataHolder, Component containerComponent, ComponentInstance currentResourceInstance, Component originComponent);
+    void saveDataBeforeMerge(DataForMergeHolder dataHolder, Component containerComponent, ComponentInstance currentResourceInstance,
+                             Component originComponent);
 
     Component mergeDataAfterCreate(User user, DataForMergeHolder dataHolder, Component updatedContainerComponent, String newInstanceId);
 }
index 8a0b628..e6205a2 100644 (file)
@@ -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.
  * limitations under the License.
  * ============LICENSE_END=========================================================
  */
-
 package org.openecomp.sdc.be.components.merge.instance;
 
+import static org.openecomp.sdc.be.components.merge.resource.ResourceDataMergeBusinessLogic.ANY_ORDER_COMMAND;
+
 import fj.data.Either;
+import java.util.Collections;
+import java.util.List;
+import java.util.Map;
+import java.util.function.Function;
+import java.util.stream.Collectors;
 import org.openecomp.sdc.be.components.merge.VspComponentsMergeCommand;
 import org.openecomp.sdc.be.components.merge.property.DataDefinitionsValuesMergingBusinessLogic;
 import org.openecomp.sdc.be.dao.api.ActionStatus;
@@ -33,14 +39,6 @@ import org.openecomp.sdc.be.model.jsonjanusgraph.operations.ToscaOperationFacade
 import org.openecomp.sdc.be.model.operations.api.StorageOperationStatus;
 import org.springframework.core.annotation.Order;
 
-import java.util.Collections;
-import java.util.List;
-import java.util.Map;
-import java.util.function.Function;
-import java.util.stream.Collectors;
-
-import static org.openecomp.sdc.be.components.merge.resource.ResourceDataMergeBusinessLogic.ANY_ORDER_COMMAND;
-
 @org.springframework.stereotype.Component
 @Order(ANY_ORDER_COMMAND)
 public class ComponentInstancePropertiesMergeBL implements VspComponentsMergeCommand {
@@ -49,12 +47,26 @@ public class ComponentInstancePropertiesMergeBL implements VspComponentsMergeCom
     private final ComponentsUtils componentsUtils;
     private final DataDefinitionsValuesMergingBusinessLogic propertyValuesMergingBusinessLogic;
 
-    public ComponentInstancePropertiesMergeBL(ToscaOperationFacade toscaOperationFacade, ComponentsUtils componentsUtils, DataDefinitionsValuesMergingBusinessLogic propertyValuesMergingBusinessLogic) {
+    public ComponentInstancePropertiesMergeBL(ToscaOperationFacade toscaOperationFacade, ComponentsUtils componentsUtils,
+                                              DataDefinitionsValuesMergingBusinessLogic propertyValuesMergingBusinessLogic) {
         this.toscaOperationFacade = toscaOperationFacade;
         this.componentsUtils = componentsUtils;
         this.propertyValuesMergingBusinessLogic = propertyValuesMergingBusinessLogic;
     }
 
+    private static Map<String, String> getComponentNameByUniqueId(Component component) {
+        return asMap(component, ComponentInstance::getUniqueId, ComponentInstance::getName);
+    }
+
+    private static Map<String, String> getComponentUniqueIdByName(Component component) {
+        return asMap(component, ComponentInstance::getName, ComponentInstance::getUniqueId);
+    }
+
+    private static Map<String, String> asMap(Component component, Function<? super ComponentInstance, ? extends String> keyMapper,
+                                             Function<? super ComponentInstance, ? extends String> valueMapper) {
+        return component.safeGetComponentInstances().stream().collect(Collectors.toMap(keyMapper, valueMapper));
+    }
+
     @Override
     public ActionStatus mergeComponents(Component prevComponent, Component currentComponent) {
         Map<String, List<ComponentInstanceProperty>> newInstProps = currentComponent.getComponentInstancesProperties();
@@ -63,11 +75,9 @@ public class ComponentInstancePropertiesMergeBL implements VspComponentsMergeCom
         }
         Map<String, String> currComponentNames = getComponentNameByUniqueId(currentComponent);
         Map<String, String> prevComponentUniqueIds = getComponentUniqueIdByName(prevComponent);
-        
         newInstProps.forEach((instanceId, newProps) -> {
             String instanceName = currComponentNames.get(instanceId);
             String oldInstanceId = prevComponentUniqueIds.get(instanceName);
-            
             mergeOldInstancePropertiesValues(prevComponent, currentComponent, oldInstanceId, newProps);
         });
         return updateComponentInstancesProperties(currentComponent, newInstProps);
@@ -78,8 +88,8 @@ public class ComponentInstancePropertiesMergeBL implements VspComponentsMergeCom
         return "merge component instance properties";
     }
 
-
-    public ActionStatus mergeComponentInstanceProperties(List<ComponentInstanceProperty> oldInstProps, List<InputDefinition> oldInputs, Component newComponent, String instanceId) {
+    public ActionStatus mergeComponentInstanceProperties(List<ComponentInstanceProperty> oldInstProps, List<InputDefinition> oldInputs,
+                                                         Component newComponent, String instanceId) {
         List<ComponentInstanceProperty> newInstProps = newComponent.safeGetComponentInstanceProperties(instanceId);
         if (newInstProps == null) {
             return ActionStatus.OK;
@@ -87,28 +97,18 @@ public class ComponentInstancePropertiesMergeBL implements VspComponentsMergeCom
         propertyValuesMergingBusinessLogic.mergeInstanceDataDefinitions(oldInstProps, oldInputs, newInstProps, newComponent.getInputs());
         return updateComponentInstanceProperties(newComponent, instanceId, newInstProps);
     }
-    
-    private static Map<String, String> getComponentNameByUniqueId(Component component) {
-        return asMap(component, ComponentInstance::getUniqueId, ComponentInstance::getName);
-    }
-    
-    private static Map<String, String> getComponentUniqueIdByName(Component component) {
-        return asMap(component, ComponentInstance::getName, ComponentInstance::getUniqueId);
-    }
-    
-    private static Map<String, String> asMap(Component component, Function<? super ComponentInstance, ? extends String> keyMapper, Function<? super ComponentInstance, ? extends String> valueMapper) {
-        return component.safeGetComponentInstances().stream().
-            collect(Collectors.toMap(keyMapper, valueMapper));
-    }
 
-    private void mergeOldInstancePropertiesValues(Component oldComponent, Component newComponent, String instanceId, List<ComponentInstanceProperty> newProps) {
-        List<ComponentInstanceProperty> oldInstProperties = oldComponent == null ? Collections.emptyList() : oldComponent.safeGetComponentInstanceProperties(instanceId);
+    private void mergeOldInstancePropertiesValues(Component oldComponent, Component newComponent, String instanceId,
+                                                  List<ComponentInstanceProperty> newProps) {
+        List<ComponentInstanceProperty> oldInstProperties =
+            oldComponent == null ? Collections.emptyList() : oldComponent.safeGetComponentInstanceProperties(instanceId);
         List<InputDefinition> oldInputs = oldComponent == null ? Collections.emptyList() : oldComponent.getInputs();
         propertyValuesMergingBusinessLogic.mergeInstanceDataDefinitions(oldInstProperties, oldInputs, newProps, newComponent.getInputs());
     }
 
     private ActionStatus updateComponentInstancesProperties(Component newComponent, Map<String, List<ComponentInstanceProperty>> newInstProps) {
-        Either<Map<String, List<ComponentInstanceProperty>>, StorageOperationStatus> mapStorageOperationStatusEither = toscaOperationFacade.updateComponentInstancePropsToComponent(newInstProps, newComponent.getUniqueId());
+        Either<Map<String, List<ComponentInstanceProperty>>, StorageOperationStatus> mapStorageOperationStatusEither = toscaOperationFacade
+            .updateComponentInstancePropsToComponent(newInstProps, newComponent.getUniqueId());
         if (mapStorageOperationStatusEither.isRight()) {
             return componentsUtils.convertFromStorageResponse(mapStorageOperationStatusEither.right().value());
         }
@@ -122,5 +122,4 @@ public class ComponentInstancePropertiesMergeBL implements VspComponentsMergeCom
         }
         return ActionStatus.OK;
     }
-
 }
index cbfc970..d896e4a 100644 (file)
@@ -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.
  * limitations under the License.
  * ============LICENSE_END=========================================================
  */
-
 package org.openecomp.sdc.be.components.merge.instance;
 
+import static org.apache.commons.collections.CollectionUtils.isNotEmpty;
+
 import fj.data.Either;
+import java.util.ArrayList;
+import java.util.List;
 import org.openecomp.sdc.be.components.impl.exceptions.ByActionStatusComponentException;
 import org.openecomp.sdc.be.dao.api.ActionStatus;
 import org.openecomp.sdc.be.impl.ComponentsUtils;
@@ -35,11 +38,6 @@ import org.openecomp.sdc.be.model.jsonjanusgraph.operations.ToscaOperationFacade
 import org.openecomp.sdc.be.model.operations.api.StorageOperationStatus;
 import org.openecomp.sdc.common.log.wrappers.Logger;
 
-import java.util.ArrayList;
-import java.util.List;
-
-import static org.apache.commons.collections.CollectionUtils.isNotEmpty;
-
 /**
  * Created by chaya on 9/20/2017.
  */
@@ -47,14 +45,16 @@ import static org.apache.commons.collections.CollectionUtils.isNotEmpty;
 public class ComponentInstancePropsAndInputsMerge implements ComponentInstanceMergeInterface {
 
     private static final Logger log = Logger.getLogger(ComponentInstancePropsAndInputsMerge.class);
-
     private final ToscaOperationFacade toscaOperationFacade;
     private final ComponentsUtils componentsUtils;
     private final ComponentInstancePropertiesMergeBL componentInstancePropertiesMergeBL;
     private final ComponentInstanceInputsMergeBL resourceInstanceInputsMergeBL;
     private final ComponentInstanceInputsRedeclareHandler instanceInputsRedeclareHandler;
 
-    public ComponentInstancePropsAndInputsMerge(ToscaOperationFacade toscaOperationFacade, ComponentsUtils componentsUtils, ComponentInstancePropertiesMergeBL componentInstancePropertiesMergeBL, ComponentInstanceInputsMergeBL resourceInstanceInputsMergeBL, ComponentInstanceInputsRedeclareHandler instanceInputsRedeclareHandler) {
+    public ComponentInstancePropsAndInputsMerge(ToscaOperationFacade toscaOperationFacade, ComponentsUtils componentsUtils,
+                                                ComponentInstancePropertiesMergeBL componentInstancePropertiesMergeBL,
+                                                ComponentInstanceInputsMergeBL resourceInstanceInputsMergeBL,
+                                                ComponentInstanceInputsRedeclareHandler instanceInputsRedeclareHandler) {
         this.toscaOperationFacade = toscaOperationFacade;
         this.componentsUtils = componentsUtils;
         this.componentInstancePropertiesMergeBL = componentInstancePropertiesMergeBL;
@@ -63,7 +63,8 @@ public class ComponentInstancePropsAndInputsMerge implements ComponentInstanceMe
     }
 
     @Override
-    public void saveDataBeforeMerge(DataForMergeHolder dataHolder, Component containerComponent, ComponentInstance currentResourceInstance, Component originComponent) {
+    public void saveDataBeforeMerge(DataForMergeHolder dataHolder, Component containerComponent, ComponentInstance currentResourceInstance,
+                                    Component originComponent) {
         dataHolder.setOrigComponentInstanceInputs(containerComponent.safeGetComponentInstanceInputsByName(currentResourceInstance.getName()));
         dataHolder.setOrigComponentInstanceProperties(containerComponent.safeGetComponentInstanceProperties(currentResourceInstance.getUniqueId()));
         dataHolder.setOrigComponentInputs(containerComponent.getInputs());
@@ -71,17 +72,20 @@ public class ComponentInstancePropsAndInputsMerge implements ComponentInstanceMe
 
     @Override
     public Component mergeDataAfterCreate(User user, DataForMergeHolder dataHolder, Component updatedContainerComponent, String newInstanceId) {
-        Either<List<ComponentInstanceInput>, ActionStatus> instanceInputsEither = mergeComponentInstanceInputsIntoContainer(dataHolder, updatedContainerComponent, newInstanceId);
+        Either<List<ComponentInstanceInput>, ActionStatus> instanceInputsEither = mergeComponentInstanceInputsIntoContainer(dataHolder,
+            updatedContainerComponent, newInstanceId);
         if (instanceInputsEither.isRight()) {
             ActionStatus actionStatus = instanceInputsEither.right().value();
             throw new ByActionStatusComponentException(actionStatus);
         }
-        Either<List<ComponentInstanceProperty>, ActionStatus> instancePropsEither = mergeComponentInstancePropsIntoContainer(dataHolder, updatedContainerComponent, newInstanceId);
+        Either<List<ComponentInstanceProperty>, ActionStatus> instancePropsEither = mergeComponentInstancePropsIntoContainer(dataHolder,
+            updatedContainerComponent, newInstanceId);
         if (instancePropsEither.isRight()) {
             ActionStatus actionStatus = instancePropsEither.right().value();
             throw new ByActionStatusComponentException(actionStatus);
         }
-        Either<List<InputDefinition>, ActionStatus> inputsEither = mergeComponentInputsIntoContainer(dataHolder, updatedContainerComponent.getUniqueId(), newInstanceId);
+        Either<List<InputDefinition>, ActionStatus> inputsEither = mergeComponentInputsIntoContainer(dataHolder,
+            updatedContainerComponent.getUniqueId(), newInstanceId);
         if (inputsEither.isRight()) {
             ActionStatus actionStatus = inputsEither.right().value();
             throw new ByActionStatusComponentException(actionStatus);
@@ -89,12 +93,14 @@ public class ComponentInstancePropsAndInputsMerge implements ComponentInstanceMe
         return updatedContainerComponent;
     }
 
-    private Either<List<ComponentInstanceProperty>, ActionStatus> mergeComponentInstancePropsIntoContainer(DataForMergeHolder dataHolder, Component updatedComponent, String instanceId) {
+    private Either<List<ComponentInstanceProperty>, ActionStatus> mergeComponentInstancePropsIntoContainer(DataForMergeHolder dataHolder,
+                                                                                                           Component updatedComponent,
+                                                                                                           String instanceId) {
         List<ComponentInstanceProperty> originComponentInstanceProps = dataHolder.getOrigComponentInstanceProperties();
         List<InputDefinition> originComponentsInputs = dataHolder.getOrigComponentInputs();
         List<ComponentInstanceProperty> newComponentInstancesProps = updatedComponent.safeGetComponentInstanceProperties(instanceId);
-        ActionStatus actionStatus = componentInstancePropertiesMergeBL.mergeComponentInstanceProperties(originComponentInstanceProps, originComponentsInputs, updatedComponent, instanceId);
-
+        ActionStatus actionStatus = componentInstancePropertiesMergeBL
+            .mergeComponentInstanceProperties(originComponentInstanceProps, originComponentsInputs, updatedComponent, instanceId);
         if (actionStatus != ActionStatus.OK) {
             log.error("Failed to update component {} with merged instance properties", updatedComponent.getUniqueId(), newComponentInstancesProps);
             return Either.right(actionStatus);
@@ -102,11 +108,14 @@ public class ComponentInstancePropsAndInputsMerge implements ComponentInstanceMe
         return Either.left(newComponentInstancesProps);
     }
 
-    private Either<List<ComponentInstanceInput>, ActionStatus> mergeComponentInstanceInputsIntoContainer(DataForMergeHolder dataHolder, Component updatedComponent, String instanceId) {
+    private Either<List<ComponentInstanceInput>, ActionStatus> mergeComponentInstanceInputsIntoContainer(DataForMergeHolder dataHolder,
+                                                                                                         Component updatedComponent,
+                                                                                                         String instanceId) {
         List<ComponentInstanceInput> originComponentInstanceInputs = dataHolder.getOrigComponentInstanceInputs();
         List<InputDefinition> originComponentsInputs = dataHolder.getOrigComponentInputs();
         List<ComponentInstanceInput> newComponentInstancesInputs = updatedComponent.safeGetComponentInstanceInput(instanceId);
-        ActionStatus actionStatus = resourceInstanceInputsMergeBL.mergeComponentInstanceInputs(originComponentInstanceInputs, originComponentsInputs, updatedComponent, instanceId);
+        ActionStatus actionStatus = resourceInstanceInputsMergeBL
+            .mergeComponentInstanceInputs(originComponentInstanceInputs, originComponentsInputs, updatedComponent, instanceId);
         if (actionStatus != ActionStatus.OK) {
             log.error("Failed to update component {} with merged instance properties", updatedComponent.getUniqueId(), newComponentInstancesInputs);
             return Either.right(actionStatus);
@@ -114,19 +123,22 @@ public class ComponentInstancePropsAndInputsMerge implements ComponentInstanceMe
         return Either.left(newComponentInstancesInputs);
     }
 
-    private Either<List<InputDefinition>, ActionStatus> mergeComponentInputsIntoContainer(DataForMergeHolder dataHolder, String newContainerComponentId, String newInstanceId) {
+    private Either<List<InputDefinition>, ActionStatus> mergeComponentInputsIntoContainer(DataForMergeHolder dataHolder,
+                                                                                          String newContainerComponentId, String newInstanceId) {
         List<InputDefinition> origComponentInputs = dataHolder.getOrigComponentInputs();
         List<InputDefinition> inputsToAddToContainer = new ArrayList<>();
         if (isNotEmpty(origComponentInputs)) {
             // get  instance inputs and properties after merge
-            Either<Component, StorageOperationStatus> componentWithInstancesInputsAndProperties = getComponentWithInstancesInputsAndProperties(newContainerComponentId);
+            Either<Component, StorageOperationStatus> componentWithInstancesInputsAndProperties = getComponentWithInstancesInputsAndProperties(
+                newContainerComponentId);
             if (componentWithInstancesInputsAndProperties.isRight()) {
                 log.error("Component %s was not found", newContainerComponentId);
                 return Either.right(componentsUtils.convertFromStorageResponse(componentWithInstancesInputsAndProperties.right().value()));
             }
             Component updatedContainerComponent = componentWithInstancesInputsAndProperties.left().value();
             Component currInstanceOriginType = dataHolder.getCurrInstanceNode();
-            ActionStatus redeclareStatus = instanceInputsRedeclareHandler.redeclareComponentInputsForInstance(updatedContainerComponent, newInstanceId, currInstanceOriginType, origComponentInputs);
+            ActionStatus redeclareStatus = instanceInputsRedeclareHandler
+                .redeclareComponentInputsForInstance(updatedContainerComponent, newInstanceId, currInstanceOriginType, origComponentInputs);
             if (redeclareStatus != ActionStatus.OK) {
                 log.error("Failed to update component {} with merged inputs {}", newContainerComponentId, inputsToAddToContainer);
                 return Either.right(redeclareStatus);
index 8c515a5..7e25c02 100644 (file)
@@ -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.
  * limitations under the License.
  * ============LICENSE_END=========================================================
  */
-
 package org.openecomp.sdc.be.components.merge.instance;
 
 import fj.data.Either;
+import java.util.Collections;
+import java.util.List;
+import java.util.Map;
+import java.util.Objects;
+import java.util.function.Function;
+import java.util.stream.Collectors;
+import java.util.stream.Stream;
 import org.apache.commons.lang3.StringUtils;
 import org.openecomp.sdc.be.components.impl.exceptions.ByResponseFormatComponentException;
 import org.openecomp.sdc.be.components.merge.utils.CapabilityOwner;
@@ -38,90 +44,77 @@ import org.openecomp.sdc.common.datastructure.Wrapper;
 import org.openecomp.sdc.common.log.wrappers.Logger;
 import org.openecomp.sdc.exception.ResponseFormat;
 
-import java.util.Collections;
-import java.util.List;
-import java.util.Map;
-import java.util.Objects;
-import java.util.function.Function;
-import java.util.stream.Collectors;
-import java.util.stream.Stream;
-
-
 @org.springframework.stereotype.Component("ComponentInstanceRelashionMerge")
 public class ComponentInstanceRelationMerge implements ComponentInstanceMergeInterface {
+
     private static final Logger log = Logger.getLogger(ComponentInstanceRelationMerge.class);
-    
     private final ComponentsUtils componentsUtils;
     private final MergeInstanceUtils mergeInstanceUtils;
     private final ToscaOperationFacade toscaOperationFacade;
 
-    public ComponentInstanceRelationMerge(ComponentsUtils componentsUtils, MergeInstanceUtils mergeInstanceUtils, ToscaOperationFacade toscaOperationFacade) {
+    public ComponentInstanceRelationMerge(ComponentsUtils componentsUtils, MergeInstanceUtils mergeInstanceUtils,
+                                          ToscaOperationFacade toscaOperationFacade) {
         this.componentsUtils = componentsUtils;
         this.mergeInstanceUtils = mergeInstanceUtils;
         this.toscaOperationFacade = toscaOperationFacade;
     }
-    
 
     @Override
-    public void saveDataBeforeMerge(DataForMergeHolder dataHolder, Component containerComponent, ComponentInstance currentResourceInstance, Component originComponent) {
+    public void saveDataBeforeMerge(DataForMergeHolder dataHolder, Component containerComponent, ComponentInstance currentResourceInstance,
+                                    Component originComponent) {
         //All Relationships - container (service) holds info about all relations
-        //Filter by UniqueId in from/to
-        List<RequirementCapabilityRelDef> relationsFrom = getRelations(RequirementCapabilityRelDef::getFromNode,
-                                                                      containerComponent,
-                                                                      currentResourceInstance);
-
-        List<RequirementCapabilityRelDef> relationsTo = getRelations(RequirementCapabilityRelDef::getToNode,
-                                                                    containerComponent,
-                                                                    currentResourceInstance);
 
+        //Filter by UniqueId in from/to
+        List<RequirementCapabilityRelDef> relationsFrom = getRelations(RequirementCapabilityRelDef::getFromNode, containerComponent,
+            currentResourceInstance);
+        List<RequirementCapabilityRelDef> relationsTo = getRelations(RequirementCapabilityRelDef::getToNode, containerComponent,
+            currentResourceInstance);
         if (!relationsFrom.isEmpty() || !relationsTo.isEmpty()) {
-            ComponentInstanceBuildingBlocks instBuildingBlocks = mergeInstanceUtils.getInstanceAtomicBuildingBlocks(currentResourceInstance, originComponent);
-
-            if  (instBuildingBlocks != null) {
-                List<RelationMergeInfo> fromRelInfoList = convert(relationsFrom, rel -> mergeInstanceUtils.mapRelationRequirement(rel, instBuildingBlocks.getVfcInstances()));
-                List<RelationMergeInfo> toRelInfoList = convert(relationsTo, rel -> mergeInstanceUtils.mapRelationCapability(rel, instBuildingBlocks.getCapabilitiesOwners()));
-
+            ComponentInstanceBuildingBlocks instBuildingBlocks = mergeInstanceUtils
+                .getInstanceAtomicBuildingBlocks(currentResourceInstance, originComponent);
+            if (instBuildingBlocks != null) {
+                List<RelationMergeInfo> fromRelInfoList = convert(relationsFrom,
+                    rel -> mergeInstanceUtils.mapRelationRequirement(rel, instBuildingBlocks.getVfcInstances()));
+                List<RelationMergeInfo> toRelInfoList = convert(relationsTo,
+                    rel -> mergeInstanceUtils.mapRelationCapability(rel, instBuildingBlocks.getCapabilitiesOwners()));
                 // Encapsulate all needed info in one container
                 ContainerRelationsMergeInfo containerRelationsMergeInfo = new ContainerRelationsMergeInfo(fromRelInfoList, toRelInfoList);
                 // Save it
                 dataHolder.setVfRelationsInfo(containerRelationsMergeInfo);
             }
-        }
-        else {
+        } else {
             log.debug("No relations relevant to currentResourceInstance {} found in container component", currentResourceInstance);
         }
-
     }
 
-
     @Override
     public Component mergeDataAfterCreate(User user, DataForMergeHolder dataHolder, Component updatedContainerComponent, String newInstanceId) {
         Wrapper<Either<Component, ResponseFormat>> resultWrapper = new Wrapper<>();
-
         ContainerRelationsMergeInfo containerRelationsMergeInfo = getRelationsMergeInfo(dataHolder, updatedContainerComponent, resultWrapper);
-
         ComponentInstance newComponentInstance = null;
-        if(resultWrapper.isEmpty()) {
+        if (resultWrapper.isEmpty()) {
             //Component Instance
             newComponentInstance = loadComponentInstance(updatedContainerComponent, newInstanceId, resultWrapper);
         }
-
-        if(resultWrapper.isEmpty() && containerRelationsMergeInfo != null) {
+        if (resultWrapper.isEmpty() && containerRelationsMergeInfo != null) {
             // Load VFCI and filter them by name
             ComponentInstanceBuildingBlocks instanceBuildBlocks = mergeInstanceUtils.getInstanceAtomicBuildingBlocks(newComponentInstance);
-            if(instanceBuildBlocks != null) {
+            if (instanceBuildBlocks != null) {
                 // Process Relationships
-                Stream<RequirementCapabilityRelDef> toRelationsInfoStream = getCapabilitiesRelationInfoStream(updatedContainerComponent, newInstanceId, containerRelationsMergeInfo, instanceBuildBlocks);
-                Stream<RequirementCapabilityRelDef> fromRelationsInfoStream = getRequirementRelationsInfoStream(updatedContainerComponent, newInstanceId, containerRelationsMergeInfo, instanceBuildBlocks);
+                Stream<RequirementCapabilityRelDef> toRelationsInfoStream = getCapabilitiesRelationInfoStream(updatedContainerComponent,
+                    newInstanceId, containerRelationsMergeInfo, instanceBuildBlocks);
+                Stream<RequirementCapabilityRelDef> fromRelationsInfoStream = getRequirementRelationsInfoStream(updatedContainerComponent,
+                    newInstanceId, containerRelationsMergeInfo, instanceBuildBlocks);
                 List<RequirementCapabilityRelDef> updatedRelations = getUpdatedRelations(toRelationsInfoStream, fromRelationsInfoStream);
-                Either<List<RequirementCapabilityRelDef>, StorageOperationStatus> listStorageOperationStatusEither = toscaOperationFacade.associateResourceInstances(null, updatedContainerComponent.getUniqueId(), updatedRelations);
+                Either<List<RequirementCapabilityRelDef>, StorageOperationStatus> listStorageOperationStatusEither = toscaOperationFacade
+                    .associateResourceInstances(null, updatedContainerComponent.getUniqueId(), updatedRelations);
                 if (listStorageOperationStatusEither.isLeft()) {
                     resultWrapper.setInnerElement(Either.left(updatedContainerComponent));
-                }
-                else {
+                } else {
                     StorageOperationStatus status = listStorageOperationStatusEither.right().value();
                     log.debug("Failed to associate instances of resource {} status is {}", updatedContainerComponent.getUniqueId(), status);
-                    ResponseFormat responseFormat = componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(status), updatedContainerComponent.getUniqueId());
+                    ResponseFormat responseFormat = componentsUtils
+                        .getResponseFormat(componentsUtils.convertFromStorageResponse(status), updatedContainerComponent.getUniqueId());
                     throw new ByResponseFormatComponentException(responseFormat);
                 }
             }
@@ -129,26 +122,31 @@ public class ComponentInstanceRelationMerge implements ComponentInstanceMergeInt
         return resultWrapper.getInnerElement().left().value();
     }
 
-    private Stream<RequirementCapabilityRelDef> getRequirementRelationsInfoStream(Component updatedContainerComponent, String newInstanceId, ContainerRelationsMergeInfo containerRelationsMergeInfo, ComponentInstanceBuildingBlocks instanceBuildBlocks) {
+    private Stream<RequirementCapabilityRelDef> getRequirementRelationsInfoStream(Component updatedContainerComponent, String newInstanceId,
+                                                                                  ContainerRelationsMergeInfo containerRelationsMergeInfo,
+                                                                                  ComponentInstanceBuildingBlocks instanceBuildBlocks) {
         Map<String, ComponentInstance> vfciMap = MapUtil.toMap(instanceBuildBlocks.getVfcInstances(), ComponentInstance::getName, (p1, p2) -> p1);
         List<RelationMergeInfo> fromRelationsInfo = containerRelationsMergeInfo.getFromRelationsInfo();
         Stream<RequirementCapabilityRelDef> fromRelationsInfoStream = null;
-        iffromRelationsInfo != null) {
+        if (fromRelationsInfo != null) {
             fromRelationsInfoStream = fromRelationsInfo.stream()
-                                        .map(oldReqInfo -> mergeInstanceUtils.restoreRequirementRelation(oldReqInfo, newInstanceId, vfciMap, updatedContainerComponent))
-                                        .filter(Objects::nonNull);
+                .map(oldReqInfo -> mergeInstanceUtils.restoreRequirementRelation(oldReqInfo, newInstanceId, vfciMap, updatedContainerComponent))
+                .filter(Objects::nonNull);
         }
         return fromRelationsInfoStream;
     }
 
-    private Stream<RequirementCapabilityRelDef> getCapabilitiesRelationInfoStream(Component updatedContainerComponent, String newInstanceId, ContainerRelationsMergeInfo containerRelationsMergeInfo, ComponentInstanceBuildingBlocks instanceBuildBlocks) {
-        Map<String, CapabilityOwner> capOwnersByName = MapUtil.toMap(instanceBuildBlocks.getCapabilitiesOwners(), CapabilityOwner::getName, (p1, p2) -> p1);
+    private Stream<RequirementCapabilityRelDef> getCapabilitiesRelationInfoStream(Component updatedContainerComponent, String newInstanceId,
+                                                                                  ContainerRelationsMergeInfo containerRelationsMergeInfo,
+                                                                                  ComponentInstanceBuildingBlocks instanceBuildBlocks) {
+        Map<String, CapabilityOwner> capOwnersByName = MapUtil
+            .toMap(instanceBuildBlocks.getCapabilitiesOwners(), CapabilityOwner::getName, (p1, p2) -> p1);
         List<RelationMergeInfo> toRelationsInfo = containerRelationsMergeInfo.getToRelationsInfo();
         Stream<RequirementCapabilityRelDef> toRelationsInfoStream = null;
         if (toRelationsInfo != null) {
-            toRelationsInfoStream = toRelationsInfo.stream()
-                                    .map(oldCapInfo -> mergeInstanceUtils.restoreCapabilityRelation(oldCapInfo, newInstanceId, capOwnersByName, updatedContainerComponent))
-                                    .filter(Objects::nonNull);
+            toRelationsInfoStream = toRelationsInfo.stream().map(
+                oldCapInfo -> mergeInstanceUtils.restoreCapabilityRelation(oldCapInfo, newInstanceId, capOwnersByName, updatedContainerComponent))
+                .filter(Objects::nonNull);
         }
         return toRelationsInfoStream;
     }
@@ -160,65 +158,50 @@ public class ComponentInstanceRelationMerge implements ComponentInstanceMergeInt
      * @return
      */
     private ComponentInstance loadComponentInstance(Component containerComponent, String instanceId,
-            Wrapper<Either<Component, ResponseFormat>> resultWrapper) {
+                                                    Wrapper<Either<Component, ResponseFormat>> resultWrapper) {
         ComponentInstance componentInstance = containerComponent.getComponentInstanceById(instanceId).orElse(null);
         if (componentInstance == null) {
             log.debug("Failed to get VF instance by new VF instance ID: {}", instanceId);
             resultWrapper.setInnerElement(Either.left(containerComponent));
         }
-
         return componentInstance;
     }
 
-
-    private List<RequirementCapabilityRelDef> getUpdatedRelations(Stream<RequirementCapabilityRelDef> toRelationsInfoStream, 
+    private List<RequirementCapabilityRelDef> getUpdatedRelations(Stream<RequirementCapabilityRelDef> toRelationsInfoStream,
                                                                   Stream<RequirementCapabilityRelDef> fromRelationsInfoStream) {
         Stream<RequirementCapabilityRelDef> updatedRelationsStream = Stream.empty();
-
         if (toRelationsInfoStream != null) {
             updatedRelationsStream = Stream.concat(updatedRelationsStream, toRelationsInfoStream);
         }
-
         if (fromRelationsInfoStream != null) {
             updatedRelationsStream = Stream.concat(updatedRelationsStream, fromRelationsInfoStream);
         }
-
         return updatedRelationsStream.collect(Collectors.toList());
     }
 
-    private List<RequirementCapabilityRelDef> getRelations(Function<RequirementCapabilityRelDef, String> getNodeFunc,
-                                                           Component containerComponent,
+    private List<RequirementCapabilityRelDef> getRelations(Function<RequirementCapabilityRelDef, String> getNodeFunc, Component containerComponent,
                                                            ComponentInstance currentResourceInstance) {
-
         final List<RequirementCapabilityRelDef> componentInstancesRelations = containerComponent.getComponentInstancesRelations();
         if (componentInstancesRelations == null) {
             return Collections.emptyList();
         }
-        
         final String vfInstanceId = currentResourceInstance.getUniqueId();
-
-        return componentInstancesRelations.stream()
-                                            .filter(rel -> StringUtils.equals(getNodeFunc.apply(rel), vfInstanceId))
-                                            .collect(Collectors.toList());
+        return componentInstancesRelations.stream().filter(rel -> StringUtils.equals(getNodeFunc.apply(rel), vfInstanceId))
+            .collect(Collectors.toList());
     }
 
-    private List<RelationMergeInfo> convert(List<RequirementCapabilityRelDef> relationsDef, 
+    private List<RelationMergeInfo> convert(List<RequirementCapabilityRelDef> relationsDef,
                                             Function<RequirementCapabilityRelDef, RelationMergeInfo> mapFunc) {
-        return relationsDef.stream()
-                            .map(mapFunc)
-                            .filter(Objects::nonNull)
-                            .collect(Collectors.toList());
+        return relationsDef.stream().map(mapFunc).filter(Objects::nonNull).collect(Collectors.toList());
     }
-    
-    private ContainerRelationsMergeInfo getRelationsMergeInfo(DataForMergeHolder dataHolder,
-                                                              Component updatedContainerComponent,
+
+    private ContainerRelationsMergeInfo getRelationsMergeInfo(DataForMergeHolder dataHolder, Component updatedContainerComponent,
                                                               Wrapper<Either<Component, ResponseFormat>> resultWrapper) {
         ContainerRelationsMergeInfo containerRelationsMergeInfo = dataHolder.getContainerRelationsMergeInfo();
         if (containerRelationsMergeInfo == null) {
             log.debug("There is no info about relations should be restored.");
             resultWrapper.setInnerElement(Either.left(updatedContainerComponent));
         }
-
         return containerRelationsMergeInfo;
     }
 }
index 317f528..da8f6fd 100644 (file)
  * limitations under the License.
  * ============LICENSE_END=========================================================
  */
-
 package org.openecomp.sdc.be.components.merge.instance;
 
+import static org.openecomp.sdc.be.components.merge.resource.ResourceDataMergeBusinessLogic.LAST_COMMAND;
+
 import fj.data.Either;
+import java.util.List;
 import org.apache.commons.collections.CollectionUtils;
 import org.openecomp.sdc.be.components.merge.VspComponentsMergeCommand;
 import org.openecomp.sdc.be.components.merge.utils.MergeInstanceUtils;
@@ -32,10 +34,6 @@ import org.openecomp.sdc.be.model.jsonjanusgraph.operations.ToscaOperationFacade
 import org.openecomp.sdc.be.model.operations.api.StorageOperationStatus;
 import org.springframework.core.annotation.Order;
 
-import java.util.List;
-
-import static org.openecomp.sdc.be.components.merge.resource.ResourceDataMergeBusinessLogic.LAST_COMMAND;
-
 @org.springframework.stereotype.Component
 @Order(LAST_COMMAND)//must run after all merge commands
 public class ComponentInstanceRelationMergeCommand implements VspComponentsMergeCommand {
@@ -44,22 +42,25 @@ public class ComponentInstanceRelationMergeCommand implements VspComponentsMerge
     private final MergeInstanceUtils mergeInstanceUtils;
     private final ComponentsUtils componentsUtils;
 
-    public ComponentInstanceRelationMergeCommand(ToscaOperationFacade toscaOperationFacade, MergeInstanceUtils mergeInstanceUtils, ComponentsUtils componentsUtils) {
+    public ComponentInstanceRelationMergeCommand(ToscaOperationFacade toscaOperationFacade, MergeInstanceUtils mergeInstanceUtils,
+                                                 ComponentsUtils componentsUtils) {
         this.toscaOperationFacade = toscaOperationFacade;
         this.mergeInstanceUtils = mergeInstanceUtils;
         this.componentsUtils = componentsUtils;
     }
+
     @Override
     public ActionStatus mergeComponents(Component prevComponent, Component currentComponent) {
         List<RequirementCapabilityRelDef> updatedUiRelations = mergeInstanceUtils.getUpdatedUiRelations(prevComponent, currentComponent);
-        if(CollectionUtils.isNotEmpty(updatedUiRelations)){
+        if (CollectionUtils.isNotEmpty(updatedUiRelations)) {
             return associateResourceInstances(currentComponent, updatedUiRelations);
         }
         return ActionStatus.OK;
     }
 
     private ActionStatus associateResourceInstances(Component currentComponent, List<RequirementCapabilityRelDef> updatedUiRelations) {
-        Either<List<RequirementCapabilityRelDef>, StorageOperationStatus> listStorageOperationStatusEither = toscaOperationFacade.associateResourceInstances(null, currentComponent.getUniqueId(), updatedUiRelations);
+        Either<List<RequirementCapabilityRelDef>, StorageOperationStatus> listStorageOperationStatusEither = toscaOperationFacade
+            .associateResourceInstances(null, currentComponent.getUniqueId(), updatedUiRelations);
         if (listStorageOperationStatusEither.isLeft()) {
             currentComponent.getComponentInstancesRelations().addAll(updatedUiRelations);
         } else {
index 565fb46..d89b6ed 100644 (file)
@@ -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.
  * limitations under the License.
  * ============LICENSE_END=========================================================
  */
-
 package org.openecomp.sdc.be.components.merge.instance;
 
 import java.util.List;
 
 public class ContainerRelationsMergeInfo {
+
     private List<RelationMergeInfo> fromRelationsInfo;
     private List<RelationMergeInfo> toRelationsInfo;
 
@@ -38,5 +38,4 @@ public class ContainerRelationsMergeInfo {
     public List<RelationMergeInfo> getToRelationsInfo() {
         return toRelationsInfo;
     }
-
 }
index 926daab..623d86e 100644 (file)
@@ -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.
  * limitations under the License.
  * ============LICENSE_END=========================================================
  */
-
 package org.openecomp.sdc.be.components.merge.instance;
 
-
+import java.util.ArrayList;
+import java.util.Collections;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+import java.util.Optional;
 import org.openecomp.sdc.be.model.ArtifactDefinition;
 import org.openecomp.sdc.be.model.CapabilityDefinition;
 import org.openecomp.sdc.be.model.Component;
@@ -29,13 +33,6 @@ import org.openecomp.sdc.be.model.ComponentInstanceInterface;
 import org.openecomp.sdc.be.model.ComponentInstanceProperty;
 import org.openecomp.sdc.be.model.InputDefinition;
 
-import java.util.ArrayList;
-import java.util.Collections;
-import java.util.HashMap;
-import java.util.List;
-import java.util.Map;
-import java.util.Optional;
-
 /**
  * Created by chaya on 9/7/2017.
  */
@@ -54,7 +51,7 @@ public class DataForMergeHolder {
     private Component currInstanceNode;
     private String origComponentInstId;
     private List<ComponentInstanceInterface> origComponentInstanceInterfaces;
-    private Map <String, Integer> componentInstanceDeploymentArtifactsTimeOut;
+    private Map<String, Integer> componentInstanceDeploymentArtifactsTimeOut;
 
     public DataForMergeHolder() {
         origComponentInstanceInputs = new ArrayList<>();
@@ -131,15 +128,19 @@ public class DataForMergeHolder {
         this.origComponentInputs = origComponentInputs;
     }
 
-    Map<String, ArtifactDefinition> getOrigComponentDeploymentArtifactsCreatedOnTheInstance(){ return this.origCompInstDeploymentArtifactsCreatedOnTheInstance;}
-
-    Map<String, ArtifactDefinition> getOrigComponentInformationalArtifactsCreatedOnTheInstance(){ return origCompInstInformationalArtifactsCreatedOnTheInstance;}
+    Map<String, ArtifactDefinition> getOrigComponentDeploymentArtifactsCreatedOnTheInstance() {
+        return this.origCompInstDeploymentArtifactsCreatedOnTheInstance;
+    }
 
-    void setOrigComponentDeploymentArtifactsCreatedOnTheInstance(Map<String, ArtifactDefinition> origDeploymentArtifacts){
+    void setOrigComponentDeploymentArtifactsCreatedOnTheInstance(Map<String, ArtifactDefinition> origDeploymentArtifacts) {
         origCompInstDeploymentArtifactsCreatedOnTheInstance = origDeploymentArtifacts;
     }
 
-    void setOrigComponentInformationalArtifactsCreatedOnTheInstance(Map<String, ArtifactDefinition> origInformationalArtifacts){
+    Map<String, ArtifactDefinition> getOrigComponentInformationalArtifactsCreatedOnTheInstance() {
+        return origCompInstInformationalArtifactsCreatedOnTheInstance;
+    }
+
+    void setOrigComponentInformationalArtifactsCreatedOnTheInstance(Map<String, ArtifactDefinition> origInformationalArtifacts) {
         origCompInstInformationalArtifactsCreatedOnTheInstance = origInformationalArtifacts;
     }
 
@@ -191,14 +192,14 @@ public class DataForMergeHolder {
         this.origComponentInstId = origComponentInstId;
     }
 
-    void setComponentInstanceDeploymentArtifactsTimeOut(Map<String,Integer> componentInstancesDeploymentArtifacts) {
-        this.componentInstanceDeploymentArtifactsTimeOut = componentInstancesDeploymentArtifacts;
-    }
-
     public Map<String, Integer> getComponentInstanceDeploymentArtifactsTimeOut() {
         return componentInstanceDeploymentArtifactsTimeOut;
     }
 
+    void setComponentInstanceDeploymentArtifactsTimeOut(Map<String, Integer> componentInstancesDeploymentArtifacts) {
+        this.componentInstanceDeploymentArtifactsTimeOut = componentInstancesDeploymentArtifacts;
+    }
+
     public List<ComponentInstanceInterface> getOrigComponentInstanceInterfaces() {
         return origComponentInstanceInterfaces;
     }
@@ -206,5 +207,4 @@ public class DataForMergeHolder {
     public void setOrigComponentInstanceInterfaces(List<ComponentInstanceInterface> origComponentInstanceInterfaces) {
         this.origComponentInstanceInterfaces = origComponentInstanceInterfaces;
     }
-
 }
index e0fb643..626db53 100644 (file)
  */
 package org.openecomp.sdc.be.components.merge.instance;
 
+import static org.apache.commons.collections.MapUtils.isEmpty;
+
+import java.util.List;
+import java.util.Map;
+import java.util.Optional;
 import org.openecomp.sdc.be.components.impl.exceptions.ByActionStatusComponentException;
 import org.openecomp.sdc.be.dao.api.ActionStatus;
 import org.openecomp.sdc.be.model.Component;
@@ -28,12 +33,6 @@ import org.openecomp.sdc.be.model.ComponentInstance;
 import org.openecomp.sdc.be.model.User;
 import org.openecomp.sdc.be.model.jsonjanusgraph.operations.ExternalReferencesOperation;
 
-import java.util.List;
-import java.util.Map;
-import java.util.Optional;
-
-import static org.apache.commons.collections.MapUtils.isEmpty;
-
 @org.springframework.stereotype.Component
 public class ExternalRefsMergeBL implements ComponentInstanceMergeInterface {
 
@@ -44,10 +43,10 @@ public class ExternalRefsMergeBL implements ComponentInstanceMergeInterface {
     }
 
     @Override
-    public void saveDataBeforeMerge(DataForMergeHolder dataHolder, Component containerComponent,
-                                    ComponentInstance currentResourceInstance, Component originComponent) {
-        Map<String, List<String>> externalRefs = externalReferencesOperation.getAllExternalReferences(containerComponent.getUniqueId(),
-                currentResourceInstance.getUniqueId());
+    public void saveDataBeforeMerge(DataForMergeHolder dataHolder, Component containerComponent, ComponentInstance currentResourceInstance,
+                                    Component originComponent) {
+        Map<String, List<String>> externalRefs = externalReferencesOperation
+            .getAllExternalReferences(containerComponent.getUniqueId(), currentResourceInstance.getUniqueId());
         dataHolder.setOrigComponentInstanceExternalRefs(externalRefs);
     }
 
@@ -55,13 +54,12 @@ public class ExternalRefsMergeBL implements ComponentInstanceMergeInterface {
     public Component mergeDataAfterCreate(User user, DataForMergeHolder dataHolder, Component updatedContainerComponent, String newInstanceId) {
         Optional<ComponentInstance> componentInstance = updatedContainerComponent.getComponentInstanceById(newInstanceId);
         if (!componentInstance.isPresent()) {
-            throw new ByActionStatusComponentException(ActionStatus.COMPONENT_INSTANCE_NOT_FOUND,
-                    newInstanceId);
+            throw new ByActionStatusComponentException(ActionStatus.COMPONENT_INSTANCE_NOT_FOUND, newInstanceId);
         }
-        Map<String, List<String>>  savedExternalRefs = dataHolder.getOrigCompInstExternalRefs();
+        Map<String, List<String>> savedExternalRefs = dataHolder.getOrigCompInstExternalRefs();
         if (!isEmpty(savedExternalRefs)) {
-            externalReferencesOperation.addAllExternalReferences(updatedContainerComponent.getUniqueId(),
-                    componentInstance.get().getUniqueId(), savedExternalRefs);
+            externalReferencesOperation
+                .addAllExternalReferences(updatedContainerComponent.getUniqueId(), componentInstance.get().getUniqueId(), savedExternalRefs);
         }
         return updatedContainerComponent;
     }
index 4297aa8..fcd0906 100644 (file)
@@ -17,7 +17,6 @@
  * limitations under the License.
  * ============LICENSE_END=========================================================
  */
-
 package org.openecomp.sdc.be.components.merge.instance;
 
 import lombok.AllArgsConstructor;
@@ -32,5 +31,4 @@ public class RelationMergeInfo {
     private final String capReqName;
     private final String capOwnerName;
     private final RequirementCapabilityRelDef relDef;
-
 }
index c31c9fa..9984e0d 100644 (file)
@@ -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.
  * limitations under the License.
  * ============LICENSE_END=========================================================
  */
-
 package org.openecomp.sdc.be.components.merge.policy;
 
+import static java.util.Collections.emptyList;
+import static java.util.stream.Collectors.toList;
+import static org.apache.commons.collections.CollectionUtils.isEmpty;
+import static org.apache.commons.collections.MapUtils.isEmpty;
+import static org.openecomp.sdc.be.components.merge.resource.ResourceDataMergeBusinessLogic.ANY_ORDER_COMMAND;
+
+import java.util.ArrayList;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+import java.util.Optional;
 import org.openecomp.sdc.be.components.merge.ComponentsGlobalMergeCommand;
 import org.openecomp.sdc.be.components.merge.VspComponentsMergeCommand;
 import org.openecomp.sdc.be.dao.api.ActionStatus;
@@ -34,18 +44,6 @@ import org.openecomp.sdc.be.model.operations.api.StorageOperationStatus;
 import org.openecomp.sdc.common.log.wrappers.Logger;
 import org.springframework.core.annotation.Order;
 
-import java.util.ArrayList;
-import java.util.HashMap;
-import java.util.List;
-import java.util.Map;
-import java.util.Optional;
-
-import static java.util.Collections.emptyList;
-import static java.util.stream.Collectors.toList;
-import static org.apache.commons.collections.CollectionUtils.isEmpty;
-import static org.apache.commons.collections.MapUtils.isEmpty;
-import static org.openecomp.sdc.be.components.merge.resource.ResourceDataMergeBusinessLogic.ANY_ORDER_COMMAND;
-
 @org.springframework.stereotype.Component
 @Order(ANY_ORDER_COMMAND)
 public class PoliciesMergeCommand implements ComponentsGlobalMergeCommand, VspComponentsMergeCommand {
@@ -70,9 +68,11 @@ public class PoliciesMergeCommand implements ComponentsGlobalMergeCommand, VspCo
     }
 
     private ActionStatus associatePoliciesToComponent(Component currentComponent, Map<String, PolicyDefinition> policiesToMerge) {
-        log.debug("#associatePoliciesToComponent - associating {} policies into component {}", policiesToMerge.size(), currentComponent.getUniqueId());
+        log.debug("#associatePoliciesToComponent - associating {} policies into component {}", policiesToMerge.size(),
+            currentComponent.getUniqueId());
         currentComponent.setPolicies(policiesToMerge);
-        StorageOperationStatus associateResult = toscaOperationFacade.associatePoliciesToComponent(currentComponent.getUniqueId(), new ArrayList<>(policiesToMerge.values()));
+        StorageOperationStatus associateResult = toscaOperationFacade
+            .associatePoliciesToComponent(currentComponent.getUniqueId(), new ArrayList<>(policiesToMerge.values()));
         return componentsUtils.convertFromStorageResponse(associateResult);
     }
 
@@ -92,7 +92,7 @@ public class PoliciesMergeCommand implements ComponentsGlobalMergeCommand, VspCo
         if (isEmpty(policy.getTargets())) {
             return;
         }
-        Map<PolicyTargetType, List<String>> targets =  buildPolicyTargetsMap(policy, prevComponent, currComponent);
+        Map<PolicyTargetType, List<String>> targets = buildPolicyTargetsMap(policy, prevComponent, currComponent);
         policy.setTargets(targets);
     }
 
@@ -121,34 +121,24 @@ public class PoliciesMergeCommand implements ComponentsGlobalMergeCommand, VspCo
         return resolveGroupTargetsByInvariantName(prevComponent, currComponent, prevGroupTargets);
     }
 
-    private List<String> resolveInstanceTargetsByInstanceName(Component prevComponent, Component currComponent, List<String> prevCompInstanceTargets) {
-        return prevCompInstanceTargets.stream()
-                .map(prevInstId -> resolveNewInstId(prevComponent, currComponent, prevInstId))
-                .filter(Optional::isPresent)
-                .map(Optional::get)
-                .collect(toList());
+    private List<String> resolveInstanceTargetsByInstanceName(Component prevComponent, Component currComponent,
+                                                              List<String> prevCompInstanceTargets) {
+        return prevCompInstanceTargets.stream().map(prevInstId -> resolveNewInstId(prevComponent, currComponent, prevInstId))
+            .filter(Optional::isPresent).map(Optional::get).collect(toList());
     }
 
     private List<String> resolveGroupTargetsByInvariantName(Component prevComponent, Component currComponent, List<String> prevGroupTargets) {
-        return prevGroupTargets.stream()
-                .map(prevGroupId -> resolveNewGroupId(prevComponent, currComponent, prevGroupId))
-                .filter(Optional::isPresent)
-                .map(Optional::get)
-                .collect(toList());
+        return prevGroupTargets.stream().map(prevGroupId -> resolveNewGroupId(prevComponent, currComponent, prevGroupId)).filter(Optional::isPresent)
+            .map(Optional::get).collect(toList());
     }
 
     private Optional<String> resolveNewInstId(Component prevCmpt, Component newCmpt, String prevInstanceId) {
-        return prevCmpt.getComponentInstanceById(prevInstanceId)
-                .map(ComponentInstance::getName)
-                .flatMap(newCmpt::getComponentInstanceByName)
-                .map(ComponentInstance::getUniqueId);
+        return prevCmpt.getComponentInstanceById(prevInstanceId).map(ComponentInstance::getName).flatMap(newCmpt::getComponentInstanceByName)
+            .map(ComponentInstance::getUniqueId);
     }
 
     private Optional<String> resolveNewGroupId(Component prevCmpt, Component newCmpt, String prevGroupId) {
-        return prevCmpt.getGroupById(prevGroupId)
-                .map(GroupDefinition::getInvariantName)
-                .flatMap(newCmpt::getGroupByInvariantName)
-                .map(GroupDefinition::getUniqueId);
+        return prevCmpt.getGroupById(prevGroupId).map(GroupDefinition::getInvariantName).flatMap(newCmpt::getGroupByInvariantName)
+            .map(GroupDefinition::getUniqueId);
     }
-
 }
index 431daff..6f1a1e1 100644 (file)
@@ -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.
  * limitations under the License.
  * ============LICENSE_END=========================================================
  */
-
 package org.openecomp.sdc.be.components.merge.property;
 
-import org.openecomp.sdc.be.datatypes.elements.PropertyDataDefinition;
-import org.openecomp.sdc.be.model.InputDefinition;
-import org.springframework.stereotype.Component;
+import static org.apache.commons.collections.CollectionUtils.isEmpty;
+import static org.openecomp.sdc.be.components.merge.property.PropertyInstanceMergeDataBuilder.buildDataForMerging;
 
 import java.util.Collections;
 import java.util.List;
-
-import static org.apache.commons.collections.CollectionUtils.isEmpty;
-import static org.openecomp.sdc.be.components.merge.property.PropertyInstanceMergeDataBuilder.buildDataForMerging;
+import org.openecomp.sdc.be.datatypes.elements.PropertyDataDefinition;
+import org.openecomp.sdc.be.model.InputDefinition;
+import org.springframework.stereotype.Component;
 
 @Component
-public class DataDefinitionsValuesMergingBusinessLogic  {
+public class DataDefinitionsValuesMergingBusinessLogic {
 
     private PropertyDataValueMergeBusinessLogic propertyValueMergeBL;
 
@@ -40,24 +38,28 @@ public class DataDefinitionsValuesMergingBusinessLogic  {
     }
 
     /**
-     * Merge previous version data definition values into the new version data definition.
-     * A data definition value is merged if it had a value in previous version and has no value in the current version.
-     * in case a property get input value has no corresponding input in the current version its value will not be merged
-     * @param oldInstanceDataDefinition the currently persisted instance data definitions
-     * @param oldInputs the previous version inputs
+     * Merge previous version data definition values into the new version data definition. A data definition value is merged if it had a value in
+     * previous version and has no value in the current version. in case a property get input value has no corresponding input in the current version
+     * its value will not be merged
+     *
+     * @param oldInstanceDataDefinition     the currently persisted instance data definitions
+     * @param oldInputs                     the previous version inputs
      * @param updatedInstanceDataDefinition the currently being update instance data definitions
-     * @param newInputs the new version inputs
+     * @param newInputs                     the new version inputs
      */
-    public <T extends PropertyDataDefinition> void mergeInstanceDataDefinitions(List<T> oldInstanceDataDefinition, List<InputDefinition> oldInputs, List<T> updatedInstanceDataDefinition, List<InputDefinition> newInputs) {
+    public <T extends PropertyDataDefinition> void mergeInstanceDataDefinitions(List<T> oldInstanceDataDefinition, List<InputDefinition> oldInputs,
+                                                                                List<T> updatedInstanceDataDefinition,
+                                                                                List<InputDefinition> newInputs) {
         if (isEmpty(updatedInstanceDataDefinition) || isEmpty(oldInstanceDataDefinition)) {
             return;
         }
-        List<MergePropertyData> mergePropertyData = buildDataForMerging(oldInstanceDataDefinition, oldInputs, updatedInstanceDataDefinition, newInputs);
+        List<MergePropertyData> mergePropertyData = buildDataForMerging(oldInstanceDataDefinition, oldInputs, updatedInstanceDataDefinition,
+            newInputs);
         mergePropertyData.forEach(this::mergeInstanceDefinition);
-
     }
 
-    public <T extends PropertyDataDefinition> void mergeInstanceDataDefinitions(List<T> oldInstanceDataDefinition,  List<T> updatedInstanceDataDefinition) {
+    public <T extends PropertyDataDefinition> void mergeInstanceDataDefinitions(List<T> oldInstanceDataDefinition,
+                                                                                List<T> updatedInstanceDataDefinition) {
         List<InputDefinition> emptyInputsList = Collections.emptyList();
         mergeInstanceDataDefinitions(oldInstanceDataDefinition, emptyInputsList, updatedInstanceDataDefinition, emptyInputsList);
     }
@@ -71,5 +73,4 @@ public class DataDefinitionsValuesMergingBusinessLogic  {
     private boolean isSameType(PropertyDataDefinition oldDataDefinition, PropertyDataDefinition updatedDataDefinition) {
         return oldDataDefinition.typeEquals(updatedDataDefinition);
     }
-
 }
index 3239608..32d1443 100644 (file)
@@ -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.
  * limitations under the License.
  * ============LICENSE_END=========================================================
  */
-
 package org.openecomp.sdc.be.components.merge.property;
 
-import org.openecomp.sdc.be.datatypes.elements.PropertyDataDefinition;
-
 import java.util.ArrayList;
 import java.util.List;
+import org.openecomp.sdc.be.datatypes.elements.PropertyDataDefinition;
 
 /**
- * A POJO which represents an instance property data definition (a {@link org.openecomp.sdc.be.model.ComponentInstanceProperty} or {@link org.openecomp.sdc.be.model.ComponentInstanceInput})
- * that its value needs to be merged during an upgrade of a VSP.
- *
+ * A POJO which represents an instance property data definition (a {@link org.openecomp.sdc.be.model.ComponentInstanceProperty} or {@link
+ * org.openecomp.sdc.be.model.ComponentInstanceInput}) that its value needs to be merged during an upgrade of a VSP.
  */
 public class MergePropertyData {
 
@@ -36,7 +33,6 @@ public class MergePropertyData {
     private PropertyDataDefinition oldProp;
     /*The new state of the instance property to merge */
     private PropertyDataDefinition newProp;
-
     private List<String> getInputNamesToMerge = new ArrayList<>();
 
     public PropertyDataDefinition getOldProp() {
@@ -48,15 +44,15 @@ public class MergePropertyData {
         return this;
     }
 
+    public PropertyDataDefinition getNewProp() {
+        return newProp;
+    }
+
     public MergePropertyData setNewProp(PropertyDataDefinition newProp) {
         this.newProp = newProp;
         return this;
     }
 
-    public PropertyDataDefinition getNewProp() {
-        return newProp;
-    }
-
     public void addAddGetInputNamesToMerge(List<String> getInputsNameToMerge) {
         getInputNamesToMerge.addAll(getInputsNameToMerge);
     }
@@ -68,5 +64,4 @@ public class MergePropertyData {
     public boolean isGetInputProp() {
         return oldProp.isGetInputProperty();
     }
-    
 }
index 0c6a6ae..9888129 100644 (file)
@@ -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.
  * limitations under the License.
  * ============LICENSE_END=========================================================
  */
-
 package org.openecomp.sdc.be.components.merge.property;
 
 import com.google.gson.Gson;
 import fj.data.Either;
+import java.util.ArrayList;
+import java.util.Collections;
+import java.util.List;
+import java.util.Map;
+import java.util.Optional;
+import java.util.stream.Collectors;
 import org.openecomp.sdc.be.dao.janusgraph.JanusGraphOperationStatus;
 import org.openecomp.sdc.be.datatypes.elements.GetInputValueDataDefinition;
 import org.openecomp.sdc.be.datatypes.elements.PropertyDataDefinition;
 import org.openecomp.sdc.be.model.DataTypeDefinition;
 import org.openecomp.sdc.be.model.cache.ApplicationDataTypeCache;
-import org.openecomp.sdc.tosca.datatypes.ToscaFunctions;
 import org.openecomp.sdc.be.tosca.PropertyConvertor;
 import org.openecomp.sdc.common.log.wrappers.Logger;
+import org.openecomp.sdc.tosca.datatypes.ToscaFunctions;
 import org.springframework.beans.factory.annotation.Autowired;
 import org.springframework.stereotype.Component;
 
-import java.util.ArrayList;
-import java.util.Collections;
-import java.util.List;
-import java.util.Map;
-import java.util.Optional;
-import java.util.stream.Collectors;
-
 @Component
 public class PropertyDataValueMergeBusinessLogic {
 
     private static final Logger LOGGER = Logger.getLogger(PropertyDataValueMergeBusinessLogic.class);
-
     private final PropertyValueMerger propertyValueMerger;
     private final ApplicationDataTypeCache dataTypeCache;
-    
     private final PropertyConvertor propertyConvertor;
     private final Gson gson = new Gson();
 
     @Autowired
-    public PropertyDataValueMergeBusinessLogic(PropertyValueMerger propertyValueMerger,
-            ApplicationDataTypeCache dataTypeCache, PropertyConvertor propertyConvertor) {
+    public PropertyDataValueMergeBusinessLogic(PropertyValueMerger propertyValueMerger, ApplicationDataTypeCache dataTypeCache,
+                                               PropertyConvertor propertyConvertor) {
         this.propertyValueMerger = propertyValueMerger;
         this.dataTypeCache = dataTypeCache;
         this.propertyConvertor = propertyConvertor;
     }
 
     /**
-     *
      * @param oldProp the old property to merge value from
      * @param newProp the new property to merge value into
      */
@@ -68,33 +63,32 @@ public class PropertyDataValueMergeBusinessLogic {
         Either<Map<String, DataTypeDefinition>, JanusGraphOperationStatus> dataTypesEither = dataTypeCache.getAll();
         if (dataTypesEither.isRight()) {
             LOGGER.debug("failed to fetch data types, skip merging of previous property values. status: {}", dataTypesEither.right().value());
-        }
-        else {
+        } else {
             mergePropertyValue(oldProp, newProp, dataTypesEither.left().value(), getInputNamesToMerge);
         }
     }
-    
-    private void mergePropertyValue(PropertyDataDefinition oldProp, PropertyDataDefinition newProp, Map<String, DataTypeDefinition> dataTypes, List<String> getInputNamesToMerge) {
+
+    private void mergePropertyValue(PropertyDataDefinition oldProp, PropertyDataDefinition newProp, Map<String, DataTypeDefinition> dataTypes,
+                                    List<String> getInputNamesToMerge) {
         Object oldValAsObject = convertPropertyStrValueToObject(oldProp, dataTypes);
         Object newValAsObject = convertPropertyStrValueToObject(newProp, dataTypes);
-        if(oldValAsObject != null){
-            Object mergedValue =  propertyValueMerger.merge(oldValAsObject, newValAsObject, getInputNamesToMerge, newProp.getType(), newProp.getSchemaType(), dataTypes);
+        if (oldValAsObject != null) {
+            Object mergedValue = propertyValueMerger
+                .merge(oldValAsObject, newValAsObject, getInputNamesToMerge, newProp.getType(), newProp.getSchemaType(), dataTypes);
             newProp.setValue(convertPropertyValueObjectToString(mergedValue));
-            
             mergePropertyGetInputsValues(oldProp, newProp);
         }
-        
     }
-    
+
     private String convertPropertyValueObjectToString(Object mergedValue) {
         if (PropertyValueMerger.isEmptyValue(mergedValue)) {
             return null;
         }
-        return mergedValue instanceof String? mergedValue.toString() : gson.toJson(mergedValue);
+        return mergedValue instanceof String ? mergedValue.toString() : gson.toJson(mergedValue);
     }
 
     private Object convertPropertyStrValueToObject(PropertyDataDefinition propertyDataDefinition, Map<String, DataTypeDefinition> dataTypes) {
-        String propValue = propertyDataDefinition.getValue() == null ? "": propertyDataDefinition.getValue();
+        String propValue = propertyDataDefinition.getValue() == null ? "" : propertyDataDefinition.getValue();
         String propertyType = propertyDataDefinition.getType();
         String innerType = propertyDataDefinition.getSchemaType();
         return propertyConvertor.convertToToscaObject(propertyDataDefinition, propValue, dataTypes, true);
@@ -114,10 +108,8 @@ public class PropertyDataValueMergeBusinessLogic {
         List<GetInputValueDataDefinition> oldGetInputValues = oldProp.getGetInputValues();
         List<GetInputValueDataDefinition> newGetInputValues = Optional.ofNullable(newProp.getGetInputValues()).orElse(Collections.emptyList());
         List<String> newGetInputNames = newGetInputValues.stream().map(GetInputValueDataDefinition::getInputName).collect(Collectors.toList());
-        return oldGetInputValues.stream()
-                .filter(getInput -> !newGetInputNames.contains(getInput.getInputName()))
-                .filter(getInput -> isValueContainsGetInput(getInput.getInputName(), newProp.getValue()))
-                .collect(Collectors.toList());
+        return oldGetInputValues.stream().filter(getInput -> !newGetInputNames.contains(getInput.getInputName()))
+            .filter(getInput -> isValueContainsGetInput(getInput.getInputName(), newProp.getValue())).collect(Collectors.toList());
     }
 
     private boolean isValueContainsGetInput(String inputName, String value) {
index d67f46f..79e0403 100644 (file)
@@ -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.
  * limitations under the License.
  * ============LICENSE_END=========================================================
  */
-
 package org.openecomp.sdc.be.components.merge.property;
 
-import org.openecomp.sdc.be.dao.utils.MapUtil;
-import org.openecomp.sdc.be.datatypes.elements.GetInputValueDataDefinition;
-import org.openecomp.sdc.be.datatypes.elements.PropertyDataDefinition;
-import org.openecomp.sdc.be.model.InputDefinition;
-
 import java.util.ArrayList;
 import java.util.List;
 import java.util.Map;
 import java.util.Objects;
 import java.util.stream.Collectors;
+import org.openecomp.sdc.be.dao.utils.MapUtil;
+import org.openecomp.sdc.be.datatypes.elements.GetInputValueDataDefinition;
+import org.openecomp.sdc.be.datatypes.elements.PropertyDataDefinition;
+import org.openecomp.sdc.be.model.InputDefinition;
 
 class PropertyInstanceMergeDataBuilder {
 
     private PropertyInstanceMergeDataBuilder() {
     }
 
-    static <T extends PropertyDataDefinition> List<MergePropertyData> buildDataForMerging(List<T> oldProps,
-                                                                                          List<InputDefinition> oldInputs,
-                                                                                          List<T> newProps,
-                                                                                          List<InputDefinition> newInputs) {
-
+    static <T extends PropertyDataDefinition> List<MergePropertyData> buildDataForMerging(List<T> oldProps, List<InputDefinition> oldInputs,
+                                                                                          List<T> newProps, List<InputDefinition> newInputs) {
         Map<String, T> oldPropsByName = MapUtil.toMap(oldProps, T::getName);
         Map<String, InputDefinition> oldInputsByName = MapUtil.toMap(oldInputs, InputDefinition::getName);
         Map<String, T> newPropsByName = MapUtil.toMap(newProps, T::getName);
         Map<String, InputDefinition> newInputsByName = MapUtil.toMap(newInputs, InputDefinition::getName);
         return buildMergeData(oldPropsByName, oldInputsByName, newPropsByName, newInputsByName);
-
     }
 
-    private static <T extends PropertyDataDefinition> List<MergePropertyData> buildMergeData(Map<String, T> oldPropsByName, Map<String, InputDefinition> oldInputsByName, Map<String, T> newPropsByName, Map<String, InputDefinition> newInputsByName) {
+    private static <T extends PropertyDataDefinition> List<MergePropertyData> buildMergeData(Map<String, T> oldPropsByName,
+                                                                                             Map<String, InputDefinition> oldInputsByName,
+                                                                                             Map<String, T> newPropsByName,
+                                                                                             Map<String, InputDefinition> newInputsByName) {
         List<MergePropertyData> mergeData = new ArrayList<>();
         newPropsByName.forEach((name, prop) -> {
             if (oldPropsByName.containsKey(name)) {
@@ -59,36 +56,34 @@ class PropertyInstanceMergeDataBuilder {
         return mergeData;
     }
 
-    private static MergePropertyData buildMergePropertyData(PropertyDataDefinition oldProp,
-                                                    Map<String, InputDefinition> oldInputsByName,
-                                                    PropertyDataDefinition newProp,
-                                                    Map<String, InputDefinition> newInputsByName) {
+    private static MergePropertyData buildMergePropertyData(PropertyDataDefinition oldProp, Map<String, InputDefinition> oldInputsByName,
+                                                            PropertyDataDefinition newProp, Map<String, InputDefinition> newInputsByName) {
         MergePropertyData mergePropertyData = new MergePropertyData();
-        mergePropertyData.setOldProp(oldProp)
-                         .setNewProp(newProp);
+        mergePropertyData.setOldProp(oldProp).setNewProp(newProp);
         if (oldProp.isGetInputProperty()) {
             setGetInputData(oldProp, oldInputsByName, newInputsByName, mergePropertyData);
-
         }
         return mergePropertyData;
     }
 
-    private static void setGetInputData(PropertyDataDefinition oldProp, Map<String, InputDefinition> oldInputsByName, Map<String, InputDefinition> newInputsByName, MergePropertyData mergePropertyData) {
+    private static void setGetInputData(PropertyDataDefinition oldProp, Map<String, InputDefinition> oldInputsByName,
+                                        Map<String, InputDefinition> newInputsByName, MergePropertyData mergePropertyData) {
         List<String> oldDeclaredByUserInputNames = getOldDeclaredInputsByUser(oldProp.getGetInputValues(), oldInputsByName);
         List<String> oldGetInputNamesWhichExistInNewVersion = getOldGetInputNamesWhichExistInNewVersion(oldProp.getGetInputValues(), newInputsByName);
         mergePropertyData.addAddGetInputNamesToMerge(oldDeclaredByUserInputNames);
         mergePropertyData.addAddGetInputNamesToMerge(oldGetInputNamesWhichExistInNewVersion);
     }
 
-    private static List<String> getOldGetInputNamesWhichExistInNewVersion(List<GetInputValueDataDefinition> getInputValues, Map<String, InputDefinition> newInputsByName) {
-        return getInputValues.stream().map(GetInputValueDataDefinition::getInputName).filter(newInputsByName::containsKey).collect(Collectors.toList());
+    private static List<String> getOldGetInputNamesWhichExistInNewVersion(List<GetInputValueDataDefinition> getInputValues,
+                                                                          Map<String, InputDefinition> newInputsByName) {
+        return getInputValues.stream().map(GetInputValueDataDefinition::getInputName).filter(newInputsByName::containsKey)
+            .collect(Collectors.toList());
     }
 
-    private static List<String> getOldDeclaredInputsByUser(List<GetInputValueDataDefinition> getInputValues, Map<String, InputDefinition> oldInputsByName) {
-        return getInputValues.stream().map(GetInputValueDataDefinition::getInputName)
-                                      .map(oldInputsByName::get)
-                                      .filter(oldInput ->  Objects.nonNull(oldInput) && oldInput.getInstanceUniqueId() != null)
-                                      .map(PropertyDataDefinition::getName)
-                                      .collect(Collectors.toList());
+    private static List<String> getOldDeclaredInputsByUser(List<GetInputValueDataDefinition> getInputValues,
+                                                           Map<String, InputDefinition> oldInputsByName) {
+        return getInputValues.stream().map(GetInputValueDataDefinition::getInputName).map(oldInputsByName::get)
+            .filter(oldInput -> Objects.nonNull(oldInput) && oldInput.getInstanceUniqueId() != null).map(PropertyDataDefinition::getName)
+            .collect(Collectors.toList());
     }
 }
index 39aec8f..de6a4f9 100644 (file)
@@ -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.
  * limitations under the License.
  * ============LICENSE_END=========================================================
  */
-
 package org.openecomp.sdc.be.components.merge.property;
 
+import java.util.ArrayList;
+import java.util.List;
+import java.util.Map;
+import java.util.Optional;
+import java.util.stream.Collectors;
 import org.apache.commons.lang.StringUtils;
 import org.apache.commons.lang3.tuple.ImmutablePair;
 import org.openecomp.sdc.be.model.DataTypeDefinition;
@@ -28,21 +32,21 @@ import org.openecomp.sdc.be.model.tosca.ToscaPropertyType;
 import org.openecomp.sdc.be.utils.TypeUtils;
 import org.springframework.stereotype.Component;
 
-import java.util.ArrayList;
-import java.util.List;
-import java.util.Map;
-import java.util.Optional;
-import java.util.stream.Collectors;
-
 @Component
 public class PropertyValueMerger {
-    
+
+    static boolean isEmptyValue(Object val) {
+        return val == null || val instanceof String && StringUtils.isEmpty((String) val) || val instanceof Map && ((Map<?, ?>) val).isEmpty()
+            || val instanceof List && ((List<?>) val).isEmpty();
+    }
+
     @SuppressWarnings("unchecked")
     /**
      * merges property value oldVal into property value newVal recursively
      * @param oldVal - cannot be {@code Null}
      */
-    protected Object merge(Object oldVal, Object newVal, List<String> inputNamesToMerge, String type, String innerType, Map<String, DataTypeDefinition> dataTypes) {
+    protected Object merge(Object oldVal, Object newVal, List<String> inputNamesToMerge, String type, String innerType,
+                           Map<String, DataTypeDefinition> dataTypes) {
         if (isEmptyValue(newVal)) {
             return removeUnwantedGetInputValues(oldVal, inputNamesToMerge);
         }
@@ -57,26 +61,28 @@ public class PropertyValueMerger {
         }
         return newVal;
     }
-    
-    private Map<String, Object> mergeMapValue(Map<String, Object> oldValMap, Map<String, Object> newValMap, List<String> inputNamesToMerge, String type, String innertType, Map<String, DataTypeDefinition> dataTypes) {
+
+    private Map<String, Object> mergeMapValue(Map<String, Object> oldValMap, Map<String, Object> newValMap, List<String> inputNamesToMerge,
+                                              String type, String innertType, Map<String, DataTypeDefinition> dataTypes) {
         mergeEntriesExistInOldValue(oldValMap, newValMap, inputNamesToMerge, type, innertType, dataTypes);//continue the recursion
         if (type != null && !type.equals("map") && !type.equals("json")) {
             setOldEntriesNotExistInNewValue(oldValMap, newValMap, inputNamesToMerge);
         }
-        
         return newValMap;
     }
 
-    private void mergeEntriesExistInOldValue(Map<String, Object> oldValMap, Map<String, Object> newValMap, List<String> inputNamesToMerge, String type, String innerType, Map<String, DataTypeDefinition> dataTypes) {
+    private void mergeEntriesExistInOldValue(Map<String, Object> oldValMap, Map<String, Object> newValMap, List<String> inputNamesToMerge,
+                                             String type, String innerType, Map<String, DataTypeDefinition> dataTypes) {
         for (Map.Entry<String, Object> newValEntry : newValMap.entrySet()) {
             Object oldVal = oldValMap.get(newValEntry.getKey());
             if (oldVal != null) {
                 ImmutablePair<String, String> types = getTypeAndInnerTypePair(newValEntry.getKey(), type, innerType, dataTypes);
-                newValMap.put(newValEntry.getKey(), merge(oldVal, newValEntry.getValue(), inputNamesToMerge, types.getLeft(), types.getRight(), dataTypes));
+                newValMap.put(newValEntry.getKey(),
+                    merge(oldVal, newValEntry.getValue(), inputNamesToMerge, types.getLeft(), types.getRight(), dataTypes));
             }
         }
     }
-    
+
     private void setOldEntriesNotExistInNewValue(Map<String, Object> oldVal, Map<String, Object> newVal, List<String> getInputNamesToMerge) {
         for (Map.Entry<String, Object> oldValEntry : oldVal.entrySet()) {
             if (!isInputEntry(oldValEntry) || isInputToMerge(getInputNamesToMerge, oldValEntry)) {
@@ -85,48 +91,40 @@ public class PropertyValueMerger {
             }
         }
     }
-    
-    private ImmutablePair<String, String> getTypeAndInnerTypePair(String propName, String type, String innerType, Map<String, DataTypeDefinition> dataTypes) {
+
+    private ImmutablePair<String, String> getTypeAndInnerTypePair(String propName, String type, String innerType,
+                                                                  Map<String, DataTypeDefinition> dataTypes) {
         if (type == null || (ToscaPropertyType.isScalarType(type) && ToscaPropertyType.isScalarType(innerType))) {
             return ImmutablePair.of(innerType, null);
         }
-        
         String newInnerType = null;
         DataTypeDefinition innerTypeDef = dataTypes.get(type);
         if (innerTypeDef != null) {
             List<PropertyDefinition> properties = innerTypeDef.getProperties();
-            if (properties!= null) {
+            if (properties != null) {
                 Optional<PropertyDefinition> optionalProperty = findProperty(properties, propName);
-                
-                innerType = optionalProperty.map(PropertyDefinition::getType)
-                                            .orElse(innerType);
-                
-                newInnerType = optionalProperty.map(PropertyDefinition::getSchemaType)
-                                               .orElse(null);
+                innerType = optionalProperty.map(PropertyDefinition::getType).orElse(innerType);
+                newInnerType = optionalProperty.map(PropertyDefinition::getSchemaType).orElse(null);
             }
         }
-                
         return ImmutablePair.of(innerType, newInnerType);
     }
-    
+
     private Optional<PropertyDefinition> findProperty(List<PropertyDefinition> properties, String propName) {
-        return properties.stream()
-                .filter(p -> propName.equals(p.getName()))
-                .findFirst();
+        return properties.stream().filter(p -> propName.equals(p.getName())).findFirst();
     }
 
-    private List<Object> mergeListValue(List<Object> oldVal, List<Object> newVal, List<String> inputNamesToMerge, String innerType, Map<String, DataTypeDefinition> dataTypes) {
+    private List<Object> mergeListValue(List<Object> oldVal, List<Object> newVal, List<String> inputNamesToMerge, String innerType,
+                                        Map<String, DataTypeDefinition> dataTypes) {
         List<Object> mergedList = newVal;
-    
         if (oldVal.size() == newVal.size()) {
             mergedList = mergeLists(oldVal, newVal, inputNamesToMerge, innerType, dataTypes);
         }
-
         return mergedList;
     }
-    
 
-    private List<Object> mergeLists(List<Object> oldVal, List<Object> newVal, List<String> inputNamesToMerge, String innerType, Map<String, DataTypeDefinition> dataTypes) {
+    private List<Object> mergeLists(List<Object> oldVal, List<Object> newVal, List<String> inputNamesToMerge, String innerType,
+                                    Map<String, DataTypeDefinition> dataTypes) {
         int minListSize = Math.min(oldVal.size(), newVal.size());
         List<Object> mergedList = new ArrayList<>();
         for (int i = 0; i < minListSize; i++) {
@@ -135,27 +133,18 @@ public class PropertyValueMerger {
         }
         return mergedList;
     }
-    
-    
+
     private Object mergeScalarValue(Object oldVal, Object newVal) {
         return isEmptyValue(newVal) ? oldVal : newVal;
     }
-    
-    static boolean isEmptyValue(Object val) {
-        return val == null ||
-               val instanceof String && StringUtils.isEmpty((String)val) ||
-               val instanceof Map && ((Map<?,?>) val).isEmpty() ||
-               val instanceof List && ((List<?>) val).isEmpty();
 
-    }
-    
     @SuppressWarnings("unchecked")
     Object removeUnwantedGetInputValues(Object val, List<String> inputNamesToMerge) {
-        if (val instanceof  Map) {
+        if (val instanceof Map) {
             return removeUnwantedGetInputValues((Map<String, Object>) val, inputNamesToMerge);
         }
         if (val instanceof List) {
-            return removeUnwantedGetInputValues((List<Object>)val, inputNamesToMerge);
+            return removeUnwantedGetInputValues((List<Object>) val, inputNamesToMerge);
         }
         return val;
     }
@@ -166,7 +155,7 @@ public class PropertyValueMerger {
 
     private Map<String, Object> removeUnwantedGetInputValues(Map<String, Object> val, List<String> inputNamesToMerge) {
         return val.entrySet().stream().filter(entry -> !isInputEntry(entry) || isInputToMerge(inputNamesToMerge, entry))
-                .collect(Collectors.toMap(Map.Entry::getKey, entry -> removeUnwantedGetInputValues(entry.getValue(), inputNamesToMerge)));
+            .collect(Collectors.toMap(Map.Entry::getKey, entry -> removeUnwantedGetInputValues(entry.getValue(), inputNamesToMerge)));
     }
 
     private boolean isInputToMerge(List<String> inputNamesToMerge, Map.Entry<String, Object> entry) {
@@ -186,12 +175,10 @@ public class PropertyValueMerger {
     }
 
     private String retrieveInputName(Object inputValue) {
-        return inputValue instanceof List ? (String)((List<?>) inputValue).get(0) : (String)inputValue;
+        return inputValue instanceof List ? (String) ((List<?>) inputValue).get(0) : (String) inputValue;
     }
 
     protected boolean isInputEntry(Map.Entry<String, Object> oldValEntry) {
         return oldValEntry.getKey().equals(TypeUtils.ToscaTagNamesEnum.GET_INPUT.getElementName());
     }
-    
-    
 }
index ec25a9d..31a09e9 100644 (file)
@@ -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.
  * limitations under the License.
  * ============LICENSE_END=========================================================
  */
-
 package org.openecomp.sdc.be.components.merge.resource;
 
 import fj.data.Either;
+import java.util.List;
 import org.openecomp.sdc.be.components.merge.ComponentsGlobalMergeCommand;
 import org.openecomp.sdc.be.components.merge.ComponentsMergeCommand;
 import org.openecomp.sdc.be.components.merge.TopologyComparator;
@@ -29,8 +29,6 @@ import org.openecomp.sdc.be.dao.api.ActionStatus;
 import org.openecomp.sdc.be.model.Resource;
 import org.springframework.stereotype.Component;
 
-import java.util.List;
-
 @Component
 public class MergeCommandsFactory {
 
@@ -38,16 +36,15 @@ public class MergeCommandsFactory {
     private final List<VspComponentsMergeCommand> mergeCommands;
     private final TopologyComparator topologyComparator;
 
-    public MergeCommandsFactory(List<ComponentsGlobalMergeCommand> globalMergeCommands, List<VspComponentsMergeCommand> mergeCommands, TopologyComparator topologyComparator) {
+    public MergeCommandsFactory(List<ComponentsGlobalMergeCommand> globalMergeCommands, List<VspComponentsMergeCommand> mergeCommands,
+                                TopologyComparator topologyComparator) {
         this.globalMergeCommands = globalMergeCommands;
         this.mergeCommands = mergeCommands;
         this.topologyComparator = topologyComparator;
     }
 
     public Either<List<? extends ComponentsMergeCommand>, ActionStatus> getMergeCommands(Resource prevResource, Resource currResource) {
-        return topologyComparator.isTopologyChanged(prevResource, currResource)
-                .left()
-                .map(topologyChanged -> topologyChanged ? globalMergeCommands : mergeCommands);
-
+        return topologyComparator.isTopologyChanged(prevResource, currResource).left()
+            .map(topologyChanged -> topologyChanged ? globalMergeCommands : mergeCommands);
     }
 }
index 7058a62..a24a4f3 100644 (file)
@@ -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.
@@ -17,7 +17,6 @@
  * limitations under the License.
  * ============LICENSE_END=========================================================
  */
-
 package org.openecomp.sdc.be.components.merge.resource;
 
 import org.openecomp.sdc.be.dao.api.ActionStatus;
@@ -26,5 +25,4 @@ import org.openecomp.sdc.be.model.Resource;
 public interface MergeResourceBusinessLogic {
 
     ActionStatus mergeResourceEntities(Resource oldResource, Resource newResource);
-
 }
index 98957e0..d8d6841 100644 (file)
@@ -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.
  * limitations under the License.
  * ============LICENSE_END=========================================================
  */
-
 package org.openecomp.sdc.be.components.merge.resource;
 
+import java.util.List;
 import org.openecomp.sdc.be.components.merge.ComponentsMergeCommand;
 import org.openecomp.sdc.be.dao.api.ActionStatus;
 import org.openecomp.sdc.be.model.Resource;
 import org.openecomp.sdc.common.log.wrappers.Logger;
 import org.springframework.stereotype.Component;
 
-import java.util.List;
-
 @Component
 public class ResourceDataMergeBusinessLogic implements MergeResourceBusinessLogic {
 
-    private static final Logger log = Logger.getLogger(ResourceDataMergeBusinessLogic.class);
     public static final int FIRST_COMMAND = 0;
     public static final int PENULTIMATE_COMMAND = Integer.MAX_VALUE - 1;
     public static final int LAST_COMMAND = Integer.MAX_VALUE;
     public static final int ANY_ORDER_COMMAND = 1;
-
+    private static final Logger log = Logger.getLogger(ResourceDataMergeBusinessLogic.class);
     private MergeCommandsFactory mergeCommandsFactory;
 
     public ResourceDataMergeBusinessLogic(MergeCommandsFactory mergeCommandsFactory) {
@@ -49,19 +46,19 @@ public class ResourceDataMergeBusinessLogic implements MergeResourceBusinessLogi
             return ActionStatus.OK;
         }
         return mergeCommandsFactory.getMergeCommands(oldResource, newResource)
-                .either(mergeCommands -> executeMergeCommands(oldResource, newResource, mergeCommands),
-                        err -> err);
+            .either(mergeCommands -> executeMergeCommands(oldResource, newResource, mergeCommands), err -> err);
     }
 
-    private ActionStatus executeMergeCommands(Resource oldResource, Resource newResource, List<? extends ComponentsMergeCommand> componentMergingCommands) {
+    private ActionStatus executeMergeCommands(Resource oldResource, Resource newResource,
+                                              List<? extends ComponentsMergeCommand> componentMergingCommands) {
         for (ComponentsMergeCommand componentMergeCommand : componentMergingCommands) {
             ActionStatus mergeStatus = componentMergeCommand.mergeComponents(oldResource, newResource);
             if (mergeStatus != ActionStatus.OK) {
-                log.debug("failed on merge command {} of resource {} status is {}", componentMergeCommand.description(), newResource.getUniqueId(), mergeStatus);
+                log.debug("failed on merge command {} of resource {} status is {}", componentMergeCommand.description(), newResource.getUniqueId(),
+                    mergeStatus);
                 return mergeStatus;
             }
         }
         return ActionStatus.OK;
     }
-
 }
index 61d3ba8..f304090 100644 (file)
@@ -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.
  * limitations under the License.
  * ============LICENSE_END=========================================================
  */
-
 package org.openecomp.sdc.be.components.merge.utils;
 
-import org.openecomp.sdc.be.model.CapabilityDefinition;
+import static java.util.Collections.emptyMap;
 
 import java.util.List;
 import java.util.Map;
-
-import static java.util.Collections.emptyMap;
+import org.openecomp.sdc.be.model.CapabilityDefinition;
 
 public class CapabilityOwner {
 
index 549a14d..5f9fbf4 100644 (file)
@@ -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.
  * limitations under the License.
  * ============LICENSE_END=========================================================
  */
-
 package org.openecomp.sdc.be.components.merge.utils;
 
-import org.openecomp.sdc.be.datatypes.elements.GroupDataDefinition;
-import org.openecomp.sdc.be.model.ComponentInstance;
-import org.openecomp.sdc.be.model.GroupDefinition;
+import static org.openecomp.sdc.be.dao.utils.MapUtil.mergeMaps;
+import static org.openecomp.sdc.be.dao.utils.MapUtil.toMap;
 
 import java.util.ArrayList;
 import java.util.HashMap;
@@ -30,23 +28,24 @@ import java.util.List;
 import java.util.Map;
 import java.util.stream.Collectors;
 import java.util.stream.Stream;
-
-import static org.openecomp.sdc.be.dao.utils.MapUtil.mergeMaps;
-import static org.openecomp.sdc.be.dao.utils.MapUtil.toMap;
+import org.openecomp.sdc.be.datatypes.elements.GroupDataDefinition;
+import org.openecomp.sdc.be.model.ComponentInstance;
+import org.openecomp.sdc.be.model.GroupDefinition;
 
 public class ComponentInstanceBuildingBlocks {
 
     private Map<String, GroupDefinition> groups = new HashMap<>();
     private Map<String, ComponentInstance> vfcInstances = new HashMap<>();
 
-    private ComponentInstanceBuildingBlocks(){}
+    private ComponentInstanceBuildingBlocks() {
+    }
 
     private ComponentInstanceBuildingBlocks(List<GroupDefinition> groups, List<ComponentInstance> vfcInstances) {
         this.groups = groups == null ? new HashMap<>() : toMap(groups, GroupDataDefinition::getUniqueId);
         this.vfcInstances = vfcInstances == null ? new HashMap<>() : toMap(vfcInstances, ComponentInstance::getUniqueId);
     }
 
-    private ComponentInstanceBuildingBlocks(Map<String, GroupDefinition> groups,  Map<String, ComponentInstance> vfcInstances) {
+    private ComponentInstanceBuildingBlocks(Map<String, GroupDefinition> groups, Map<String, ComponentInstance> vfcInstances) {
         this.groups = groups == null ? new HashMap<>() : groups;
         this.vfcInstances = vfcInstances == null ? new HashMap<>() : vfcInstances;
     }
@@ -59,11 +58,9 @@ public class ComponentInstanceBuildingBlocks {
         return new ComponentInstanceBuildingBlocks();
     }
 
-
     @SuppressWarnings("unchecked")
     static ComponentInstanceBuildingBlocks merge(ComponentInstanceBuildingBlocks first, ComponentInstanceBuildingBlocks second) {
-        return new ComponentInstanceBuildingBlocks(mergeMaps(first.groups, second.groups),
-                                                   mergeMaps(first.vfcInstances, second.vfcInstances));
+        return new ComponentInstanceBuildingBlocks(mergeMaps(first.groups, second.groups), mergeMaps(first.vfcInstances, second.vfcInstances));
     }
 
     public List<GroupDefinition> getGroups() {
@@ -76,12 +73,9 @@ public class ComponentInstanceBuildingBlocks {
 
     public List<CapabilityOwner> getCapabilitiesOwners() {
         Stream<CapabilityOwner> groupsStream = groups.values().stream()
-                .map(grp -> new CapabilityOwner(grp.getUniqueId(), grp.getInvariantName(), grp.getCapabilities()));
-
+            .map(grp -> new CapabilityOwner(grp.getUniqueId(), grp.getInvariantName(), grp.getCapabilities()));
         Stream<CapabilityOwner> instanceStream = vfcInstances.values().stream()
-                .map(instance -> new CapabilityOwner(instance.getUniqueId(), instance.getName(), instance.getCapabilities()));
-
+            .map(instance -> new CapabilityOwner(instance.getUniqueId(), instance.getName(), instance.getCapabilities()));
         return Stream.concat(groupsStream, instanceStream).collect(Collectors.toList());
     }
-    
 }
index 00a2f68..e347df9 100644 (file)
@@ -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.
  * limitations under the License.
  * ============LICENSE_END=========================================================
  */
-
 package org.openecomp.sdc.be.components.merge.utils;
 
+import static java.util.Collections.emptyMap;
+import static java.util.Collections.singletonList;
+import static org.openecomp.sdc.be.dao.utils.MapUtil.toMap;
+
 import fj.data.Either;
+import java.util.ArrayList;
+import java.util.Collection;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+import java.util.Objects;
+import java.util.function.Function;
+import java.util.function.Predicate;
+import java.util.stream.Collectors;
 import org.apache.commons.lang3.StringUtils;
 import org.apache.commons.lang3.tuple.ImmutablePair;
 import org.openecomp.sdc.be.components.impl.utils.ExceptionUtils;
@@ -39,29 +51,15 @@ import org.openecomp.sdc.be.model.jsonjanusgraph.utils.ModelConverter;
 import org.openecomp.sdc.be.model.operations.api.StorageOperationStatus;
 import org.openecomp.sdc.common.log.wrappers.Logger;
 
-import java.util.ArrayList;
-import java.util.Collection;
-import java.util.HashMap;
-import java.util.List;
-import java.util.Map;
-import java.util.Objects;
-import java.util.function.Function;
-import java.util.function.Predicate;
-import java.util.stream.Collectors;
-
-import static java.util.Collections.emptyMap;
-import static java.util.Collections.singletonList;
-import static org.openecomp.sdc.be.dao.utils.MapUtil.toMap;
-
 /**
  * This class is Utils class but it should be bean
- * @author dr2032
  *
+ * @author dr2032
  */
 @org.springframework.stereotype.Component
 public class MergeInstanceUtils {
+
     private static final Logger log = Logger.getLogger(MergeInstanceUtils.class);
-    
     private final ToscaOperationFacade toscaOperationFacade;
     private final ExceptionUtils exceptionUtils;
 
@@ -70,27 +68,31 @@ public class MergeInstanceUtils {
         this.exceptionUtils = exceptionUtils;
     }
 
+    private static boolean isCVFC(Component component) {
+        ComponentTypeEnum componentType = component.getComponentType();
+        if (!componentType.equals(ComponentTypeEnum.RESOURCE)) {
+            return false;
+        }
+        Resource resource = (Resource) component;
+        ResourceTypeEnum resourceType = resource.getResourceType();
+        return resourceType == ResourceTypeEnum.CVFC;
+    }
+
     /**
-     * @param container containing new component instance
-     * @param origInstanceNode old component (in case of PROXY it should be actual service)
-     * @param newInstanceId - ID of new instance of the component
+     * @param container               containing new component instance
+     * @param origInstanceNode        old component (in case of PROXY it should be actual service)
+     * @param newInstanceId           - ID of new instance of the component
      * @param oldCapabilitiesOwnerIds the old capabilities owner ids
      * @return a map of capability owner IDs of old component instance to capability owner IDs of the new component instance
      */
-    public Map<String, String> mapOldToNewCapabilitiesOwnerIds(Component container,
-                                                               Component origInstanceNode,
-                                                               String newInstanceId,
+    public Map<String, String> mapOldToNewCapabilitiesOwnerIds(Component container, Component origInstanceNode, String newInstanceId,
                                                                List<String> oldCapabilitiesOwnerIds) {
-
         Map<String, String> resultMap;
-
         if (ModelConverter.isAtomicComponent(origInstanceNode) || isCVFC(origInstanceNode)) {
             resultMap = prepareMapForAtomicComponent(newInstanceId, oldCapabilitiesOwnerIds);
-        }
-        else {
+        } else {
             resultMap = prepareMapForNonAtomicComponent(container, origInstanceNode, newInstanceId, oldCapabilitiesOwnerIds);
         }
-
         return resultMap;
     }
 
@@ -100,8 +102,8 @@ public class MergeInstanceUtils {
      * @return a map between capability owner IDs of old component instance to capability owner IDs of the new component instance
      */
     public Map<String, String> mapOldToNewCapabilitiesOwnerIds(ComponentInstance oldInstance, ComponentInstance newInstance) {
-        List<CapabilityOwner> prevCapabilityOwners  = getInstanceAtomicBuildingBlocks(oldInstance).getCapabilitiesOwners();
-        List<CapabilityOwner> newCapOwners  = getInstanceAtomicBuildingBlocks(newInstance).getCapabilitiesOwners();
+        List<CapabilityOwner> prevCapabilityOwners = getInstanceAtomicBuildingBlocks(oldInstance).getCapabilitiesOwners();
+        List<CapabilityOwner> newCapOwners = getInstanceAtomicBuildingBlocks(newInstance).getCapabilitiesOwners();
         return getCapabilitiesOwnerMapping(prevCapabilityOwners, newCapOwners);
     }
 
@@ -113,15 +115,11 @@ public class MergeInstanceUtils {
     public List<RequirementCapabilityRelDef> getUpdatedUiRelations(Component oldResource, Component newResource) {
         Map<String, ComponentInstance> mapOldComponentInstances = buildComponentInstanceMap(oldResource, ComponentInstance::getUniqueId);
         Map<String, ComponentInstance> mapNewComponentInstances = buildComponentInstanceMap(newResource, ComponentInstance::getName);
-
-        return getUpdatedCapReqDefs(oldResource, newResource,
-                mapOldComponentInstances,
-                mapNewComponentInstances,
-                RequirementCapabilityRelDef::isOriginUI);
+        return getUpdatedCapReqDefs(oldResource, newResource, mapOldComponentInstances, mapNewComponentInstances,
+            RequirementCapabilityRelDef::isOriginUI);
     }
 
     /**
-     *
      * @param componentInstance the instance which its building blocks are to be returned
      * @return the atomic building (groups and instances) blocks which the given component instance is a composition of
      */
@@ -135,9 +133,8 @@ public class MergeInstanceUtils {
     }
 
     /**
-     *
      * @param componentInstance the instance which its building blocks are to be returned
-     * @param component the type thar the given component instance was created from
+     * @param component         the type thar the given component instance was created from
      * @return the atomic building blocks (groups and instances) which the given component instance is a composition of
      */
     public ComponentInstanceBuildingBlocks getInstanceAtomicBuildingBlocks(ComponentInstance componentInstance, Component component) {
@@ -149,20 +146,19 @@ public class MergeInstanceUtils {
             if (componentInstance.getIsProxy()) {
                 // Component is proxy and it doesn't contain required data
                 instanceBuildingBlocks = getInstanceAtomicBuildingBlocks(componentInstance);
-            }
-            else {
+            } else {
                 instanceBuildingBlocks = ComponentInstanceBuildingBlocks.of(new ArrayList<>(), singletonList(componentInstance));
             }
             return instanceBuildingBlocks;
-        }
-        else {
+        } else {
             instanceBuildingBlocks = recursiveScanForAtomicBuildingBlocks(component);
-            if(org.apache.commons.collections.MapUtils.isNotEmpty(component.getCapabilities()) || org.apache.commons.collections.MapUtils.isNotEmpty(component.getRequirements())) {
-                ComponentInstanceBuildingBlocks nonAtomicBlocks = ComponentInstanceBuildingBlocks.of(new ArrayList<>(), singletonList(componentInstance));
+            if (org.apache.commons.collections.MapUtils.isNotEmpty(component.getCapabilities()) || org.apache.commons.collections.MapUtils
+                .isNotEmpty(component.getRequirements())) {
+                ComponentInstanceBuildingBlocks nonAtomicBlocks = ComponentInstanceBuildingBlocks
+                    .of(new ArrayList<>(), singletonList(componentInstance));
                 return ComponentInstanceBuildingBlocks.merge(instanceBuildingBlocks, nonAtomicBlocks);
             }
             return instanceBuildingBlocks;
-        
         }
     }
 
@@ -176,13 +172,9 @@ public class MergeInstanceUtils {
         return createRequirementRelationMergeInfo(vfcInstances, ownerId, relDef);
     }
 
-
-    public RequirementCapabilityRelDef restoreCapabilityRelation(RelationMergeInfo oldCapInfo,
-                                                                 String newInstanceId,
-                                                                 Map<String, CapabilityOwner> capOwnerByName,
-                                                                 Component updatedContainerComponent) {
+    public RequirementCapabilityRelDef restoreCapabilityRelation(RelationMergeInfo oldCapInfo, String newInstanceId,
+                                                                 Map<String, CapabilityOwner> capOwnerByName, Component updatedContainerComponent) {
         String oldCapOwnerName = oldCapInfo.getCapOwnerName();
-
         CapabilityOwner newCapOwner = capOwnerByName.get(oldCapOwnerName);
         if (newCapOwner != null) {
             // Append relation to updated container
@@ -203,41 +195,30 @@ public class MergeInstanceUtils {
         }
     }
 
-
-
-    public RequirementCapabilityRelDef restoreRequirementRelation(RelationMergeInfo oldReqInfo,
-                                                                  String newInstanceId,
-                                                                  Map<String, ComponentInstance> vfciMap,
-                                                                  Component updatedContainerComponent) {
+    public RequirementCapabilityRelDef restoreRequirementRelation(RelationMergeInfo oldReqInfo, String newInstanceId,
+                                                                  Map<String, ComponentInstance> vfciMap, Component updatedContainerComponent) {
         String oldVfcInstanceName = oldReqInfo.getCapOwnerName();
-
         ComponentInstance newVfcInstance = vfciMap.get(oldReqInfo.getCapOwnerName());
         if (newVfcInstance != null) {
             // Append relation to updated container
             RequirementCapabilityRelDef oldRelDef = oldReqInfo.getRelDef();
             oldRelDef.setFromNode(newInstanceId);
-
             RelationshipInfo oldRelationshipInfo = oldRelDef.resolveSingleRelationship().getRelation();
             oldRelationshipInfo.setRequirementOwnerId(newVfcInstance.getUniqueId());
             oldRelationshipInfo.getRelationship().setType(oldReqInfo.getCapReqType());
-
             String vfcUid = newVfcInstance.getComponentUid();
             Either<Component, StorageOperationStatus> eitherComponent = toscaOperationFacade.getToscaElement(vfcUid);
-
-            if(eitherComponent.isLeft()) {
-                String requirementUid = retrieveRequirementUid(oldReqInfo.getCapReqName() , eitherComponent.left().value());
+            if (eitherComponent.isLeft()) {
+                String requirementUid = retrieveRequirementUid(oldReqInfo.getCapReqName(), eitherComponent.left().value());
                 oldRelationshipInfo.setRequirementUid(requirementUid);
-            }
-            else {
+            } else {
                 log.debug("#restoreRequirementCapabilityRelDef - Unexpected error: resource was not loaded for VF ID: {}", vfcUid);
             }
-
             if (updatedContainerComponent != null) {
                 updatedContainerComponent.getComponentInstancesRelations().add(oldRelDef);
             }
             return oldRelDef;
-        }
-        else {
+        } else {
             log.debug("#restoreRequirementCapabilityRelDef - Skip relation since it was not found VFC Instance with name {}", oldVfcInstanceName);
             return null;
         }
@@ -249,254 +230,204 @@ public class MergeInstanceUtils {
 
     private Map<String, String> getCapabilitiesOwnerMapping(List<CapabilityOwner> oldCapOwners, List<CapabilityOwner> newCapOwners) {
         Map<String, CapabilityOwner> newCapOwnerNameMap = toMap(newCapOwners, CapabilityOwner::getName, (p1, p2) -> p1);
-        return oldCapOwners.stream()
-                .filter(oldCapOwner -> newCapOwnerNameMap.containsKey(oldCapOwner.getName()))
-                .collect(Collectors.toMap(CapabilityOwner::getUniqueId, oldCapOwner -> newCapOwnerNameMap.get(oldCapOwner.getName()).getUniqueId(), (p1, p2) -> p1));
-    }
-
-    private static boolean isCVFC(Component component) {
-        ComponentTypeEnum componentType = component.getComponentType();
-        if (!componentType.equals(ComponentTypeEnum.RESOURCE)) {
-            return false;
-        }
-        Resource resource = (Resource) component;
-        ResourceTypeEnum resourceType = resource.getResourceType();
-        return resourceType == ResourceTypeEnum.CVFC;
+        return oldCapOwners.stream().filter(oldCapOwner -> newCapOwnerNameMap.containsKey(oldCapOwner.getName())).collect(Collectors
+            .toMap(CapabilityOwner::getUniqueId, oldCapOwner -> newCapOwnerNameMap.get(oldCapOwner.getName()).getUniqueId(), (p1, p2) -> p1));
     }
 
-
     private RequirementCapabilityRelDef mergeCapRelDefs(RequirementCapabilityRelDef capRelDefFrom, RequirementCapabilityRelDef capRelDefTo) {
         if (capRelDefFrom == capRelDefTo) {
             return capRelDefFrom;
-        }
-        else if (capRelDefFrom == null) {
+        } else if (capRelDefFrom == null) {
             return capRelDefTo;
-        }
-        else if (capRelDefTo == null) {
+        } else if (capRelDefTo == null) {
             return capRelDefFrom;
         }
-        
         RelationshipInfo relationshipInfoFrom = capRelDefFrom.resolveSingleRelationship().getRelation();
         RelationshipInfo relationshipInfoTo = capRelDefTo.resolveSingleRelationship().getRelation();
-        
         relationshipInfoFrom.setCapabilityOwnerId(relationshipInfoTo.getCapabilityOwnerId());
         relationshipInfoFrom.setCapabilityUid(relationshipInfoTo.getCapabilityUid());
-        
         return capRelDefFrom;
     }
-    
-
 
     private Map<String, ComponentInstance> buildComponentInstanceMap(Component oldRresource, Function<ComponentInstance, String> getKeyFunc) {
-        return oldRresource.getComponentInstances().stream()
-                .collect(Collectors.toMap(getKeyFunc, Function.identity(), (p1, p2) -> p1));
+        return oldRresource.getComponentInstances().stream().collect(Collectors.toMap(getKeyFunc, Function.identity(), (p1, p2) -> p1));
     }
 
     private List<RequirementCapabilityRelDef> getUpdatedCapReqDefs(Component oldResource, Component newComponent,
                                                                    Map<String, ComponentInstance> mapOldComponentInstances,
                                                                    Map<String, ComponentInstance> mapNewComponentInstances,
                                                                    Predicate<? super RequirementCapabilityRelDef> filter) {
-        return oldResource.getComponentInstancesRelations().stream()
-                        .filter(filter)
-                        .map(rel -> createRelationMergeInfoPair(rel, mapOldComponentInstances))
-                        .map(infoPair -> restoreRequirementCapabilityRelDef(infoPair, mapNewComponentInstances))
-                        .filter(Objects::nonNull)
-                        .filter(r-> capReqMatchExist(r, newComponent))
-                        .collect(Collectors.toList());
+        return oldResource.getComponentInstancesRelations().stream().filter(filter)
+            .map(rel -> createRelationMergeInfoPair(rel, mapOldComponentInstances))
+            .map(infoPair -> restoreRequirementCapabilityRelDef(infoPair, mapNewComponentInstances)).filter(Objects::nonNull)
+            .filter(r -> capReqMatchExist(r, newComponent)).collect(Collectors.toList());
     }
 
-
     private boolean capReqMatchExist(RequirementCapabilityRelDef rel, Component currentComponent) {
-        return currentComponent.getComponentInstances().stream()
-                    .anyMatch(i->isFromInstance(i, rel)) &&
-                currentComponent.getComponentInstances().stream()
-                    .anyMatch(i->isToInstance(i, rel));
+        return currentComponent.getComponentInstances().stream().anyMatch(i -> isFromInstance(i, rel)) && currentComponent.getComponentInstances()
+            .stream().anyMatch(i -> isToInstance(i, rel));
     }
 
     private boolean isToInstance(ComponentInstance inst, RequirementCapabilityRelDef rel) {
-        return inst.getUniqueId().equals(rel.getToNode()) &&
-                inst.getCapabilities().values()
-                        .stream()
-                        .flatMap(Collection::stream)
-                        .anyMatch(cap->cap.getName().equals(rel.resolveSingleRelationship().getRelation().getCapability())
-                                && cap.getOwnerId().equals(rel.resolveSingleRelationship().getRelation().getCapabilityOwnerId()));
+        return inst.getUniqueId().equals(rel.getToNode()) && inst.getCapabilities().values().stream().flatMap(Collection::stream).anyMatch(
+            cap -> cap.getName().equals(rel.resolveSingleRelationship().getRelation().getCapability()) && cap.getOwnerId()
+                .equals(rel.resolveSingleRelationship().getRelation().getCapabilityOwnerId()));
     }
 
     private boolean isFromInstance(ComponentInstance inst, RequirementCapabilityRelDef rel) {
-        return inst.getUniqueId().equals(rel.getFromNode()) &&
-                inst.getRequirements().values()
-                        .stream()
-                        .flatMap(Collection::stream)
-                        .anyMatch(req->req.getName().equals(rel.resolveSingleRelationship().getRelation().getRequirement())
-                                && req.getOwnerId().equals(rel.resolveSingleRelationship().getRelation().getRequirementOwnerId()));
+        return inst.getUniqueId().equals(rel.getFromNode()) && inst.getRequirements().values().stream().flatMap(Collection::stream).anyMatch(
+            req -> req.getName().equals(rel.resolveSingleRelationship().getRelation().getRequirement()) && req.getOwnerId()
+                .equals(rel.resolveSingleRelationship().getRelation().getRequirementOwnerId()));
     }
 
     private ImmutablePair<RelationMergeInfo, RelationMergeInfo> createRelationMergeInfoPair(RequirementCapabilityRelDef reqCapDef,
                                                                                             Map<String, ComponentInstance> mapOldComponentInstances) {
-        
         ComponentInstance oldComponentInstanceFrom = mapOldComponentInstances.get(reqCapDef.getFromNode());
         RelationMergeInfo fromRelationMergeInfo = createRequirmentRelationMergeInfo(oldComponentInstanceFrom, reqCapDef);
-        
         ComponentInstance oldComponentInstanceTo = mapOldComponentInstances.get(reqCapDef.getToNode());
         RelationMergeInfo toRelationMergeInfo = createCapabilityRelationMergeInfo(oldComponentInstanceTo, reqCapDef);
         return new ImmutablePair<>(fromRelationMergeInfo, toRelationMergeInfo);
     }
 
-    private RelationMergeInfo createRequirmentRelationMergeInfo(ComponentInstance componentInstance, RequirementCapabilityRelDef reqCapDef ) {
-        
+    private RelationMergeInfo createRequirmentRelationMergeInfo(ComponentInstance componentInstance, RequirementCapabilityRelDef reqCapDef) {
         List<ComponentInstance> vfcInstances = getVfcInstances(componentInstance);
-        if  (vfcInstances != null) { 
+        if (vfcInstances != null) {
             return mapRelationRequirement(reqCapDef, vfcInstances);
-        }
-        else {
+        } else {
             log.debug("#createRelationMergeInfo - It's unexpected that vfc instnaces were not found for {}", componentInstance);
             return null;
         }
     }
 
-    private RelationMergeInfo createCapabilityRelationMergeInfo(ComponentInstance componentInstance,
-                                                      RequirementCapabilityRelDef reqCapDef) {
+    private RelationMergeInfo createCapabilityRelationMergeInfo(ComponentInstance componentInstance, RequirementCapabilityRelDef reqCapDef) {
         List<CapabilityOwner> capabilityOwners = getInstanceAtomicBuildingBlocks(componentInstance).getCapabilitiesOwners();
         return mapRelationCapability(reqCapDef, capabilityOwners);
     }
 
-    
-    private RequirementCapabilityRelDef restoreRequirementCapabilityRelDef(ImmutablePair<RelationMergeInfo, RelationMergeInfo> mergeInfoPair, Map<String, ComponentInstance> mapNewComponentInstances) {
+    private RequirementCapabilityRelDef restoreRequirementCapabilityRelDef(ImmutablePair<RelationMergeInfo, RelationMergeInfo> mergeInfoPair,
+                                                                           Map<String, ComponentInstance> mapNewComponentInstances) {
         RequirementCapabilityRelDef capRelDefFrom = restoreRequirementRelDef(mergeInfoPair, mapNewComponentInstances);
         RequirementCapabilityRelDef capRelDefTo = restoreCapabilityRelDef(mergeInfoPair, mapNewComponentInstances);
-
         return mergeCapRelDefs(capRelDefFrom, capRelDefTo);
     }
 
-    private RequirementCapabilityRelDef restoreRequirementRelDef(ImmutablePair<RelationMergeInfo, RelationMergeInfo> mergeInfoPair, Map<String, ComponentInstance> mapNewComponentInstances) {
+    private RequirementCapabilityRelDef restoreRequirementRelDef(ImmutablePair<RelationMergeInfo, RelationMergeInfo> mergeInfoPair,
+                                                                 Map<String, ComponentInstance> mapNewComponentInstances) {
         RequirementCapabilityRelDef capRelDefFrom = null;
         RelationMergeInfo mergeInfoFrom = mergeInfoPair.getLeft();
         if (mergeInfoFrom != null) {
             ComponentInstance newComponentInstanceFrom = mapNewComponentInstances.get(mergeInfoFrom.getCapOwnerName());
-            if(newComponentInstanceFrom != null){
-                capRelDefFrom = restoreRequirementRelDef(newComponentInstanceFrom, mergeInfoFrom,  newComponentInstanceFrom.getUniqueId());
+            if (newComponentInstanceFrom != null) {
+                capRelDefFrom = restoreRequirementRelDef(newComponentInstanceFrom, mergeInfoFrom, newComponentInstanceFrom.getUniqueId());
             }
-        }
-        else {
+        } else {
             capRelDefFrom = null;
         }
         return capRelDefFrom;
     }
 
-    private RequirementCapabilityRelDef restoreCapabilityRelDef(ImmutablePair<RelationMergeInfo, RelationMergeInfo> mergeInfoPair, Map<String, ComponentInstance> mapNewComponentInstances) {
+    private RequirementCapabilityRelDef restoreCapabilityRelDef(ImmutablePair<RelationMergeInfo, RelationMergeInfo> mergeInfoPair,
+                                                                Map<String, ComponentInstance> mapNewComponentInstances) {
         RequirementCapabilityRelDef capRelDefTo;
         RelationMergeInfo mergeInfoTo = mergeInfoPair.getRight();
         if (mergeInfoTo != null) {
             ComponentInstance newComponentInstanceTo = mapNewComponentInstances.get(mergeInfoTo.getCapOwnerName());
             capRelDefTo = restoreCapabilityRelDef(newComponentInstanceTo, mergeInfoTo, newComponentInstanceTo.getUniqueId());
-        }
-        else {
+        } else {
             capRelDefTo = null;
         }
         return capRelDefTo;
     }
 
-    private RequirementCapabilityRelDef  restoreRequirementRelDef(ComponentInstance newComponentInstance, RelationMergeInfo mergeInfoFrom, String newComponentInstanceFromId) {
+    private RequirementCapabilityRelDef restoreRequirementRelDef(ComponentInstance newComponentInstance, RelationMergeInfo mergeInfoFrom,
+                                                                 String newComponentInstanceFromId) {
         if (newComponentInstance != null) {
             List<ComponentInstance> vfcInstances = getVfcInstances(newComponentInstance);
-            if(vfcInstances != null) {
+            if (vfcInstances != null) {
                 Map<String, ComponentInstance> vfciMap = toMap(vfcInstances, ComponentInstance::getName, (p1, p2) -> p1);
                 return restoreRequirementRelation(mergeInfoFrom, newComponentInstanceFromId, vfciMap, null);
-            }
-            else {
+            } else {
                 log.debug("#restoreRequirementCapabilityRelDef - It was not found VFC instances for component instance {}", newComponentInstance);
             }
         }
         return null;
     }
 
-    private RequirementCapabilityRelDef restoreCapabilityRelDef(ComponentInstance newComponentInstance, RelationMergeInfo mergeInfoTo, String newComponentInstanceToId) {
+    private RequirementCapabilityRelDef restoreCapabilityRelDef(ComponentInstance newComponentInstance, RelationMergeInfo mergeInfoTo,
+                                                                String newComponentInstanceToId) {
         if (newComponentInstance != null) {
             List<CapabilityOwner> capsOwners = getInstanceAtomicBuildingBlocks(newComponentInstance).getCapabilitiesOwners();
-            if(capsOwners != null) {
+            if (capsOwners != null) {
                 Map<String, CapabilityOwner> vfciMap = toMap(capsOwners, CapabilityOwner::getName, (p1, p2) -> p1);
                 return restoreCapabilityRelation(mergeInfoTo, newComponentInstanceToId, vfciMap, null);
-            }
-            else {
+            } else {
                 log.debug("#restoreRequirementCapabilityRelDef - It was not found VFC instances for component instance {}", newComponentInstance);
             }
         }
         return null;
     }
 
-
     private ComponentInstanceBuildingBlocks recursiveScanForAtomicBuildingBlocks(Component component) {
         ComponentInstanceBuildingBlocks capsOwners = ComponentInstanceBuildingBlocks.of(component.getGroups(), null);
         List<ComponentInstance> componentInstances = component.safeGetComponentInstances();
         // Go recursively to collect atomic components only
-        ComponentInstanceBuildingBlocks propsOwnersRec = componentInstances.stream()
-                .map(this::getInstanceAtomicBuildingBlocks)
-                .reduce(ComponentInstanceBuildingBlocks::merge)
-                .orElse(ComponentInstanceBuildingBlocks.empty());
+        ComponentInstanceBuildingBlocks propsOwnersRec = componentInstances.stream().map(this::getInstanceAtomicBuildingBlocks)
+            .reduce(ComponentInstanceBuildingBlocks::merge).orElse(ComponentInstanceBuildingBlocks.empty());
         return ComponentInstanceBuildingBlocks.merge(capsOwners, propsOwnersRec);
     }
 
-
     private Map<String, String> prepareMapForAtomicComponent(String newInstanceId, List<String> oldCapabilitiesOwnerIds) {
         Map<String, String> resultMap;
-
         int oldCapabilityOwnerIdsSize = oldCapabilitiesOwnerIds.size();
         if (oldCapabilityOwnerIdsSize == 1) {
             resultMap = new HashMap<>();
             resultMap.put(oldCapabilitiesOwnerIds.get(0), newInstanceId);
-        }
-        else {
-            log.debug("#prepareMapForAtomicComponent - For atomic component the list of old capabilities owner Ids should contains one element while actual size is {},", oldCapabilityOwnerIdsSize);
+        } else {
+            log.debug(
+                "#prepareMapForAtomicComponent - For atomic component the list of old capabilities owner Ids should contains one element while actual size is {},",
+                oldCapabilityOwnerIdsSize);
             resultMap = emptyMap();
         }
-
         return resultMap;
     }
 
-    private Map<String, String> prepareMapForNonAtomicComponent(Component container, Component origInstanceNode,
-                                                                    String newInstanceId, List<String> oldCapabilitiesOwnerIds) {
+    private Map<String, String> prepareMapForNonAtomicComponent(Component container, Component origInstanceNode, String newInstanceId,
+                                                                List<String> oldCapabilitiesOwnerIds) {
         ComponentInstance newInstance = container.getComponentInstanceById(newInstanceId).orElse(null);
         if (newInstance == null) {
             log.debug("#prepareMapForNonAtomicComponent - Failed to get component instance by newInstanceId: {}.", newInstanceId);
             return emptyMap();
         }
         List<CapabilityOwner> prevCapOwners = recursiveScanForAtomicBuildingBlocks(origInstanceNode).getCapabilitiesOwners();
-        Component origNewCmpt = toscaOperationFacade.getToscaElement(newInstance.getActualComponentUid()).left().on(err -> exceptionUtils.rollBackAndThrow(err, newInstance.getActualComponentUid()));
+        Component origNewCmpt = toscaOperationFacade.getToscaElement(newInstance.getActualComponentUid()).left()
+            .on(err -> exceptionUtils.rollBackAndThrow(err, newInstance.getActualComponentUid()));
         return mapOldOwnerIdsToNewOnes(oldCapabilitiesOwnerIds, prevCapOwners, newInstance, origNewCmpt);
     }
 
-    private Map<String, String> mapOldOwnerIdsToNewOnes(List<String> oldCapabilitiesOwnerIds,
-                                                        List<CapabilityOwner> prevCapOwners, ComponentInstance newInstance, Component origNewInstanceType) {
+    private Map<String, String> mapOldOwnerIdsToNewOnes(List<String> oldCapabilitiesOwnerIds, List<CapabilityOwner> prevCapOwners,
+                                                        ComponentInstance newInstance, Component origNewInstanceType) {
         List<CapabilityOwner> newCapOwners = getInstanceAtomicBuildingBlocks(newInstance, origNewInstanceType).getCapabilitiesOwners();
         return getCapabilitiesOwnerMapping(oldCapabilitiesOwnerIds, prevCapOwners, newCapOwners);
     }
 
-    private Map<String, String> getCapabilitiesOwnerMapping(List<String> oldCapabilitiesOwnerIds, List<CapabilityOwner> prevCapOwners, List<CapabilityOwner> newCapOwners) {
+    private Map<String, String> getCapabilitiesOwnerMapping(List<String> oldCapabilitiesOwnerIds, List<CapabilityOwner> prevCapOwners,
+                                                            List<CapabilityOwner> newCapOwners) {
         Map<String, CapabilityOwner> capOwnersByName = toMap(newCapOwners, CapabilityOwner::getName, (p1, p2) -> p1);
-        return prevCapOwners
-                .stream()
-                .filter(oldCapOwner -> oldCapabilitiesOwnerIds.contains(oldCapOwner.getUniqueId()))
-                .filter(oldCapOwner -> capOwnersByName.containsKey(oldCapOwner.getName()))
-                .collect(Collectors.toMap(CapabilityOwner::getUniqueId, oldCapOwner -> capOwnersByName.get(oldCapOwner.getName()).getUniqueId(), (p1, p2) -> p1));
+        return prevCapOwners.stream().filter(oldCapOwner -> oldCapabilitiesOwnerIds.contains(oldCapOwner.getUniqueId()))
+            .filter(oldCapOwner -> capOwnersByName.containsKey(oldCapOwner.getName())).collect(Collectors
+                .toMap(CapabilityOwner::getUniqueId, oldCapOwner -> capOwnersByName.get(oldCapOwner.getName()).getUniqueId(), (p1, p2) -> p1));
     }
 
-
-    private RelationMergeInfo createCapabilityRelationMergeInfo(List<CapabilityOwner> vfcInstances, String ownerId, RequirementCapabilityRelDef relation) {
-        return vfcInstances.stream()
-                            .filter(inst -> StringUtils.equals(inst.getUniqueId(), ownerId))
-                            .map(capabilityOwner -> getCapabilityMergeInfo(capabilityOwner, relation))
-                            .findAny()
-                            .orElse(null);
+    private RelationMergeInfo createCapabilityRelationMergeInfo(List<CapabilityOwner> vfcInstances, String ownerId,
+                                                                RequirementCapabilityRelDef relation) {
+        return vfcInstances.stream().filter(inst -> StringUtils.equals(inst.getUniqueId(), ownerId))
+            .map(capabilityOwner -> getCapabilityMergeInfo(capabilityOwner, relation)).findAny().orElse(null);
     }
 
-
-    private RelationMergeInfo createRequirementRelationMergeInfo(List<ComponentInstance> vfcInstances, String ownerId, RequirementCapabilityRelDef relation) {
-        return vfcInstances.stream()
-                .filter(inst -> StringUtils.equals(inst.getUniqueId(), ownerId))
-                .map(currVfcInst -> mapVfcInstanceRequirement(currVfcInst, relation))
-                .filter(Objects::nonNull)
-                .findAny()
-                .orElse(null);
+    private RelationMergeInfo createRequirementRelationMergeInfo(List<ComponentInstance> vfcInstances, String ownerId,
+                                                                 RequirementCapabilityRelDef relation) {
+        return vfcInstances.stream().filter(inst -> StringUtils.equals(inst.getUniqueId(), ownerId))
+            .map(currVfcInst -> mapVfcInstanceRequirement(currVfcInst, relation)).filter(Objects::nonNull).findAny().orElse(null);
     }
 
     private RelationMergeInfo getCapabilityMergeInfo(CapabilityOwner capabilityOwner, RequirementCapabilityRelDef relDef) {
@@ -509,80 +440,57 @@ public class MergeInstanceUtils {
             capabilityType = capabilityDef.getType();
             capabilityName = capabilityDef.getName();
         } else {
-            log.debug("#getCapabilityMergeInfo - Failed to retrieve capability type for relation with name: {} and uniqueId {}", relDef.resolveSingleRelationship().getRelation().getCapability(), capabilityUniqueId);
+            log.debug("#getCapabilityMergeInfo - Failed to retrieve capability type for relation with name: {} and uniqueId {}",
+                relDef.resolveSingleRelationship().getRelation().getCapability(), capabilityUniqueId);
             capabilityType = null;
             capabilityName = null;
         }
         return new RelationMergeInfo(capabilityType, capabilityName, capOwnerName, relDef);
     }
-    
+
     private RelationMergeInfo mapVfcInstanceRequirement(ComponentInstance vfcInstance, RequirementCapabilityRelDef relDef) {
         String requirementUniqueId = relDef.resolveSingleRelationship().getRelation().getRequirementUid();
-        
         String vfcInstanceName = vfcInstance.getName();
         String vfcUid = vfcInstance.getComponentUid();
-        
         Either<Resource, StorageOperationStatus> vfcResource = toscaOperationFacade.getToscaElement(vfcUid);
-        if(vfcResource.isLeft()) {
+        if (vfcResource.isLeft()) {
             Resource vfc = vfcResource.left().value();
-            
             RequirementDefinition requirementDef = retrieveRequirementDefinition(requirementUniqueId, vfc);
             String requirementType;
             String requirementName;
             if (requirementDef != null) {
                 requirementType = requirementDef.getCapability();
                 requirementName = requirementDef.getName();
-            }
-            else {
-                log.debug("#mapVfcInstanceRequirement - Failed to retrieve requirement type for relation with name: {} and uniqueId {}", relDef.resolveSingleRelationship().getRelation().getRequirement(), requirementUniqueId);
+            } else {
+                log.debug("#mapVfcInstanceRequirement - Failed to retrieve requirement type for relation with name: {} and uniqueId {}",
+                    relDef.resolveSingleRelationship().getRelation().getRequirement(), requirementUniqueId);
                 requirementType = null;
-                requirementName = null;                
+                requirementName = null;
             }
-            
             return new RelationMergeInfo(requirementType, requirementName, vfcInstanceName, relDef);
-        }
-        else {
-            log.debug("#mapVfcInstanceRequirement - Failed to load VFC by uid {}", vfcUid); 
+        } else {
+            log.debug("#mapVfcInstanceRequirement - Failed to load VFC by uid {}", vfcUid);
             return null;
         }
     }
 
     private CapabilityDefinition retrieveCapabilityDefinition(String uniqueId, CapabilityOwner capabilityOwner) {
-        return capabilityOwner.getCapabilities().values().stream()
-                                                .flatMap(List::stream)
-                                                .filter(Objects::nonNull)
-                                                .filter(def -> uniqueId.equals(def.getUniqueId()))
-                                                .findFirst()
-                                                .orElse(null);
-    }
-    
+        return capabilityOwner.getCapabilities().values().stream().flatMap(List::stream).filter(Objects::nonNull)
+            .filter(def -> uniqueId.equals(def.getUniqueId())).findFirst().orElse(null);
+    }
+
     private RequirementDefinition retrieveRequirementDefinition(String uniqueId, Resource vfc) {
-        return vfc.getRequirements().values().stream()
-                .flatMap(List::stream)
-                .filter(Objects::nonNull)
-                .filter(def -> uniqueId.equals(def.getUniqueId()))
-                .findFirst()
-                .orElse(null);
-    }
-    
+        return vfc.getRequirements().values().stream().flatMap(List::stream).filter(Objects::nonNull)
+            .filter(def -> uniqueId.equals(def.getUniqueId())).findFirst().orElse(null);
+    }
+
     private String retrieveCapabilityUid(String name, CapabilityOwner capabilityOwner) {
-        return capabilityOwner.getCapabilities().values()
-                                                .stream()
-                                                .flatMap(List::stream)
-                                                .filter(Objects::nonNull)
-                                                .filter(def -> name.equals(def.getName()))
-                                                .findFirst()
-                                                .map(CapabilityDefinition::getUniqueId)
-                                                .orElse(null);
+        return capabilityOwner.getCapabilities().values().stream().flatMap(List::stream).filter(Objects::nonNull)
+            .filter(def -> name.equals(def.getName())).findFirst().map(CapabilityDefinition::getUniqueId).orElse(null);
     }
 
     private String retrieveRequirementUid(String name, Component vfc) {
-        return vfc.getRequirements().values().stream()
-                                                .flatMap(List::stream)
-                                                .filter(Objects::nonNull)
-                                                .filter(def -> name.equals(def.getName()))
-                                                .findFirst()
-                                                .map(RequirementDefinition::getUniqueId)
-                                                .orElse(null);
+        return vfc.getRequirements().values().stream().flatMap(List::stream).filter(Objects::nonNull).filter(def -> name.equals(def.getName()))
+            .findFirst().map(RequirementDefinition::getUniqueId).orElse(null);
     }
 }
index 9150e5e..ab9b0a5 100644 (file)
@@ -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.
  * limitations under the License.
  * ============LICENSE_END=========================================================
  */
-
 package org.openecomp.sdc.be.components.path;
 
 import fj.data.Either;
+import java.util.Collection;
+import java.util.HashMap;
+import java.util.Map;
 import org.apache.commons.lang.StringUtils;
 import org.openecomp.sdc.be.components.impl.ResponseFormatManager;
 import org.openecomp.sdc.be.components.impl.exceptions.ByActionStatusComponentException;
@@ -34,23 +36,17 @@ import org.openecomp.sdc.common.log.wrappers.Logger;
 import org.springframework.beans.factory.annotation.Autowired;
 import org.springframework.stereotype.Component;
 
-import java.util.Collection;
-import java.util.HashMap;
-import java.util.Map;
-
 @Component("forwardingPathValidator")
 public class ForwardingPathValidator {
 
     @Autowired
     protected ToscaOperationFacade toscaOperationFacade;
-
     private static final Logger logger = Logger.getLogger(ForwardingPathValidator.class);
-    private static final int  PATH_NAME_LENGTH = 200;
-    private static final int  PROTOCOL_LENGTH = 200;
-    private static final int  DESTINATION_PORT_LENGTH = 200;
+    private static final int PATH_NAME_LENGTH = 200;
+    private static final int PROTOCOL_LENGTH = 200;
+    private static final int DESTINATION_PORT_LENGTH = 200;
 
-    public void validateForwardingPaths(Collection<ForwardingPathDataDefinition> paths,
-                                        String serviceId, boolean isUpdate) {
+    public void validateForwardingPaths(Collection<ForwardingPathDataDefinition> paths, String serviceId, boolean isUpdate) {
         for (ForwardingPathDataDefinition path : paths) {
             validateForwardingPath(path, serviceId, isUpdate);
         }
@@ -64,12 +60,11 @@ public class ForwardingPathValidator {
     }
 
     private void validateDestinationPortNumber(ForwardingPathDataDefinition dataDefinition) {
-        if (dataDefinition.getDestinationPortNumber() != null &&
-            dataDefinition.getDestinationPortNumber().length() > DESTINATION_PORT_LENGTH ) {
-            logger.debug("Forwarding path destination port {} too long, , maximum allowed 200 characters ",
-                    dataDefinition.getDestinationPortNumber());
-            throw new ByActionStatusComponentException(ActionStatus
-                    .FORWARDING_PATH_DESTINATION_PORT_MAXIMUM_LENGTH, dataDefinition.getDestinationPortNumber());
+        if (dataDefinition.getDestinationPortNumber() != null && dataDefinition.getDestinationPortNumber().length() > DESTINATION_PORT_LENGTH) {
+            logger
+                .debug("Forwarding path destination port {} too long, , maximum allowed 200 characters ", dataDefinition.getDestinationPortNumber());
+            throw new ByActionStatusComponentException(ActionStatus.FORWARDING_PATH_DESTINATION_PORT_MAXIMUM_LENGTH,
+                dataDefinition.getDestinationPortNumber());
         }
     }
 
@@ -80,15 +75,12 @@ public class ForwardingPathValidator {
         }
     }
 
-    private void validateName(ForwardingPathDataDefinition dataDefinition,
-                                                         ResponseFormatManager responseFormatManager,
-                                                         String serviceId, boolean isUpdate) {
+    private void validateName(ForwardingPathDataDefinition dataDefinition, ResponseFormatManager responseFormatManager, String serviceId,
+                              boolean isUpdate) {
         String pathName = dataDefinition.getName();
         validatePathNameIfEmpty(responseFormatManager, pathName);
-
         validatePathNameLength(responseFormatManager, pathName);
-
-        Boolean isPathNameUniqueResponse = validatePathIfUnique(dataDefinition, serviceId, isUpdate, responseFormatManager );
+        Boolean isPathNameUniqueResponse = validatePathIfUnique(dataDefinition, serviceId, isUpdate, responseFormatManager);
         if (!isPathNameUniqueResponse) {
             logger.debug("Forwarding path name {} already in use ", dataDefinition.getName());
             throw new ByActionStatusComponentException(ActionStatus.FORWARDING_PATH_NAME_ALREADY_IN_USE, dataDefinition.getName());
@@ -109,44 +101,34 @@ public class ForwardingPathValidator {
         }
     }
 
-
-    private Boolean validatePathIfUnique(ForwardingPathDataDefinition dataDefinition, String serviceId,
-                                                                 boolean isUpdate, ResponseFormatManager responseFormatManager) {
+    private Boolean validatePathIfUnique(ForwardingPathDataDefinition dataDefinition, String serviceId, boolean isUpdate,
+                                         ResponseFormatManager responseFormatManager) {
         boolean isPathNameUnique = false;
         ComponentParametersView filter = new ComponentParametersView(true);
         filter.setIgnoreServicePath(false);
-        Either<Service, StorageOperationStatus> forwardingPathOrigin = toscaOperationFacade
-                .getToscaElement(serviceId, filter);
-        if (forwardingPathOrigin.isRight()){
+        Either<Service, StorageOperationStatus> forwardingPathOrigin = toscaOperationFacade.getToscaElement(serviceId, filter);
+        if (forwardingPathOrigin.isRight()) {
             throw new ByActionStatusComponentException(ActionStatus.GENERAL_ERROR);
         }
         Collection<ForwardingPathDataDefinition> allPaths = forwardingPathOrigin.left().value().getForwardingPaths().values();
         Map<String, String> pathNames = new HashMap<>();
-        allPaths.forEach( path -> pathNames.put(path.getUniqueId(), path.getName()) );
-
-        if (isUpdate){
-            for(Map.Entry<String, String> entry : pathNames.entrySet()){
-                if (entry.getKey().equals(dataDefinition.getUniqueId()) && entry.getValue().
-                        equals(dataDefinition.getName())) {
+        allPaths.forEach(path -> pathNames.put(path.getUniqueId(), path.getName()));
+        if (isUpdate) {
+            for (Map.Entry<String, String> entry : pathNames.entrySet()) {
+                if (entry.getKey().equals(dataDefinition.getUniqueId()) && entry.getValue().equals(dataDefinition.getName())) {
                     isPathNameUnique = true;
                 }
-
-                if(entry.getKey().equals(dataDefinition.getUniqueId()) && !pathNames.values().contains(dataDefinition.getName())){
+                if (entry.getKey().equals(dataDefinition.getUniqueId()) && !pathNames.values().contains(dataDefinition.getName())) {
                     isPathNameUnique = true;
                 }
             }
-        }
-        else
-        if (!pathNames.values().contains(dataDefinition.getName())){
+        } else if (!pathNames.values().contains(dataDefinition.getName())) {
             isPathNameUnique = true;
         }
-
         return isPathNameUnique;
     }
 
     protected ResponseFormatManager getResponseFormatManager() {
         return ResponseFormatManager.getInstance();
     }
-
-
 }
index c7d9cfb..40a6223 100644 (file)
@@ -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.
  * limitations under the License.
  * ============LICENSE_END=========================================================
  */
-
 package org.openecomp.sdc.be.components.property;
 
+import static org.apache.commons.collections.CollectionUtils.isEmpty;
+import static org.openecomp.sdc.be.model.utils.ComponentUtilities.getInputAnnotations;
+
 import fj.data.Either;
+import java.util.ArrayList;
+import java.util.Collections;
+import java.util.List;
+import java.util.Map;
+import java.util.Optional;
 import org.openecomp.sdc.be.components.impl.ComponentInstanceBusinessLogic;
 import org.openecomp.sdc.be.components.impl.utils.ExceptionUtils;
 import org.openecomp.sdc.be.datatypes.elements.Annotation;
@@ -37,15 +44,6 @@ import org.openecomp.sdc.be.model.operations.api.StorageOperationStatus;
 import org.openecomp.sdc.be.model.operations.impl.PropertyOperation;
 import org.openecomp.sdc.common.log.wrappers.Logger;
 
-import java.util.ArrayList;
-import java.util.Collections;
-import java.util.List;
-import java.util.Map;
-import java.util.Optional;
-
-import static org.apache.commons.collections.CollectionUtils.isEmpty;
-import static org.openecomp.sdc.be.model.utils.ComponentUtilities.getInputAnnotations;
-
 @org.springframework.stereotype.Component
 public class ComponentInstanceInputPropertyDeclarator extends DefaultPropertyDeclarator<ComponentInstance, ComponentInstanceInput> {
 
@@ -54,7 +52,9 @@ public class ComponentInstanceInputPropertyDeclarator extends DefaultPropertyDec
     private final ComponentInstanceBusinessLogic componentInstanceBusinessLogic;
     private final ExceptionUtils exceptionUtils;
 
-    public ComponentInstanceInputPropertyDeclarator(ComponentsUtils componentsUtils, PropertyOperation propertyOperation, ToscaOperationFacade toscaOperationFacade, ComponentInstanceBusinessLogic componentInstanceBusinessLogic, ExceptionUtils exceptionUtils) {
+    public ComponentInstanceInputPropertyDeclarator(ComponentsUtils componentsUtils, PropertyOperation propertyOperation,
+                                                    ToscaOperationFacade toscaOperationFacade,
+                                                    ComponentInstanceBusinessLogic componentInstanceBusinessLogic, ExceptionUtils exceptionUtils) {
         super(componentsUtils, propertyOperation);
         this.toscaOperationFacade = toscaOperationFacade;
         this.componentInstanceBusinessLogic = componentInstanceBusinessLogic;
@@ -67,8 +67,10 @@ public class ComponentInstanceInputPropertyDeclarator extends DefaultPropertyDec
     }
 
     @Override
-    public Either<?, StorageOperationStatus> updatePropertiesValues(Component component, String cmptInstanceId, List<ComponentInstanceInput> properties) {
-        log.debug("#updatePropertiesValues - updating component instance inputs for instance {} on component {}", cmptInstanceId, component.getUniqueId());
+    public Either<?, StorageOperationStatus> updatePropertiesValues(Component component, String cmptInstanceId,
+                                                                    List<ComponentInstanceInput> properties) {
+        log.debug("#updatePropertiesValues - updating component instance inputs for instance {} on component {}", cmptInstanceId,
+            component.getUniqueId());
         Map<String, List<ComponentInstanceInput>> instProperties = Collections.singletonMap(cmptInstanceId, properties);
         return toscaOperationFacade.addComponentInstanceInputsToComponent(component, instProperties);
     }
@@ -82,7 +84,7 @@ public class ComponentInstanceInputPropertyDeclarator extends DefaultPropertyDec
     @Override
     public void addPropertiesListToInput(ComponentInstanceInput declaredProp, InputDefinition input) {
         List<ComponentInstanceInput> inputsValueList = input.getInputs();
-        if(inputsValueList == null) {
+        if (inputsValueList == null) {
             inputsValueList = new ArrayList<>(); // adding the property with the new value for UI
         }
         inputsValueList.add(declaredProp);
@@ -91,26 +93,33 @@ public class ComponentInstanceInputPropertyDeclarator extends DefaultPropertyDec
 
     @Override
     public StorageOperationStatus unDeclarePropertiesAsInputs(Component component, InputDefinition input) {
-        List<ComponentInstanceInput> componentInstanceInputsByInputId = componentInstanceBusinessLogic.getComponentInstanceInputsByInputId(component, input.getUniqueId());
+        List<ComponentInstanceInput> componentInstanceInputsByInputId = componentInstanceBusinessLogic
+            .getComponentInstanceInputsByInputId(component, input.getUniqueId());
         if (isEmpty(componentInstanceInputsByInputId)) {
             return StorageOperationStatus.OK;
         }
-        componentInstanceInputsByInputId.forEach(cmptInstanceInput -> prepareValueBeforeDelete(input, cmptInstanceInput, cmptInstanceInput.getPath()));
-        return toscaOperationFacade.updateComponentInstanceInputs(component, componentInstanceInputsByInputId.get(0).getComponentInstanceId(), componentInstanceInputsByInputId);
+        componentInstanceInputsByInputId
+            .forEach(cmptInstanceInput -> prepareValueBeforeDelete(input, cmptInstanceInput, cmptInstanceInput.getPath()));
+        return toscaOperationFacade.updateComponentInstanceInputs(component, componentInstanceInputsByInputId.get(0).getComponentInstanceId(),
+            componentInstanceInputsByInputId);
     }
 
     @Override
     public StorageOperationStatus unDeclarePropertiesAsListInputs(Component component, InputDefinition input) {
-        List<ComponentInstanceInput> componentInstanceInputsByInputId = componentInstanceBusinessLogic.getComponentInstanceInputsByInputId(component, input.getUniqueId());
+        List<ComponentInstanceInput> componentInstanceInputsByInputId = componentInstanceBusinessLogic
+            .getComponentInstanceInputsByInputId(component, input.getUniqueId());
         if (isEmpty(componentInstanceInputsByInputId)) {
             return StorageOperationStatus.OK;
         }
-        componentInstanceInputsByInputId.forEach(cmptInstanceInput -> prepareValueBeforeDelete(input, cmptInstanceInput, cmptInstanceInput.getPath()));
-        return toscaOperationFacade.updateComponentInstanceInputs(component, componentInstanceInputsByInputId.get(0).getComponentInstanceId(), componentInstanceInputsByInputId);
+        componentInstanceInputsByInputId
+            .forEach(cmptInstanceInput -> prepareValueBeforeDelete(input, cmptInstanceInput, cmptInstanceInput.getPath()));
+        return toscaOperationFacade.updateComponentInstanceInputs(component, componentInstanceInputsByInputId.get(0).getComponentInstanceId(),
+            componentInstanceInputsByInputId);
     }
 
     @Override
-    InputDefinition createInputFromProperty(String componentId, ComponentInstance propertiesOwner, String inputName, ComponentInstancePropInput propInput, PropertyDataDefinition prop) {
+    InputDefinition createInputFromProperty(String componentId, ComponentInstance propertiesOwner, String inputName,
+                                            ComponentInstancePropInput propInput, PropertyDataDefinition prop) {
         InputDefinition inputFromProperty = super.createInputFromProperty(componentId, propertiesOwner, inputName, propInput, prop);
         Component propertiesOwnerNodeType = getInstanceOriginType(propertiesOwner);
         enrichInputWithAnnotations(prop, inputFromProperty, propertiesOwnerNodeType);
@@ -119,15 +128,14 @@ public class ComponentInstanceInputPropertyDeclarator extends DefaultPropertyDec
 
     private void enrichInputWithAnnotations(PropertyDataDefinition prop, InputDefinition inputFromProperty, Component propertiesOwnerNodeType) {
         List<Annotation> inputAnnotations = getInputAnnotations(propertiesOwnerNodeType, prop.getName());
-        if(!isEmpty(inputAnnotations)){
+        if (!isEmpty(inputAnnotations)) {
             inputFromProperty.setAnnotations(inputAnnotations);
         }
     }
 
     private Component getInstanceOriginType(ComponentInstance propertiesOwner) {
-        return toscaOperationFacade.getToscaElement(propertiesOwner.getActualComponentUid(), getFilterComponentInputs())
-                    .left()
-                    .on(err -> exceptionUtils.rollBackAndThrow(err, propertiesOwner.getActualComponentUid()));
+        return toscaOperationFacade.getToscaElement(propertiesOwner.getActualComponentUid(), getFilterComponentInputs()).left()
+            .on(err -> exceptionUtils.rollBackAndThrow(err, propertiesOwner.getActualComponentUid()));
     }
 
     private ComponentParametersView getFilterComponentInputs() {
index 1d8a23e..3c5ca44 100644 (file)
@@ -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.
  * limitations under the License.
  * ============LICENSE_END=========================================================
  */
-
 package org.openecomp.sdc.be.components.property;
 
 import fj.data.Either;
+import java.util.ArrayList;
+import java.util.Collections;
+import java.util.List;
+import java.util.Map;
+import java.util.Optional;
 import org.apache.commons.collections.CollectionUtils;
 import org.openecomp.sdc.be.components.impl.ComponentInstanceBusinessLogic;
 import org.openecomp.sdc.be.components.utils.PropertiesUtils;
@@ -36,12 +40,6 @@ import org.openecomp.sdc.be.model.operations.api.StorageOperationStatus;
 import org.openecomp.sdc.be.model.operations.impl.PropertyOperation;
 import org.openecomp.sdc.common.log.wrappers.Logger;
 
-import java.util.ArrayList;
-import java.util.Collections;
-import java.util.List;
-import java.util.Map;
-import java.util.Optional;
-
 @org.springframework.stereotype.Component
 public class ComponentInstancePropertyDeclarator extends DefaultPropertyDeclarator<ComponentInstance, ComponentInstanceProperty> {
 
@@ -49,7 +47,9 @@ public class ComponentInstancePropertyDeclarator extends DefaultPropertyDeclarat
     private ToscaOperationFacade toscaOperationFacade;
     private ComponentInstanceBusinessLogic componentInstanceBusinessLogic;
 
-    public ComponentInstancePropertyDeclarator(ComponentsUtils componentsUtils, PropertyOperation propertyOperation, ToscaOperationFacade toscaOperationFacade, ComponentInstanceBusinessLogic componentInstanceBusinessLogic) {
+    public ComponentInstancePropertyDeclarator(ComponentsUtils componentsUtils, PropertyOperation propertyOperation,
+                                               ToscaOperationFacade toscaOperationFacade,
+                                               ComponentInstanceBusinessLogic componentInstanceBusinessLogic) {
         super(componentsUtils, propertyOperation);
         this.toscaOperationFacade = toscaOperationFacade;
         this.componentInstanceBusinessLogic = componentInstanceBusinessLogic;
@@ -61,8 +61,10 @@ public class ComponentInstancePropertyDeclarator extends DefaultPropertyDeclarat
     }
 
     @Override
-    public Either<?, StorageOperationStatus> updatePropertiesValues(Component component, String cmptInstanceId, List<ComponentInstanceProperty> properties) {
-        log.debug("#updatePropertiesValues - updating component instance properties for instance {} on component {}", cmptInstanceId, component.getUniqueId());
+    public Either<?, StorageOperationStatus> updatePropertiesValues(Component component, String cmptInstanceId,
+                                                                    List<ComponentInstanceProperty> properties) {
+        log.debug("#updatePropertiesValues - updating component instance properties for instance {} on component {}", cmptInstanceId,
+            component.getUniqueId());
         Map<String, List<ComponentInstanceProperty>> instProperties = Collections.singletonMap(cmptInstanceId, properties);
         return toscaOperationFacade.addComponentInstancePropertiesToComponent(component, instProperties);
     }
@@ -76,7 +78,7 @@ public class ComponentInstancePropertyDeclarator extends DefaultPropertyDeclarat
     @Override
     public void addPropertiesListToInput(ComponentInstanceProperty declaredProp, InputDefinition input) {
         List<ComponentInstanceProperty> propertiesList = input.getProperties();
-        if(propertiesList == null) {
+        if (propertiesList == null) {
             propertiesList = new ArrayList<>(); // adding the property with the new value for UI
         }
         propertiesList.add(declaredProp);
@@ -85,44 +87,44 @@ public class ComponentInstancePropertyDeclarator extends DefaultPropertyDeclarat
 
     @Override
     public StorageOperationStatus unDeclarePropertiesAsInputs(Component component, InputDefinition input) {
-
-        Optional<ComponentInstanceProperty> propertyByInputId = PropertiesUtils.getPropertyByInputId(component,
-                input.getUniqueId());
-        if(propertyByInputId.isPresent()) {
-            List<ComponentInstanceProperty> capabilityPropertyDeclaredAsInput =
-                   PropertiesUtils.getCapabilityProperty(propertyByInputId.get(), input.getUniqueId());
-            capabilityPropertyDeclaredAsInput.forEach(cmptInstanceProperty -> prepareValueBeforeDeleteOfCapProp(input,
-                    cmptInstanceProperty));
-
-            Optional<CapabilityDefinition> propertyCapabilityOptional = PropertiesUtils.getPropertyCapabilityOfChildInstance(
-                    capabilityPropertyDeclaredAsInput.get(0).getParentUniqueId(), component.getCapabilities());
-            if(!propertyCapabilityOptional.isPresent()) {
+        Optional<ComponentInstanceProperty> propertyByInputId = PropertiesUtils.getPropertyByInputId(component, input.getUniqueId());
+        if (propertyByInputId.isPresent()) {
+            List<ComponentInstanceProperty> capabilityPropertyDeclaredAsInput = PropertiesUtils
+                .getCapabilityProperty(propertyByInputId.get(), input.getUniqueId());
+            capabilityPropertyDeclaredAsInput.forEach(cmptInstanceProperty -> prepareValueBeforeDeleteOfCapProp(input, cmptInstanceProperty));
+            Optional<CapabilityDefinition> propertyCapabilityOptional = PropertiesUtils
+                .getPropertyCapabilityOfChildInstance(capabilityPropertyDeclaredAsInput.get(0).getParentUniqueId(), component.getCapabilities());
+            if (!propertyCapabilityOptional.isPresent()) {
                 return StorageOperationStatus.OK;
             }
-
-            return toscaOperationFacade.updateInstanceCapabilityProperty(component, input.getInstanceUniqueId(),
-                    capabilityPropertyDeclaredAsInput.get(0), propertyCapabilityOptional.get() );
+            return toscaOperationFacade
+                .updateInstanceCapabilityProperty(component, input.getInstanceUniqueId(), capabilityPropertyDeclaredAsInput.get(0),
+                    propertyCapabilityOptional.get());
         } else {
             List<ComponentInstanceProperty> componentInstancePropertiesDeclaredAsInput = componentInstanceBusinessLogic
-                    .getComponentInstancePropertiesByInputId(component, input.getUniqueId());
+                .getComponentInstancePropertiesByInputId(component, input.getUniqueId());
             if (CollectionUtils.isEmpty(componentInstancePropertiesDeclaredAsInput)) {
                 return StorageOperationStatus.OK;
             }
-            componentInstancePropertiesDeclaredAsInput.forEach(cmptInstanceProperty -> prepareValueBeforeDelete(input,
-                    cmptInstanceProperty, cmptInstanceProperty.getPath()));
-            return toscaOperationFacade.updateComponentInstanceProperties(component,
-                    componentInstancePropertiesDeclaredAsInput.get(0).getComponentInstanceId(),
+            componentInstancePropertiesDeclaredAsInput
+                .forEach(cmptInstanceProperty -> prepareValueBeforeDelete(input, cmptInstanceProperty, cmptInstanceProperty.getPath()));
+            return toscaOperationFacade
+                .updateComponentInstanceProperties(component, componentInstancePropertiesDeclaredAsInput.get(0).getComponentInstanceId(),
                     componentInstancePropertiesDeclaredAsInput);
         }
     }
 
     @Override
     public StorageOperationStatus unDeclarePropertiesAsListInputs(Component component, InputDefinition input) {
-        List<ComponentInstanceProperty> componentInstancePropertiesDeclaredAsInput = componentInstanceBusinessLogic.getComponentInstancePropertiesByInputId(component, input.getUniqueId());
+        List<ComponentInstanceProperty> componentInstancePropertiesDeclaredAsInput = componentInstanceBusinessLogic
+            .getComponentInstancePropertiesByInputId(component, input.getUniqueId());
         if (CollectionUtils.isEmpty(componentInstancePropertiesDeclaredAsInput)) {
             return StorageOperationStatus.OK;
         }
-        componentInstancePropertiesDeclaredAsInput.forEach(cmptInstanceProperty -> prepareValueBeforeDelete(input, cmptInstanceProperty, cmptInstanceProperty.getPath()));
-        return toscaOperationFacade.updateComponentInstanceProperties(component, componentInstancePropertiesDeclaredAsInput.get(0).getComponentInstanceId(), componentInstancePropertiesDeclaredAsInput);
+        componentInstancePropertiesDeclaredAsInput
+            .forEach(cmptInstanceProperty -> prepareValueBeforeDelete(input, cmptInstanceProperty, cmptInstanceProperty.getPath()));
+        return toscaOperationFacade
+            .updateComponentInstanceProperties(component, componentInstancePropertiesDeclaredAsInput.get(0).getComponentInstanceId(),
+                componentInstancePropertiesDeclaredAsInput);
     }
 }
index 14479d4..dc5b95f 100644 (file)
  * See the License for the specific language governing permissions and
  * limitations under the License.
  */
-
 package org.openecomp.sdc.be.components.property;
 
 import fj.data.Either;
+import java.util.ArrayList;
+import java.util.Collections;
+import java.util.List;
+import java.util.Optional;
 import org.apache.commons.collections.CollectionUtils;
 import org.openecomp.sdc.be.components.impl.PropertyBusinessLogic;
 import org.openecomp.sdc.be.datatypes.elements.GetInputValueDataDefinition;
@@ -30,183 +33,140 @@ import org.openecomp.sdc.be.model.jsonjanusgraph.operations.ToscaOperationFacade
 import org.openecomp.sdc.be.model.operations.api.StorageOperationStatus;
 import org.openecomp.sdc.be.model.operations.impl.PropertyOperation;
 
-import java.util.ArrayList;
-import java.util.Collections;
-import java.util.List;
-import java.util.Optional;
-
 @org.springframework.stereotype.Component
 public class ComponentPropertyDeclarator extends DefaultPropertyDeclarator<Component, PropertyDataDefinition> {
 
-  private ToscaOperationFacade toscaOperationFacade;
-  PropertyBusinessLogic propertyBL;
-
-
-  public ComponentPropertyDeclarator(ComponentsUtils componentsUtils,
-                                     PropertyOperation propertyOperation,
-                                     ToscaOperationFacade toscaOperationFacade,
-                                     PropertyBusinessLogic propertyBL) {
-    super(componentsUtils, propertyOperation);
-    this.toscaOperationFacade = toscaOperationFacade;
-    this.propertyBL = propertyBL;
-  }
+    PropertyBusinessLogic propertyBL;
+    private ToscaOperationFacade toscaOperationFacade;
 
-  @Override
-  public PropertyDataDefinition createDeclaredProperty(PropertyDataDefinition prop) {
-    return new PropertyDataDefinition(prop);
-  }
-
-  @Override
-  public Either<?, StorageOperationStatus> updatePropertiesValues(Component component,
-                                                           String propertiesOwnerId,
-                                                           List<PropertyDataDefinition> properties) {
-    if(CollectionUtils.isNotEmpty(properties)) {
-      for(PropertyDataDefinition property : properties) {
-        Either<PropertyDefinition, StorageOperationStatus>
-            storageStatus = toscaOperationFacade
-            .updatePropertyOfComponent(component, new PropertyDefinition(property));
-        if(storageStatus.isRight()) {
-          return Either.right(storageStatus.right().value());
-        }
-      }
+    public ComponentPropertyDeclarator(ComponentsUtils componentsUtils, PropertyOperation propertyOperation,
+                                       ToscaOperationFacade toscaOperationFacade, PropertyBusinessLogic propertyBL) {
+        super(componentsUtils, propertyOperation);
+        this.toscaOperationFacade = toscaOperationFacade;
+        this.propertyBL = propertyBL;
     }
-    return Either.left(properties);
-  }
-
-  @Override
-  public Optional<Component> resolvePropertiesOwner(Component component, String propertiesOwnerId) {
-    return Optional.of(component);
-  }
 
-  @Override
-  public void addPropertiesListToInput(PropertyDataDefinition declaredProp,
-                                InputDefinition input) {
-
-    List<ComponentInstanceProperty> propertiesList = input.getProperties();
-    if(propertiesList == null) {
-      propertiesList = new ArrayList<>(); // adding the property with the new value for UI
+    @Override
+    public PropertyDataDefinition createDeclaredProperty(PropertyDataDefinition prop) {
+        return new PropertyDataDefinition(prop);
     }
-    propertiesList.add(new ComponentInstanceProperty(declaredProp));
-    input.setProperties(propertiesList);
-  }
-
-  @Override
-  public StorageOperationStatus unDeclarePropertiesAsInputs(Component component,
-                                                            InputDefinition input) {
-    PropertyDefinition propertyDefinition = new PropertyDefinition(input);
 
-    if(propertyBL.isPropertyUsedByOperation(component, propertyDefinition)) {
-      return StorageOperationStatus.DECLARED_INPUT_USED_BY_OPERATION;
-    }
-
-    Optional<PropertyDefinition> propertyToUpdateCandidate =
-        getDeclaredPropertyByInputId(component, input.getUniqueId());
-
-    if(propertyToUpdateCandidate.isPresent()) {
-      PropertyDefinition propertyToUpdate = propertyToUpdateCandidate.get();
-      return unDeclareInput(component, input, propertyToUpdate);
+    @Override
+    public Either<?, StorageOperationStatus> updatePropertiesValues(Component component, String propertiesOwnerId,
+                                                                    List<PropertyDataDefinition> properties) {
+        if (CollectionUtils.isNotEmpty(properties)) {
+            for (PropertyDataDefinition property : properties) {
+                Either<PropertyDefinition, StorageOperationStatus> storageStatus = toscaOperationFacade
+                    .updatePropertyOfComponent(component, new PropertyDefinition(property));
+                if (storageStatus.isRight()) {
+                    return Either.right(storageStatus.right().value());
+                }
+            }
+        }
+        return Either.left(properties);
     }
 
-
-    return StorageOperationStatus.OK;
-  }
-
-  @Override
-  public StorageOperationStatus unDeclarePropertiesAsListInputs(Component component,
-                                                            InputDefinition input) {
-    PropertyDefinition propertyDefinition = new PropertyDefinition(input);
-
-    if(propertyBL.isPropertyUsedByOperation(component, propertyDefinition)) {
-      return StorageOperationStatus.DECLARED_INPUT_USED_BY_OPERATION;
+    @Override
+    public Optional<Component> resolvePropertiesOwner(Component component, String propertiesOwnerId) {
+        return Optional.of(component);
     }
 
-    Optional<List <PropertyDefinition>> propertyToUpdateCandidate =
-            getDeclaredPropertiesByInputId(component, input.getUniqueId());
-
-    if(propertyToUpdateCandidate.isPresent()) {
-      List<PropertyDefinition> propertiesToUpdate = propertyToUpdateCandidate.get();
-      if (!propertiesToUpdate.isEmpty()) {
-        return unDeclareInputs(component, input, propertiesToUpdate);
-      }
+    @Override
+    public void addPropertiesListToInput(PropertyDataDefinition declaredProp, InputDefinition input) {
+        List<ComponentInstanceProperty> propertiesList = input.getProperties();
+        if (propertiesList == null) {
+            propertiesList = new ArrayList<>(); // adding the property with the new value for UI
+        }
+        propertiesList.add(new ComponentInstanceProperty(declaredProp));
+        input.setProperties(propertiesList);
     }
 
-    return StorageOperationStatus.OK;
-  }
-
-  private StorageOperationStatus unDeclareInputs(Component component,
-                                                 InputDefinition input,
-                                                 List <PropertyDefinition> propertiesToUpdate) {
-    for (PropertyDefinition propertyToUpdate : propertiesToUpdate) {
-      StorageOperationStatus storageOperationStatus = unDeclareInput(component, input, propertyToUpdate);
-      if (StorageOperationStatus.OK != storageOperationStatus) {
-        return storageOperationStatus;
-      }
+    @Override
+    public StorageOperationStatus unDeclarePropertiesAsInputs(Component component, InputDefinition input) {
+        PropertyDefinition propertyDefinition = new PropertyDefinition(input);
+        if (propertyBL.isPropertyUsedByOperation(component, propertyDefinition)) {
+            return StorageOperationStatus.DECLARED_INPUT_USED_BY_OPERATION;
+        }
+        Optional<PropertyDefinition> propertyToUpdateCandidate = getDeclaredPropertyByInputId(component, input.getUniqueId());
+        if (propertyToUpdateCandidate.isPresent()) {
+            PropertyDefinition propertyToUpdate = propertyToUpdateCandidate.get();
+            return unDeclareInput(component, input, propertyToUpdate);
+        }
+        return StorageOperationStatus.OK;
     }
-    return StorageOperationStatus.OK;
-  }
 
-  private StorageOperationStatus unDeclareInput(Component component,
-                                                InputDefinition input,
-                                                PropertyDefinition propertyToUpdate) {
-    prepareValueBeforeDelete(input, propertyToUpdate, Collections.emptyList());
-    propertyToUpdate.setValue(input.getDefaultValue());
-    Either<PropertyDefinition, StorageOperationStatus> status = toscaOperationFacade
-        .updatePropertyOfComponent(component, propertyToUpdate);
-    if(status.isRight()) {
-      return status.right().value();
+    @Override
+    public StorageOperationStatus unDeclarePropertiesAsListInputs(Component component, InputDefinition input) {
+        PropertyDefinition propertyDefinition = new PropertyDefinition(input);
+        if (propertyBL.isPropertyUsedByOperation(component, propertyDefinition)) {
+            return StorageOperationStatus.DECLARED_INPUT_USED_BY_OPERATION;
+        }
+        Optional<List<PropertyDefinition>> propertyToUpdateCandidate = getDeclaredPropertiesByInputId(component, input.getUniqueId());
+        if (propertyToUpdateCandidate.isPresent()) {
+            List<PropertyDefinition> propertiesToUpdate = propertyToUpdateCandidate.get();
+            if (!propertiesToUpdate.isEmpty()) {
+                return unDeclareInputs(component, input, propertiesToUpdate);
+            }
+        }
+        return StorageOperationStatus.OK;
     }
 
-    return StorageOperationStatus.OK;
-  }
-
-  private Optional<PropertyDefinition> getDeclaredPropertyByInputId(Component component, String inputId) {
-    List<PropertyDefinition> properties = component.getProperties();
-
-    if (CollectionUtils.isEmpty(properties)) {
-      return Optional.empty();
+    private StorageOperationStatus unDeclareInputs(Component component, InputDefinition input, List<PropertyDefinition> propertiesToUpdate) {
+        for (PropertyDefinition propertyToUpdate : propertiesToUpdate) {
+            StorageOperationStatus storageOperationStatus = unDeclareInput(component, input, propertyToUpdate);
+            if (StorageOperationStatus.OK != storageOperationStatus) {
+                return storageOperationStatus;
+            }
+        }
+        return StorageOperationStatus.OK;
     }
 
-    for (PropertyDefinition propertyDefinition : properties) {
-      List<GetInputValueDataDefinition> getInputValues = propertyDefinition.getGetInputValues();
-      if (CollectionUtils.isEmpty(getInputValues)) {
-        continue;
-      }
-
-      Optional<GetInputValueDataDefinition> getInputCandidate =
-              getInputValues.stream().filter(getInput -> getInput.getInputId().equals(inputId)).findAny();
-
-      if (getInputCandidate.isPresent()) {
-        return Optional.of(propertyDefinition);
-      }
+    private StorageOperationStatus unDeclareInput(Component component, InputDefinition input, PropertyDefinition propertyToUpdate) {
+        prepareValueBeforeDelete(input, propertyToUpdate, Collections.emptyList());
+        propertyToUpdate.setValue(input.getDefaultValue());
+        Either<PropertyDefinition, StorageOperationStatus> status = toscaOperationFacade.updatePropertyOfComponent(component, propertyToUpdate);
+        if (status.isRight()) {
+            return status.right().value();
+        }
+        return StorageOperationStatus.OK;
     }
 
-    return Optional.empty();
-  }
-
-  private Optional<List <PropertyDefinition>> getDeclaredPropertiesByInputId(Component component,
-                                                                    String inputId) {
-    List<PropertyDefinition> properties = component.getProperties();
-    List<PropertyDefinition> propertiesToUpdate = new ArrayList<>();
-
-    if(CollectionUtils.isEmpty(properties)) {
-      return Optional.empty();
+    private Optional<PropertyDefinition> getDeclaredPropertyByInputId(Component component, String inputId) {
+        List<PropertyDefinition> properties = component.getProperties();
+        if (CollectionUtils.isEmpty(properties)) {
+            return Optional.empty();
+        }
+        for (PropertyDefinition propertyDefinition : properties) {
+            List<GetInputValueDataDefinition> getInputValues = propertyDefinition.getGetInputValues();
+            if (CollectionUtils.isEmpty(getInputValues)) {
+                continue;
+            }
+            Optional<GetInputValueDataDefinition> getInputCandidate = getInputValues.stream()
+                .filter(getInput -> getInput.getInputId().equals(inputId)).findAny();
+            if (getInputCandidate.isPresent()) {
+                return Optional.of(propertyDefinition);
+            }
+        }
+        return Optional.empty();
     }
 
-    for(PropertyDefinition propertyDefinition : properties) {
-      List<GetInputValueDataDefinition> getInputValues = propertyDefinition.getGetInputValues();
-      if(CollectionUtils.isEmpty(getInputValues)) {
-        continue;
-      }
-
-      Optional<GetInputValueDataDefinition> getInputCandidate =
-              getInputValues.stream().filter(getInput -> getInput.getInputId().equals(inputId))
-                      .findAny();
-
-      if(getInputCandidate.isPresent()) {
-        propertiesToUpdate.add(propertyDefinition);
-      }
+    private Optional<List<PropertyDefinition>> getDeclaredPropertiesByInputId(Component component, String inputId) {
+        List<PropertyDefinition> properties = component.getProperties();
+        List<PropertyDefinition> propertiesToUpdate = new ArrayList<>();
+        if (CollectionUtils.isEmpty(properties)) {
+            return Optional.empty();
+        }
+        for (PropertyDefinition propertyDefinition : properties) {
+            List<GetInputValueDataDefinition> getInputValues = propertyDefinition.getGetInputValues();
+            if (CollectionUtils.isEmpty(getInputValues)) {
+                continue;
+            }
+            Optional<GetInputValueDataDefinition> getInputCandidate = getInputValues.stream()
+                .filter(getInput -> getInput.getInputId().equals(inputId)).findAny();
+            if (getInputCandidate.isPresent()) {
+                propertiesToUpdate.add(propertyDefinition);
+            }
+        }
+        return Optional.of(propertiesToUpdate);
     }
-
-    return Optional.of(propertiesToUpdate);
-  }
 }
index 9d65a66..575a54d 100644 (file)
@@ -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.
  * limitations under the License.
  * ============LICENSE_END=========================================================
  */
-
 package org.openecomp.sdc.be.components.property;
 
+import static org.openecomp.sdc.common.api.Constants.GET_INPUT;
+import static org.openecomp.sdc.common.api.Constants.GET_POLICY;
+
 import com.google.gson.Gson;
 import fj.data.Either;
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.Collection;
+import java.util.HashMap;
+import java.util.HashSet;
+import java.util.List;
+import java.util.Map;
+import java.util.Objects;
+import java.util.Optional;
+import java.util.Set;
+import java.util.stream.Collectors;
 import org.apache.commons.collections.CollectionUtils;
 import org.apache.commons.collections.MapUtils;
 import org.apache.commons.lang.StringUtils;
@@ -48,30 +61,16 @@ import org.openecomp.sdc.common.log.wrappers.Logger;
 import org.openecomp.sdc.exception.ResponseFormat;
 import org.yaml.snakeyaml.Yaml;
 
-import java.util.ArrayList;
-import java.util.Arrays;
-import java.util.Collection;
-import java.util.HashMap;
-import java.util.HashSet;
-import java.util.List;
-import java.util.Map;
-import java.util.Objects;
-import java.util.Optional;
-import java.util.Set;
-import java.util.stream.Collectors;
-
-import static org.openecomp.sdc.common.api.Constants.GET_INPUT;
-import static org.openecomp.sdc.common.api.Constants.GET_POLICY;
-
-public abstract class DefaultPropertyDeclarator<PROPERTYOWNER extends PropertiesOwner, PROPERTYTYPE extends PropertyDataDefinition> implements PropertyDeclarator {
+public abstract class DefaultPropertyDeclarator<PROPERTYOWNER extends PropertiesOwner, PROPERTYTYPE extends PropertyDataDefinition> implements
+    PropertyDeclarator {
 
     private static final Logger log = Logger.getLogger(DefaultPropertyDeclarator.class);
     private static final short LOOP_PROTECTION_LEVEL = 10;
     private static final String UNDERSCORE = "_";
+    private static final String GET_INPUT_INDEX = "INDEX";
     private final Gson gson = new Gson();
     private ComponentsUtils componentsUtils;
     private PropertyOperation propertyOperation;
-    private static final String GET_INPUT_INDEX = "INDEX";
 
     public DefaultPropertyDeclarator(ComponentsUtils componentsUtils, PropertyOperation propertyOperation) {
         this.componentsUtils = componentsUtils;
@@ -79,34 +78,40 @@ public abstract class DefaultPropertyDeclarator<PROPERTYOWNER extends Properties
     }
 
     @Override
-    public Either<List<InputDefinition>, StorageOperationStatus> declarePropertiesAsInputs(Component component, String propertiesOwnerId, List<ComponentInstancePropInput> propsToDeclare) {
-        log.debug("#declarePropertiesAsInputs - declaring properties as inputs for component {} from properties owner {}", component.getUniqueId(), propertiesOwnerId);
+    public Either<List<InputDefinition>, StorageOperationStatus> declarePropertiesAsInputs(Component component, String propertiesOwnerId,
+                                                                                           List<ComponentInstancePropInput> propsToDeclare) {
+        log.debug("#declarePropertiesAsInputs - declaring properties as inputs for component {} from properties owner {}", component.getUniqueId(),
+            propertiesOwnerId);
         return resolvePropertiesOwner(component, propertiesOwnerId)
-                .map(propertyOwner -> declarePropertiesAsInputs(component, propertyOwner, propsToDeclare))
-                .orElse(Either.right(onPropertiesOwnerNotFound(component.getUniqueId(), propertiesOwnerId)));
+            .map(propertyOwner -> declarePropertiesAsInputs(component, propertyOwner, propsToDeclare))
+            .orElse(Either.right(onPropertiesOwnerNotFound(component.getUniqueId(), propertiesOwnerId)));
     }
 
     protected abstract PROPERTYTYPE createDeclaredProperty(PropertyDataDefinition prop);
 
-    protected abstract Either<?, StorageOperationStatus> updatePropertiesValues(Component component, String propertiesOwnerId, List<PROPERTYTYPE> properties);
+    protected abstract Either<?, StorageOperationStatus> updatePropertiesValues(Component component, String propertiesOwnerId,
+                                                                                List<PROPERTYTYPE> properties);
 
     protected abstract Optional<PROPERTYOWNER> resolvePropertiesOwner(Component component, String propertiesOwnerId);
 
     protected abstract void addPropertiesListToInput(PROPERTYTYPE declaredProp, InputDefinition input);
 
     @Override
-    public Either<List<PolicyDefinition>, StorageOperationStatus> declarePropertiesAsPolicies(Component component,
-            String propertiesOwnerId,
-            List<ComponentInstancePropInput> propsToDeclare) {
-        log.debug("#declarePropertiesAsPolicies - declaring properties as policies for component {} from properties owner {}", component.getUniqueId(), propertiesOwnerId);
+    public Either<List<PolicyDefinition>, StorageOperationStatus> declarePropertiesAsPolicies(Component component, String propertiesOwnerId,
+                                                                                              List<ComponentInstancePropInput> propsToDeclare) {
+        log.debug("#declarePropertiesAsPolicies - declaring properties as policies for component {} from properties owner {}",
+            component.getUniqueId(), propertiesOwnerId);
         return resolvePropertiesOwner(component, propertiesOwnerId)
-                       .map(propertyOwner -> declarePropertiesAsPolicies(component, propertyOwner, propsToDeclare))
-                       .orElse(Either.right(onPropertiesOwnerNotFound(component.getUniqueId(), propertiesOwnerId)));
+            .map(propertyOwner -> declarePropertiesAsPolicies(component, propertyOwner, propsToDeclare))
+            .orElse(Either.right(onPropertiesOwnerNotFound(component.getUniqueId(), propertiesOwnerId)));
     }
 
     @Override
-    public Either<InputDefinition, StorageOperationStatus> declarePropertiesAsListInput(Component component, String propertiesOwnerId, List<ComponentInstancePropInput> propsToDeclare, InputDefinition input) {
-        log.debug("#declarePropertiesAsListInput - declaring properties as inputs for component {} from properties owner {}", component.getUniqueId(), propertiesOwnerId);
+    public Either<InputDefinition, StorageOperationStatus> declarePropertiesAsListInput(Component component, String propertiesOwnerId,
+                                                                                        List<ComponentInstancePropInput> propsToDeclare,
+                                                                                        InputDefinition input) {
+        log.debug("#declarePropertiesAsListInput - declaring properties as inputs for component {} from properties owner {}", component.getUniqueId(),
+            propertiesOwnerId);
         Optional<PROPERTYOWNER> propertyOwner = resolvePropertiesOwner(component, propertiesOwnerId);
         if (propertyOwner.isPresent()) {
             return declarePropertiesAsListInput(component, propertyOwner.get(), propsToDeclare, input);
@@ -119,11 +124,12 @@ public abstract class DefaultPropertyDeclarator<PROPERTYOWNER extends Properties
         return StorageOperationStatus.OK;
     }
 
-    private Either<List<PolicyDefinition>, StorageOperationStatus> declarePropertiesAsPolicies(Component component, PROPERTYOWNER propertiesOwner, List<ComponentInstancePropInput> propsToDeclare) {
-        PropertiesDeclarationData policyProperties = createPoliciesAndOverridePropertiesValues(propertiesOwner.getUniqueId(), propertiesOwner, propsToDeclare);
-        return updatePropertiesValues(component, propertiesOwner.getUniqueId(), policyProperties.getPropertiesToUpdate())
-                       .left()
-                       .map(updatePropsRes -> policyProperties.getPoliciesToCreate());
+    private Either<List<PolicyDefinition>, StorageOperationStatus> declarePropertiesAsPolicies(Component component, PROPERTYOWNER propertiesOwner,
+                                                                                               List<ComponentInstancePropInput> propsToDeclare) {
+        PropertiesDeclarationData policyProperties = createPoliciesAndOverridePropertiesValues(propertiesOwner.getUniqueId(), propertiesOwner,
+            propsToDeclare);
+        return updatePropertiesValues(component, propertiesOwner.getUniqueId(), policyProperties.getPropertiesToUpdate()).left()
+            .map(updatePropsRes -> policyProperties.getPoliciesToCreate());
     }
 
     private StorageOperationStatus onPropertiesOwnerNotFound(String componentId, String propertiesOwnerId) {
@@ -131,69 +137,59 @@ public abstract class DefaultPropertyDeclarator<PROPERTYOWNER extends Properties
         return StorageOperationStatus.NOT_FOUND;
     }
 
-    private Either<List<InputDefinition>, StorageOperationStatus> declarePropertiesAsInputs(Component component, PROPERTYOWNER propertiesOwner, List<ComponentInstancePropInput> propsToDeclare) {
+    private Either<List<InputDefinition>, StorageOperationStatus> declarePropertiesAsInputs(Component component, PROPERTYOWNER propertiesOwner,
+                                                                                            List<ComponentInstancePropInput> propsToDeclare) {
         PropertiesDeclarationData inputsProperties = createInputsAndOverridePropertiesValues(component, propertiesOwner, propsToDeclare);
-        return updatePropertiesValues(component, propertiesOwner.getUniqueId(), inputsProperties.getPropertiesToUpdate())
-                .left()
-                .map(updatePropsRes -> inputsProperties.getInputsToCreate());
+        return updatePropertiesValues(component, propertiesOwner.getUniqueId(), inputsProperties.getPropertiesToUpdate()).left()
+            .map(updatePropsRes -> inputsProperties.getInputsToCreate());
     }
-    private PropertiesDeclarationData createPoliciesAndOverridePropertiesValues(String componentId, PROPERTYOWNER propertiesOwner, List<ComponentInstancePropInput> propsToDeclare) {
+
+    private PropertiesDeclarationData createPoliciesAndOverridePropertiesValues(String componentId, PROPERTYOWNER propertiesOwner,
+                                                                                List<ComponentInstancePropInput> propsToDeclare) {
         List<PROPERTYTYPE> declaredProperties = new ArrayList<>();
         List<PolicyDefinition> policies = new ArrayList<>();
         propsToDeclare.forEach(property -> policies.add(declarePropertyPolicy(componentId, declaredProperties, property)));
         return new PropertiesDeclarationData(null, policies, declaredProperties);
     }
 
-    private PolicyDefinition declarePropertyPolicy(String componentId, List<PROPERTYTYPE> declaredProperties,
-            ComponentInstancePropInput propInput) {
+    private PolicyDefinition declarePropertyPolicy(String componentId, List<PROPERTYTYPE> declaredProperties, ComponentInstancePropInput propInput) {
         PropertyDataDefinition prop = resolveProperty(declaredProperties, propInput);
         propInput.setOwnerId(null);
         propInput.setParentUniqueId(null);
-
         PolicyDefinition policyDefinition = new PolicyDefinition(prop);
         policyDefinition.setUniqueId(UniqueIdBuilder.buildPolicyUniqueId(componentId, prop.getName()));
         policyDefinition.setInputPath(prop.getName());
         policyDefinition.setInstanceUniqueId(componentId);
         policyDefinition.setPropertyId(prop.getUniqueId());
-
         changePropertyValueToGetPolicy(prop, policyDefinition);
         PROPERTYTYPE declaredProperty = createDeclaredProperty(prop);
-
-
-        if(!declaredProperties.contains(declaredProperty)){
+        if (!declaredProperties.contains(declaredProperty)) {
             declaredProperties.add(declaredProperty);
         }
-
         return policyDefinition;
     }
 
     private void changePropertyValueToGetPolicy(PropertyDataDefinition prop, PolicyDefinition policyDefinition) {
         JSONObject jsonObject = new JSONObject();
-
         String origValue = Objects.isNull(prop.getValue()) ? prop.getDefaultValue() : prop.getValue();
         jsonObject.put(GET_POLICY, null);
         prop.setValue(jsonObject.toJSONString());
         policyDefinition.setValue(jsonObject.toJSONString());
-
-        if(CollectionUtils.isEmpty(prop.getGetPolicyValues())){
+        if (CollectionUtils.isEmpty(prop.getGetPolicyValues())) {
             prop.setGetPolicyValues(new ArrayList<>());
         }
         List<GetPolicyValueDataDefinition> getPolicyValues = prop.getGetPolicyValues();
-
         GetPolicyValueDataDefinition getPolicyValueDataDefinition = new GetPolicyValueDataDefinition();
         getPolicyValueDataDefinition.setPolicyId(policyDefinition.getUniqueId());
         getPolicyValueDataDefinition.setPropertyName(prop.getName());
-
         getPolicyValueDataDefinition.setOrigPropertyValue(origValue);
-
         getPolicyValues.add(getPolicyValueDataDefinition);
-
         policyDefinition.setGetPolicyValues(getPolicyValues);
-
     }
 
-
-    private Either<InputDefinition, StorageOperationStatus> declarePropertiesAsListInput(Component component, PROPERTYOWNER propertiesOwner, List<ComponentInstancePropInput> propsToDeclare, InputDefinition input) {
+    private Either<InputDefinition, StorageOperationStatus> declarePropertiesAsListInput(Component component, PROPERTYOWNER propertiesOwner,
+                                                                                         List<ComponentInstancePropInput> propsToDeclare,
+                                                                                         InputDefinition input) {
         List<PROPERTYTYPE> declaredProperties = new ArrayList<>();
         for (ComponentInstancePropInput propInput : propsToDeclare) {
             if (StringUtils.isNotEmpty(propInput.getPropertiesName()) && propInput.getInput() != null) {
@@ -202,11 +198,9 @@ public abstract class DefaultPropertyDeclarator<PROPERTYOWNER extends Properties
                 continue;
             }
             PROPERTYTYPE declaredProperty = createDeclaredProperty(propInput);
-
             JSONObject jsonObject = new JSONObject();
             jsonObject.put(GET_INPUT, Arrays.asList(input.getName(), GET_INPUT_INDEX, propInput.getName()));
             declaredProperty.setValue(jsonObject.toJSONString());
-
             GetInputValueDataDefinition getInputValueDataDefinition = new GetInputValueDataDefinition();
             getInputValueDataDefinition.setInputId(input.getUniqueId());
             getInputValueDataDefinition.setInputName(input.getName());
@@ -216,54 +210,51 @@ public abstract class DefaultPropertyDeclarator<PROPERTYOWNER extends Properties
                 declaredProperty.setGetInputValues(getInputValues);
             }
             getInputValues.add(getInputValueDataDefinition);
-
             if (!declaredProperties.contains(declaredProperty)) {
                 // Add property to the list if not contain in declareProperties.
                 declaredProperties.add(declaredProperty);
             }
         }
-        return updatePropertiesValues(component, propertiesOwner.getUniqueId(), declaredProperties)
-                .left().map(x -> input);
+        return updatePropertiesValues(component, propertiesOwner.getUniqueId(), declaredProperties).left().map(x -> input);
     }
 
-    private PropertiesDeclarationData createInputsAndOverridePropertiesValues(Component component, PROPERTYOWNER propertiesOwner, List<ComponentInstancePropInput> propsToDeclare) {
+    private PropertiesDeclarationData createInputsAndOverridePropertiesValues(Component component, PROPERTYOWNER propertiesOwner,
+                                                                              List<ComponentInstancePropInput> propsToDeclare) {
         List<PROPERTYTYPE> declaredProperties = new ArrayList<>();
         List<InputDefinition> createdInputs = propsToDeclare.stream()
-                .map(propInput -> declarePropertyInput(component, propertiesOwner, declaredProperties, propInput))
-                .collect(Collectors.toList());
+            .map(propInput -> declarePropertyInput(component, propertiesOwner, declaredProperties, propInput)).collect(Collectors.toList());
         return new PropertiesDeclarationData(createdInputs, null, declaredProperties);
     }
 
-    private InputDefinition declarePropertyInput(Component component, PROPERTYOWNER propertiesOwner, List<PROPERTYTYPE> declaredProperties, ComponentInstancePropInput propInput) {
+    private InputDefinition declarePropertyInput(Component component, PROPERTYOWNER propertiesOwner, List<PROPERTYTYPE> declaredProperties,
+                                                 ComponentInstancePropInput propInput) {
         PropertyDataDefinition prop = resolveProperty(declaredProperties, propInput);
         InputDefinition inputDefinition = createInput(component, propertiesOwner, propInput, prop);
         PROPERTYTYPE declaredProperty = createDeclaredProperty(prop);
-        if(!declaredProperties.contains(declaredProperty)){
+        if (!declaredProperties.contains(declaredProperty)) {
             declaredProperties.add(declaredProperty);
         }
         addPropertiesListToInput(declaredProperty, inputDefinition);
         return inputDefinition;
     }
 
-    private InputDefinition createInput(Component component, PROPERTYOWNER propertiesOwner,
-                                        ComponentInstancePropInput propInput, PropertyDataDefinition prop) {
+    private InputDefinition createInput(Component component, PROPERTYOWNER propertiesOwner, ComponentInstancePropInput propInput,
+                                        PropertyDataDefinition prop) {
         String generatedInputPrefix = propertiesOwner.getNormalizedName();
         if (propertiesOwner.getUniqueId().equals(propInput.getParentUniqueId())) {
             //Creating input from property create on self using add property..Do not add the prefix
             generatedInputPrefix = null;
         }
-
-        Optional<CapabilityDefinition> propertyCapability = PropertiesUtils.getPropertyCapabilityOfChildInstance(propInput
-                .getParentUniqueId(), component.getCapabilities());
+        Optional<CapabilityDefinition> propertyCapability = PropertiesUtils
+            .getPropertyCapabilityOfChildInstance(propInput.getParentUniqueId(), component.getCapabilities());
         if (propertyCapability.isPresent()) {
             String capName = propertyCapability.get().getName();
-            if(capName.contains(".")) {
+            if (capName.contains(".")) {
                 capName = capName.replaceAll("\\.", UNDERSCORE);
             }
-            generatedInputPrefix = generatedInputPrefix ==  null || generatedInputPrefix.isEmpty()?
-                    capName : generatedInputPrefix + UNDERSCORE + capName;
+            generatedInputPrefix =
+                generatedInputPrefix == null || generatedInputPrefix.isEmpty() ? capName : generatedInputPrefix + UNDERSCORE + capName;
         }
-
         String generatedInputName = generateInputName(generatedInputPrefix, propInput);
         log.debug("createInput: propOwner.uniqueId={}, propInput.parentUniqueId={}", propertiesOwner.getUniqueId(), propInput.getParentUniqueId());
         return createInputFromProperty(component.getUniqueId(), propertiesOwner, generatedInputName, propInput, prop);
@@ -272,56 +263,50 @@ public abstract class DefaultPropertyDeclarator<PROPERTYOWNER extends Properties
     private String generateInputName(String inputName, ComponentInstancePropInput propInput) {
         String declaredInputName;
         String[] parsedPropNames = propInput.getParsedPropNames();
-
-        if(parsedPropNames != null){
+        if (parsedPropNames != null) {
             declaredInputName = handleInputName(inputName, parsedPropNames);
         } else {
             String[] propName = {propInput.getName()};
             declaredInputName = handleInputName(inputName, propName);
         }
-
         return declaredInputName;
     }
 
     private String handleInputName(String inputName, String[] parsedPropNames) {
         StringBuilder prefix = new StringBuilder();
         int startingIndex;
-
-        if(Objects.isNull(inputName)) {
+        if (Objects.isNull(inputName)) {
             prefix.append(parsedPropNames[0]);
             startingIndex = 1;
         } else {
             prefix.append(inputName);
             startingIndex = 0;
         }
-
-        while(startingIndex < parsedPropNames.length){
+        while (startingIndex < parsedPropNames.length) {
             prefix.append(UNDERSCORE);
             prefix.append(parsedPropNames[startingIndex]);
-            startingIndex ++;
+            startingIndex++;
         }
-
         return prefix.toString();
     }
 
     private PropertyDataDefinition resolveProperty(List<PROPERTYTYPE> propertiesToCreate, ComponentInstancePropInput propInput) {
-        Optional<PROPERTYTYPE> resolvedProperty = propertiesToCreate.stream()
-                .filter(p -> p.getName().equals(propInput.getName()))
-                .findFirst();
+        Optional<PROPERTYTYPE> resolvedProperty = propertiesToCreate.stream().filter(p -> p.getName().equals(propInput.getName())).findFirst();
         return resolvedProperty.isPresent() ? resolvedProperty.get() : propInput;
     }
 
-    InputDefinition createInputFromProperty(String componentId, PROPERTYOWNER propertiesOwner, String inputName, ComponentInstancePropInput propInput, PropertyDataDefinition prop) {
-        String propertiesName = propInput.getPropertiesName() ;
+    InputDefinition createInputFromProperty(String componentId, PROPERTYOWNER propertiesOwner, String inputName, ComponentInstancePropInput propInput,
+                                            PropertyDataDefinition prop) {
+        String propertiesName = propInput.getPropertiesName();
         PropertyDefinition selectedProp = propInput.getInput();
         String[] parsedPropNames = propInput.getParsedPropNames();
         InputDefinition input;
         boolean complexProperty = false;
-        if(propertiesName != null && !propertiesName.isEmpty() && selectedProp != null){
+        if (propertiesName != null && !propertiesName.isEmpty() && selectedProp != null) {
             complexProperty = true;
             input = new InputDefinition(selectedProp);
             input.setDefaultValue(selectedProp.getValue());
-        }else{
+        } else {
             input = new InputDefinition(prop);
             input.setDefaultValue(prop.getValue());
         }
@@ -330,172 +315,125 @@ public abstract class DefaultPropertyDeclarator<PROPERTYOWNER extends Properties
         input.setInputPath(propertiesName);
         input.setInstanceUniqueId(propertiesOwner.getUniqueId());
         input.setPropertyId(propInput.getUniqueId());
-               if (Objects.isNull(input.getSubPropertyInputPath())
-                               || (Objects.nonNull(propertiesName)
-                               && input.getSubPropertyInputPath().substring(input.getSubPropertyInputPath().lastIndexOf('#'))
-                               .equals(propertiesName.substring(propertiesName.lastIndexOf('#'))))) {
-                       input.setParentPropertyType(propInput.getType());
-                       input.setSubPropertyInputPath(propertiesName);
-               }
-
+        if (Objects.isNull(input.getSubPropertyInputPath()) || (Objects.nonNull(propertiesName) && input.getSubPropertyInputPath()
+            .substring(input.getSubPropertyInputPath().lastIndexOf('#')).equals(propertiesName.substring(propertiesName.lastIndexOf('#'))))) {
+            input.setParentPropertyType(propInput.getType());
+            input.setSubPropertyInputPath(propertiesName);
+        }
         changePropertyValueToGetInputValue(inputName, parsedPropNames, input, prop, complexProperty);
-
-        if(prop instanceof IComponentInstanceConnectedElement) {
-            ((IComponentInstanceConnectedElement) prop)
-                .setComponentInstanceId(propertiesOwner.getUniqueId());
-            ((IComponentInstanceConnectedElement) prop)
-                .setComponentInstanceName(propertiesOwner.getName());
+        if (prop instanceof IComponentInstanceConnectedElement) {
+            ((IComponentInstanceConnectedElement) prop).setComponentInstanceId(propertiesOwner.getUniqueId());
+            ((IComponentInstanceConnectedElement) prop).setComponentInstanceName(propertiesOwner.getName());
         }
         return input;
     }
 
-    private void changePropertyValueToGetInputValue(String inputName, String[] parsedPropNames, InputDefinition input, PropertyDataDefinition prop, boolean complexProperty) {
+    private void changePropertyValueToGetInputValue(String inputName, String[] parsedPropNames, InputDefinition input, PropertyDataDefinition prop,
+                                                    boolean complexProperty) {
         JSONObject jsonObject = new JSONObject();
         String value = prop.getValue();
-        if(value == null || value.isEmpty()){
-            if(complexProperty){
-
-                jsonObject = createJSONValueForProperty(parsedPropNames.length -1, parsedPropNames, jsonObject, inputName);
+        if (value == null || value.isEmpty()) {
+            if (complexProperty) {
+                jsonObject = createJSONValueForProperty(parsedPropNames.length - 1, parsedPropNames, jsonObject, inputName);
                 prop.setValue(jsonObject.toJSONString());
-
-            }else{
-
+            } else {
                 jsonObject.put(GET_INPUT, input.getName());
                 prop.setValue(jsonObject.toJSONString());
-
             }
-
-        }else{
-
-            Object objValue =  new Yaml().load(value);
-            if( objValue instanceof Map || objValue  instanceof List){
-                if(!complexProperty){
+        } else {
+            Object objValue = new Yaml().load(value);
+            if (objValue instanceof Map || objValue instanceof List) {
+                if (!complexProperty) {
                     jsonObject.put(GET_INPUT, input.getName());
                     prop.setValue(jsonObject.toJSONString());
-
-
-                }else{
+                } else {
                     Map<String, Object> mappedToscaTemplate = (Map<String, Object>) objValue;
                     createInputValue(mappedToscaTemplate, 1, parsedPropNames, inputName);
-
                     String json = gson.toJson(mappedToscaTemplate);
                     prop.setValue(json);
-
                 }
-
-            }else{
+            } else {
                 jsonObject.put(GET_INPUT, input.getName());
                 prop.setValue(jsonObject.toJSONString());
-
             }
-
         }
-
-        if(CollectionUtils.isEmpty(prop.getGetInputValues())){
+        if (CollectionUtils.isEmpty(prop.getGetInputValues())) {
             prop.setGetInputValues(new ArrayList<>());
         }
         List<GetInputValueDataDefinition> getInputValues = prop.getGetInputValues();
-
         GetInputValueDataDefinition getInputValueDataDefinition = new GetInputValueDataDefinition();
         getInputValueDataDefinition.setInputId(input.getUniqueId());
         getInputValueDataDefinition.setInputName(input.getName());
         getInputValues.add(getInputValueDataDefinition);
     }
 
-    private  JSONObject createJSONValueForProperty (int i, String [] parsedPropNames, JSONObject ooj, String inputName){
-
-        while(i >= 1){
-            if( i == parsedPropNames.length -1){
+    private JSONObject createJSONValueForProperty(int i, String[] parsedPropNames, JSONObject ooj, String inputName) {
+        while (i >= 1) {
+            if (i == parsedPropNames.length - 1) {
                 JSONObject jobProp = new JSONObject();
                 jobProp.put(GET_INPUT, inputName);
                 ooj.put(parsedPropNames[i], jobProp);
                 i--;
-                return createJSONValueForProperty (i, parsedPropNames, ooj, inputName);
-            }else{
+                return createJSONValueForProperty(i, parsedPropNames, ooj, inputName);
+            } else {
                 JSONObject res = new JSONObject();
                 res.put(parsedPropNames[i], ooj);
-                i --;
-                res =  createJSONValueForProperty (i, parsedPropNames, res, inputName);
+                i--;
+                res = createJSONValueForProperty(i, parsedPropNames, res, inputName);
                 return res;
             }
         }
-
         return ooj;
     }
 
-    private  Map<String, Object> createInputValue(Map<String, Object> lhm1, int index, String[] inputNames, String inputName){
-        while(index < inputNames.length){
-            if(lhm1.containsKey(inputNames[index])){
+    private Map<String, Object> createInputValue(Map<String, Object> lhm1, int index, String[] inputNames, String inputName) {
+        while (index < inputNames.length) {
+            if (lhm1.containsKey(inputNames[index])) {
                 Object value = lhm1.get(inputNames[index]);
-                if (value instanceof Map){
-                    if(index == inputNames.length -1){
+                if (value instanceof Map) {
+                    if (index == inputNames.length - 1) {
                         ((Map) value).put(GET_INPUT, inputName);
                         return (Map) value;
-
-                    }else{
+                    } else {
                         index++;
-                        return  createInputValue((Map)value, index, inputNames, inputName);
+                        return createInputValue((Map) value, index, inputNames, inputName);
                     }
-                }else{
+                } else {
                     Map<String, Object> jobProp = new HashMap<>();
-                    if(index == inputNames.length -1){
+                    if (index == inputNames.length - 1) {
                         jobProp.put(GET_INPUT, inputName);
                         lhm1.put(inputNames[index], jobProp);
                         return lhm1;
-                    }else{
+                    } else {
                         lhm1.put(inputNames[index], jobProp);
                         index++;
-                        return  createInputValue(jobProp, index, inputNames, inputName);
+                        return createInputValue(jobProp, index, inputNames, inputName);
                     }
                 }
-            }else{
+            } else {
                 Map<String, Object> jobProp = new HashMap<>();
                 lhm1.put(inputNames[index], jobProp);
-                if(index == inputNames.length -1){
+                if (index == inputNames.length - 1) {
                     jobProp.put(GET_INPUT, inputName);
                     return jobProp;
-                }else{
+                } else {
                     index++;
-                    return  createInputValue(jobProp, index, inputNames, inputName);
+                    return createInputValue(jobProp, index, inputNames, inputName);
                 }
             }
         }
         return lhm1;
     }
 
-    private class PropertiesDeclarationData {
-        private List<InputDefinition> inputsToCreate;
-        private List<PolicyDefinition> policiesToCreate;
-        private List<PROPERTYTYPE> propertiesToUpdate;
-
-        PropertiesDeclarationData(List<InputDefinition> inputsToCreate, List<PolicyDefinition> policiesToCreate, List<PROPERTYTYPE> propertiesToUpdate) {
-            this.inputsToCreate = inputsToCreate;
-            this.policiesToCreate = policiesToCreate;
-            this.propertiesToUpdate = propertiesToUpdate;
-        }
-
-        List<InputDefinition> getInputsToCreate() {
-            return inputsToCreate;
-        }
-
-        public List<PolicyDefinition> getPoliciesToCreate() { return policiesToCreate; }
-
-        List<PROPERTYTYPE> getPropertiesToUpdate() {
-            return propertiesToUpdate;
-        }
-    }
-
-    Either<InputDefinition, ResponseFormat>  prepareValueBeforeDelete(InputDefinition inputForDelete, PropertyDataDefinition inputValue, List<String> pathOfComponentInstances) {
+    Either<InputDefinition, ResponseFormat> prepareValueBeforeDelete(InputDefinition inputForDelete, PropertyDataDefinition inputValue,
+                                                                     List<String> pathOfComponentInstances) {
         Either<InputDefinition, ResponseFormat> deleteEither = prepareValueBeforeDelete(inputForDelete, inputValue);
-
         Either<String, JanusGraphOperationStatus> findDefaultValue = propertyOperation
-            .findDefaultValueFromSecondPosition(pathOfComponentInstances, inputValue.getUniqueId(),
-                (String) inputValue.getDefaultValue());
+            .findDefaultValueFromSecondPosition(pathOfComponentInstances, inputValue.getUniqueId(), (String) inputValue.getDefaultValue());
         if (findDefaultValue.isRight()) {
             deleteEither = Either.right(componentsUtils.getResponseFormat(componentsUtils
                 .convertFromStorageResponse(DaoStatusConverter.convertJanusGraphStatusToStorageStatus(findDefaultValue.right().value()))));
             return deleteEither;
-
         }
         String defaultValue = findDefaultValue.left().value();
         inputValue.setDefaultValue(defaultValue);
@@ -503,22 +441,18 @@ public abstract class DefaultPropertyDeclarator<PROPERTYOWNER extends Properties
         return deleteEither;
     }
 
-    Either<InputDefinition, ResponseFormat>  prepareValueBeforeDeleteOfCapProp(InputDefinition inputForDelete,
-                                                                               PropertyDataDefinition inputValue) {
+    Either<InputDefinition, ResponseFormat> prepareValueBeforeDeleteOfCapProp(InputDefinition inputForDelete, PropertyDataDefinition inputValue) {
         Either<InputDefinition, ResponseFormat> deleteEither = prepareValueBeforeDelete(inputForDelete, inputValue);
         inputValue.setDefaultValue(inputForDelete.getDefaultValue());
         log.debug("The returned default value in ResourceInstanceProperty is {}", inputForDelete.getDefaultValue());
         return deleteEither;
     }
 
-    private Either<InputDefinition, ResponseFormat> prepareValueBeforeDelete(InputDefinition inputForDelete,
-                                                                             PropertyDataDefinition inputValue) {
+    private Either<InputDefinition, ResponseFormat> prepareValueBeforeDelete(InputDefinition inputForDelete, PropertyDataDefinition inputValue) {
         Either<InputDefinition, ResponseFormat> deleteEither = Either.left(inputForDelete);
         String value = inputValue.getValue();
         Map<String, Object> mappedToscaTemplate = (Map<String, Object>) new Yaml().load(value);
-
         resetInputName(mappedToscaTemplate, inputForDelete.getName());
-
         value = "";
         if (!mappedToscaTemplate.isEmpty()) {
             Either result = cleanNestedMap(mappedToscaTemplate, true);
@@ -527,32 +461,29 @@ public abstract class DefaultPropertyDeclarator<PROPERTYOWNER extends Properties
                 modifiedMappedToscaTemplate = (Map) result.left().value();
             } else {
                 log.warn("Map cleanup failed -> " + result.right().value()
-                        .toString());    //continue, don't break operation
+                    .toString());    //continue, don't break operation
             }
             value = gson.toJson(modifiedMappedToscaTemplate);
         }
         inputValue.setValue(value);
-
-
         List<GetInputValueDataDefinition> getInputsValues = inputValue.getGetInputValues();
         if (getInputsValues != null && !getInputsValues.isEmpty()) {
-            Optional<GetInputValueDataDefinition> op =
-                    getInputsValues.stream().filter(gi -> gi.getInputId().equals(inputForDelete.getUniqueId()))
-                            .findAny();
+            Optional<GetInputValueDataDefinition> op = getInputsValues.stream().filter(gi -> gi.getInputId().equals(inputForDelete.getUniqueId()))
+                .findAny();
             op.ifPresent(getInputsValues::remove);
         }
         inputValue.setGetInputValues(getInputsValues);
         return deleteEither;
     }
 
-    private void resetInputName(Map<String, Object> lhm1, String inputName){
+    private void resetInputName(Map<String, Object> lhm1, String inputName) {
         for (Map.Entry<String, Object> entry : lhm1.entrySet()) {
             String key = entry.getKey();
             Object value = entry.getValue();
             if (value instanceof String && ((String) value).equalsIgnoreCase(inputName) && key.equals(GET_INPUT)) {
                 lhm1.remove(key);
             } else if (value instanceof Map) {
-                Map<String, Object> subMap = (Map<String, Object>)value;
+                Map<String, Object> subMap = (Map<String, Object>) value;
                 resetInputName(subMap, inputName);
             } else if (value instanceof List && ((List) value).contains(inputName) && key.equals(GET_INPUT)) {
                 lhm1.remove(key);
@@ -560,17 +491,17 @@ public abstract class DefaultPropertyDeclarator<PROPERTYOWNER extends Properties
         }
     }
 
-    private Either cleanNestedMap( Map mappedToscaTemplate , boolean deepClone  ){
-        if (MapUtils.isNotEmpty( mappedToscaTemplate ) ){
-            if (deepClone){
-                if (!(mappedToscaTemplate instanceof HashMap))
-                    return Either.right("expecting mappedToscaTemplate as HashMap ,recieved "+ mappedToscaTemplate.getClass().getSimpleName() );
-                else
-                    mappedToscaTemplate = (HashMap)((HashMap) mappedToscaTemplate).clone();
+    private Either cleanNestedMap(Map mappedToscaTemplate, boolean deepClone) {
+        if (MapUtils.isNotEmpty(mappedToscaTemplate)) {
+            if (deepClone) {
+                if (!(mappedToscaTemplate instanceof HashMap)) {
+                    return Either.right("expecting mappedToscaTemplate as HashMap ,recieved " + mappedToscaTemplate.getClass().getSimpleName());
+                } else {
+                    mappedToscaTemplate = (HashMap) ((HashMap) mappedToscaTemplate).clone();
+                }
             }
-            return Either.left( (Map) cleanEmptyNestedValuesInMap( mappedToscaTemplate , LOOP_PROTECTION_LEVEL ) );
-        }
-        else {
+            return Either.left((Map) cleanEmptyNestedValuesInMap(mappedToscaTemplate, LOOP_PROTECTION_LEVEL));
+        } else {
             log.debug("mappedToscaTemplate is empty ");
             return Either.right("mappedToscaTemplate is empty ");
         }
@@ -583,43 +514,44 @@ public abstract class DefaultPropertyDeclarator<PROPERTYOWNER extends Properties
      *        @param  toscaElement - expected map of tosca values
      *        @return mutated @param toscaElement , where empty maps are deleted , return null for empty map.
      **/
-    private Object cleanEmptyNestedValuesInMap(Object toscaElement , short loopProtectionLevel ){
-        if (loopProtectionLevel<=0 || toscaElement==null || !(toscaElement instanceof  Map))
+    private Object cleanEmptyNestedValuesInMap(Object toscaElement, short loopProtectionLevel) {
+        if (loopProtectionLevel <= 0 || toscaElement == null || !(toscaElement instanceof Map)) {
             return toscaElement;
-        if ( MapUtils.isNotEmpty( (Map)toscaElement ) ) {
+        }
+        if (MapUtils.isNotEmpty((Map) toscaElement)) {
             Object ret;
             Set<Object> keysToRemove = new HashSet<>();                                                                 // use different set to avoid ConcurrentModificationException
-            for( Object key : ((Map)toscaElement).keySet() ) {
+            for (Object key : ((Map) toscaElement).keySet()) {
                 Object value = ((Map) toscaElement).get(key);
-                ret = cleanEmptyNestedValuesInMap(value , --loopProtectionLevel );
-                if ( ret == null )
+                ret = cleanEmptyNestedValuesInMap(value, --loopProtectionLevel);
+                if (ret == null) {
                     keysToRemove.add(key);
+                }
             }
             Collection set = ((Map) toscaElement).keySet();
-            if (CollectionUtils.isNotEmpty(set))
+            if (CollectionUtils.isNotEmpty(set)) {
                 set.removeAll(keysToRemove);
-
-            if ( isEmptyNestedMap(toscaElement) )
+            }
+            if (isEmptyNestedMap(toscaElement)) {
                 return null;
-        }
-        else
+            }
+        } else {
             return null;
+        }
         return toscaElement;
     }
 
-    //@returns true iff map nested maps are all empty
     //ignores other collection objects
-    private boolean isEmptyNestedMap(Object element){
+    private boolean isEmptyNestedMap(Object element) {
         boolean isEmpty = true;
-        if (element != null){
-            if ( element instanceof Map ){
-                if (MapUtils.isEmpty((Map)element))
+        if (element != null) {
+            if (element instanceof Map) {
+                if (MapUtils.isEmpty((Map) element)) {
                     isEmpty = true;
-                else
-                {
-                    for( Object key : ((Map)(element)).keySet() ){
-                        Object value =  ((Map)(element)).get(key);
-                        isEmpty &= isEmptyNestedMap( value );
+                } else {
+                    for (Object key : ((Map) (element)).keySet()) {
+                        Object value = ((Map) (element)).get(key);
+                        isEmpty &= isEmptyNestedMap(value);
                     }
                 }
             } else {
@@ -628,5 +560,31 @@ public abstract class DefaultPropertyDeclarator<PROPERTYOWNER extends Properties
         }
         return isEmpty;
     }
+    //@returns true iff map nested maps are all empty
+
+    private class PropertiesDeclarationData {
+
+        private List<InputDefinition> inputsToCreate;
+        private List<PolicyDefinition> policiesToCreate;
+        private List<PROPERTYTYPE> propertiesToUpdate;
+
+        PropertiesDeclarationData(List<InputDefinition> inputsToCreate, List<PolicyDefinition> policiesToCreate,
+                                  List<PROPERTYTYPE> propertiesToUpdate) {
+            this.inputsToCreate = inputsToCreate;
+            this.policiesToCreate = policiesToCreate;
+            this.propertiesToUpdate = propertiesToUpdate;
+        }
+
+        List<InputDefinition> getInputsToCreate() {
+            return inputsToCreate;
+        }
+
+        public List<PolicyDefinition> getPoliciesToCreate() {
+            return policiesToCreate;
+        }
 
+        List<PROPERTYTYPE> getPropertiesToUpdate() {
+            return propertiesToUpdate;
+        }
+    }
 }
index 875321e..42a9053 100644 (file)
@@ -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.
@@ -17,7 +17,6 @@
  * limitations under the License.
  * ============LICENSE_END=========================================================
  */
-
 package org.openecomp.sdc.be.components.property;
 
 import org.openecomp.sdc.be.datatypes.elements.GetInputValueDataDefinition;
@@ -28,6 +27,7 @@ public class GetInputUtils {
     }
 
     public static boolean isGetInputValueForInput(GetInputValueDataDefinition inputData, String inputId) {
-        return inputData.getInputId().equals(inputId) || (inputData.getGetInputIndex() != null && inputData.getGetInputIndex().getInputId().equals(inputId));
+        return inputData.getInputId().equals(inputId) || (inputData.getGetInputIndex() != null && inputData.getGetInputIndex().getInputId()
+            .equals(inputId));
     }
 }
index b27cbee..2700c80 100644 (file)
  * limitations under the License.
  * ============LICENSE_END=========================================================
  */
-
 package org.openecomp.sdc.be.components.property;
 
+import static java.util.stream.Collectors.toList;
+import static org.apache.commons.collections.CollectionUtils.isEmpty;
+import static org.openecomp.sdc.be.components.property.GetInputUtils.isGetInputValueForInput;
+
 import fj.data.Either;
+import java.util.ArrayList;
+import java.util.Collections;
+import java.util.List;
+import java.util.Objects;
+import java.util.Optional;
 import org.apache.commons.collections.CollectionUtils;
 import org.openecomp.sdc.be.datatypes.elements.PropertyDataDefinition;
 import org.openecomp.sdc.be.impl.ComponentsUtils;
@@ -33,16 +41,6 @@ import org.openecomp.sdc.be.model.operations.impl.GroupOperation;
 import org.openecomp.sdc.be.model.operations.impl.PropertyOperation;
 import org.openecomp.sdc.common.log.wrappers.Logger;
 
-import java.util.ArrayList;
-import java.util.Collections;
-import java.util.List;
-import java.util.Objects;
-import java.util.Optional;
-
-import static java.util.stream.Collectors.toList;
-import static org.apache.commons.collections.CollectionUtils.isEmpty;
-import static org.openecomp.sdc.be.components.property.GetInputUtils.isGetInputValueForInput;
-
 @org.springframework.stereotype.Component
 public class GroupPropertyDeclarator extends DefaultPropertyDeclarator<GroupDefinition, PropertyDataDefinition> {
 
@@ -75,26 +73,23 @@ public class GroupPropertyDeclarator extends DefaultPropertyDeclarator<GroupDefi
     @Override
     public void addPropertiesListToInput(PropertyDataDefinition declaredProp, InputDefinition input) {
         List<ComponentInstanceProperty> propertiesList = input.getProperties();
-        if(propertiesList == null) {
+        if (propertiesList == null) {
             propertiesList = new ArrayList<>(); // adding the property with the new value for UI
         }
         propertiesList.add(new ComponentInstanceProperty(declaredProp));
         input.setProperties(propertiesList);
-
     }
 
     @Override
     public StorageOperationStatus unDeclarePropertiesAsInputs(Component component, InputDefinition inputForDelete) {
         return getGroupPropertiesDeclaredAsInput(component, inputForDelete.getUniqueId())
-                .map(groupProperties -> unDeclareGroupProperties(component, inputForDelete, groupProperties))
-                .orElse(StorageOperationStatus.OK);
+            .map(groupProperties -> unDeclareGroupProperties(component, inputForDelete, groupProperties)).orElse(StorageOperationStatus.OK);
     }
 
     @Override
     public StorageOperationStatus unDeclarePropertiesAsListInputs(Component component, InputDefinition inputForDelete) {
         return getGroupPropertiesDeclaredAsInput(component, inputForDelete.getUniqueId())
-                .map(groupProperties -> unDeclareGroupProperties(component, inputForDelete, groupProperties))
-                .orElse(StorageOperationStatus.OK);
+            .map(groupProperties -> unDeclareGroupProperties(component, inputForDelete, groupProperties)).orElse(StorageOperationStatus.OK);
     }
 
     private StorageOperationStatus unDeclareGroupProperties(Component container, InputDefinition input, GroupProperties groupProperties) {
@@ -108,20 +103,13 @@ public class GroupPropertyDeclarator extends DefaultPropertyDeclarator<GroupDefi
         if (container.getGroups() == null) {
             return Optional.empty();
         }
-        return container.getGroups()
-                .stream()
-                .filter(group -> Objects.nonNull(group.getProperties()))
-                .map(grp -> getGroupPropertiesDeclaredAsInput(grp, inputId))
-                .filter(GroupProperties::isNotEmpty)
-                .findFirst();
+        return container.getGroups().stream().filter(group -> Objects.nonNull(group.getProperties()))
+            .map(grp -> getGroupPropertiesDeclaredAsInput(grp, inputId)).filter(GroupProperties::isNotEmpty).findFirst();
     }
 
-
     private GroupProperties getGroupPropertiesDeclaredAsInput(GroupDefinition group, String inputId) {
-        List<PropertyDataDefinition> propertyDataDefinitions = group.getProperties()
-                .stream()
-                .filter(prop -> isPropertyDeclaredAsInputByInputId(prop, inputId))
-                .collect(toList());
+        List<PropertyDataDefinition> propertyDataDefinitions = group.getProperties().stream()
+            .filter(prop -> isPropertyDeclaredAsInputByInputId(prop, inputId)).collect(toList());
         return new GroupProperties(group.getUniqueId(), propertyDataDefinitions);
     }
 
@@ -129,19 +117,17 @@ public class GroupPropertyDeclarator extends DefaultPropertyDeclarator<GroupDefi
         if (isEmpty(property.getGetInputValues())) {
             return false;
         }
-        return property.getGetInputValues().stream()
-                .filter(Objects::nonNull)
-                .anyMatch(getInputVal -> isGetInputValueForInput(getInputVal, inputId));
+        return property.getGetInputValues().stream().filter(Objects::nonNull).anyMatch(getInputVal -> isGetInputValueForInput(getInputVal, inputId));
     }
 
-
     private class GroupProperties {
+
         private String groupId;
         private List<PropertyDataDefinition> properties;
 
         GroupProperties(String groupId, List<PropertyDataDefinition> properties) {
             this.groupId = groupId;
-            this.properties = (properties == null)? null :new ArrayList<>(properties);
+            this.properties = (properties == null) ? null : new ArrayList<>(properties);
         }
 
         String getGroupId() {
index eb7dd68..0d07fad 100644 (file)
  */
 package org.openecomp.sdc.be.components.property;
 
+import static org.openecomp.sdc.be.components.property.GetInputUtils.isGetInputValueForInput;
+
 import fj.data.Either;
+import java.util.ArrayList;
+import java.util.Collections;
+import java.util.List;
+import java.util.Objects;
+import java.util.Optional;
+import java.util.stream.Collectors;
 import org.apache.commons.collections.CollectionUtils;
 import org.openecomp.sdc.be.datatypes.elements.PropertyDataDefinition;
 import org.openecomp.sdc.be.impl.ComponentsUtils;
@@ -32,15 +40,6 @@ import org.openecomp.sdc.be.model.operations.api.StorageOperationStatus;
 import org.openecomp.sdc.be.model.operations.impl.PropertyOperation;
 import org.openecomp.sdc.common.log.wrappers.Logger;
 
-import java.util.ArrayList;
-import java.util.Collections;
-import java.util.List;
-import java.util.Objects;
-import java.util.Optional;
-import java.util.stream.Collectors;
-
-import static org.openecomp.sdc.be.components.property.GetInputUtils.isGetInputValueForInput;
-
 @org.springframework.stereotype.Component
 public class PolicyPropertyDeclarator extends DefaultPropertyDeclarator<PolicyDefinition, PropertyDataDefinition> {
 
@@ -73,26 +72,23 @@ public class PolicyPropertyDeclarator extends DefaultPropertyDeclarator<PolicyDe
     @Override
     public void addPropertiesListToInput(PropertyDataDefinition declaredProp, InputDefinition input) {
         List<ComponentInstanceProperty> propertiesList = input.getProperties();
-        if(propertiesList == null) {
+        if (propertiesList == null) {
             propertiesList = new ArrayList<>(); // adding the property with the new value for UI
         }
         propertiesList.add(new ComponentInstanceProperty(declaredProp));
         input.setProperties(propertiesList);
-
     }
 
     @Override
     public StorageOperationStatus unDeclarePropertiesAsInputs(Component component, InputDefinition inputForDelete) {
         return getPolicyPropertiesDeclaredAsInput(component, inputForDelete.getUniqueId())
-                .map(policyProperties -> unDeclarePolicyProperties(component, inputForDelete, policyProperties))
-                .orElse(StorageOperationStatus.OK);
+            .map(policyProperties -> unDeclarePolicyProperties(component, inputForDelete, policyProperties)).orElse(StorageOperationStatus.OK);
     }
 
     @Override
     public StorageOperationStatus unDeclarePropertiesAsListInputs(Component component, InputDefinition inputForDelete) {
         return getPolicyPropertiesDeclaredAsInput(component, inputForDelete.getUniqueId())
-                .map(policyProperties -> unDeclarePolicyProperties(component, inputForDelete, policyProperties))
-                .orElse(StorageOperationStatus.OK);
+            .map(policyProperties -> unDeclarePolicyProperties(component, inputForDelete, policyProperties)).orElse(StorageOperationStatus.OK);
     }
 
     private StorageOperationStatus unDeclarePolicyProperties(Component container, InputDefinition input, PolicyProperties policyProperties) {
@@ -106,40 +102,31 @@ public class PolicyPropertyDeclarator extends DefaultPropertyDeclarator<PolicyDe
         if (container.getPolicies() == null) {
             return Optional.empty();
         }
-        return container.getPolicies()
-                .values()
-                .stream()
-                .filter(policy -> Objects.nonNull(policy.getProperties()))
-                .map(policy -> getPolicyPropertiesDeclaredAsInput(policy, inputId))
-                .filter(PolicyProperties::isNotEmpty)
-                .findFirst();
+        return container.getPolicies().values().stream().filter(policy -> Objects.nonNull(policy.getProperties()))
+            .map(policy -> getPolicyPropertiesDeclaredAsInput(policy, inputId)).filter(PolicyProperties::isNotEmpty).findFirst();
     }
 
     private boolean isPropertyDeclaredAsInputByInputId(PropertyDataDefinition property, String inputId) {
         if (CollectionUtils.isEmpty(property.getGetInputValues())) {
             return false;
         }
-        return property.getGetInputValues().stream()
-                .filter(Objects::nonNull)
-                .anyMatch(getInputVal -> isGetInputValueForInput(getInputVal, inputId));
+        return property.getGetInputValues().stream().filter(Objects::nonNull).anyMatch(getInputVal -> isGetInputValueForInput(getInputVal, inputId));
     }
 
     private PolicyProperties getPolicyPropertiesDeclaredAsInput(PolicyDefinition policy, String inputId) {
-        List<PropertyDataDefinition> collect = policy.getProperties()
-                .stream()
-                .filter(prop -> isPropertyDeclaredAsInputByInputId(prop, inputId))
-                .collect(Collectors.toList());
+        List<PropertyDataDefinition> collect = policy.getProperties().stream().filter(prop -> isPropertyDeclaredAsInputByInputId(prop, inputId))
+            .collect(Collectors.toList());
         return new PolicyProperties(policy.getUniqueId(), collect);
-
     }
 
     private class PolicyProperties {
+
         private String policyId;
         private List<PropertyDataDefinition> properties;
 
         PolicyProperties(String policyId, List<PropertyDataDefinition> properties) {
             this.policyId = policyId;
-            this.properties = (properties == null)? null : new ArrayList<>(properties);
+            this.properties = (properties == null) ? null : new ArrayList<>(properties);
         }
 
         String getPolicyId() {
index 85370d2..bd21876 100644 (file)
  * limitations under the License.
  * ============LICENSE_END=========================================================
  */
-
 package org.openecomp.sdc.be.components.property;
 
+import static java.util.Objects.nonNull;
+import static java.util.stream.Collectors.toMap;
+
+import java.util.List;
+import java.util.Map;
 import org.openecomp.sdc.be.components.impl.exceptions.ByActionStatusComponentException;
 import org.openecomp.sdc.be.model.PropertyConstraint;
 import org.openecomp.sdc.be.model.PropertyDefinition;
@@ -27,41 +31,28 @@ import org.openecomp.sdc.be.model.Resource;
 import org.openecomp.sdc.be.model.tosca.constraints.ConstraintType;
 import org.openecomp.sdc.be.model.tosca.constraints.exception.PropertyConstraintException;
 
-import java.util.List;
-import java.util.Map;
-
-import static java.util.Objects.nonNull;
-import static java.util.stream.Collectors.toMap;
-
 /**
  * Provides specific functionality for property constraints
  */
 public class PropertyConstraintsUtils {
 
-    private PropertyConstraintsUtils(){}
+    private PropertyConstraintsUtils() {
+    }
 
     public static void validatePropertiesConstraints(Resource newResource, Resource oldResource) {
-        if(oldResource.getProperties() != null && newResource.getProperties() != null){
-            Map<String, PropertyDefinition> oldPropWithConstraints = oldResource.getProperties()
-                    .stream()
-                    .filter(p -> p.getConstraints() != null)
-                    .collect(toMap(PropertyDefinition::getName,p -> p));
-
-            newResource.getProperties()
-                    .stream()
-                    .filter(p -> p.getConstraints() != null && oldPropWithConstraints.containsKey(p.getName()))
-                    .forEach(p -> validatePropertyConstraints(p.getConstraints(), oldPropWithConstraints.get(p.getName()).getConstraints()));
+        if (oldResource.getProperties() != null && newResource.getProperties() != null) {
+            Map<String, PropertyDefinition> oldPropWithConstraints = oldResource.getProperties().stream().filter(p -> p.getConstraints() != null)
+                .collect(toMap(PropertyDefinition::getName, p -> p));
+            newResource.getProperties().stream().filter(p -> p.getConstraints() != null && oldPropWithConstraints.containsKey(p.getName()))
+                .forEach(p -> validatePropertyConstraints(p.getConstraints(), oldPropWithConstraints.get(p.getName()).getConstraints()));
         }
     }
 
     private static void validatePropertyConstraints(List<PropertyConstraint> newConstraints, List<PropertyConstraint> oldConstraints) {
-        Map <ConstraintType, PropertyConstraint> oldConstraintsByType = oldConstraints.stream()
-                .filter(c -> nonNull(c) && nonNull(c.getConstraintType()))
-                .collect(toMap(PropertyConstraint::getConstraintType, c -> c));
-
-        newConstraints.stream()
-                .filter(c -> nonNull(c) && oldConstraintsByType.containsKey(c.getConstraintType()))
-                .forEach(c -> validatePropertyConstraint(c, oldConstraintsByType.get(c.getConstraintType())));
+        Map<ConstraintType, PropertyConstraint> oldConstraintsByType = oldConstraints.stream()
+            .filter(c -> nonNull(c) && nonNull(c.getConstraintType())).collect(toMap(PropertyConstraint::getConstraintType, c -> c));
+        newConstraints.stream().filter(c -> nonNull(c) && oldConstraintsByType.containsKey(c.getConstraintType()))
+            .forEach(c -> validatePropertyConstraint(c, oldConstraintsByType.get(c.getConstraintType())));
     }
 
     private static void validatePropertyConstraint(PropertyConstraint newConstraint, PropertyConstraint currConstraint) {
@@ -71,5 +62,4 @@ public class PropertyConstraintsUtils {
             throw new ByActionStatusComponentException(e.getActionStatus(), e.getParams());
         }
     }
-
 }
index a0d499d..e5367c4 100644 (file)
@@ -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.
  * limitations under the License.
  * ============LICENSE_END=========================================================
  */
-
 package org.openecomp.sdc.be.components.property;
 
+import static org.apache.commons.collections.MapUtils.isNotEmpty;
+
 import fj.data.Either;
+import java.util.Arrays;
+import java.util.List;
+import java.util.Map;
+import java.util.Optional;
+import java.util.stream.Collectors;
 import org.apache.commons.collections.CollectionUtils;
 import org.apache.commons.lang3.tuple.Pair;
 import org.openecomp.sdc.be.components.property.propertytopolicydeclarators.ComponentInstancePropertyToPolicyDeclarator;
@@ -34,14 +40,6 @@ import org.openecomp.sdc.be.model.PolicyDefinition;
 import org.openecomp.sdc.be.model.operations.api.StorageOperationStatus;
 import org.openecomp.sdc.common.log.wrappers.Logger;
 
-import java.util.Arrays;
-import java.util.List;
-import java.util.Map;
-import java.util.Optional;
-import java.util.stream.Collectors;
-
-import static org.apache.commons.collections.MapUtils.isNotEmpty;
-
 @org.springframework.stereotype.Component("propertyDeclarationOrchestrator")
 public class PropertyDeclarationOrchestrator {
 
@@ -57,10 +55,11 @@ public class PropertyDeclarationOrchestrator {
     private ComponentInstancePropertyToPolicyDeclarator componentInstancePropertyToPolicyDeclarator;
 
     public PropertyDeclarationOrchestrator(ComponentInstanceInputPropertyDeclarator componentInstanceInputPropertyDeclarator,
-            ComponentInstancePropertyDeclarator componentInstancePropertyDeclarator, PolicyPropertyDeclarator policyPropertyDeclarator,
-            GroupPropertyDeclarator groupPropertyDeclarator, ComponentPropertyDeclarator servicePropertyDeclarator,
-            ComponentPropertyToPolicyDeclarator componentPropertyToPolicyDeclarator,
-            ComponentInstancePropertyToPolicyDeclarator componentInstancePropertyToPolicyDeclarator) {
+                                           ComponentInstancePropertyDeclarator componentInstancePropertyDeclarator,
+                                           PolicyPropertyDeclarator policyPropertyDeclarator, GroupPropertyDeclarator groupPropertyDeclarator,
+                                           ComponentPropertyDeclarator servicePropertyDeclarator,
+                                           ComponentPropertyToPolicyDeclarator componentPropertyToPolicyDeclarator,
+                                           ComponentInstancePropertyToPolicyDeclarator componentInstancePropertyToPolicyDeclarator) {
         this.componentInstanceInputPropertyDeclarator = componentInstanceInputPropertyDeclarator;
         this.componentInstancePropertyDeclarator = componentInstancePropertyDeclarator;
         this.policyPropertyDeclarator = policyPropertyDeclarator;
@@ -68,11 +67,14 @@ public class PropertyDeclarationOrchestrator {
         this.servicePropertyDeclarator = servicePropertyDeclarator;
         this.componentPropertyToPolicyDeclarator = componentPropertyToPolicyDeclarator;
         this.componentInstancePropertyToPolicyDeclarator = componentInstancePropertyToPolicyDeclarator;
-        propertyDeclaratorsToInput = Arrays.asList(componentInstanceInputPropertyDeclarator, componentInstancePropertyDeclarator, policyPropertyDeclarator, groupPropertyDeclarator, servicePropertyDeclarator);
+        propertyDeclaratorsToInput = Arrays
+            .asList(componentInstanceInputPropertyDeclarator, componentInstancePropertyDeclarator, policyPropertyDeclarator, groupPropertyDeclarator,
+                servicePropertyDeclarator);
         propertyDeclaratorsToPolicy = Arrays.asList(componentPropertyToPolicyDeclarator, componentInstancePropertyToPolicyDeclarator);
     }
 
-    public Either<List<InputDefinition>, StorageOperationStatus> declarePropertiesToInputs(Component component, ComponentInstInputsMap componentInstInputsMap) {
+    public Either<List<InputDefinition>, StorageOperationStatus> declarePropertiesToInputs(Component component,
+                                                                                           ComponentInstInputsMap componentInstInputsMap) {
         updatePropertiesConstraints(component, componentInstInputsMap);
         PropertyDeclarator propertyDeclarator = getPropertyDeclarator(componentInstInputsMap);
         Pair<String, List<ComponentInstancePropInput>> propsToDeclare = componentInstInputsMap.resolvePropertiesToDeclare();
@@ -80,63 +82,63 @@ public class PropertyDeclarationOrchestrator {
     }
 
     private void updatePropertiesConstraints(Component component, ComponentInstInputsMap componentInstInputsMap) {
-        componentInstInputsMap.getComponentInstanceProperties().forEach((k, v) -> updatePropsConstraints(component.safeGetComponentInstancesProperties(), k, v));
-        componentInstInputsMap.getComponentInstanceInputsMap().forEach((k, v) -> updatePropsConstraints(component.safeGetComponentInstancesInputs(), k, v));
+        componentInstInputsMap.getComponentInstanceProperties()
+            .forEach((k, v) -> updatePropsConstraints(component.safeGetComponentInstancesProperties(), k, v));
+        componentInstInputsMap.getComponentInstanceInputsMap()
+            .forEach((k, v) -> updatePropsConstraints(component.safeGetComponentInstancesInputs(), k, v));
         componentInstInputsMap.getGroupProperties().forEach((k, v) -> updatePropsConstraints(component.safeGetPolicyProperties(), k, v));
         componentInstInputsMap.getPolicyProperties().forEach((k, v) -> updatePropsConstraints(component.safeGetGroupsProperties(), k, v));
     }
 
-    public Either<List<PolicyDefinition>, StorageOperationStatus> declarePropertiesToPolicies(Component component, ComponentInstInputsMap componentInstInputsMap) {
+    public Either<List<PolicyDefinition>, StorageOperationStatus> declarePropertiesToPolicies(Component component,
+                                                                                              ComponentInstInputsMap componentInstInputsMap) {
         PropertyDeclarator propertyDeclarator = getPropertyDeclarator(componentInstInputsMap);
         Pair<String, List<ComponentInstancePropInput>> propsToDeclare = componentInstInputsMap.resolvePropertiesToDeclare();
         return propertyDeclarator.declarePropertiesAsPolicies(component, propsToDeclare.getLeft(), propsToDeclare.getRight());
     }
 
-    public Either<InputDefinition, StorageOperationStatus> declarePropertiesToListInput(Component component, ComponentInstInputsMap componentInstInputsMap, InputDefinition input) {
+    public Either<InputDefinition, StorageOperationStatus> declarePropertiesToListInput(Component component,
+                                                                                        ComponentInstInputsMap componentInstInputsMap,
+                                                                                        InputDefinition input) {
         PropertyDeclarator propertyDeclarator = getPropertyDeclarator(componentInstInputsMap);
         Pair<String, List<ComponentInstancePropInput>> propsToDeclare = componentInstInputsMap.resolvePropertiesToDeclare();
         log.debug("#declarePropertiesToInputs: componentId={}, propOwnerId={}", component.getUniqueId(), propsToDeclare.getLeft());
         return propertyDeclarator.declarePropertiesAsListInput(component, propsToDeclare.getLeft(), propsToDeclare.getRight(), input);
     }
 
-    private <T extends PropertyDataDefinition> void updatePropsConstraints(Map<String, List<T>> instancesProperties , String ownerId, List<ComponentInstancePropInput> inputs) {
-        Optional<List<T>> propertiesOpt = instancesProperties.entrySet()
-                .stream()
-                .filter(e -> e.getKey().equals(ownerId))
-                .map(Map.Entry::getValue)
-                .findFirst();
-        if(propertiesOpt.isPresent()){
-            Map<String, PropertyDataDefinition> instProps = propertiesOpt.get()
-                    .stream()
-                    .collect(Collectors.toMap(PropertyDataDefinition::getName, p->p));
-            inputs.stream()
-                    .filter(i->instProps.containsKey(i.getName()))
-                    .forEach(i->updatePropConstraints(i, instProps.get(i.getName())));
-
+    private <T extends PropertyDataDefinition> void updatePropsConstraints(Map<String, List<T>> instancesProperties, String ownerId,
+                                                                           List<ComponentInstancePropInput> inputs) {
+        Optional<List<T>> propertiesOpt = instancesProperties.entrySet().stream().filter(e -> e.getKey().equals(ownerId)).map(Map.Entry::getValue)
+            .findFirst();
+        if (propertiesOpt.isPresent()) {
+            Map<String, PropertyDataDefinition> instProps = propertiesOpt.get().stream()
+                .collect(Collectors.toMap(PropertyDataDefinition::getName, p -> p));
+            inputs.stream().filter(i -> instProps.containsKey(i.getName())).forEach(i -> updatePropConstraints(i, instProps.get(i.getName())));
         }
     }
 
     private void updatePropConstraints(PropertyDataDefinition input, PropertyDataDefinition property) {
-        if(CollectionUtils.isNotEmpty(property.getPropertyConstraints())){
+        if (CollectionUtils.isNotEmpty(property.getPropertyConstraints())) {
             input.setPropertyConstraints(property.getPropertyConstraints());
-        } else if(property.getSchemaProperty() != null && CollectionUtils.isNotEmpty(property.getSchemaProperty().getPropertyConstraints())){
+        } else if (property.getSchemaProperty() != null && CollectionUtils.isNotEmpty(property.getSchemaProperty().getPropertyConstraints())) {
             input.setPropertyConstraints(property.getSchemaProperty().getPropertyConstraints());
         }
     }
 
-
     public StorageOperationStatus unDeclarePropertiesAsInputs(Component component, InputDefinition inputToDelete) {
-        log.debug("#unDeclarePropertiesAsInputs - removing input declaration for input {} on component {}", inputToDelete.getName(), component.getUniqueId());
+        log.debug("#unDeclarePropertiesAsInputs - removing input declaration for input {} on component {}", inputToDelete.getName(),
+            component.getUniqueId());
         for (PropertyDeclarator propertyDeclarator : propertyDeclaratorsToInput) {
             StorageOperationStatus storageOperationStatus = propertyDeclarator.unDeclarePropertiesAsInputs(component, inputToDelete);
             if (StorageOperationStatus.OK != storageOperationStatus) {
-                log.debug("#unDeclarePropertiesAsInputs - failed to remove input declaration for input {} on component {}. reason {}", inputToDelete.getName(), component.getUniqueId(), storageOperationStatus);
+                log.debug("#unDeclarePropertiesAsInputs - failed to remove input declaration for input {} on component {}. reason {}",
+                    inputToDelete.getName(), component.getUniqueId(), storageOperationStatus);
                 return storageOperationStatus;
             }
         }
         return StorageOperationStatus.OK;
-
     }
+
     /**
      * Un declare properties declared as list type input
      *
@@ -145,16 +147,17 @@ public class PropertyDeclarationOrchestrator {
      * @return
      */
     public StorageOperationStatus unDeclarePropertiesAsListInputs(Component component, InputDefinition inputToDelete) {
-        log.debug("#unDeclarePropertiesAsListInputs - removing input declaration for input {} on component {}", inputToDelete.getName(), component.getUniqueId());
+        log.debug("#unDeclarePropertiesAsListInputs - removing input declaration for input {} on component {}", inputToDelete.getName(),
+            component.getUniqueId());
         for (PropertyDeclarator propertyDeclarator : propertyDeclaratorsToInput) {
             StorageOperationStatus storageOperationStatus = propertyDeclarator.unDeclarePropertiesAsListInputs(component, inputToDelete);
             if (StorageOperationStatus.OK != storageOperationStatus) {
-                log.debug("#unDeclarePropertiesAsListInputs - failed to remove input declaration for input {} on component {}. reason {}", inputToDelete.getName(), component.getUniqueId(), storageOperationStatus);
+                log.debug("#unDeclarePropertiesAsListInputs - failed to remove input declaration for input {} on component {}. reason {}",
+                    inputToDelete.getName(), component.getUniqueId(), storageOperationStatus);
                 return storageOperationStatus;
             }
         }
         return StorageOperationStatus.OK;
-
     }
 
     /**
@@ -169,20 +172,17 @@ public class PropertyDeclarationOrchestrator {
     }
 
     public StorageOperationStatus unDeclarePropertiesAsPolicies(Component component, PolicyDefinition policyToDelete) {
-        log.debug("#unDeclarePropertiesAsInputs - removing policy declaration for input {} on component {}", policyToDelete
-                                                                                                                     .getName(), component.getUniqueId());
-        for(PropertyDeclarator propertyDeclarator : propertyDeclaratorsToPolicy) {
-            StorageOperationStatus storageOperationStatus =
-                    propertyDeclarator.unDeclarePropertiesAsPolicies(component, policyToDelete);
+        log.debug("#unDeclarePropertiesAsInputs - removing policy declaration for input {} on component {}", policyToDelete.getName(),
+            component.getUniqueId());
+        for (PropertyDeclarator propertyDeclarator : propertyDeclaratorsToPolicy) {
+            StorageOperationStatus storageOperationStatus = propertyDeclarator.unDeclarePropertiesAsPolicies(component, policyToDelete);
             if (StorageOperationStatus.OK != storageOperationStatus) {
-                log.debug("#unDeclarePropertiesAsInputs - failed to remove policy declaration for policy {} on component {}. reason {}", policyToDelete
-                                                                                                                                                 .getName(), component.getUniqueId(), storageOperationStatus);
+                log.debug("#unDeclarePropertiesAsInputs - failed to remove policy declaration for policy {} on component {}. reason {}",
+                    policyToDelete.getName(), component.getUniqueId(), storageOperationStatus);
                 return storageOperationStatus;
             }
         }
-
         return StorageOperationStatus.OK;
-
     }
 
     private PropertyDeclarator getPropertyDeclarator(ComponentInstInputsMap componentInstInputsMap) {
@@ -198,17 +198,15 @@ public class PropertyDeclarationOrchestrator {
         if (isNotEmpty(componentInstInputsMap.getGroupProperties())) {
             return groupPropertyDeclarator;
         }
-        if(isNotEmpty(componentInstInputsMap.getServiceProperties())) {
+        if (isNotEmpty(componentInstInputsMap.getServiceProperties())) {
             return servicePropertyDeclarator;
         }
-        if(isNotEmpty(componentInstInputsMap.getComponentPropertiesToPolicies())) {
+        if (isNotEmpty(componentInstInputsMap.getComponentPropertiesToPolicies())) {
             return componentPropertyToPolicyDeclarator;
         }
-        if(isNotEmpty(componentInstInputsMap.getComponentInstancePropertiesToPolicies())) {
+        if (isNotEmpty(componentInstInputsMap.getComponentInstancePropertiesToPolicies())) {
             return componentInstancePropertyToPolicyDeclarator;
         }
         throw new IllegalStateException("there are no properties selected for declaration");
-
     }
-
 }
index e067b0c..f033c7c 100644 (file)
@@ -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.
  * limitations under the License.
  * ============LICENSE_END=========================================================
  */
-
 package org.openecomp.sdc.be.components.property;
 
 import fj.data.Either;
+import java.util.List;
 import org.openecomp.sdc.be.model.Component;
 import org.openecomp.sdc.be.model.ComponentInstancePropInput;
 import org.openecomp.sdc.be.model.InputDefinition;
 import org.openecomp.sdc.be.model.PolicyDefinition;
 import org.openecomp.sdc.be.model.operations.api.StorageOperationStatus;
 
-import java.util.List;
-
 public interface PropertyDeclarator {
 
     /**
      * creates a list of inputs from the given list of properties and updates the properties accordingly
-     * @param component the container
+     *
+     * @param component         the container
      * @param propertiesOwnerId the id of the owner of the properties to declare (e.g ComponentInstance, Policy, Group etc)
-     * @param propsToDeclare the list of properties that are being declared as inputs
+     * @param propsToDeclare    the list of properties that are being declared as inputs
      * @return the list of inputs that were created from the given properties
      */
-    Either<List<InputDefinition>, StorageOperationStatus> declarePropertiesAsInputs(Component component, String propertiesOwnerId, List<ComponentInstancePropInput> propsToDeclare);
+    Either<List<InputDefinition>, StorageOperationStatus> declarePropertiesAsInputs(Component component, String propertiesOwnerId,
+                                                                                    List<ComponentInstancePropInput> propsToDeclare);
 
     /**
-     * returns the values of declared properties to each original state before it was declared as an input.
-     * this function is to be called when an input, that was created by declaring a property, is deleted.
+     * returns the values of declared properties to each original state before it was declared as an input. this function is to be called when an
+     * input, that was created by declaring a property, is deleted.
+     *
      * @param component the container of the input to be deleted
-     * @param input the input to be deleted
+     * @param input     the input to be deleted
      */
     StorageOperationStatus unDeclarePropertiesAsInputs(Component component, InputDefinition input);
 
     /**
      * creates a list of policies from the given list of properties and updates the properties accordingly
-     * @param component the container
+     *
+     * @param component         the container
      * @param propertiesOwnerId the id of the owner of the properties to declare (e.g ComponentInstance, Policy, Group etc)
-     * @param propsToDeclare the list of properties that are being declared as inputs
+     * @param propsToDeclare    the list of properties that are being declared as inputs
      * @return the list of policies that were created from the given properties
      */
-    Either<List<PolicyDefinition>, StorageOperationStatus> declarePropertiesAsPolicies(Component component, String propertiesOwnerId, List<ComponentInstancePropInput> propsToDeclare);
+    Either<List<PolicyDefinition>, StorageOperationStatus> declarePropertiesAsPolicies(Component component, String propertiesOwnerId,
+                                                                                       List<ComponentInstancePropInput> propsToDeclare);
 
     /**
-     * returns the values of declared properties to each original state before it was declared as an policy.
-     * this function is to be called when an policy, that was created by declaring a property, is deleted.
+     * returns the values of declared properties to each original state before it was declared as an policy. this function is to be called when an
+     * policy, that was created by declaring a property, is deleted.
+     *
      * @param component the container of the input to be deleted
-     * @param policy the policy to be deleted
+     * @param policy    the policy to be deleted
      */
     StorageOperationStatus unDeclarePropertiesAsPolicies(Component component, PolicyDefinition policy);
 
     /**
-     * Updates given list of properties to get values from the specified "list input" with get_input function.
-     * This function does NOT create "list input", it needs to be created separately.
-     * @param component the container
+     * Updates given list of properties to get values from the specified "list input" with get_input function. This function does NOT create "list
+     * input", it needs to be created separately.
+     *
+     * @param component         the container
      * @param propertiesOwnerId the id of the owner of the properties to declare (e.g ComponentInstance, Policy, Group etc)
-     * @param propsToDeclare the list of properties that are being declared as inputs
-     * @param input the input from which properties get values
+     * @param propsToDeclare    the list of properties that are being declared as inputs
+     * @param input             the input from which properties get values
      * @return the input same as passed one at 4th argument
      */
-    Either<InputDefinition, StorageOperationStatus> declarePropertiesAsListInput(Component component, String propertiesOwnerId, List<ComponentInstancePropInput> propsToDeclare, InputDefinition input);
+    Either<InputDefinition, StorageOperationStatus> declarePropertiesAsListInput(Component component, String propertiesOwnerId,
+                                                                                 List<ComponentInstancePropInput> propsToDeclare,
+                                                                                 InputDefinition input);
 
     /**
      * Un declare properties declared as list type input
+     *
      * @param component the container of the input to be deleted
-     * @param input the input to be deleted
+     * @param input     the input to be deleted
      */
     StorageOperationStatus unDeclarePropertiesAsListInputs(Component component, InputDefinition input);
 }
index f8e0ea0..c078210 100644 (file)
@@ -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.
  * limitations under the License.
  * ============LICENSE_END=========================================================
  */
-
 package org.openecomp.sdc.be.components.property.propertytopolicydeclarators;
 
 import fj.data.Either;
+import java.util.Collections;
+import java.util.List;
+import java.util.Map;
+import java.util.Optional;
 import org.openecomp.sdc.be.components.impl.ComponentInstanceBusinessLogic;
 import org.openecomp.sdc.be.components.impl.PropertyBusinessLogic;
 import org.openecomp.sdc.be.components.property.DefaultPropertyDeclarator;
@@ -35,22 +38,16 @@ import org.openecomp.sdc.be.model.jsonjanusgraph.operations.ToscaOperationFacade
 import org.openecomp.sdc.be.model.operations.api.StorageOperationStatus;
 import org.openecomp.sdc.be.model.operations.impl.PropertyOperation;
 
-import java.util.Collections;
-import java.util.List;
-import java.util.Map;
-import java.util.Optional;
-
 @org.springframework.stereotype.Component
-public class ComponentInstancePropertyToPolicyDeclarator extends
-        DefaultPropertyDeclarator<ComponentInstance, ComponentInstanceProperty> {
+public class ComponentInstancePropertyToPolicyDeclarator extends DefaultPropertyDeclarator<ComponentInstance, ComponentInstanceProperty> {
 
-    private ToscaOperationFacade toscaOperationFacade;
     PropertyBusinessLogic propertyBl;
+    private ToscaOperationFacade toscaOperationFacade;
     private ComponentInstanceBusinessLogic componentInstanceBl;
 
-    public ComponentInstancePropertyToPolicyDeclarator(ComponentsUtils componentsUtils,
-            PropertyOperation propertyOperation, ToscaOperationFacade toscaOperationFacade,
-            PropertyBusinessLogic propertyBl, ComponentInstanceBusinessLogic componentInstanceBl) {
+    public ComponentInstancePropertyToPolicyDeclarator(ComponentsUtils componentsUtils, PropertyOperation propertyOperation,
+                                                       ToscaOperationFacade toscaOperationFacade, PropertyBusinessLogic propertyBl,
+                                                       ComponentInstanceBusinessLogic componentInstanceBl) {
         super(componentsUtils, propertyOperation);
         this.toscaOperationFacade = toscaOperationFacade;
         this.propertyBl = propertyBl;
@@ -64,9 +61,8 @@ public class ComponentInstancePropertyToPolicyDeclarator extends
 
     @Override
     protected Either<?, StorageOperationStatus> updatePropertiesValues(Component component, String componentInstanceId,
-            List<ComponentInstanceProperty> properties) {
-        Map<String, List<ComponentInstanceProperty>>
-                instProperties = Collections.singletonMap(componentInstanceId, properties);
+                                                                       List<ComponentInstanceProperty> properties) {
+        Map<String, List<ComponentInstanceProperty>> instProperties = Collections.singletonMap(componentInstanceId, properties);
         return toscaOperationFacade.addComponentInstancePropertiesToComponent(component, instProperties);
     }
 
@@ -92,16 +88,10 @@ public class ComponentInstancePropertyToPolicyDeclarator extends
 
     @Override
     public StorageOperationStatus unDeclarePropertiesAsPolicies(Component component, PolicyDefinition policy) {
-
-        Optional<ComponentInstanceProperty> propertyCandidate =
-                componentInstanceBl.getComponentInstancePropertyByPolicyId(component, policy);
-
-
-        if(propertyCandidate.isPresent()) {
-            return toscaOperationFacade
-                           .updateComponentInstanceProperty(component, policy.getInstanceUniqueId(), propertyCandidate.get());
+        Optional<ComponentInstanceProperty> propertyCandidate = componentInstanceBl.getComponentInstancePropertyByPolicyId(component, policy);
+        if (propertyCandidate.isPresent()) {
+            return toscaOperationFacade.updateComponentInstanceProperty(component, policy.getInstanceUniqueId(), propertyCandidate.get());
         }
-
         return StorageOperationStatus.OK;
     }
 }
index 9ac38c3..a4d2952 100644 (file)
@@ -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.
  * limitations under the License.
  * ============LICENSE_END=========================================================
  */
-
 package org.openecomp.sdc.be.components.property.propertytopolicydeclarators;
 
 import fj.data.Either;
+import java.util.List;
+import java.util.Optional;
 import org.apache.commons.collections4.CollectionUtils;
 import org.openecomp.sdc.be.components.impl.PropertyBusinessLogic;
 import org.openecomp.sdc.be.components.property.DefaultPropertyDeclarator;
@@ -35,18 +36,14 @@ import org.openecomp.sdc.be.model.jsonjanusgraph.operations.ToscaOperationFacade
 import org.openecomp.sdc.be.model.operations.api.StorageOperationStatus;
 import org.openecomp.sdc.be.model.operations.impl.PropertyOperation;
 
-import java.util.List;
-import java.util.Optional;
-
 @org.springframework.stereotype.Component
 public class ComponentPropertyToPolicyDeclarator extends DefaultPropertyDeclarator<Component, PropertyDataDefinition> {
 
-    private ToscaOperationFacade toscaOperationFacade;
     PropertyBusinessLogic propertyBL;
-
+    private ToscaOperationFacade toscaOperationFacade;
 
     public ComponentPropertyToPolicyDeclarator(ComponentsUtils componentsUtils, PropertyOperation propertyOperation,
-            ToscaOperationFacade toscaOperationFacade, PropertyBusinessLogic propertyBusinessLogic) {
+                                               ToscaOperationFacade toscaOperationFacade, PropertyBusinessLogic propertyBusinessLogic) {
         super(componentsUtils, propertyOperation);
         this.toscaOperationFacade = toscaOperationFacade;
         this.propertyBL = propertyBusinessLogic;
@@ -58,20 +55,17 @@ public class ComponentPropertyToPolicyDeclarator extends DefaultPropertyDeclarat
     }
 
     @Override
-    public Either<?, StorageOperationStatus> updatePropertiesValues(Component component, String policyId,
-            List<PropertyDataDefinition> properties) {
-        if(CollectionUtils.isNotEmpty(properties)) {
-            for(PropertyDataDefinition property : properties) {
-                Either<PropertyDefinition, StorageOperationStatus>
-                        storageStatus = toscaOperationFacade
-                                                .updatePropertyOfComponent(component, new PropertyDefinition(property));
-                if(storageStatus.isRight()) {
+    public Either<?, StorageOperationStatus> updatePropertiesValues(Component component, String policyId, List<PropertyDataDefinition> properties) {
+        if (CollectionUtils.isNotEmpty(properties)) {
+            for (PropertyDataDefinition property : properties) {
+                Either<PropertyDefinition, StorageOperationStatus> storageStatus = toscaOperationFacade
+                    .updatePropertyOfComponent(component, new PropertyDefinition(property));
+                if (storageStatus.isRight()) {
                     return Either.right(storageStatus.right().value());
                 }
             }
         }
         return Either.left(properties);
-
     }
 
     @Override
@@ -98,66 +92,49 @@ public class ComponentPropertyToPolicyDeclarator extends DefaultPropertyDeclarat
 
     @Override
     public StorageOperationStatus unDeclarePropertiesAsPolicies(Component component, PolicyDefinition policy) {
-        Optional<PropertyDefinition> propertyToUpdateCandidate =
-                getDeclaredPropertyByPolicyId(component, policy.getUniqueId());
-
-        if(propertyToUpdateCandidate.isPresent()) {
+        Optional<PropertyDefinition> propertyToUpdateCandidate = getDeclaredPropertyByPolicyId(component, policy.getUniqueId());
+        if (propertyToUpdateCandidate.isPresent()) {
             return unDeclarePolicy(component, propertyToUpdateCandidate.get(), policy);
         }
-
         return StorageOperationStatus.OK;
     }
 
     private StorageOperationStatus unDeclarePolicy(Component component, PropertyDefinition propertyToUpdate, PolicyDefinition policy) {
         updatePropertyAfterUndeclaration(propertyToUpdate, policy);
-
-        Either<PropertyDefinition, StorageOperationStatus> status = toscaOperationFacade
-                                                                            .updatePropertyOfComponent(component, propertyToUpdate);
-        if(status.isRight()) {
+        Either<PropertyDefinition, StorageOperationStatus> status = toscaOperationFacade.updatePropertyOfComponent(component, propertyToUpdate);
+        if (status.isRight()) {
             return status.right().value();
         }
-
         return StorageOperationStatus.OK;
     }
 
     private void updatePropertyAfterUndeclaration(PropertyDefinition propertyToUpdate, PolicyDefinition policy) {
         List<GetPolicyValueDataDefinition> getPolicyValues = propertyToUpdate.getGetPolicyValues();
         Optional<GetPolicyValueDataDefinition> getPolicyCandidateToRemove = getPolicyValues.stream()
-                                                                                    .filter(getPolicyValue -> getPolicyValue.getPolicyId()
-                                                                                                                      .equals(policy.getUniqueId()))
-                                                                                    .findAny();
-
+            .filter(getPolicyValue -> getPolicyValue.getPolicyId().equals(policy.getUniqueId())).findAny();
         getPolicyCandidateToRemove.ifPresent(getPolicyValue -> {
             getPolicyValues.remove(getPolicyValue);
             propertyToUpdate.setValue(getPolicyValue.getOrigPropertyValue());
         });
     }
 
-    private Optional<PropertyDefinition> getDeclaredPropertyByPolicyId(Component component,
-            String policyId) {
+    private Optional<PropertyDefinition> getDeclaredPropertyByPolicyId(Component component, String policyId) {
         List<PropertyDefinition> properties = component.getProperties();
-
-        if(CollectionUtils.isEmpty(properties)) {
+        if (CollectionUtils.isEmpty(properties)) {
             return Optional.empty();
         }
-
-        for(PropertyDefinition propertyDefinition : properties) {
+        for (PropertyDefinition propertyDefinition : properties) {
             List<GetPolicyValueDataDefinition> getPolicyValues = propertyDefinition.getGetPolicyValues();
-            if(CollectionUtils.isEmpty(getPolicyValues)) {
+            if (CollectionUtils.isEmpty(getPolicyValues)) {
                 continue;
             }
-
-
-            Optional<GetPolicyValueDataDefinition> getPolicyCandidate =
-                    getPolicyValues.stream().filter(getPolicy -> getPolicy.getPolicyId().equals(policyId)).findAny();
-
-            if(getPolicyCandidate.isPresent()) {
+            Optional<GetPolicyValueDataDefinition> getPolicyCandidate = getPolicyValues.stream()
+                .filter(getPolicy -> getPolicy.getPolicyId().equals(policyId)).findAny();
+            if (getPolicyCandidate.isPresent()) {
                 propertyDefinition.setValue(getPolicyCandidate.get().getOrigPropertyValue());
                 return Optional.of(propertyDefinition);
             }
         }
-
         return Optional.empty();
     }
-
 }
index 8c951e1..e1f51cf 100644 (file)
@@ -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.
  * limitations under the License.
  * ============LICENSE_END=========================================================
  */
-
 package org.openecomp.sdc.be.components.scheduledtasks;
 
-import org.openecomp.sdc.common.log.wrappers.Logger;
-
 import java.util.concurrent.ExecutorService;
 import java.util.concurrent.TimeUnit;
-
+import org.openecomp.sdc.common.log.wrappers.Logger;
 
 public abstract class AbstractScheduleTaskRunner {
+
     private static final Logger log = Logger.getLogger(AbstractScheduleTaskRunner.class);
+
     public abstract ExecutorService getExecutorService();
 
     protected void shutdownExecutor() {
         ExecutorService executorService = getExecutorService();
-        if (executorService == null)
+        if (executorService == null) {
             return;
-
+        }
         executorService.shutdown(); // Disable new tasks from being submitted
         try {
             // Wait a while for existing tasks to terminate
             if (!executorService.awaitTermination(60, TimeUnit.SECONDS)) {
                 executorService.shutdownNow(); // Cancel currently executing
-                                                // tasks
+
+                // tasks
+
                 // Wait a while for tasks to respond to being cancelled
-                if (!executorService.awaitTermination(60, TimeUnit.SECONDS))
+                if (!executorService.awaitTermination(60, TimeUnit.SECONDS)) {
                     log.debug("Pool did not terminate");
+                }
             }
         } catch (InterruptedException ie) {
             // (Re-)Cancel if current thread also interrupted
index e67b2e1..64874a9 100644 (file)
@@ -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.
  * limitations under the License.
  * ============LICENSE_END=========================================================
  */
-
 package org.openecomp.sdc.be.components.scheduledtasks;
 
+import java.util.ArrayList;
+import java.util.List;
+import java.util.concurrent.ExecutorService;
+import java.util.concurrent.Executors;
+import java.util.concurrent.ScheduledExecutorService;
+import java.util.concurrent.ScheduledFuture;
+import java.util.concurrent.TimeUnit;
+import javax.annotation.PostConstruct;
+import javax.annotation.PreDestroy;
 import org.apache.commons.lang3.concurrent.BasicThreadFactory;
 import org.openecomp.sdc.be.config.BeEcompErrorManager;
 import org.openecomp.sdc.be.config.CleanComponentsConfiguration;
@@ -29,43 +37,27 @@ import org.openecomp.sdc.be.datatypes.enums.NodeTypeEnum;
 import org.openecomp.sdc.common.log.wrappers.Logger;
 import org.springframework.stereotype.Component;
 
-import javax.annotation.PostConstruct;
-import javax.annotation.PreDestroy;
-import java.util.ArrayList;
-import java.util.List;
-import java.util.concurrent.ExecutorService;
-import java.util.concurrent.Executors;
-import java.util.concurrent.ScheduledExecutorService;
-import java.util.concurrent.ScheduledFuture;
-import java.util.concurrent.TimeUnit;
-
 @Component("asdcComponentsCleaner")
 public class AsdcComponentsCleanerTask extends AbstractScheduleTaskRunner implements Runnable {
 
     private static final Logger log = Logger.getLogger(AsdcComponentsCleanerTask.class);
-
+    ScheduledFuture<?> scheduledFuture = null;
     @javax.annotation.Resource
     private ComponentsCleanBusinessLogic componentsCleanBusinessLogic = null;
-
     private List<NodeTypeEnum> componentsToClean;
     private long cleaningIntervalInMinutes;
-
-    private ScheduledExecutorService scheduledService = Executors.newScheduledThreadPool(1,
-            new BasicThreadFactory.Builder().namingPattern("ComponentsCleanThread-%d").build());
-    ScheduledFuture<?> scheduledFuture = null;
+    private ScheduledExecutorService scheduledService = Executors
+        .newScheduledThreadPool(1, new BasicThreadFactory.Builder().namingPattern("ComponentsCleanThread-%d").build());
 
     @PostConstruct
     public void init() {
         log.info("Enter init method of AsdcComponentsCleaner");
         Configuration configuration = ConfigurationManager.getConfigurationManager().getConfiguration();
         CleanComponentsConfiguration cleanComponentsConfiguration = configuration.getCleanComponentsConfiguration();
-
         if (cleanComponentsConfiguration == null) {
             log.info("ERROR - configuration is not valid!!! missing cleanComponentsConfiguration");
-            BeEcompErrorManager.getInstance().logBeComponentCleanerSystemError("AsdcComponentsCleanerTask-init",
-                    "fecth configuration");
+            BeEcompErrorManager.getInstance().logBeComponentCleanerSystemError("AsdcComponentsCleanerTask-init", "fecth configuration");
             return;
-
         }
         componentsToClean = new ArrayList<>();
         List<String> components = cleanComponentsConfiguration.getComponentsToClean();
@@ -74,20 +66,17 @@ public class AsdcComponentsCleanerTask extends AbstractScheduleTaskRunner implem
         }
         for (String component : components) {
             NodeTypeEnum typeEnum = NodeTypeEnum.getByNameIgnoreCase(component);
-            if (typeEnum != null)
-                componentsToClean.add(typeEnum);
+         if (typeEnum != null) {
+          componentsToClean.add(typeEnum);
+         }
         }
-
         long intervalInMinutes = cleanComponentsConfiguration.getCleanIntervalInMinutes();
-
         if (intervalInMinutes < 1) {
             log.warn("cleaningIntervalInMinutes value should be greater than or equal to 1 minute. use default");
             intervalInMinutes = 60;
         }
         cleaningIntervalInMinutes = intervalInMinutes;
-
         startTask();
-
         log.info("End init method of AsdcComponentsCleaner");
     }
 
@@ -98,22 +87,15 @@ public class AsdcComponentsCleanerTask extends AbstractScheduleTaskRunner implem
     }
 
     public void startTask() {
-
         log.debug("start task for cleaning components");
-
         try {
-
             if (scheduledService != null) {
                 log.debug("Start Cleaning components task. interval {} minutes", cleaningIntervalInMinutes);
-                scheduledFuture = scheduledService.scheduleAtFixedRate(this, 5, cleaningIntervalInMinutes,
-                        TimeUnit.MINUTES);
-
+                scheduledFuture = scheduledService.scheduleAtFixedRate(this, 5, cleaningIntervalInMinutes, TimeUnit.MINUTES);
             }
         } catch (Exception e) {
             log.debug("unexpected error occured", e);
-            BeEcompErrorManager.getInstance().logBeComponentCleanerSystemError("AsdcComponentsCleanerTask-startTask",
-                    e.getMessage());
-
+            BeEcompErrorManager.getInstance().logBeComponentCleanerSystemError("AsdcComponentsCleanerTask-startTask", e.getMessage());
         }
     }
 
@@ -122,12 +104,11 @@ public class AsdcComponentsCleanerTask extends AbstractScheduleTaskRunner implem
             boolean cancelTaskSuccessfully = scheduledFuture.cancel(true);
             log.debug("Stop cleaning task. result = {}", cancelTaskSuccessfully);
             if (!cancelTaskSuccessfully) {
-                BeEcompErrorManager.getInstance().logBeComponentCleanerSystemError("AsdcComponentsCleanerTask-stopTask",
-                        "try to stop the polling task");
+                BeEcompErrorManager.getInstance()
+                    .logBeComponentCleanerSystemError("AsdcComponentsCleanerTask-stopTask", "try to stop the polling task");
             }
             scheduledFuture = null;
         }
-
     }
 
     @Override
@@ -136,10 +117,8 @@ public class AsdcComponentsCleanerTask extends AbstractScheduleTaskRunner implem
             componentsCleanBusinessLogic.cleanComponents(componentsToClean);
         } catch (Exception e) {
             log.error("unexpected error occured", e);
-            BeEcompErrorManager.getInstance().logBeComponentCleanerSystemError("AsdcComponentsCleanerTask-run",
-                    e.getMessage());
+            BeEcompErrorManager.getInstance().logBeComponentCleanerSystemError("AsdcComponentsCleanerTask-run", e.getMessage());
         }
-
     }
 
     @Override
index 8c56052..f3b11e8 100644 (file)
@@ -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.
  * Modifications copyright (c) 2019 Nokia
  * ================================================================================
  */
-
 package org.openecomp.sdc.be.components.scheduledtasks;
 
 import com.google.common.annotations.VisibleForTesting;
 import fj.data.Either;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
 import org.openecomp.sdc.be.components.impl.BaseBusinessLogic;
 import org.openecomp.sdc.be.components.impl.ComponentBusinessLogic;
 import org.openecomp.sdc.be.components.impl.ResourceBusinessLogic;
@@ -43,44 +45,32 @@ import org.openecomp.sdc.exception.ResponseFormat;
 import org.springframework.beans.factory.annotation.Autowired;
 import org.springframework.stereotype.Component;
 
-import java.util.HashMap;
-import java.util.List;
-import java.util.Map;
-
 @Component("componentsCleanBusinessLogic")
 public class ComponentsCleanBusinessLogic extends BaseBusinessLogic {
 
-    private final ResourceBusinessLogic resourceBusinessLogic;
-    private final ServiceBusinessLogic serviceBusinessLogic;
-
     @VisibleForTesting
     static final String DELETE_LOCKER = "DELETE_LOCKER";
-
     private static final Logger log = Logger.getLogger(ComponentsCleanBusinessLogic.class.getName());
+    private final ResourceBusinessLogic resourceBusinessLogic;
+    private final ServiceBusinessLogic serviceBusinessLogic;
 
     @Autowired
-    public ComponentsCleanBusinessLogic(IElementOperation elementDao,
-        IGroupOperation groupOperation,
-        IGroupInstanceOperation groupInstanceOperation,
-        IGroupTypeOperation groupTypeOperation,
-        InterfaceOperation interfaceOperation,
-        InterfaceLifecycleOperation interfaceLifecycleTypeOperation, ResourceBusinessLogic resourceBusinessLogic,
-        ServiceBusinessLogic serviceBusinessLogic,
-        ArtifactsOperations artifactToscaOperation) {
-        super(elementDao, groupOperation, groupInstanceOperation, groupTypeOperation,
-            interfaceOperation, interfaceLifecycleTypeOperation, artifactToscaOperation);
+    public ComponentsCleanBusinessLogic(IElementOperation elementDao, IGroupOperation groupOperation, IGroupInstanceOperation groupInstanceOperation,
+                                        IGroupTypeOperation groupTypeOperation, InterfaceOperation interfaceOperation,
+                                        InterfaceLifecycleOperation interfaceLifecycleTypeOperation, ResourceBusinessLogic resourceBusinessLogic,
+                                        ServiceBusinessLogic serviceBusinessLogic, ArtifactsOperations artifactToscaOperation) {
+        super(elementDao, groupOperation, groupInstanceOperation, groupTypeOperation, interfaceOperation, interfaceLifecycleTypeOperation,
+            artifactToscaOperation);
         this.resourceBusinessLogic = resourceBusinessLogic;
         this.serviceBusinessLogic = serviceBusinessLogic;
     }
 
-    public Map<NodeTypeEnum, Either<List<String>, ResponseFormat>> cleanComponents(List<NodeTypeEnum> componentsToClean){
+    public Map<NodeTypeEnum, Either<List<String>, ResponseFormat>> cleanComponents(List<NodeTypeEnum> componentsToClean) {
         return cleanComponents(componentsToClean, false);
     }
 
     public Map<NodeTypeEnum, Either<List<String>, ResponseFormat>> cleanComponents(List<NodeTypeEnum> componentsToClean, boolean isAlreadyLocked) {
-
         Map<NodeTypeEnum, Either<List<String>, ResponseFormat>> cleanedComponents = new HashMap<>();
-
         boolean isLockSucceeded = false;
         log.trace("start cleanComponents");
         try {
@@ -106,18 +96,17 @@ public class ComponentsCleanBusinessLogic extends BaseBusinessLogic {
                         break;
                 }
             }
-        }
-        finally {
+        } finally {
             if (!isAlreadyLocked && isLockSucceeded) {
                 unlockDeleteOperation();
             }
         }
-
         log.trace("end cleanComponents");
         return cleanedComponents;
     }
 
-    private void processDeletionForType(Map<NodeTypeEnum, Either<List<String>, ResponseFormat>> cleanedComponents, NodeTypeEnum type, ComponentBusinessLogic componentBusinessLogic) {
+    private void processDeletionForType(Map<NodeTypeEnum, Either<List<String>, ResponseFormat>> cleanedComponents, NodeTypeEnum type,
+                                        ComponentBusinessLogic componentBusinessLogic) {
         Either<List<String>, ResponseFormat> deleteMarkedResources = componentBusinessLogic.deleteMarkedComponents();
         if (deleteMarkedResources.isRight()) {
             log.debug("failed to clean deleted components of type {}. error: {}", type, deleteMarkedResources.right().value().getFormattedMessage());
@@ -142,5 +131,4 @@ public class ComponentsCleanBusinessLogic extends BaseBusinessLogic {
     public boolean isDeleteOperationLockFailed() {
         return lockDeleteOperation() != StorageOperationStatus.OK;
     }
-
 }
index 4aa6136..594e0b9 100644 (file)
@@ -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.
  * limitations under the License.
  * ============LICENSE_END=========================================================
  */
-
 package org.openecomp.sdc.be.components.scheduledtasks;
 
+import static org.apache.commons.collections.CollectionUtils.isEmpty;
+import static org.openecomp.sdc.common.datastructure.FunctionalInterfaces.convertToFunction;
+
 import com.google.common.annotations.VisibleForTesting;
 import fj.data.Either;
+import java.util.List;
+import java.util.concurrent.ExecutorService;
+import java.util.concurrent.Executors;
+import java.util.concurrent.ScheduledExecutorService;
+import java.util.concurrent.TimeUnit;
+import java.util.stream.Collectors;
+import javax.annotation.PostConstruct;
+import javax.annotation.PreDestroy;
+import javax.annotation.Resource;
 import org.apache.commons.lang.math.NumberUtils;
 import org.apache.commons.lang3.concurrent.BasicThreadFactory;
 import org.openecomp.sdc.be.components.distribution.engine.EnvironmentsEngine;
@@ -36,45 +47,28 @@ import org.openecomp.sdc.common.log.wrappers.Logger;
 import org.springframework.beans.factory.annotation.Autowired;
 import org.springframework.stereotype.Component;
 
-import javax.annotation.PostConstruct;
-import javax.annotation.PreDestroy;
-import javax.annotation.Resource;
-import java.util.List;
-import java.util.concurrent.ExecutorService;
-import java.util.concurrent.Executors;
-import java.util.concurrent.ScheduledExecutorService;
-import java.util.concurrent.TimeUnit;
-import java.util.stream.Collectors;
-
-import static org.apache.commons.collections.CollectionUtils.isEmpty;
-import static org.openecomp.sdc.common.datastructure.FunctionalInterfaces.convertToFunction;
-
 @Component("recoveryThreadManager")
 public class RecoveryThreadManager extends AbstractScheduleTaskRunner {
 
     private static final Logger log = Logger.getLogger(RecoveryThreadManager.class);
     @VisibleForTesting
     FixEnvironmentTask task = new FixEnvironmentTask();
-
+    @VisibleForTesting
+    Integer allowedTimeBeforeStaleSec;
     @Resource
     private OperationalEnvironmentDao operationalEnvironmentDao;
-
     @Autowired
     private EnvironmentsEngine environmentsEngine;
-
-    private ScheduledExecutorService scheduledService = Executors.newScheduledThreadPool(NumberUtils.INTEGER_ONE,
-            new BasicThreadFactory.Builder().namingPattern("EnvironmentCleanThread-%d").build());
-    @VisibleForTesting
-    Integer allowedTimeBeforeStaleSec;
+    private ScheduledExecutorService scheduledService = Executors
+        .newScheduledThreadPool(NumberUtils.INTEGER_ONE, new BasicThreadFactory.Builder().namingPattern("EnvironmentCleanThread-%d").build());
 
     @PostConstruct
     public void init() {
         log.debug("Enter init method of RecoveryThreadManager");
-        final DistributionEngineConfiguration distributionEngineConfiguration = ConfigurationManager
-                .getConfigurationManager().getDistributionEngineConfiguration();
+        final DistributionEngineConfiguration distributionEngineConfiguration = ConfigurationManager.getConfigurationManager()
+            .getDistributionEngineConfiguration();
         Integer opEnvRecoveryIntervalSec = distributionEngineConfiguration.getOpEnvRecoveryIntervalSec();
-        scheduledService.scheduleAtFixedRate(task, NumberUtils.INTEGER_ZERO, opEnvRecoveryIntervalSec,
-                TimeUnit.SECONDS);
+        scheduledService.scheduleAtFixedRate(task, NumberUtils.INTEGER_ZERO, opEnvRecoveryIntervalSec, TimeUnit.SECONDS);
         this.allowedTimeBeforeStaleSec = distributionEngineConfiguration.getAllowedTimeBeforeStaleSec();
         log.debug("End init method of AsdcComponentsCleaner");
     }
@@ -84,29 +78,31 @@ public class RecoveryThreadManager extends AbstractScheduleTaskRunner {
         shutdownExecutor();
     }
 
+    @Override
+    public ExecutorService getExecutorService() {
+        return scheduledService;
+    }
+
     protected class FixEnvironmentTask implements Runnable {
+
         @Override
         public void run() {
             try {
                 // Failed Envs
                 Either<List<OperationalEnvironmentEntry>, CassandraOperationStatus> eitherFailedEnv = operationalEnvironmentDao
-                        .getByEnvironmentsStatus(EnvironmentStatusEnum.FAILED);
-                eitherFailedEnv.bimap(convertToFunction(this::handleFailedeEnvironmentsRecords), convertToFunction(
-                        cassandraError -> logFailedRetrieveRecord(EnvironmentStatusEnum.FAILED, cassandraError)));
-
+                    .getByEnvironmentsStatus(EnvironmentStatusEnum.FAILED);
+                eitherFailedEnv.bimap(convertToFunction(this::handleFailedeEnvironmentsRecords),
+                    convertToFunction(cassandraError -> logFailedRetrieveRecord(EnvironmentStatusEnum.FAILED, cassandraError)));
                 // In-Progress Envs
                 Either<List<OperationalEnvironmentEntry>, CassandraOperationStatus> eitherInProgressEnv = operationalEnvironmentDao
-                        .getByEnvironmentsStatus(EnvironmentStatusEnum.IN_PROGRESS);
+                    .getByEnvironmentsStatus(EnvironmentStatusEnum.IN_PROGRESS);
                 eitherInProgressEnv.bimap(convertToFunction(this::handleInProgressEnvironmentsRecords),
-                        convertToFunction(cassandraError -> logFailedRetrieveRecord(EnvironmentStatusEnum.IN_PROGRESS,
-                                cassandraError)));
-
+                    convertToFunction(cassandraError -> logFailedRetrieveRecord(EnvironmentStatusEnum.IN_PROGRESS, cassandraError)));
                 // Envs To Connect to UEB topics
                 Either<List<OperationalEnvironmentEntry>, CassandraOperationStatus> eitherCompleteEnv = operationalEnvironmentDao
-                        .getByEnvironmentsStatus(EnvironmentStatusEnum.COMPLETED);
-                eitherCompleteEnv.bimap(convertToFunction(this::handleCompleteEnvironmentsRecords), convertToFunction(
-                        cassandraError -> logFailedRetrieveRecord(EnvironmentStatusEnum.COMPLETED, cassandraError)));
-
+                    .getByEnvironmentsStatus(EnvironmentStatusEnum.COMPLETED);
+                eitherCompleteEnv.bimap(convertToFunction(this::handleCompleteEnvironmentsRecords),
+                    convertToFunction(cassandraError -> logFailedRetrieveRecord(EnvironmentStatusEnum.COMPLETED, cassandraError)));
             } catch (Exception e) {
                 log.debug("error while handling operational environments to be fixed :{}", e.getMessage(), e);
             }
@@ -114,49 +110,33 @@ public class RecoveryThreadManager extends AbstractScheduleTaskRunner {
 
         private void handleCompleteEnvironmentsRecords(List<OperationalEnvironmentEntry> completeEnvironmentsRecords) {
             if (!isEmpty(completeEnvironmentsRecords)) {
-                completeEnvironmentsRecords.stream().filter(env -> !environmentsEngine.isInMap(env))
-                        .forEach(opEnvEntry -> {
-                            environmentsEngine.createUebTopicsForEnvironment(opEnvEntry);
-                            environmentsEngine.addToMap(opEnvEntry);
-                        });
+                completeEnvironmentsRecords.stream().filter(env -> !environmentsEngine.isInMap(env)).forEach(opEnvEntry -> {
+                    environmentsEngine.createUebTopicsForEnvironment(opEnvEntry);
+                    environmentsEngine.addToMap(opEnvEntry);
+                });
             }
-
         }
 
         private void handleFailedeEnvironmentsRecords(List<OperationalEnvironmentEntry> failedEnvironmentsRecords) {
             if (!isEmpty(failedEnvironmentsRecords)) {
-                failedEnvironmentsRecords.parallelStream()
-                        .forEach(env -> environmentsEngine.buildOpEnv(new Wrapper<>(), env));
+                failedEnvironmentsRecords.parallelStream().forEach(env -> environmentsEngine.buildOpEnv(new Wrapper<>(), env));
             }
-
         }
 
         private void handleInProgressEnvironmentsRecords(List<OperationalEnvironmentEntry> inProgressEnvList) {
             if (!isEmpty(inProgressEnvList)) {
-
                 long currentTimeMillis = System.currentTimeMillis();
                 if (!isEmpty(inProgressEnvList)) {
                     List<OperationalEnvironmentEntry> staleInProgressEnvList = inProgressEnvList.stream()
-                            .filter(record -> (record.getLastModified().getTime() + (allowedTimeBeforeStaleSec * 1000)) < currentTimeMillis)
-                            .collect(Collectors.toList());
-                    staleInProgressEnvList.parallelStream()
-                            .forEach(env -> environmentsEngine.buildOpEnv(new Wrapper<>(), env));
+                        .filter(record -> (record.getLastModified().getTime() + (allowedTimeBeforeStaleSec * 1000)) < currentTimeMillis)
+                        .collect(Collectors.toList());
+                    staleInProgressEnvList.parallelStream().forEach(env -> environmentsEngine.buildOpEnv(new Wrapper<>(), env));
                 }
-
             }
-
         }
 
         private void logFailedRetrieveRecord(EnvironmentStatusEnum recordStatus, CassandraOperationStatus error) {
             log.debug("error: {} while retrieving operational environments with status: {}", error, recordStatus);
         }
-
-
     }
-
-    @Override
-    public ExecutorService getExecutorService() {
-        return scheduledService;
-    }
-
 }
index 025ee58..080d38e 100644 (file)
@@ -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.
  * limitations under the License.
  * ============LICENSE_END=========================================================
  */
-
 package org.openecomp.sdc.be.components.upgrade;
 
 import org.openecomp.sdc.be.dao.api.ActionStatus;
 
 public class ServiceInfo {
+
     private String uniqueId;
     private String version;
     private String name;
     private ActionStatus status;
-    public ServiceInfo(){
+
+    public ServiceInfo() {
         status = ActionStatus.OK;
     }
-    
-    public ServiceInfo(String id, ActionStatus status){
+
+    public ServiceInfo(String id, ActionStatus status) {
         this.uniqueId = id;
         this.status = status;
     }
+
     public String getUniqueId() {
         return uniqueId;
     }
+
     public void setUniqueId(String uniqueId) {
         this.uniqueId = uniqueId;
     }
+
     public String getVersion() {
         return version;
     }
+
     public void setVersion(String version) {
         this.version = version;
     }
+
     public String getName() {
         return name;
     }
+
     public void setName(String name) {
         this.name = name;
     }
+
     public ActionStatus getStatus() {
         return status;
     }
+
     public void setStatus(ActionStatus status) {
         this.status = status;
     }
@@ -74,31 +82,40 @@ public class ServiceInfo {
 
     @Override
     public boolean equals(Object obj) {
-        if (this == obj)
-            return true;
-        if (obj == null)
-            return false;
-        if (getClass() != obj.getClass())
-            return false;
+     if (this == obj) {
+      return true;
+     }
+     if (obj == null) {
+      return false;
+     }
+     if (getClass() != obj.getClass()) {
+      return false;
+     }
         ServiceInfo other = (ServiceInfo) obj;
         if (name == null) {
-            if (other.name != null)
-                return false;
-        } else if (!name.equals(other.name))
-            return false;
-        if (status != other.status)
-            return false;
+         if (other.name != null) {
+          return false;
+         }
+        } else if (!name.equals(other.name)) {
+         return false;
+        }
+     if (status != other.status) {
+      return false;
+     }
         if (uniqueId == null) {
-            if (other.uniqueId != null)
-                return false;
-        } else if (!uniqueId.equals(other.uniqueId))
-            return false;
+         if (other.uniqueId != null) {
+          return false;
+         }
+        } else if (!uniqueId.equals(other.uniqueId)) {
+         return false;
+        }
         if (version == null) {
-            if (other.version != null)
-                return false;
-        } else if (!version.equals(other.version))
-            return false;
+         if (other.version != null) {
+          return false;
+         }
+        } else if (!version.equals(other.version)) {
+         return false;
+        }
         return true;
     }
-    
 }
index dbe5141..fb8c873 100644 (file)
@@ -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.
  * limitations under the License.
  * ============LICENSE_END=========================================================
  */
-
 package org.openecomp.sdc.be.components.upgrade;
 
 import fj.data.Either;
+import java.util.ArrayList;
+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.components.impl.ComponentInstanceBusinessLogic;
 import org.openecomp.sdc.be.components.lifecycle.LifecycleBusinessLogic;
 import org.openecomp.sdc.be.components.lifecycle.LifecycleChangeInfoWithAction;
@@ -48,16 +53,13 @@ import org.openecomp.sdc.be.user.Role;
 import org.openecomp.sdc.common.log.wrappers.Logger;
 import org.openecomp.sdc.exception.ResponseFormat;
 
-import java.util.ArrayList;
-import java.util.Arrays;
-import java.util.HashMap;
-import java.util.List;
-import java.util.Map;
-import java.util.stream.Collectors;
-
 @org.springframework.stereotype.Component("upgradeBusinessLogic")
 public class UpgradeBusinessLogic {
 
+    private static final List<String> UUID_PROPS_NAMES = Arrays.asList("depending_service_uuid", "providing_service_uuid");
+    private static final List<String> INV_UUID_PROPS_NAMES = Arrays.asList("depending_service_invariant_uuid", "providing_service_invariant_uuid");
+    private static final List<String> NAME_PROPS_NAMES = Arrays.asList("depending_service_name", "providing_service_name");
+    private static final Logger LOGGER = Logger.getLogger(UpgradeBusinessLogic.class);
     private final LifecycleBusinessLogic lifecycleBusinessLogic;
     private final ComponentInstanceBusinessLogic componentInstanceBusinessLogic;
     private final UserValidations userValidations;
@@ -67,13 +69,8 @@ public class UpgradeBusinessLogic {
     private final JanusGraphDao janusGraphDao;
     private LifecycleChangeInfoWithAction changeInfo = new LifecycleChangeInfoWithAction("automated upgrade");
 
-    private static final List<String> UUID_PROPS_NAMES = Arrays.asList("depending_service_uuid", "providing_service_uuid");
-    private static final List<String> INV_UUID_PROPS_NAMES = Arrays.asList("depending_service_invariant_uuid", "providing_service_invariant_uuid");
-    private static final List<String> NAME_PROPS_NAMES = Arrays.asList("depending_service_name", "providing_service_name");
-
-    private static final Logger LOGGER = Logger.getLogger(UpgradeBusinessLogic.class);
-
-    public UpgradeBusinessLogic(LifecycleBusinessLogic lifecycleBusinessLogic, ComponentInstanceBusinessLogic componentInstanceBusinessLogic, UserValidations userValidations, ToscaOperationFacade toscaOperationFacade, ComponentsUtils componentsUtils,
+    public UpgradeBusinessLogic(LifecycleBusinessLogic lifecycleBusinessLogic, ComponentInstanceBusinessLogic componentInstanceBusinessLogic,
+                                UserValidations userValidations, ToscaOperationFacade toscaOperationFacade, ComponentsUtils componentsUtils,
                                 UpgradeOperation upgradeOperation, JanusGraphDao janusGraphDao) {
         this.lifecycleBusinessLogic = lifecycleBusinessLogic;
         this.componentInstanceBusinessLogic = componentInstanceBusinessLogic;
@@ -84,9 +81,7 @@ public class UpgradeBusinessLogic {
         this.janusGraphDao = janusGraphDao;
     }
 
-
     /**
-     * 
      * @param componentId
      * @param userId
      * @return
@@ -94,61 +89,56 @@ public class UpgradeBusinessLogic {
     public UpgradeStatus automatedUpgrade(String componentId, List<UpgradeRequest> upgradeRequest, String userId) {
         UpgradeStatus status = new UpgradeStatus();
         User user = userValidations.validateUserExists(userId);
-
         Either<Component, StorageOperationStatus> storageStatus = toscaOperationFacade.getToscaFullElement(componentId);
         if (storageStatus.isRight()) {
-            status.setError(componentsUtils.getResponseFormatByResource(componentsUtils.convertFromStorageResponse(storageStatus.right().value()), componentId));
+            status.setError(
+                componentsUtils.getResponseFormatByResource(componentsUtils.convertFromStorageResponse(storageStatus.right().value()), componentId));
             return status;
         }
         Component component = storageStatus.left().value();
         if (!component.isHighestVersion() || component.getLifecycleState() != LifecycleStateEnum.CERTIFIED) {
-            LOGGER.debug("automated Upgrade failed - target is not higest certified component {} state {} version {} ", component.getName(), component.getLifecycleState(), component.getVersion());
+            LOGGER.debug("automated Upgrade failed - target is not higest certified component {} state {} version {} ", component.getName(),
+                component.getLifecycleState(), component.getVersion());
             ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.COMPONENT_IS_NOT_HIHGEST_CERTIFIED, component.getName());
             status.setError(responseFormat);
             componentsUtils.auditComponentAdmin(responseFormat, user, component, getAuditTypeByComponent(component), component.getComponentType());
-
             return status;
         }
-        if ( component.isArchived() ){
+        if (component.isArchived()) {
             LOGGER.debug("automated Upgrade failed - target is archived component {}  version {} ", component.getName(), component.getVersion());
             ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.COMPONENT_IS_ARCHIVED, component.getName());
             status.setError(responseFormat);
             componentsUtils.auditComponentAdmin(responseFormat, user, component, getAuditTypeByComponent(component), component.getComponentType());
-
             return status;
         }
         switch (component.getComponentType()) {
-        case RESOURCE:
-            hadnleUpgradeVFInService(component, upgradeRequest, user, status);
-            break;
-        case SERVICE:
-            hadnleUpgradeService(component, upgradeRequest, user, status);
-            break;
-        default:
-            LOGGER.debug("automated Upgrade failed - Not supported type {} for component {} ", component.getComponentType(), component.getName());
-            status.setError(componentsUtils.getResponseFormat(ActionStatus.UNSUPPORTED_ERROR));
+            case RESOURCE:
+                hadnleUpgradeVFInService(component, upgradeRequest, user, status);
+                break;
+            case SERVICE:
+                hadnleUpgradeService(component, upgradeRequest, user, status);
+                break;
+            default:
+                LOGGER.debug("automated Upgrade failed - Not supported type {} for component {} ", component.getComponentType(), component.getName());
+                status.setError(componentsUtils.getResponseFormat(ActionStatus.UNSUPPORTED_ERROR));
         }
         return status;
     }
 
     /**
-     * 
      * @param componentId
      * @param userId
      * @return
      */
     public Either<List<ComponentDependency>, ResponseFormat> getComponentDependencies(String componentId, String userId) {
-
         User user = userValidations.validateUserExists(userId);
         try {
-            return upgradeOperation.getComponentDependencies(componentId)
-                    .right()
-                    .map(rf -> componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(rf)));
+            return upgradeOperation.getComponentDependencies(componentId).right()
+                .map(rf -> componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(rf)));
         } finally {
             // all operation were read only. no commit needed
             janusGraphDao.rollback();
         }
-
     }
 
     private UpgradeStatus hadnleUpgradeVFInService(Component component, List<UpgradeRequest> componentUids, User user, UpgradeStatus upgradeStatus) {
@@ -156,26 +146,30 @@ public class UpgradeBusinessLogic {
         if (vfResource.getResourceType() != ResourceTypeEnum.VF) {
             LOGGER.debug("automated Upgrade failed - target is not VF resource {} {} ", vfResource.getName(), vfResource.getResourceType());
             upgradeStatus.setStatus(ActionStatus.GENERAL_ERROR);
-            componentsUtils.auditComponentAdmin(componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR), user, component, getAuditTypeByComponent(component), component.getComponentType());
+            componentsUtils.auditComponentAdmin(componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR), user, component,
+                getAuditTypeByComponent(component), component.getComponentType());
             return upgradeStatus;
         }
         componentUids.forEach(request -> upgradeInSingleService(request, vfResource, user, upgradeStatus));
         upgradeStatus.setStatus(ActionStatus.OK);
-        componentsUtils.auditComponentAdmin(componentsUtils.getResponseFormat(ActionStatus.OK), user, component, AuditingActionEnum.VF_UPGRADE_SERVICES, component.getComponentType());
-
+        componentsUtils
+            .auditComponentAdmin(componentsUtils.getResponseFormat(ActionStatus.OK), user, component, AuditingActionEnum.VF_UPGRADE_SERVICES,
+                component.getComponentType());
         return upgradeStatus;
     }
 
     private UpgradeStatus hadnleUpgradeService(Component component, List<UpgradeRequest> upgradeRequest, User user, UpgradeStatus upgradeStatus) {
-        if ( Role.TESTER.name().equals(user.getRole()) ){
+        if (Role.TESTER.name().equals(user.getRole())) {
             user.setRole(Role.DESIGNER.name());
             LOGGER.debug("Change temporary for update service reference user role from TESTER to DESINGER");
         }
         Service service = (Service) component;
         upgradeRequest.forEach(request -> upgradeSingleService(request, service, user, upgradeStatus));
         upgradeStatus.setStatus(ActionStatus.OK);
-        componentsUtils.auditComponentAdmin(componentsUtils.getResponseFormat(ActionStatus.OK), user, component, AuditingActionEnum.UPDATE_SERVICE_REFERENCE, component.getComponentType());
-       return upgradeStatus;
+        componentsUtils
+            .auditComponentAdmin(componentsUtils.getResponseFormat(ActionStatus.OK), user, component, AuditingActionEnum.UPDATE_SERVICE_REFERENCE,
+                component.getComponentType());
+        return upgradeStatus;
     }
 
     private ActionStatus upgradeSingleService(UpgradeRequest request, Service service, User user, UpgradeStatus upgradeStatus) {
@@ -190,8 +184,7 @@ public class UpgradeBusinessLogic {
 
     private ActionStatus upgradeInSingleService(UpgradeRequest request, Component newVersionComponent, User user, UpgradeStatus upgradeStatus) {
         String serviceId = request.getServiceId();
-        return toscaOperationFacade.getToscaFullElement(serviceId)
-                .either(l -> handleService(l, newVersionComponent, user, upgradeStatus), err -> {
+        return toscaOperationFacade.getToscaFullElement(serviceId).either(l -> handleService(l, newVersionComponent, user, upgradeStatus), err -> {
             LOGGER.debug("Failed to fetch service by id {} error {}", serviceId, err);
             ActionStatus errS = componentsUtils.convertFromStorageResponse(err);
             upgradeStatus.addServiceStatus(serviceId, errS);
@@ -205,10 +198,8 @@ public class UpgradeBusinessLogic {
         if (upgradeAllottedResource.isRight()) {
             return upgradeAllottedResource.right().value();
         }
-
         resource = upgradeAllottedResource.left().value();
         // update VF instance in service
-
         Either<Component, StorageOperationStatus> serviceContainer = toscaOperationFacade.getToscaFullElement(request.getServiceId());
         if (serviceContainer.isRight()) {
             LOGGER.debug("Failed to fetch resource by id {} error {}", request.getServiceId(), serviceContainer.right().value());
@@ -217,82 +208,84 @@ public class UpgradeBusinessLogic {
             return errS;
         }
         return handleService(serviceContainer.left().value(), resource, user, upgradeStatus);
-
     }
 
-    private Either<? extends Component, ActionStatus> upgradeAllottedResource(UpgradeRequest request, User user, UpgradeStatus upgradeStatus, Service service) {
-        return getElement(request.getResourceId(), upgradeStatus, request)
-                .left()
-                .bind(l -> upgradeStateAlloted(request, user, upgradeStatus, service, l));
+    private Either<? extends Component, ActionStatus> upgradeAllottedResource(UpgradeRequest request, User user, UpgradeStatus upgradeStatus,
+                                                                              Service service) {
+        return getElement(request.getResourceId(), upgradeStatus, request).left()
+            .bind(l -> upgradeStateAlloted(request, user, upgradeStatus, service, l));
     }
 
     private Either<Component, ActionStatus> getElement(String id, UpgradeStatus upgradeStatus, UpgradeRequest request) {
-        return toscaOperationFacade.getToscaElement(id)
-                .right()
-                .map(err -> {
+        return toscaOperationFacade.getToscaElement(id).right().map(err -> {
             ActionStatus errS = componentsUtils.convertFromStorageResponse(err);
             upgradeStatus.addServiceStatus(request.getServiceId(), errS);
             return errS;
         });
     }
 
-    private Either<? extends Component, ActionStatus> upgradeStateAlloted(UpgradeRequest request, User user, UpgradeStatus upgradeStatus, Service service, Component resource) {
+    private Either<? extends Component, ActionStatus> upgradeStateAlloted(UpgradeRequest request, User user, UpgradeStatus upgradeStatus,
+                                                                          Service service, Component resource) {
         if (resource.getLifecycleState() == LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT) {
             LOGGER.debug("Automated upgrade failedd. Alloted vf {} is in state NOT_CERTIFIED_CHECKOUT", request.getResourceId());
             upgradeStatus.addServiceStatus(request.getServiceId(), ActionStatus.RESOURCE_LIFECYCLE_STATE_NOT_VALID);
             return Either.right(ActionStatus.RESOURCE_LIFECYCLE_STATE_NOT_VALID);
         }
         // check out VF
+
         // update properties-reference to service in VF on VFCI
-        return changeComponentState(resource, LifeCycleTransitionEnum.CHECKOUT, user,  upgradeStatus, request.getServiceId())
-                .left()
-                .bind(l -> updateAllottedPropsAndCertify(request, user, upgradeStatus, service, l));
+        return changeComponentState(resource, LifeCycleTransitionEnum.CHECKOUT, user, upgradeStatus, request.getServiceId()).left()
+            .bind(l -> updateAllottedPropsAndCertify(request, user, upgradeStatus, service, l));
     }
 
-    private Either<? extends Component, ActionStatus> updateAllottedPropsAndCertify(UpgradeRequest request, User user, UpgradeStatus upgradeStatus, Service service, Component resource) {
+    private Either<? extends Component, ActionStatus> updateAllottedPropsAndCertify(UpgradeRequest request, User user, UpgradeStatus upgradeStatus,
+                                                                                    Service service, Component resource) {
         Either<? extends Component, ActionStatus> result = null;
         try {
             List<String> instanceIds = upgradeOperation.getInstanceIdFromAllottedEdge(resource.getUniqueId(), service.getInvariantUUID());
             if (instanceIds != null) {
                 Map<String, List<ComponentInstanceProperty>> componentInstancesProperties = resource.getComponentInstancesProperties();
                 Map<String, List<ComponentInstanceProperty>> propertiesToUpdate = new HashMap<>();
-
                 instanceIds.forEach(id -> findPropertiesToUpdate(id, componentInstancesProperties, propertiesToUpdate, service));
-
-                Either<Map<String, List<ComponentInstanceProperty>>, StorageOperationStatus> updatePropsResult = toscaOperationFacade.updateComponentInstancePropsToComponent(propertiesToUpdate, resource.getUniqueId());
+                Either<Map<String, List<ComponentInstanceProperty>>, StorageOperationStatus> updatePropsResult = toscaOperationFacade
+                    .updateComponentInstancePropsToComponent(propertiesToUpdate, resource.getUniqueId());
                 if (updatePropsResult.isRight()) {
-                    LOGGER.debug("Failed to update properties in  Allotted resource {} {}, Error {}. ", resource.getName(), resource.getUniqueId(), updatePropsResult.right().value());
-
+                    LOGGER.debug("Failed to update properties in  Allotted resource {} {}, Error {}. ", resource.getName(), resource.getUniqueId(),
+                        updatePropsResult.right().value());
                     result = Either.right(ActionStatus.GENERAL_ERROR);
                     return result;
                 }
-
                 // certify VF
-                result =  changeComponentState(resource, LifeCycleTransitionEnum.CERTIFY, user,  upgradeStatus, request.getServiceId());
+                result = changeComponentState(resource, LifeCycleTransitionEnum.CERTIFY, user, upgradeStatus, request.getServiceId());
             } else {
                 // nothing to update
                 LOGGER.debug("No Instances to update in allotted resource {} ", resource.getName());
                 result = Either.right(ActionStatus.NO_INSTANCES_TO_UPGRADE);
             }
             return result;
-        } finally  {
-            if ( result != null && result.isRight() ){
+        } finally {
+            if (result != null && result.isRight()) {
                 // undo checkout resource in case of failure
-                LOGGER.debug("Failed to update Allotted resource {} {}, Error {}. UNDOCHEKOUT our resource", resource.getName(), resource.getUniqueId(), result.right().value());
-
+                LOGGER
+                    .debug("Failed to update Allotted resource {} {}, Error {}. UNDOCHEKOUT our resource", resource.getName(), resource.getUniqueId(),
+                        result.right().value());
                 upgradeStatus.addServiceStatus(request.getServiceId(), ActionStatus.GENERAL_ERROR);
             }
         }
     }
 
     private void undocheckoutComponent(User user, Component resource) {
-        Either<? extends Component, ResponseFormat> changeComponentState = lifecycleBusinessLogic.changeComponentState(resource.getComponentType(), resource.getUniqueId(), user, LifeCycleTransitionEnum.UNDO_CHECKOUT, changeInfo, false, true);
+        Either<? extends Component, ResponseFormat> changeComponentState = lifecycleBusinessLogic
+            .changeComponentState(resource.getComponentType(), resource.getUniqueId(), user, LifeCycleTransitionEnum.UNDO_CHECKOUT, changeInfo, false,
+                true);
         if (changeComponentState.isRight()) {
-            LOGGER.debug("Failed to UNDOCHECKOUT Service {} {}, Error {}", resource.getName(), resource.getUniqueId(), changeComponentState.right().value());
+            LOGGER.debug("Failed to UNDOCHECKOUT Service {} {}, Error {}", resource.getName(), resource.getUniqueId(),
+                changeComponentState.right().value());
         }
     }
 
-    private void findPropertiesToUpdate(String id, Map<String, List<ComponentInstanceProperty>> componentInstancesProperties, Map<String, List<ComponentInstanceProperty>> propertiesToUpdate, Service service) {
+    private void findPropertiesToUpdate(String id, Map<String, List<ComponentInstanceProperty>> componentInstancesProperties,
+                                        Map<String, List<ComponentInstanceProperty>> propertiesToUpdate, Service service) {
         List<ComponentInstanceProperty> list = componentInstancesProperties.get(id);
         List<ComponentInstanceProperty> propsPerInstance = new ArrayList<>();
         list.forEach(p -> {
@@ -314,29 +307,30 @@ public class UpgradeBusinessLogic {
 
     private ActionStatus handleService(Component component, Component newVersionComponent, User user, UpgradeStatus upgradeStatus) {
         if (component.getComponentType() != ComponentTypeEnum.SERVICE) {
-            LOGGER.debug("component with id  {} and name {} isn't SERVICE.  type{} ", component.getName(), component.getUniqueId(), component.getComponentType());
+            LOGGER.debug("component with id  {} and name {} isn't SERVICE.  type{} ", component.getName(), component.getUniqueId(),
+                component.getComponentType());
             upgradeStatus.addServiceStatus(component, ActionStatus.GENERAL_ERROR);
             return ActionStatus.GENERAL_ERROR;
         }
-        
         Service service = (Service) component;
         if (component.getLifecycleState() != LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT) {
             LOGGER.debug("Service {} {} is not in CHECKOUT state . Try to checkout it", component.getName(), component.getUniqueId());
-            Either<? extends Component, ActionStatus> changeComponentState = changeComponentState(component, LifeCycleTransitionEnum.CHECKOUT, user,  upgradeStatus, null);
-            if ( changeComponentState.isRight() ){
+            Either<? extends Component, ActionStatus> changeComponentState = changeComponentState(component, LifeCycleTransitionEnum.CHECKOUT, user,
+                upgradeStatus, null);
+            if (changeComponentState.isRight()) {
                 return changeComponentState.right().value();
             }
             service = (Service) changeComponentState.left().value();
             //need to fetch service again with capability properties
             Either<Component, StorageOperationStatus> toscaFullElement = toscaOperationFacade.getToscaFullElement(service.getUniqueId());
-            if ( toscaFullElement.isRight() ){
+            if (toscaFullElement.isRight()) {
                 return componentsUtils.convertFromStorageResponse(toscaFullElement.right().value());
             }
             service = (Service) toscaFullElement.left().value();
-        }else{
+        } else {
             LOGGER.debug("Service {} {} is  in CHECKOUT state . Restricted update operation", component.getName(), component.getUniqueId());
             upgradeStatus.addServiceStatus(component, ActionStatus.COMPONENT_IN_CHECKOUT_STATE);
-            return ActionStatus.COMPONENT_IN_CHECKOUT_STATE;          
+            return ActionStatus.COMPONENT_IN_CHECKOUT_STATE;
         }
         ActionStatus status = ActionStatus.GENERAL_ERROR;
         try {
@@ -345,34 +339,34 @@ public class UpgradeBusinessLogic {
             if (status != ActionStatus.OK) {
                 LOGGER.debug("Failed to upgrade instance for service {} status {}. Undocheckout service", service.getName(), status);
                 undocheckoutComponent(user, service);
-
                 upgradeStatus.addServiceStatus(component, status);
             }
         }
         return status;
     }
-    
-    private Either<? extends Component,ActionStatus> changeComponentState(Component component, LifeCycleTransitionEnum nextState, User user, UpgradeStatus upgradeStatus, String idForStatus){
-        if ( component.isArchived() ){
-            LOGGER.debug("Component  {} from type {} id {} is archived, Error {}", nextState, component.getName(), component.getComponentType(), component.getUniqueId());
+
+    private Either<? extends Component, ActionStatus> changeComponentState(Component component, LifeCycleTransitionEnum nextState, User user,
+                                                                           UpgradeStatus upgradeStatus, String idForStatus) {
+        if (component.isArchived()) {
+            LOGGER.debug("Component  {} from type {} id {} is archived, Error {}", nextState, component.getName(), component.getComponentType(),
+                component.getUniqueId());
             setUpgradeStatus(component, upgradeStatus, idForStatus);
             return Either.right(ActionStatus.COMPONENT_IS_ARCHIVED);
         }
-        return lifecycleBusinessLogic.changeComponentState(component.getComponentType(), component.getUniqueId(), user, nextState, changeInfo, false, true)
-                .right()
-                .map(err-> {
-                    LOGGER.debug("Failed to {} Component  {} from type {} id {}, Error {}", nextState, component.getName(), component.getComponentType(), component.getUniqueId(), err);
-                    setUpgradeStatus(component, upgradeStatus, idForStatus);
-                    return ActionStatus.GENERAL_ERROR;
-                         
-                });
+        return lifecycleBusinessLogic
+            .changeComponentState(component.getComponentType(), component.getUniqueId(), user, nextState, changeInfo, false, true).right()
+            .map(err -> {
+                LOGGER.debug("Failed to {} Component  {} from type {} id {}, Error {}", nextState, component.getName(), component.getComponentType(),
+                    component.getUniqueId(), err);
+                setUpgradeStatus(component, upgradeStatus, idForStatus);
+                return ActionStatus.GENERAL_ERROR;
+            });
     }
 
-
     private void setUpgradeStatus(Component component, UpgradeStatus upgradeStatus, String idForStatus) {
-        if ( idForStatus == null ){ 
+        if (idForStatus == null) {
             upgradeStatus.addServiceStatus(component, ActionStatus.GENERAL_ERROR);
-        }else{
+        } else {
             upgradeStatus.addServiceStatus(idForStatus, ActionStatus.GENERAL_ERROR);
         }
     }
@@ -380,10 +374,8 @@ public class UpgradeBusinessLogic {
     private ActionStatus handleInstances(Component newVersionComponent, User user, UpgradeStatus upgradeStatus, Service service) {
         List<ComponentInstance> componentInstances = service.getComponentInstances();
         if (componentInstances != null) {
-            List<ComponentInstance> instanceToChange = componentInstances
-                    .stream()
-                    .filter(ci -> matchInstance(ci, newVersionComponent))
-                    .collect(Collectors.toList());
+            List<ComponentInstance> instanceToChange = componentInstances.stream().filter(ci -> matchInstance(ci, newVersionComponent))
+                .collect(Collectors.toList());
             if (instanceToChange != null && !instanceToChange.isEmpty()) {
                 return changeInstances(newVersionComponent, user, upgradeStatus, service, instanceToChange);
             } else {
@@ -394,11 +386,12 @@ public class UpgradeBusinessLogic {
         return ActionStatus.OK;
     }
 
-    private ActionStatus changeInstances(Component newVersionComponent, User user, UpgradeStatus upgradeStatus, Service service, List<ComponentInstance> instanceToChange) {
+    private ActionStatus changeInstances(Component newVersionComponent, User user, UpgradeStatus upgradeStatus, Service service,
+                                         List<ComponentInstance> instanceToChange) {
         Component serviceToUpgrade = service;
         for (ComponentInstance ci : instanceToChange) {
-            Either<Component, ActionStatus> fetchService = fetchService(service.getUniqueId(),service.getName());
-            if ( fetchService.isRight()){
+            Either<Component, ActionStatus> fetchService = fetchService(service.getUniqueId(), service.getName());
+            if (fetchService.isRight()) {
                 upgradeStatus.addServiceStatus(service, fetchService.right().value());
                 return fetchService.right().value();
             }
@@ -410,36 +403,34 @@ public class UpgradeBusinessLogic {
                 return status;
             }
         }
-        Either<Component, ActionStatus> fetchService = fetchService(service.getUniqueId(),service.getName());
-        if ( fetchService.isRight()){
+        Either<Component, ActionStatus> fetchService = fetchService(service.getUniqueId(), service.getName());
+        if (fetchService.isRight()) {
             upgradeStatus.addServiceStatus(service, fetchService.right().value());
             return fetchService.right().value();
         }
         serviceToUpgrade = fetchService.left().value();
-        
-        Either<? extends Component, ActionStatus> changeComponentState = changeComponentState(serviceToUpgrade, LifeCycleTransitionEnum.CHECKIN, user,  upgradeStatus, null);
-        if ( changeComponentState.isRight() ){
+        Either<? extends Component, ActionStatus> changeComponentState = changeComponentState(serviceToUpgrade, LifeCycleTransitionEnum.CHECKIN, user,
+            upgradeStatus, null);
+        if (changeComponentState.isRight()) {
             return changeComponentState.right().value();
         }
         upgradeStatus.addServiceStatus(serviceToUpgrade, ActionStatus.OK);
         return ActionStatus.OK;
     }
 
-
     private Either<Component, ActionStatus> fetchService(String uniqueId, String name) {
-        return toscaOperationFacade.getToscaFullElement(uniqueId)
-                .right()
-                .map(r->{
-                    LOGGER.debug("Failed to fetch service {} id {} error {}", name, uniqueId, r);
-                    return ActionStatus.GENERAL_ERROR;
-                });
+        return toscaOperationFacade.getToscaFullElement(uniqueId).right().map(r -> {
+            LOGGER.debug("Failed to fetch service {} id {} error {}", name, uniqueId, r);
+            return ActionStatus.GENERAL_ERROR;
+        });
     }
 
     private ActionStatus changeVersionOfInstance(Component service, ComponentInstance ci, Component newVersionComponent, User user) {
         LOGGER.debug("In Service {} change instance version {} to version {}", service.getName(), ci.getName(), newVersionComponent.getVersion());
         ComponentInstance newComponentInstance = new ComponentInstance();
         newComponentInstance.setComponentUid(newVersionComponent.getUniqueId());
-        ComponentInstance changeInstanceVersion = componentInstanceBusinessLogic.changeInstanceVersion(service, ci, newComponentInstance, user, service.getComponentType());
+        ComponentInstance changeInstanceVersion = componentInstanceBusinessLogic
+            .changeInstanceVersion(service, ci, newComponentInstance, user, service.getComponentType());
         return ActionStatus.OK;
     }
 
@@ -457,18 +448,19 @@ public class UpgradeBusinessLogic {
         }
         if (toscaElement.isLeft()) {
             Component origin = toscaElement.left().value();
-            if (newVersionComponent.getInvariantUUID().equals(origin.getInvariantUUID()) && !newVersionComponent.getVersion().equals(origin.getVersion())) {
+            if (newVersionComponent.getInvariantUUID().equals(origin.getInvariantUUID()) && !newVersionComponent.getVersion()
+                .equals(origin.getVersion())) {
                 // only for same invariant UUID (same component) but different versions
                 return true;
             }
         }
         return false;
     }
-    private AuditingActionEnum getAuditTypeByComponent(Component component){
-        if ( ComponentTypeEnum.RESOURCE == component.getComponentType()){
+
+    private AuditingActionEnum getAuditTypeByComponent(Component component) {
+        if (ComponentTypeEnum.RESOURCE == component.getComponentType()) {
             return AuditingActionEnum.VF_UPGRADE_SERVICES;
         }
         return AuditingActionEnum.UPDATE_SERVICE_REFERENCE;
     }
-
 }
index d432459..d84c32b 100644 (file)
@@ -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.
  * limitations under the License.
  * ============LICENSE_END=========================================================
  */
-
 package org.openecomp.sdc.be.components.upgrade;
 
 public class UpgradeRequest {
+
     private String serviceId;
     private String resourceId;
-     
-    public UpgradeRequest(){
-        
+
+    public UpgradeRequest() {
     }
-    public UpgradeRequest(String serviceId ){
+
+    public UpgradeRequest(String serviceId) {
         this.serviceId = serviceId;
     }
-    public UpgradeRequest(String serviceId, String resourceId ){
+
+    public UpgradeRequest(String serviceId, String resourceId) {
         this.serviceId = serviceId;
         this.resourceId = resourceId;
     }
-    
+
     public String getServiceId() {
         return serviceId;
     }
+
     public void setServiceId(String serviceId) {
         this.serviceId = serviceId;
     }
+
     public String getResourceId() {
         return resourceId;
     }
+
     public void setResourceId(String resourceId) {
         this.resourceId = resourceId;
     }
-    
-
 }
index da4dd6b..46d7307 100644 (file)
@@ -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.
  * limitations under the License.
  * ============LICENSE_END=========================================================
  */
-
 package org.openecomp.sdc.be.components.upgrade;
 
+import java.util.ArrayList;
+import java.util.List;
 import org.openecomp.sdc.be.dao.api.ActionStatus;
 import org.openecomp.sdc.be.model.Component;
 import org.openecomp.sdc.exception.ResponseFormat;
 
-import java.util.ArrayList;
-import java.util.List;
-
 public class UpgradeStatus {
+
     ActionStatus status;
     ResponseFormat error;
-    
-    
     List<ServiceInfo> componentToUpgradeStatus;
 
     public ActionStatus getStatus() {
@@ -54,14 +51,16 @@ public class UpgradeStatus {
         checkAndCreate();
         componentToUpgradeStatus.add(info);
     }
+
     public void addServiceStatus(String serviceId, ActionStatus status) {
         checkAndCreate();
-        ServiceInfo info = new ServiceInfo(serviceId, status );
+        ServiceInfo info = new ServiceInfo(serviceId, status);
         componentToUpgradeStatus.add(info);
     }
+
     public void addServiceStatus(Component component, ActionStatus status) {
         checkAndCreate();
-        ServiceInfo info = new ServiceInfo(component.getUniqueId(), status );
+        ServiceInfo info = new ServiceInfo(component.getUniqueId(), status);
         info.setName(component.getName());
         info.setVersion(component.getVersion());
         componentToUpgradeStatus.add(info);
@@ -80,5 +79,4 @@ public class UpgradeStatus {
     public void setError(ResponseFormat error) {
         this.error = error;
     }
-    
 }
index 9f95caa..ffe1d40 100644 (file)
@@ -19,7 +19,6 @@
  * Modifications copyright (c) 2019 Nokia
  * ================================================================================
  */
-
 package org.openecomp.sdc.be.components.utils;
 
 import com.google.gson.Gson;
index d6e881d..c4eaa3a 100644 (file)
  * See the License for the specific language governing permissions and
  * limitations under the License.
  */
-
 package org.openecomp.sdc.be.components.utils;
 
 import com.google.gson.Gson;
 import fj.data.Either;
+import java.util.ArrayList;
+import java.util.Collection;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+import java.util.stream.Collectors;
 import org.apache.commons.collections.CollectionUtils;
 import org.openecomp.sdc.be.components.impl.ResponseFormatManager;
 import org.openecomp.sdc.be.dao.api.ActionStatus;
@@ -28,37 +33,27 @@ import org.openecomp.sdc.be.model.CapabilityDefinition;
 import org.openecomp.sdc.be.model.ComponentInstanceProperty;
 import org.openecomp.sdc.be.model.Operation;
 import org.openecomp.sdc.be.model.PropertyDefinition;
-import org.openecomp.sdc.tosca.datatypes.ToscaFunctions;
 import org.openecomp.sdc.be.model.tosca.ToscaPropertyType;
 import org.openecomp.sdc.be.model.tosca.validators.PropertyTypeValidator;
 import org.openecomp.sdc.be.types.ServiceConsumptionData;
 import org.openecomp.sdc.exception.ResponseFormat;
-
-import java.util.ArrayList;
-import java.util.Collection;
-import java.util.HashMap;
-import java.util.List;
-import java.util.Map;
-import java.util.stream.Collectors;
+import org.openecomp.sdc.tosca.datatypes.ToscaFunctions;
 
 public class ConsumptionUtils {
 
     private ConsumptionUtils() {
-
     }
 
-    public static Either<Operation, ResponseFormat> handleConsumptionInputMappedToCapabilityProperty(
-            Operation operation,
-            OperationInputDefinition operationInputDefinition, ServiceConsumptionData serviceConsumptionData,
-            Map<String, List<CapabilityDefinition>> capabilities, String componentName) {
-
-        List<CapabilityDefinition> componentCapabilityDefinitions = capabilities.values().stream()
-                .flatMap(Collection::stream)
-                .collect(Collectors.toList());
+    public static Either<Operation, ResponseFormat> handleConsumptionInputMappedToCapabilityProperty(Operation operation,
+                                                                                                     OperationInputDefinition operationInputDefinition,
+                                                                                                     ServiceConsumptionData serviceConsumptionData,
+                                                                                                     Map<String, List<CapabilityDefinition>> capabilities,
+                                                                                                     String componentName) {
+        List<CapabilityDefinition> componentCapabilityDefinitions = capabilities.values().stream().flatMap(Collection::stream)
+            .collect(Collectors.toList());
         if (CollectionUtils.isEmpty(componentCapabilityDefinitions)) {
             return Either.left(operation);
         }
-
         for (CapabilityDefinition capabilityDefinition : componentCapabilityDefinitions) {
             String capabilityName = capabilityDefinition.getName();
             List<ComponentInstanceProperty> capabilityProperties = capabilityDefinition.getProperties();
@@ -69,14 +64,12 @@ public class ConsumptionUtils {
                 String capabilityPropertyName = capabilityProperty.getName();
                 String capabilityPropertyIdentifier = capabilityName + "_" + capabilityPropertyName;
                 if (capabilityPropertyIdentifier.equals(serviceConsumptionData.getValue())) {
-                    boolean isInputTypeSimilarToOperation =
-                            isAssignedValueFromValidType(operationInputDefinition.getType(), capabilityProperty);
+                    boolean isInputTypeSimilarToOperation = isAssignedValueFromValidType(operationInputDefinition.getType(), capabilityProperty);
                     if (!isInputTypeSimilarToOperation) {
-                        return Either.right(getResponseFormatManager().getResponseFormat(
-                                ActionStatus.INVALID_CONSUMPTION_TYPE, operationInputDefinition.getType()));
+                        return Either.right(
+                            getResponseFormatManager().getResponseFormat(ActionStatus.INVALID_CONSUMPTION_TYPE, operationInputDefinition.getType()));
                     }
-                    addCapabilityPropertyToInputValue(componentName, capabilityName, operation,
-                            operationInputDefinition, capabilityProperty);
+                    addCapabilityPropertyToInputValue(componentName, capabilityName, operation, operationInputDefinition, capabilityProperty);
                 }
             }
         }
@@ -84,21 +77,16 @@ public class ConsumptionUtils {
     }
 
     private static void addCapabilityPropertyToInputValue(String componentName, String capabilityName, Operation operation,
-                                                   OperationInputDefinition operationInputDefinition,
-                                                   PropertyDefinition capabilityProperty) {
-
+                                                          OperationInputDefinition operationInputDefinition, PropertyDefinition capabilityProperty) {
         List<String> getPropertyValues = new ArrayList<>();
         getPropertyValues.add(componentName);
         getPropertyValues.add(capabilityName);
         getPropertyValues.add(capabilityProperty.getName());
-
         Map<String, List<String>> getProperty = new HashMap<>();
         getProperty.put(ToscaFunctions.GET_PROPERTY.getFunctionName(), getPropertyValues);
-
         operationInputDefinition.setSourceProperty(capabilityProperty.getUniqueId());
         operation.getInputs().delete(operationInputDefinition);
-        operationInputDefinition.setToscaPresentationValue(JsonPresentationFields.GET_PROPERTY,
-                getPropertyValues);
+        operationInputDefinition.setToscaPresentationValue(JsonPresentationFields.GET_PROPERTY, getPropertyValues);
         operationInputDefinition.setValue((new Gson()).toJson(getProperty));
         operation.getInputs().add(operationInputDefinition);
     }
@@ -108,7 +96,7 @@ public class ConsumptionUtils {
             // validate static value
             ToscaPropertyType actualType = ToscaPropertyType.isValidType(operationInputType);
             PropertyTypeValidator validator = actualType.getValidator();
-            return validator.isValid((String)actualValue, operationInputType);
+            return validator.isValid((String) actualValue, operationInputType);
         } else if (actualValue instanceof PropertyDefinition) {
             // validate input / property value
             String actualType = ((PropertyDefinition) actualValue).getType();
index 17c4b04..edbad79 100644 (file)
  * See the License for the specific language governing permissions and
  * limitations under the License.
  */
-
 package org.openecomp.sdc.be.components.utils;
 
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+import java.util.Objects;
+import java.util.Optional;
+import java.util.stream.Collectors;
 import org.apache.commons.collections.CollectionUtils;
 import org.apache.commons.collections4.MapUtils;
 import org.openecomp.sdc.be.datatypes.elements.InterfaceDataDefinition;
@@ -27,90 +34,63 @@ import org.openecomp.sdc.be.model.Component;
 import org.openecomp.sdc.be.model.InputDefinition;
 import org.openecomp.sdc.be.model.InterfaceDefinition;
 import org.openecomp.sdc.be.model.Operation;
-import org.openecomp.sdc.tosca.datatypes.ToscaFunctions;
 import org.openecomp.sdc.be.tosca.InterfacesOperationsConverter;
-
-import java.util.ArrayList;
-import java.util.Arrays;
-import java.util.HashMap;
-import java.util.List;
-import java.util.Map;
-import java.util.Objects;
-import java.util.Optional;
-import java.util.stream.Collectors;
+import org.openecomp.sdc.tosca.datatypes.ToscaFunctions;
 
 public class InterfaceOperationUtils {
 
     private InterfaceOperationUtils() {
     }
 
-    public static Optional<InterfaceDefinition> getInterfaceDefinitionFromComponentByInterfaceType(Component component,
-            String interfaceType) {
+    public static Optional<InterfaceDefinition> getInterfaceDefinitionFromComponentByInterfaceType(Component component, String interfaceType) {
         if (MapUtils.isEmpty(component.getInterfaces())) {
             return Optional.empty();
         }
         return component.getInterfaces().values().stream()
-                       .filter(interfaceDefinition -> interfaceDefinition.getType() != null && interfaceDefinition
-                                                                                                       .getType()
-                                                                                                       .equals(interfaceType))
-                       .findAny();
+            .filter(interfaceDefinition -> interfaceDefinition.getType() != null && interfaceDefinition.getType().equals(interfaceType)).findAny();
     }
 
-    public static Optional<InterfaceDefinition> getInterfaceDefinitionFromComponentByInterfaceId(Component component,
-            String interfaceId) {
+    public static Optional<InterfaceDefinition> getInterfaceDefinitionFromComponentByInterfaceId(Component component, String interfaceId) {
         if (MapUtils.isEmpty(component.getInterfaces())) {
             return Optional.empty();
         }
         return component.getInterfaces().values().stream()
-                       .filter(interfaceDefinition -> interfaceDefinition.getUniqueId() != null && interfaceDefinition
-                                                                                                           .getUniqueId()
-                                                                                                           .equals(interfaceId))
-                       .findAny();
+            .filter(interfaceDefinition -> interfaceDefinition.getUniqueId() != null && interfaceDefinition.getUniqueId().equals(interfaceId))
+            .findAny();
     }
 
-    public static Optional<Map.Entry<String, Operation>> getOperationFromInterfaceDefinition(
-            InterfaceDefinition interfaceDefinition, String operationId) {
+    public static Optional<Map.Entry<String, Operation>> getOperationFromInterfaceDefinition(InterfaceDefinition interfaceDefinition,
+                                                                                             String operationId) {
         if (MapUtils.isEmpty(interfaceDefinition.getOperationsMap())) {
             return Optional.empty();
         }
-        return interfaceDefinition.getOperationsMap().entrySet().stream()
-                       .filter(entry -> entry.getValue().getUniqueId().equals(operationId)).findAny();
+        return interfaceDefinition.getOperationsMap().entrySet().stream().filter(entry -> entry.getValue().getUniqueId().equals(operationId))
+            .findAny();
     }
 
-    public static Optional<InterfaceDefinition> getInterfaceDefinitionFromOperationId(List<InterfaceDefinition> interfaces,
-            String operationId) {
+    public static Optional<InterfaceDefinition> getInterfaceDefinitionFromOperationId(List<InterfaceDefinition> interfaces, String operationId) {
         if (CollectionUtils.isEmpty(interfaces)) {
             return Optional.empty();
         }
-        return interfaces.stream()
-                       .filter(interfaceDefinition -> interfaceDefinition.getOperationsMap().containsKey(operationId))
-                       .findAny();
+        return interfaces.stream().filter(interfaceDefinition -> interfaceDefinition.getOperationsMap().containsKey(operationId)).findAny();
     }
 
-    public static boolean isOperationInputMappedToComponentInput(OperationInputDefinition input,
-                                                                                    List<InputDefinition> inputs) {
+    public static boolean isOperationInputMappedToComponentInput(OperationInputDefinition input, List<InputDefinition> inputs) {
         if (CollectionUtils.isEmpty(inputs)) {
             return false;
         }
-
         boolean matchedInput = inputs.stream().anyMatch(inp -> inp.getUniqueId().equals(input.getInputId()));
         if (!matchedInput && input.getInputId().contains(".")) {
-            return inputs.stream()
-                    .anyMatch(inp -> inp.getUniqueId()
-                            .equals(input.getInputId().substring(0, input.getInputId().lastIndexOf('.'))));
+            return inputs.stream().anyMatch(inp -> inp.getUniqueId().equals(input.getInputId().substring(0, input.getInputId().lastIndexOf('.'))));
         }
         return matchedInput;
     }
 
-    public static boolean isOperationInputMappedToOtherOperationOutput(String outputName,
-                                                                       List<OperationOutputDefinition>
-                                                                               otherOperationOutputs) {
+    public static boolean isOperationInputMappedToOtherOperationOutput(String outputName, List<OperationOutputDefinition> otherOperationOutputs) {
         if (CollectionUtils.isEmpty(otherOperationOutputs)) {
             return false;
         }
-        return otherOperationOutputs.stream()
-                .anyMatch(output -> output.getName().equals(outputName));
-
+        return otherOperationOutputs.stream().anyMatch(output -> output.getName().equals(outputName));
     }
 
     public static Map<String, List<String>> createMappedInputPropertyDefaultValue(String propertyName) {
@@ -124,13 +104,11 @@ public class InterfaceOperationUtils {
         return getPropertyMap;
     }
 
-    public static Map<String, List<String>> createMappedCapabilityPropertyDefaultValue(String capabilityName,
-                                                                                       String propertyName) {
+    public static Map<String, List<String>> createMappedCapabilityPropertyDefaultValue(String capabilityName, String propertyName) {
         Map<String, List<String>> getPropertyMap = new HashMap<>();
         List<String> values = new ArrayList<>();
         values.add(InterfacesOperationsConverter.SELF);
         values.add(capabilityName);
-
         if (Objects.nonNull(propertyName) && !propertyName.isEmpty()) {
             values.addAll(Arrays.asList(propertyName.split("\\.")));
         }
@@ -140,18 +118,17 @@ public class InterfaceOperationUtils {
 
     /**
      * Get the list of outputs of other operations of all the interfaces in the component.
+     *
      * @param currentOperationIdentifier Fully qualified operation name e.g. org.test.interfaces.node.lifecycle.Abc.stop
-     * @param componentInterfaces VF or service interfaces
+     * @param componentInterfaces        VF or service interfaces
      */
-
-    public static ListDataDefinition<OperationOutputDefinition> getOtherOperationOutputsOfComponent(
-            String currentOperationIdentifier, Map<String, ? extends InterfaceDataDefinition> componentInterfaces) {
+    public static ListDataDefinition<OperationOutputDefinition> getOtherOperationOutputsOfComponent(String currentOperationIdentifier,
+                                                                                                    Map<String, ? extends InterfaceDataDefinition> componentInterfaces) {
         ListDataDefinition<OperationOutputDefinition> componentOutputs = new ListDataDefinition<>();
         if (MapUtils.isEmpty(componentInterfaces)) {
             return componentOutputs;
         }
-        for (Map.Entry<String, ? extends InterfaceDataDefinition> interfaceDefinitionEntry :
-                componentInterfaces.entrySet()) {
+        for (Map.Entry<String, ? extends InterfaceDataDefinition> interfaceDefinitionEntry : componentInterfaces.entrySet()) {
             String interfaceName = interfaceDefinitionEntry.getKey();
             final Map<String, OperationDataDefinition> operations = interfaceDefinitionEntry.getValue().getOperations();
             if (MapUtils.isEmpty(operations)) {
@@ -170,13 +147,16 @@ public class InterfaceOperationUtils {
 
     /**
      * Create the value for operation input mapped to an operation output.
+     *
      * @param propertyName the mapped other operation output full name
      * @return input map for tosca
      */
     public static Map<String, List<String>> createMappedOutputDefaultValue(String componentName, String propertyName) {
         Map<String, List<String>> getOperationOutputMap = new HashMap<>();
         //For operation input mapped to other operation output parameter, the mapped property value
+
         // should be of the format <interface name>.<operation name>.<output parameter name>
+
         // Operation name and output param name should not contain "."
         List<String> defaultMappedOperationOutputValue = new ArrayList<>();
         String[] tokens = propertyName.split("\\.");
@@ -184,26 +164,21 @@ public class InterfaceOperationUtils {
             defaultMappedOperationOutputValue.add(componentName);
             String outputPropertyName = tokens[tokens.length - 1];
             String operationName = tokens[tokens.length - 2];
-            String mappedPropertyInterfaceType =
-                    propertyName.substring(0, propertyName.indexOf(operationName + '.' + outputPropertyName) - 1);
-            defaultMappedOperationOutputValue.addAll(Arrays.asList(mappedPropertyInterfaceType, operationName,
-                    outputPropertyName));
-            getOperationOutputMap.put(ToscaFunctions.GET_OPERATION_OUTPUT.getFunctionName(),
-                    defaultMappedOperationOutputValue);
+            String mappedPropertyInterfaceType = propertyName.substring(0, propertyName.indexOf(operationName + '.' + outputPropertyName) - 1);
+            defaultMappedOperationOutputValue.addAll(Arrays.asList(mappedPropertyInterfaceType, operationName, outputPropertyName));
+            getOperationOutputMap.put(ToscaFunctions.GET_OPERATION_OUTPUT.getFunctionName(), defaultMappedOperationOutputValue);
         }
         return getOperationOutputMap;
     }
 
     public static String getOperationOutputName(String fullOutputIdentifier) {
-        return fullOutputIdentifier.contains(".")
-                ? fullOutputIdentifier.substring(fullOutputIdentifier.lastIndexOf('.') + 1)
-                : fullOutputIdentifier;
+        return fullOutputIdentifier.contains(".") ? fullOutputIdentifier.substring(fullOutputIdentifier.lastIndexOf('.') + 1) : fullOutputIdentifier;
     }
 
     public static boolean isArtifactInUse(Component component, String operationId, String artifactUniqueId) {
         return MapUtils.emptyIfNull(component.getInterfaces()).values().stream()
-                       .filter(o -> MapUtils.isNotEmpty(o.getOperations()) && !o.getOperations().containsKey(operationId))
-                       .flatMap(o -> o.getOperations().values().stream()).collect(Collectors.toList()).stream()
-                       .anyMatch(op -> op.getImplementation().getUniqueId().equals(artifactUniqueId));
+            .filter(o -> MapUtils.isNotEmpty(o.getOperations()) && !o.getOperations().containsKey(operationId))
+            .flatMap(o -> o.getOperations().values().stream()).collect(Collectors.toList()).stream()
+            .anyMatch(op -> op.getImplementation().getUniqueId().equals(artifactUniqueId));
     }
 }
index bf28790..045658d 100644 (file)
@@ -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.
  * limitations under the License.
  * ============LICENSE_END=========================================================
  */
-
 package org.openecomp.sdc.be.components.utils;
 
 import java.util.List;
 import java.util.Map;
 
 public class MapUtils {
-  public static boolean compareMaps(Map<String, Object> source, Map<String, Object> target) {
-    if (source == null && target == null) {
-      return true;
-    }
-    if ((source == null && target != null) || source != null && target == null
-        || source.keySet().size() != target.keySet().size()) {
-      return false;
-    }
-
-    for (Map.Entry<String, Object> entry : source.entrySet()) {
-      Object sourceObj = entry.getValue();
-      Object targetObj = target.get(entry.getKey());
-      if ((sourceObj == null && targetObj != null) || (sourceObj != null && targetObj == null)) {
-        return false;
-      }
-      if (!handleSourceAndTargetObjects(sourceObj, targetObj)) {
-        return false;
-      }
-    }
-    return true;
-
-  }
-
-  public static boolean compareLists(List<Object> source, List<Object> target) {
-    if (source == null && target == null) {
-      return true;
-    }
-    if ((source == null && target != null) || source != null && target == null ||
-        source.size() != target.size()) {
-      return false;
-    }
-    for (int i = 0; i < source.size(); i++) {
-      Object sourceObj = source.get(i);
-      Object targetObj = target.get(i);
-      if ((sourceObj == null && targetObj != null) || sourceObj != null && targetObj == null) {
-        return false;
-      }
-      if (!handleSourceAndTargetObjects(sourceObj, targetObj)) {
-        return false;
-      }
-    }
-    return true;
-  }
-
-  public static boolean handleSourceAndTargetObjects(Object sourceObj, Object targetObj) {
 
-    if (sourceObj == null && targetObj == null) {
-      return true;
+    public static boolean compareMaps(Map<String, Object> source, Map<String, Object> target) {
+        if (source == null && target == null) {
+            return true;
+        }
+        if ((source == null && target != null) || source != null && target == null || source.keySet().size() != target.keySet().size()) {
+            return false;
+        }
+        for (Map.Entry<String, Object> entry : source.entrySet()) {
+            Object sourceObj = entry.getValue();
+            Object targetObj = target.get(entry.getKey());
+            if ((sourceObj == null && targetObj != null) || (sourceObj != null && targetObj == null)) {
+                return false;
+            }
+            if (!handleSourceAndTargetObjects(sourceObj, targetObj)) {
+                return false;
+            }
+        }
+        return true;
     }
 
-    if (sourceObj == null && targetObj != null) {
-      return false;
-    }
-    if (sourceObj.getClass().equals(targetObj.getClass())) {
-      if (sourceObj instanceof Map) {
-        if (!compareMaps((Map<String, Object>) sourceObj, (Map<String, Object>) targetObj)) {
-          return false;
+    public static boolean compareLists(List<Object> source, List<Object> target) {
+        if (source == null && target == null) {
+            return true;
         }
-      } else if (sourceObj instanceof List) {
-        if (!compareLists((List<Object>) sourceObj, (List<Object>) targetObj)) {
-          return false;
+        if ((source == null && target != null) || source != null && target == null || source.size() != target.size()) {
+            return false;
         }
-      } else  {
-
-        if(sourceObj.getClass() != targetObj.getClass()){
-          return false;
+        for (int i = 0; i < source.size(); i++) {
+            Object sourceObj = source.get(i);
+            Object targetObj = target.get(i);
+            if ((sourceObj == null && targetObj != null) || sourceObj != null && targetObj == null) {
+                return false;
+            }
+            if (!handleSourceAndTargetObjects(sourceObj, targetObj)) {
+                return false;
+            }
         }
+        return true;
+    }
 
-        if (!sourceObj.equals(targetObj)) {
-          return false;
+    public static boolean handleSourceAndTargetObjects(Object sourceObj, Object targetObj) {
+        if (sourceObj == null && targetObj == null) {
+            return true;
+        }
+        if (sourceObj == null && targetObj != null) {
+            return false;
+        }
+        if (sourceObj.getClass().equals(targetObj.getClass())) {
+            if (sourceObj instanceof Map) {
+                if (!compareMaps((Map<String, Object>) sourceObj, (Map<String, Object>) targetObj)) {
+                    return false;
+                }
+            } else if (sourceObj instanceof List) {
+                if (!compareLists((List<Object>) sourceObj, (List<Object>) targetObj)) {
+                    return false;
+                }
+            } else {
+                if (sourceObj.getClass() != targetObj.getClass()) {
+                    return false;
+                }
+                if (!sourceObj.equals(targetObj)) {
+                    return false;
+                }
+            }
         }
-      }
+        return true;
     }
-    return true;
-  }
-
-
 }
index 351e2a3..15f56b9 100644 (file)
  * See the License for the specific language governing permissions and
  * limitations under the License.
  */
-
 package org.openecomp.sdc.be.components.utils;
 
+import static org.openecomp.sdc.be.components.property.GetInputUtils.isGetInputValueForInput;
+
 import com.google.common.base.CharMatcher;
+import java.util.ArrayList;
+import java.util.Collection;
+import java.util.HashSet;
+import java.util.List;
+import java.util.Map;
+import java.util.Objects;
+import java.util.Optional;
+import java.util.Set;
+import java.util.function.Function;
+import java.util.function.Predicate;
+import java.util.stream.Collectors;
 import org.apache.commons.collections.CollectionUtils;
 import org.apache.commons.collections.MapUtils;
 import org.apache.commons.collections4.ListUtils;
@@ -31,20 +43,6 @@ import org.openecomp.sdc.be.model.InputDefinition;
 import org.openecomp.sdc.be.model.PropertyDefinition;
 import org.openecomp.sdc.be.model.Resource;
 
-import java.util.ArrayList;
-import java.util.Collection;
-import java.util.HashSet;
-import java.util.List;
-import java.util.Map;
-import java.util.Objects;
-import java.util.Optional;
-import java.util.Set;
-import java.util.function.Function;
-import java.util.function.Predicate;
-import java.util.stream.Collectors;
-
-import static org.openecomp.sdc.be.components.property.GetInputUtils.isGetInputValueForInput;
-
 public class PropertiesUtils {
 
     private PropertiesUtils() {
@@ -57,41 +55,29 @@ public class PropertiesUtils {
             properties = new ArrayList<>();
         }
         Set<PropertyDefinition> serviceProperties = new HashSet<>(properties);
-        SetUtils.emptyIfNull(serviceProperties)
-                .forEach(propertyDefinition -> resolvePropertyValueFromInput(propertyDefinition,
-                        service.getInputs()));
-        Set<PropertyDefinition> inputs = ListUtils.emptyIfNull(service.getInputs()).stream()
-                        .map(PropertyDefinition::new)
-                        .collect(Collectors.toSet());
+        SetUtils.emptyIfNull(serviceProperties).forEach(propertyDefinition -> resolvePropertyValueFromInput(propertyDefinition, service.getInputs()));
+        Set<PropertyDefinition> inputs = ListUtils.emptyIfNull(service.getInputs()).stream().map(PropertyDefinition::new).collect(Collectors.toSet());
         serviceProperties.addAll(inputs);
-        serviceProperties = serviceProperties.stream()
-                .filter(distinctByKey(PropertyDefinition::getName))
-                .collect(Collectors.toSet());
+        serviceProperties = serviceProperties.stream().filter(distinctByKey(PropertyDefinition::getName)).collect(Collectors.toSet());
         return new ArrayList<>(serviceProperties);
     }
 
-    public static PropertyDefinition resolvePropertyValueFromInput(PropertyDefinition propertyDefinition,
-                                                                   List<InputDefinition> componentInputs) {
+    public static PropertyDefinition resolvePropertyValueFromInput(PropertyDefinition propertyDefinition, List<InputDefinition> componentInputs) {
         if (Objects.isNull(propertyDefinition) || CollectionUtils.isEmpty(componentInputs)) {
             return propertyDefinition;
         }
-        Optional<InputDefinition> mappedInput = componentInputs.stream()
-                .filter(componentInput -> Objects.nonNull(componentInput.getPropertyId())
-                        && componentInput.getPropertyId().equals(propertyDefinition.getUniqueId()))
-                .findFirst();
+        Optional<InputDefinition> mappedInput = componentInputs.stream().filter(
+            componentInput -> Objects.nonNull(componentInput.getPropertyId()) && componentInput.getPropertyId()
+                .equals(propertyDefinition.getUniqueId())).findFirst();
         mappedInput.ifPresent(inputDefinition -> propertyDefinition.setValue(inputDefinition.getValue()));
         return propertyDefinition;
     }
 
-
-    public static Optional<ComponentInstanceProperty> isCapabilityProperty(String propertyUniqueId,
-                                               Component containerComponent) {
-
+    public static Optional<ComponentInstanceProperty> isCapabilityProperty(String propertyUniqueId, Component containerComponent) {
         Optional<List<ComponentInstanceProperty>> capPropertiesOptional = getCapProperties(containerComponent);
-
-        if(capPropertiesOptional.isPresent()) {
-            return capPropertiesOptional.get().stream().filter(propertyDefinition ->
-                    propertyDefinition.getUniqueId().equals(propertyUniqueId)).findAny();
+        if (capPropertiesOptional.isPresent()) {
+            return capPropertiesOptional.get().stream().filter(propertyDefinition -> propertyDefinition.getUniqueId().equals(propertyUniqueId))
+                .findAny();
         } else {
             return Optional.empty();
         }
@@ -99,50 +85,44 @@ public class PropertiesUtils {
 
     private static Optional<List<ComponentInstanceProperty>> getCapProperties(Component containerComponent) {
         Map<String, List<CapabilityDefinition>> componentCapabilities = containerComponent.getCapabilities();
-        if(MapUtils.isEmpty(componentCapabilities)){
+        if (MapUtils.isEmpty(componentCapabilities)) {
             return Optional.empty();
         }
-        List<CapabilityDefinition> capabilityDefinitionList = componentCapabilities.values()
-                .stream().flatMap(Collection::stream).collect(Collectors.toList());
-        if(CollectionUtils.isEmpty(capabilityDefinitionList)){
+        List<CapabilityDefinition> capabilityDefinitionList = componentCapabilities.values().stream().flatMap(Collection::stream)
+            .collect(Collectors.toList());
+        if (CollectionUtils.isEmpty(capabilityDefinitionList)) {
             return Optional.empty();
         }
-        List<ComponentInstanceProperty> allComponentInstanceCapProperties= new ArrayList<>();
-        capabilityDefinitionList.stream().filter(capabilityDefinition -> CollectionUtils.isNotEmpty(capabilityDefinition
-                .getProperties())).collect(Collectors.toList()).forEach(capabilityDefinition ->
-                allComponentInstanceCapProperties.addAll(capabilityDefinition.getProperties()));
+        List<ComponentInstanceProperty> allComponentInstanceCapProperties = new ArrayList<>();
+        capabilityDefinitionList.stream().filter(capabilityDefinition -> CollectionUtils.isNotEmpty(capabilityDefinition.getProperties()))
+            .collect(Collectors.toList())
+            .forEach(capabilityDefinition -> allComponentInstanceCapProperties.addAll(capabilityDefinition.getProperties()));
         return Optional.of(allComponentInstanceCapProperties);
     }
 
     public static Optional<CapabilityDefinition> getPropertyCapabilityOfChildInstance(String propertyParentUniqueId,
-                                                                                      Map<String, List<CapabilityDefinition>>
-                                                                               componentCapabilities) {
-        if(MapUtils.isEmpty(componentCapabilities)){
+                                                                                      Map<String, List<CapabilityDefinition>> componentCapabilities) {
+        if (MapUtils.isEmpty(componentCapabilities)) {
             return Optional.empty();
         }
-        List<CapabilityDefinition> capabilityDefinitionList = componentCapabilities.values()
-                .stream().flatMap(Collection::stream).collect(Collectors.toList());
-        if(CollectionUtils.isEmpty(capabilityDefinitionList)){
+        List<CapabilityDefinition> capabilityDefinitionList = componentCapabilities.values().stream().flatMap(Collection::stream)
+            .collect(Collectors.toList());
+        if (CollectionUtils.isEmpty(capabilityDefinitionList)) {
             return Optional.empty();
         }
-        return capabilityDefinitionList.stream()
-                .filter(capabilityDefinition -> capabilityDefinition.getUniqueId().equals(propertyParentUniqueId) &&
-                        capabilityDefinition.getPath().size() == 1)
-                .findAny();
+        return capabilityDefinitionList.stream().filter(
+            capabilityDefinition -> capabilityDefinition.getUniqueId().equals(propertyParentUniqueId) && capabilityDefinition.getPath().size() == 1)
+            .findAny();
     }
 
     public static Optional<CapabilityDefinition> getPropertyCapabilityFromAllCapProps(String propertyParentUniqueId,
-                                                                                      List<CapabilityDefinition>
-                                                                                   capabilityDefinitionList) {
-        return capabilityDefinitionList.stream()
-                .filter(capabilityDefinition -> capabilityDefinition.getUniqueId().equals(propertyParentUniqueId))
-                .findAny();
+                                                                                      List<CapabilityDefinition> capabilityDefinitionList) {
+        return capabilityDefinitionList.stream().filter(capabilityDefinition -> capabilityDefinition.getUniqueId().equals(propertyParentUniqueId))
+            .findAny();
     }
 
     public static boolean isNodeProperty(String propertyName, List<PropertyDefinition> properties) {
-
-        return !CollectionUtils.isEmpty(properties) && properties.stream().anyMatch(property -> property.getName()
-                .equals(propertyName));
+        return !CollectionUtils.isEmpty(properties) && properties.stream().anyMatch(property -> property.getName().equals(propertyName));
     }
 
     private static <T> Predicate<T> distinctByKey(Function<? super T, ?> keyExtractor) {
@@ -152,31 +132,28 @@ public class PropertiesUtils {
 
     public static Optional<ComponentInstanceProperty> getPropertyByInputId(Component component, String inputId) {
         List<InputDefinition> componentInputs = component.getInputs();
-        if(CollectionUtils.isEmpty(componentInputs)) {
+        if (CollectionUtils.isEmpty(componentInputs)) {
             return Optional.empty();
         }
-        Optional<InputDefinition> inputDefinition = componentInputs.stream().filter(cip -> cip.getUniqueId()
-                .equals(inputId)).findFirst();
-        if(!inputDefinition.isPresent()) {
+        Optional<InputDefinition> inputDefinition = componentInputs.stream().filter(cip -> cip.getUniqueId().equals(inputId)).findFirst();
+        if (!inputDefinition.isPresent()) {
             return Optional.empty();
         }
         Optional<List<ComponentInstanceProperty>> capProperties = getCapProperties(component);
-        if(!capProperties.isPresent()) {
+        if (!capProperties.isPresent()) {
             return Optional.empty();
         }
-
-        return capProperties.get().stream().filter(capProp -> CollectionUtils.isNotEmpty(capProp.getGetInputValues()) &&
-                capProp.getGetInputValues().stream().anyMatch(capPropInp -> capPropInp.getInputId().equals(inputId)) &&
-                capProp.getUniqueId().equals(inputDefinition.get().getPropertyId())).findAny();
+        return capProperties.get().stream().filter(
+            capProp -> CollectionUtils.isNotEmpty(capProp.getGetInputValues()) && capProp.getGetInputValues().stream()
+                .anyMatch(capPropInp -> capPropInp.getInputId().equals(inputId)) && capProp.getUniqueId()
+                .equals(inputDefinition.get().getPropertyId())).findAny();
     }
 
-    public static List<ComponentInstanceProperty> getCapabilityProperty(ComponentInstanceProperty capabilityProperty,
-                                                                  String inputId) {
+    public static List<ComponentInstanceProperty> getCapabilityProperty(ComponentInstanceProperty capabilityProperty, String inputId) {
         List<ComponentInstanceProperty> resList = new ArrayList<>();
         List<GetInputValueDataDefinition> inputsValues = capabilityProperty.getGetInputValues();
-        if (CollectionUtils.isNotEmpty(inputsValues) &&  inputsValues.stream().anyMatch(inputData ->
-                isGetInputValueForInput(inputData, inputId))) {
-                resList.add(capabilityProperty);
+        if (CollectionUtils.isNotEmpty(inputsValues) && inputsValues.stream().anyMatch(inputData -> isGetInputValueForInput(inputData, inputId))) {
+            resList.add(capabilityProperty);
         }
         return resList;
     }
@@ -192,6 +169,7 @@ public class PropertiesUtils {
 
     /**
      * Trim " and ' quotes
+     *
      * @return String
      */
     public static String trimQuotes(String incomingString) {
index 929cd46..ec414b9 100644 (file)
@@ -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.
  * limitations under the License.
  * ============LICENSE_END=========================================================
  */
-
 package org.openecomp.sdc.be.components.utils;
 
-import org.apache.tinkerpop.shaded.minlog.Log;
-
-import javax.validation.constraints.NotNull;
 import java.security.SecureRandom;
 import java.util.List;
 import java.util.regex.Matcher;
 import java.util.regex.Pattern;
+import javax.validation.constraints.NotNull;
+import org.apache.tinkerpop.shaded.minlog.Log;
 
 public class Utils {
 
     private static final Pattern COUNTER_PATTERN = Pattern.compile("\\d+$");
     private static final SecureRandom random = new SecureRandom();
 
-
-    private Utils() {}
+    private Utils() {
+    }
 
     public static int getNextCounter(@NotNull List<String> existingValues) {
         if (existingValues.isEmpty()) {
             return 0;
         }
         try {
-            return 1 + existingValues.stream()
-                    .map(COUNTER_PATTERN::matcher)
-                    .filter(Matcher::find)
-                    .map(matcher -> matcher.group(0))
-                    .mapToInt(Integer::parseInt)
-                    .max()
-                    .orElse(0);
-        }
-        catch (Exception e) {
+            return 1 + existingValues.stream().map(COUNTER_PATTERN::matcher).filter(Matcher::find).map(matcher -> matcher.group(0))
+                .mapToInt(Integer::parseInt).max().orElse(0);
+        } catch (Exception e) {
             Log.warn("Failed in retrieivng counter from existing value: ", e);
             return random.nextInt(100) + 50;
         }
index 5674c2b..e1f902d 100644 (file)
@@ -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.
  * limitations under the License.
  * ============LICENSE_END=========================================================
  */
-
 package org.openecomp.sdc.be.components.validation;
 
+import java.util.ArrayList;
+import java.util.List;
 import org.openecomp.sdc.be.datatypes.enums.ComponentTypeEnum;
 import org.openecomp.sdc.be.model.Component;
 import org.openecomp.sdc.be.model.User;
 import org.openecomp.sdc.be.user.Role;
 
-import java.util.ArrayList;
-import java.util.List;
-
 @org.springframework.stereotype.Component
 public class AccessValidations {
 
@@ -39,10 +37,10 @@ public class AccessValidations {
         this.componentValidations = componentValidations;
     }
 
-    public Component validateUserCanRetrieveComponentData(String componentId, String componentType, String userId, String actionContext)  {
+    public Component validateUserCanRetrieveComponentData(String componentId, String componentType, String userId, String actionContext) {
         ComponentTypeEnum componentTypeEnum = ComponentTypeEnum.findByParamName(componentType);
         retrieveUser(userId, actionContext);
-           return componentValidations.getComponent(componentId, componentTypeEnum);
+        return componentValidations.getComponent(componentId, componentTypeEnum);
     }
 
     public Component validateUserCanWorkOnComponent(String componentId, ComponentTypeEnum componentType, String userId, String actionContext) {
@@ -61,12 +59,11 @@ public class AccessValidations {
         retrieveUser(userId, context);
     }
 
-
     public void validateUserExist(String userId, String actionContext) {
         userValidations.validateUserExists(userId);
     }
 
-    public User userIsAdminOrDesigner(String userId, String actionContext){
+    public User userIsAdminOrDesigner(String userId, String actionContext) {
         User user = retrieveUser(userId, actionContext);
         validateUserIsAdminOrDesigner(user);
         return user;
@@ -82,5 +79,4 @@ public class AccessValidations {
         roles.add(Role.DESIGNER);
         userValidations.validateUserRole(user, roles);
     }
-
 }
index 428d6d9..b4f6bbe 100644 (file)
@@ -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.
  * limitations under the License.
  * ============LICENSE_END=========================================================
  */
-
 package org.openecomp.sdc.be.components.validation;
 
+import java.util.ArrayList;
+import java.util.List;
+import java.util.Map;
 import org.openecomp.sdc.be.components.impl.ResourceImportManager;
 import org.openecomp.sdc.be.components.impl.utils.ExceptionUtils;
 import org.openecomp.sdc.be.datatypes.elements.Annotation;
@@ -32,25 +34,17 @@ import org.openecomp.sdc.be.model.cache.ApplicationDataTypeCache;
 import org.openecomp.sdc.common.log.wrappers.Logger;
 import org.springframework.stereotype.Component;
 
-import java.util.ArrayList;
-import java.util.List;
-import java.util.Map;
-
 @Component
 public class AnnotationValidator {
 
-
+    private static final Logger log = Logger.getLogger(ResourceImportManager.class);
     private final PropertyValidator propertyValidator;
     private final ExceptionUtils exceptionUtils;
     private final ApplicationDataTypeCache dataTypeCache;
     private final ComponentsUtils componentsUtils;
 
-    private static final Logger log = Logger.getLogger(ResourceImportManager.class);
-
-
-    public AnnotationValidator(PropertyValidator propertyValidator
-                               , ExceptionUtils exceptionUtils, ApplicationDataTypeCache dataTypeCache
-                               ,ComponentsUtils componentsUtils) {
+    public AnnotationValidator(PropertyValidator propertyValidator, ExceptionUtils exceptionUtils, ApplicationDataTypeCache dataTypeCache,
+                               ComponentsUtils componentsUtils) {
         this.propertyValidator = propertyValidator;
         this.exceptionUtils = exceptionUtils;
         this.dataTypeCache = dataTypeCache;
@@ -59,9 +53,8 @@ public class AnnotationValidator {
 
     public List<Annotation> validateAnnotationsProperties(Annotation annotation, AnnotationTypeDefinition dbAnnotationTypeDefinition) {
         List<Annotation> validAnnotations = new ArrayList<>();
-        if (annotation != null && propertiesValidator(
-                annotation.getProperties(), dbAnnotationTypeDefinition.getProperties())) {
-                    validAnnotations.add(annotation);
+        if (annotation != null && propertiesValidator(annotation.getProperties(), dbAnnotationTypeDefinition.getProperties())) {
+            validAnnotations.add(annotation);
         }
         return validAnnotations;
     }
@@ -71,14 +64,9 @@ public class AnnotationValidator {
         if (properties == null || dbAnnotationTypeDefinitionProperties == null) {
             return false;
         }
-        properties.stream()
-                .forEach(property -> propertyDefinitionsList.add(new PropertyDefinition(property)));
-        Map<String, DataTypeDefinition> allDataTypes = dataTypeCache.getAll()
-                .left()
-                .on( error -> exceptionUtils
-                .rollBackAndThrow(error));
+        properties.stream().forEach(property -> propertyDefinitionsList.add(new PropertyDefinition(property)));
+        Map<String, DataTypeDefinition> allDataTypes = dataTypeCache.getAll().left().on(error -> exceptionUtils.rollBackAndThrow(error));
         propertyValidator.thinPropertiesValidator(propertyDefinitionsList, dbAnnotationTypeDefinitionProperties, allDataTypes);
         return true;
     }
-
 }
index 7f217b9..da8e8bb 100644 (file)
@@ -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.
@@ -17,7 +17,6 @@
  * limitations under the License.
  * ============LICENSE_END=========================================================
  */
-
 package org.openecomp.sdc.be.components.validation;
 
 import lombok.Getter;
@@ -27,11 +26,7 @@ import lombok.Getter;
  */
 @Getter
 public enum ApiResourceEnum {
-
-    ENVIRONMENT_ID("Environment ID"),
-    RESOURCE_ID("Resource ID"),
-    SERVICE_ID("Service ID");
-
+    ENVIRONMENT_ID("Environment ID"), RESOURCE_ID("Resource ID"), SERVICE_ID("Service ID");
     private String value;
 
     ApiResourceEnum(String value) {
index 2c69ee5..3f53f6b 100644 (file)
  * See the License for the specific language governing permissions and
  * limitations under the License.
  */
-
 package org.openecomp.sdc.be.components.validation;
 
 import fj.data.Either;
+import java.util.Collection;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+import java.util.regex.Pattern;
+import java.util.stream.Collectors;
 import org.apache.commons.collections.CollectionUtils;
 import org.apache.commons.collections.MapUtils;
 import org.apache.commons.lang.StringUtils;
@@ -28,26 +33,17 @@ import org.slf4j.Logger;
 import org.slf4j.LoggerFactory;
 import org.springframework.stereotype.Component;
 
-import java.util.Collection;
-import java.util.HashMap;
-import java.util.List;
-import java.util.Map;
-import java.util.regex.Pattern;
-import java.util.stream.Collectors;
-
 @Component("capabilitiesValidation")
 public class CapabilitiesValidation {
+
     private static final Logger LOGGER = LoggerFactory.getLogger(CapabilitiesValidation.class);
     private static final String CAPABILITY_NOT_FOUND_IN_COMPONENT = "Capability not found in component {} ";
     private static final Pattern NAME_VALIDATION_REGEX_PATTERN = Pattern.compile("^[a-zA-Z0-9_.]*$");
 
-    public Either<Boolean, ResponseFormat> validateCapabilities(
-            Collection<CapabilityDefinition> capabilities,
-            org.openecomp.sdc.be.model.Component component, boolean isUpdate) {
-
-        for(CapabilityDefinition capabilityDefinition : capabilities) {
-            Either<Boolean, ResponseFormat> validateCapabilityResponse = validateCapability(capabilityDefinition,
-                    component, isUpdate);
+    public Either<Boolean, ResponseFormat> validateCapabilities(Collection<CapabilityDefinition> capabilities,
+                                                                org.openecomp.sdc.be.model.Component component, boolean isUpdate) {
+        for (CapabilityDefinition capabilityDefinition : capabilities) {
+            Either<Boolean, ResponseFormat> validateCapabilityResponse = validateCapability(capabilityDefinition, component, isUpdate);
             if (validateCapabilityResponse.isRight()) {
                 return validateCapabilityResponse;
             }
@@ -56,29 +52,25 @@ public class CapabilitiesValidation {
     }
 
     private Either<Boolean, ResponseFormat> validateCapability(CapabilityDefinition capabilityDefinition,
-                                                               org.openecomp.sdc.be.model.Component component,
-                                                               boolean isUpdate) {
+                                                               org.openecomp.sdc.be.model.Component component, boolean isUpdate) {
         ResponseFormatManager responseFormatManager = getResponseFormatManager();
-
-        if(isUpdate) {
-            Either<Boolean, ResponseFormat> capabilityExistValidationEither
-                    = isCapabilityExist(capabilityDefinition, responseFormatManager, component);
+        if (isUpdate) {
+            Either<Boolean, ResponseFormat> capabilityExistValidationEither = isCapabilityExist(capabilityDefinition, responseFormatManager,
+                component);
             if (capabilityExistValidationEither.isRight()) {
                 return Either.right(capabilityExistValidationEither.right().value());
             }
         }
-        Either<Boolean, ResponseFormat> capabilityNameValidationResponse
-                = validateCapabilityName(capabilityDefinition, responseFormatManager, component, isUpdate);
+        Either<Boolean, ResponseFormat> capabilityNameValidationResponse = validateCapabilityName(capabilityDefinition, responseFormatManager,
+            component, isUpdate);
         if (capabilityNameValidationResponse.isRight()) {
             return Either.right(capabilityNameValidationResponse.right().value());
         }
-        Either<Boolean, ResponseFormat> capabilityTypeEmptyEither =
-                isCapabilityTypeEmpty(responseFormatManager, capabilityDefinition.getType());
+        Either<Boolean, ResponseFormat> capabilityTypeEmptyEither = isCapabilityTypeEmpty(responseFormatManager, capabilityDefinition.getType());
         if (capabilityTypeEmptyEither.isRight()) {
             return Either.right(capabilityTypeEmptyEither.right().value());
         }
-        Either<Boolean, ResponseFormat> capabilityOccurrencesValidationEither =
-                validateOccurrences(capabilityDefinition, responseFormatManager);
+        Either<Boolean, ResponseFormat> capabilityOccurrencesValidationEither = validateOccurrences(capabilityDefinition, responseFormatManager);
         if (capabilityOccurrencesValidationEither.isRight()) {
             return Either.right(capabilityOccurrencesValidationEither.right().value());
         }
@@ -89,9 +81,9 @@ public class CapabilitiesValidation {
                                                                 ResponseFormatManager responseFormatManager) {
         String maxOccurrences = capabilityDefinition.getMaxOccurrences();
         String minOccurrences = capabilityDefinition.getMinOccurrences();
-        if(maxOccurrences != null && minOccurrences != null) {
-            Either<Boolean, ResponseFormat> capabilityOccurrencesValidationEither =
-                    validateOccurrences(responseFormatManager, minOccurrences, maxOccurrences);
+        if (maxOccurrences != null && minOccurrences != null) {
+            Either<Boolean, ResponseFormat> capabilityOccurrencesValidationEither = validateOccurrences(responseFormatManager, minOccurrences,
+                maxOccurrences);
             if (capabilityOccurrencesValidationEither.isRight()) {
                 return Either.right(capabilityOccurrencesValidationEither.right().value());
             }
@@ -99,32 +91,26 @@ public class CapabilitiesValidation {
         return Either.left(Boolean.TRUE);
     }
 
-    private Either<Boolean, ResponseFormat> isCapabilityExist(CapabilityDefinition definition,
-                                                              ResponseFormatManager responseFormatManager,
+    private Either<Boolean, ResponseFormat> isCapabilityExist(CapabilityDefinition definition, ResponseFormatManager responseFormatManager,
                                                               org.openecomp.sdc.be.model.Component component) {
         Map<String, List<CapabilityDefinition>> componentCapabilities = component.getCapabilities();
-        if(MapUtils.isEmpty(componentCapabilities)){
+        if (MapUtils.isEmpty(componentCapabilities)) {
             LOGGER.error(CAPABILITY_NOT_FOUND_IN_COMPONENT, component.getUniqueId());
-            ResponseFormat errorResponse = responseFormatManager.getResponseFormat(ActionStatus
-                    .CAPABILITY_NOT_FOUND, component.getUniqueId());
+            ResponseFormat errorResponse = responseFormatManager.getResponseFormat(ActionStatus.CAPABILITY_NOT_FOUND, component.getUniqueId());
             return Either.right(errorResponse);
         }
-
-        List<CapabilityDefinition> capabilityDefinitionList = componentCapabilities.values()
-                .stream().flatMap(Collection::stream).collect(Collectors.toList());
-        if(CollectionUtils.isEmpty(capabilityDefinitionList)){
+        List<CapabilityDefinition> capabilityDefinitionList = componentCapabilities.values().stream().flatMap(Collection::stream)
+            .collect(Collectors.toList());
+        if (CollectionUtils.isEmpty(capabilityDefinitionList)) {
             LOGGER.error(CAPABILITY_NOT_FOUND_IN_COMPONENT, component.getUniqueId());
-            ResponseFormat errorResponse = responseFormatManager.getResponseFormat(ActionStatus
-                    .CAPABILITY_NOT_FOUND, component.getUniqueId());
+            ResponseFormat errorResponse = responseFormatManager.getResponseFormat(ActionStatus.CAPABILITY_NOT_FOUND, component.getUniqueId());
             return Either.right(errorResponse);
         }
-        boolean isCapabilityExist = capabilityDefinitionList.stream().anyMatch(capabilityDefinition ->
-                capabilityDefinition.getUniqueId().equalsIgnoreCase(definition.getUniqueId()));
-
-        if(!isCapabilityExist) {
+        boolean isCapabilityExist = capabilityDefinitionList.stream()
+            .anyMatch(capabilityDefinition -> capabilityDefinition.getUniqueId().equalsIgnoreCase(definition.getUniqueId()));
+        if (!isCapabilityExist) {
             LOGGER.error(CAPABILITY_NOT_FOUND_IN_COMPONENT, component.getUniqueId());
-            ResponseFormat errorResponse = responseFormatManager.getResponseFormat(ActionStatus
-                    .CAPABILITY_NOT_FOUND, component.getUniqueId());
+            ResponseFormat errorResponse = responseFormatManager.getResponseFormat(ActionStatus.CAPABILITY_NOT_FOUND, component.getUniqueId());
             return Either.right(errorResponse);
         }
         return Either.left(Boolean.TRUE);
@@ -132,36 +118,30 @@ public class CapabilitiesValidation {
 
     private Either<Boolean, ResponseFormat> validateCapabilityName(CapabilityDefinition capabilityDefinition,
                                                                    ResponseFormatManager responseFormatManager,
-                                                                   org.openecomp.sdc.be.model.Component component,
-                                                                   boolean isUpdate) {
-        Either<Boolean, ResponseFormat> capabilityNameEmptyEither =
-                isCapabilityNameEmpty(responseFormatManager, capabilityDefinition.getName());
+                                                                   org.openecomp.sdc.be.model.Component component, boolean isUpdate) {
+        Either<Boolean, ResponseFormat> capabilityNameEmptyEither = isCapabilityNameEmpty(responseFormatManager, capabilityDefinition.getName());
         if (capabilityNameEmptyEither.isRight()) {
             return Either.right(capabilityNameEmptyEither.right().value());
         }
-
-        Either<Boolean, ResponseFormat> capabilityNameRegexValidationResponse =
-                isCapabilityNameRegexValid(responseFormatManager, capabilityDefinition.getName());
+        Either<Boolean, ResponseFormat> capabilityNameRegexValidationResponse = isCapabilityNameRegexValid(responseFormatManager,
+            capabilityDefinition.getName());
         if (capabilityNameRegexValidationResponse.isRight()) {
             return Either.right(capabilityNameRegexValidationResponse.right().value());
         }
-
-        Either<Boolean, ResponseFormat> operationTypeUniqueResponse
-                = validateCapabilityNameUnique(capabilityDefinition, component, isUpdate );
-        if(operationTypeUniqueResponse.isRight()) {
+        Either<Boolean, ResponseFormat> operationTypeUniqueResponse = validateCapabilityNameUnique(capabilityDefinition, component, isUpdate);
+        if (operationTypeUniqueResponse.isRight()) {
             return Either.right(operationTypeUniqueResponse.right().value());
         }
         if (!operationTypeUniqueResponse.left().value()) {
             LOGGER.error("Capability name  {} already in use ", capabilityDefinition.getName());
-            ResponseFormat errorResponse = responseFormatManager.getResponseFormat(ActionStatus
-                    .CAPABILITY_NAME_ALREADY_IN_USE, capabilityDefinition.getName());
+            ResponseFormat errorResponse = responseFormatManager
+                .getResponseFormat(ActionStatus.CAPABILITY_NAME_ALREADY_IN_USE, capabilityDefinition.getName());
             return Either.right(errorResponse);
         }
         return Either.left(Boolean.TRUE);
     }
 
-    private Either<Boolean, ResponseFormat> isCapabilityNameEmpty(ResponseFormatManager responseFormatManager,
-                                                                  String capabilityName) {
+    private Either<Boolean, ResponseFormat> isCapabilityNameEmpty(ResponseFormatManager responseFormatManager, String capabilityName) {
         if (StringUtils.isEmpty(capabilityName)) {
             LOGGER.error("Capability Name is mandatory");
             ResponseFormat errorResponse = responseFormatManager.getResponseFormat(ActionStatus.CAPABILITY_NAME_MANDATORY);
@@ -170,8 +150,7 @@ public class CapabilitiesValidation {
         return Either.left(Boolean.TRUE);
     }
 
-    private Either<Boolean, ResponseFormat> isCapabilityTypeEmpty(ResponseFormatManager responseFormatManager,
-                                                                  String capabilityType) {
+    private Either<Boolean, ResponseFormat> isCapabilityTypeEmpty(ResponseFormatManager responseFormatManager, String capabilityType) {
         if (StringUtils.isEmpty(capabilityType)) {
             LOGGER.error("Capability type is mandatory");
             ResponseFormat errorResponse = responseFormatManager.getResponseFormat(ActionStatus.CAPABILITY_TYPE_MANDATORY);
@@ -180,11 +159,10 @@ public class CapabilitiesValidation {
         return Either.left(Boolean.TRUE);
     }
 
-    private Either<Boolean, ResponseFormat> validateOccurrences        (ResponseFormatManager responseFormatManager,
-                                                                    String minOccurrences, String maxOccurrences ) {
+    private Either<Boolean, ResponseFormat> validateOccurrences(ResponseFormatManager responseFormatManager, String minOccurrences,
+                                                                String maxOccurrences) {
         try {
-            if (StringUtils.isNotEmpty(maxOccurrences) && "UNBOUNDED".equalsIgnoreCase(maxOccurrences)
-                    && Integer.parseInt(minOccurrences) >= 0) {
+            if (StringUtils.isNotEmpty(maxOccurrences) && "UNBOUNDED".equalsIgnoreCase(maxOccurrences) && Integer.parseInt(minOccurrences) >= 0) {
                 return Either.left(Boolean.TRUE);
             } else if (Integer.parseInt(minOccurrences) < 0) {
                 LOGGER.debug("Invalid occurrences format.low_bound occurrence negative {}", minOccurrences);
@@ -192,8 +170,8 @@ public class CapabilitiesValidation {
                 return Either.right(responseFormat);
             } else if (Integer.parseInt(maxOccurrences) < Integer.parseInt(minOccurrences)) {
                 LOGGER.error("Capability maxOccurrences should be greater than minOccurrences");
-                ResponseFormat errorResponse = responseFormatManager.getResponseFormat(ActionStatus
-                        .MAX_OCCURRENCES_SHOULD_BE_GREATER_THAN_MIN_OCCURRENCES);
+                ResponseFormat errorResponse = responseFormatManager
+                    .getResponseFormat(ActionStatus.MAX_OCCURRENCES_SHOULD_BE_GREATER_THAN_MIN_OCCURRENCES);
                 return Either.right(errorResponse);
             }
         } catch (NumberFormatException ex) {
@@ -205,40 +183,36 @@ public class CapabilitiesValidation {
     }
 
     private Either<Boolean, ResponseFormat> validateCapabilityNameUnique(CapabilityDefinition capabilityDefinition,
-                                                                         org.openecomp.sdc.be.model.Component component,
-                                                                         boolean isUpdate) {
+                                                                         org.openecomp.sdc.be.model.Component component, boolean isUpdate) {
         boolean isCapabilityNameUnique = false;
         Map<String, List<CapabilityDefinition>> componentCapabilities = component.getCapabilities();
-        if(MapUtils.isEmpty(componentCapabilities)){
+        if (MapUtils.isEmpty(componentCapabilities)) {
             return Either.left(true);
         }
-        List<CapabilityDefinition> capabilityDefinitionList = componentCapabilities.values()
-                .stream().flatMap(Collection::stream).collect(Collectors.toList());
-        if(CollectionUtils.isEmpty(capabilityDefinitionList)){
+        List<CapabilityDefinition> capabilityDefinitionList = componentCapabilities.values().stream().flatMap(Collection::stream)
+            .collect(Collectors.toList());
+        if (CollectionUtils.isEmpty(capabilityDefinitionList)) {
             return Either.left(true);
         }
         Map<String, String> capabilityNameMap = new HashMap<>();
         capabilityDefinitionList.forEach(capability -> capabilityNameMap.put(capability.getUniqueId(), capability.getName()));
-
-        if (!capabilityNameMap.values().contains(capabilityDefinition.getName())){
+        if (!capabilityNameMap.values().contains(capabilityDefinition.getName())) {
             isCapabilityNameUnique = true;
         }
-        if (!isCapabilityNameUnique && isUpdate){
-            List<Map.Entry<String, String>> capNamesEntries = capabilityNameMap.entrySet().stream().filter(entry ->
-                    entry.getValue().equalsIgnoreCase(capabilityDefinition.getName())).collect(Collectors.toList());
-            if(capNamesEntries.size() == 1 && capNamesEntries.get(0).getKey().equals(capabilityDefinition.getUniqueId())) {
+        if (!isCapabilityNameUnique && isUpdate) {
+            List<Map.Entry<String, String>> capNamesEntries = capabilityNameMap.entrySet().stream()
+                .filter(entry -> entry.getValue().equalsIgnoreCase(capabilityDefinition.getName())).collect(Collectors.toList());
+            if (capNamesEntries.size() == 1 && capNamesEntries.get(0).getKey().equals(capabilityDefinition.getUniqueId())) {
                 isCapabilityNameUnique = true;
             }
         }
         return Either.left(isCapabilityNameUnique);
     }
 
-    private Either<Boolean, ResponseFormat> isCapabilityNameRegexValid(ResponseFormatManager responseFormatManager,
-                                                                       String capabilityName) {
+    private Either<Boolean, ResponseFormat> isCapabilityNameRegexValid(ResponseFormatManager responseFormatManager, String capabilityName) {
         if (!isValidCapabilityName(capabilityName)) {
             LOGGER.error("Capability name {} is invalid, Only alphanumeric chars, underscore and dot allowed", capabilityName);
-            ResponseFormat errorResponse = responseFormatManager
-                    .getResponseFormat(ActionStatus.INVALID_CAPABILITY_NAME, capabilityName);
+            ResponseFormat errorResponse = responseFormatManager.getResponseFormat(ActionStatus.INVALID_CAPABILITY_NAME, capabilityName);
             return Either.right(errorResponse);
         }
         return Either.left(Boolean.TRUE);
@@ -251,5 +225,4 @@ public class CapabilitiesValidation {
     protected ResponseFormatManager getResponseFormatManager() {
         return ResponseFormatManager.getInstance();
     }
-
 }
index bdd7f65..10bb1d0 100644 (file)
@@ -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.
  * Modifications copyright (c) 2019 Nokia
  * ================================================================================
  */
-
 package org.openecomp.sdc.be.components.validation;
 
+import static java.util.stream.Collectors.toList;
+
+import java.util.HashSet;
+import java.util.List;
+import java.util.Optional;
+import java.util.Set;
 import org.apache.commons.collections.CollectionUtils;
 import org.openecomp.sdc.be.components.impl.exceptions.ByActionStatusComponentException;
 import org.openecomp.sdc.be.dao.api.ActionStatus;
@@ -38,13 +43,6 @@ import org.openecomp.sdc.be.model.operations.api.StorageOperationStatus;
 import org.openecomp.sdc.be.model.operations.utils.ComponentValidationUtils;
 import org.openecomp.sdc.common.util.ValidationUtils;
 
-import java.util.HashSet;
-import java.util.List;
-import java.util.Optional;
-import java.util.Set;
-
-import static java.util.stream.Collectors.toList;
-
 @org.springframework.stereotype.Component
 public class ComponentValidations {
 
@@ -55,17 +53,13 @@ public class ComponentValidations {
     }
 
     public Optional<ComponentInstance> getComponentInstance(Component component, String instanceId) {
-        return component.getComponentInstances()
-                .stream()
-                .filter(ci -> ci.getUniqueId().equals(instanceId))
-                .findFirst();
+        return component.getComponentInstances().stream().filter(ci -> ci.getUniqueId().equals(instanceId)).findFirst();
     }
 
     public static boolean validateComponentInstanceExist(Component component, String instanceId) {
         return Optional.ofNullable(component.getComponentInstances())
-                       .map(componentInstances -> componentInstances.stream().map(ComponentInstance::getUniqueId).collect(toList()))
-                       .filter(instancesIds -> instancesIds.contains(instanceId))
-                       .isPresent();
+            .map(componentInstances -> componentInstances.stream().map(ComponentInstance::getUniqueId).collect(toList()))
+            .filter(instancesIds -> instancesIds.contains(instanceId)).isPresent();
     }
 
     public static String getNormalizedName(ToscaDataDefinition toscaDataDefinition) {
@@ -74,8 +68,8 @@ public class ComponentValidations {
     }
 
     /**
-     * The following logic is applied:
-     * For each name new or existing name we look at the normalized name which is used in Tosca representation
+     * The following logic is applied: For each name new or existing name we look at the normalized name which is used in Tosca representation
+     *
      * @param currentName
      * @param newName
      * @param component
@@ -84,7 +78,6 @@ public class ComponentValidations {
     public static boolean validateNameIsUniqueInComponent(String currentName, String newName, Component component) {
         String normalizedCurrentName = ValidationUtils.normalizeComponentInstanceName(currentName);
         String normalizedNewName = ValidationUtils.normalizeComponentInstanceName(newName);
-        
         if (normalizedCurrentName.equals(normalizedNewName)) {
             return true;    //As it's same entity, still considered unique
         }
@@ -92,17 +85,11 @@ public class ComponentValidations {
         List<ComponentInstance> componentInstances = component.getComponentInstances();
         Set<String> existingNames = new HashSet<>();
         if (CollectionUtils.isNotEmpty(groups)) {
-            List<String> existingGroupNames = groups
-                    .stream()
-                    .map(ComponentValidations::getNormalizedName)
-                    .collect(toList());
+            List<String> existingGroupNames = groups.stream().map(ComponentValidations::getNormalizedName).collect(toList());
             existingNames.addAll(existingGroupNames);
         }
         if (CollectionUtils.isNotEmpty(componentInstances)) {
-            List<String> existingInstanceNames = componentInstances
-                    .stream()
-                    .map(ComponentValidations::getNormalizedName)
-                    .collect(toList());
+            List<String> existingInstanceNames = componentInstances.stream().map(ComponentValidations::getNormalizedName).collect(toList());
             existingNames.addAll(existingInstanceNames);
         }
         return !existingNames.contains(normalizedNewName);
@@ -110,9 +97,11 @@ public class ComponentValidations {
 
     void validateComponentIsCheckedOutByUser(Component component, String userId) {
         if (!ComponentValidationUtils.canWorkOnComponent(component, userId)) {
-            throw new ByActionStatusComponentException(ActionStatus.ILLEGAL_COMPONENT_STATE, component.getComponentType().name(), component.getName(), component.getLifecycleState().name());
+            throw new ByActionStatusComponentException(ActionStatus.ILLEGAL_COMPONENT_STATE, component.getComponentType().name(), component.getName(),
+                component.getLifecycleState().name());
         }
     }
+
     Component validateComponentIsCheckedOutByUser(String componentId, ComponentTypeEnum componentTypeEnum, String userId) {
         Component component = getComponent(componentId, componentTypeEnum);
         validateComponentIsCheckedOutByUser(component, userId);
@@ -120,17 +109,14 @@ public class ComponentValidations {
     }
 
     Component getComponent(String componentId, ComponentTypeEnum componentType) {
-        Component component = toscaOperationFacade.getToscaElement(componentId, new ComponentParametersView())
-                .left()
-                .on(storageOperationStatus -> onToscaOperationError(storageOperationStatus, componentId));
-
+        Component component = toscaOperationFacade.getToscaElement(componentId, new ComponentParametersView()).left()
+            .on(storageOperationStatus -> onToscaOperationError(storageOperationStatus, componentId));
         validateComponentType(component, componentType);
-
         return component;
     }
 
     private void validateComponentType(Component component, ComponentTypeEnum componentType) {
-        if (componentType!=component.getComponentType()) {
+        if (componentType != component.getComponentType()) {
             throw new ByActionStatusComponentException(ActionStatus.INVALID_RESOURCE_TYPE);
         }
     }
@@ -138,5 +124,4 @@ public class ComponentValidations {
     private Component onToscaOperationError(StorageOperationStatus storageOperationStatus, String componentId) {
         throw new StorageException(storageOperationStatus, componentId);
     }
-
 }
index b876782..419430b 100644 (file)
  * See the License for the specific language governing permissions and
  * limitations under the License.
  */
-
 package org.openecomp.sdc.be.components.validation;
 
+import static org.openecomp.sdc.be.components.utils.InterfaceOperationUtils.getOperationOutputName;
+import static org.openecomp.sdc.be.components.utils.InterfaceOperationUtils.getOtherOperationOutputsOfComponent;
+import static org.openecomp.sdc.be.components.utils.InterfaceOperationUtils.isOperationInputMappedToComponentInput;
+import static org.openecomp.sdc.be.components.utils.PropertiesUtils.isCapabilityProperty;
+
 import com.google.common.collect.Sets;
 import fj.data.Either;
+import java.util.ArrayList;
+import java.util.Collection;
+import java.util.HashMap;
+import java.util.HashSet;
+import java.util.List;
+import java.util.Map;
+import java.util.Objects;
+import java.util.Optional;
+import java.util.Set;
+import java.util.regex.Pattern;
+import java.util.stream.Collectors;
+import java.util.stream.Stream;
 import org.apache.commons.collections.CollectionUtils;
 import org.apache.commons.collections.MapUtils;
 import org.apache.commons.lang.StringUtils;
@@ -35,262 +51,194 @@ import org.slf4j.Logger;
 import org.slf4j.LoggerFactory;
 import org.springframework.stereotype.Component;
 
-import java.util.ArrayList;
-import java.util.Collection;
-import java.util.HashMap;
-import java.util.HashSet;
-import java.util.List;
-import java.util.Map;
-import java.util.Objects;
-import java.util.Optional;
-import java.util.Set;
-import java.util.regex.Pattern;
-import java.util.stream.Collectors;
-import java.util.stream.Stream;
-
-import static org.openecomp.sdc.be.components.utils.InterfaceOperationUtils.getOperationOutputName;
-import static org.openecomp.sdc.be.components.utils.InterfaceOperationUtils.getOtherOperationOutputsOfComponent;
-import static org.openecomp.sdc.be.components.utils.InterfaceOperationUtils.isOperationInputMappedToComponentInput;
-import static org.openecomp.sdc.be.components.utils.PropertiesUtils.isCapabilityProperty;
-
 @Component("interfaceOperationValidation")
 public class InterfaceOperationValidation {
 
     private static final String TYPE_VALIDATION_REGEX = "^[a-zA-Z0-9_]{1,200}$";
-
     private static final Logger LOGGER = LoggerFactory.getLogger(InterfaceOperationValidation.class);
 
-    public Either<Boolean, ResponseFormat> validateInterfaceOperations(
-            InterfaceDefinition inputInterfaceDefinition, org.openecomp.sdc.be.model.Component component,
-            InterfaceDefinition storedInterfaceDefinition, Map<String, InterfaceDefinition> globalInterfaceTypes,
-            boolean isUpdate) {
-
-        Either<Boolean, ResponseFormat> validateAllowedOperationsOnGlobalInterfaceType =
-                validateAllowedOperationsOnGlobalInterfaceType(inputInterfaceDefinition, globalInterfaceTypes);
+    public Either<Boolean, ResponseFormat> validateInterfaceOperations(InterfaceDefinition inputInterfaceDefinition,
+                                                                       org.openecomp.sdc.be.model.Component component,
+                                                                       InterfaceDefinition storedInterfaceDefinition,
+                                                                       Map<String, InterfaceDefinition> globalInterfaceTypes, boolean isUpdate) {
+        Either<Boolean, ResponseFormat> validateAllowedOperationsOnGlobalInterfaceType = validateAllowedOperationsOnGlobalInterfaceType(
+            inputInterfaceDefinition, globalInterfaceTypes);
         if (validateAllowedOperationsOnGlobalInterfaceType.isRight()) {
             return validateAllowedOperationsOnGlobalInterfaceType;
         }
-
-        Either<Boolean, ResponseFormat> validateOperationNameUniqueness =
-                validateOperationNameUniquenessInCollection(inputInterfaceDefinition.getOperationsMap().values());
+        Either<Boolean, ResponseFormat> validateOperationNameUniqueness = validateOperationNameUniquenessInCollection(
+            inputInterfaceDefinition.getOperationsMap().values());
         if (validateOperationNameUniqueness.isRight()) {
             return validateOperationNameUniqueness;
         }
-
         for (Operation interfaceOperation : inputInterfaceDefinition.getOperationsMap().values()) {
-            Either<Boolean, ResponseFormat> interfaceOperationValidatorResponse = validateInterfaceOperation(
-                    interfaceOperation, storedInterfaceDefinition, inputInterfaceDefinition, component, isUpdate);
+            Either<Boolean, ResponseFormat> interfaceOperationValidatorResponse = validateInterfaceOperation(interfaceOperation,
+                storedInterfaceDefinition, inputInterfaceDefinition, component, isUpdate);
             if (interfaceOperationValidatorResponse.isRight()) {
                 return interfaceOperationValidatorResponse;
             }
         }
-
         return Either.left(Boolean.TRUE);
     }
 
-    public Either<Boolean, ResponseFormat> validateDeleteOperationContainsNoMappedOutput(
-            Operation interfaceOperationToDelete, org.openecomp.sdc.be.model.Component component,
-            InterfaceDefinition storedInterfaceDefinition) {
+    public Either<Boolean, ResponseFormat> validateDeleteOperationContainsNoMappedOutput(Operation interfaceOperationToDelete,
+                                                                                         org.openecomp.sdc.be.model.Component component,
+                                                                                         InterfaceDefinition storedInterfaceDefinition) {
         ResponseFormatManager responseFormatManager = getResponseFormatManager();
-        List<OperationOutputDefinition> existingOperationOutputs =
-                getInterfaceOperationOutputs(interfaceOperationToDelete.getUniqueId(), component.getInterfaces());
+        List<OperationOutputDefinition> existingOperationOutputs = getInterfaceOperationOutputs(interfaceOperationToDelete.getUniqueId(),
+            component.getInterfaces());
         if (existingOperationOutputs.isEmpty()) {
             return Either.left(Boolean.TRUE);
         }
         String mappedOutputPrefix = storedInterfaceDefinition.getType() + "." + interfaceOperationToDelete.getName();
-        List<OperationInputDefinition> interfaceOperationInputs =
-                getOtherOperationInputsOfComponent(mappedOutputPrefix, component.getInterfaces());
+        List<OperationInputDefinition> interfaceOperationInputs = getOtherOperationInputsOfComponent(mappedOutputPrefix, component.getInterfaces());
         Set<String> mappedOutputsInDeletedOperation = new HashSet<>();
-        Set<String> existingOperationOutputNames = existingOperationOutputs.stream()
-                .map(OperationOutputDefinition::getName)
-                .collect(Collectors.toSet());
+        Set<String> existingOperationOutputNames = existingOperationOutputs.stream().map(OperationOutputDefinition::getName)
+            .collect(Collectors.toSet());
         for (String existingOperationOutputName : existingOperationOutputNames) {
-            Set<String> matchedOutputsMappedToInputs = interfaceOperationInputs.stream()
-                    .filter(operationInputDefinition -> operationInputDefinition.getInputId()
-                            .equals(mappedOutputPrefix + "." + existingOperationOutputName))
-                    .map(operationInputDefinition -> getOperationOutputName(operationInputDefinition.getInputId()))
-                    .collect(Collectors.toSet());
+            Set<String> matchedOutputsMappedToInputs = interfaceOperationInputs.stream().filter(
+                operationInputDefinition -> operationInputDefinition.getInputId().equals(mappedOutputPrefix + "." + existingOperationOutputName))
+                .map(operationInputDefinition -> getOperationOutputName(operationInputDefinition.getInputId())).collect(Collectors.toSet());
             mappedOutputsInDeletedOperation.addAll(matchedOutputsMappedToInputs);
         }
-
         if (CollectionUtils.isNotEmpty(mappedOutputsInDeletedOperation)) {
             return getMappedOutputErrorResponse(responseFormatManager, mappedOutputsInDeletedOperation,
-                    "Cannot delete interface operation with output(s) '{}' mapped to another operation input",
-                    ActionStatus.INTERFACE_OPERATION_DELETE_WITH_MAPPED_OUTPUT);
+                "Cannot delete interface operation with output(s) '{}' mapped to another operation input",
+                ActionStatus.INTERFACE_OPERATION_DELETE_WITH_MAPPED_OUTPUT);
         }
         return Either.left(Boolean.TRUE);
     }
 
-    private Either<Boolean, ResponseFormat> validateAllowedOperationsOnGlobalInterfaceType(
-            InterfaceDefinition interfaceDefinition, Map<String, InterfaceDefinition> globalInterfaceTypes) {
-
+    private Either<Boolean, ResponseFormat> validateAllowedOperationsOnGlobalInterfaceType(InterfaceDefinition interfaceDefinition,
+                                                                                           Map<String, InterfaceDefinition> globalInterfaceTypes) {
         if (globalInterfaceTypes == null) {
             return Either.left(Boolean.TRUE);
         }
-        boolean isOperationValidOnGlobalInterfaceType = Stream.of(interfaceDefinition)
-                .filter(interfaceDef -> globalInterfaceTypes.values().stream().anyMatch(interfaceDef1 ->
-                        interfaceDef1.getType().equalsIgnoreCase(interfaceDef.getType())))
-                .flatMap(interfaceDef -> interfaceDef.getOperationsMap().values().stream().map(Operation::getName))
-                .allMatch(operationName -> globalInterfaceTypes.values().stream()
-                        .flatMap(interfaceDef -> interfaceDef.getOperationsMap().keySet().stream())
-                        .anyMatch(opName -> opName.equalsIgnoreCase(operationName)));
+        boolean isOperationValidOnGlobalInterfaceType = Stream.of(interfaceDefinition).filter(interfaceDef -> globalInterfaceTypes.values().stream()
+            .anyMatch(interfaceDef1 -> interfaceDef1.getType().equalsIgnoreCase(interfaceDef.getType())))
+            .flatMap(interfaceDef -> interfaceDef.getOperationsMap().values().stream().map(Operation::getName)).allMatch(
+                operationName -> globalInterfaceTypes.values().stream().flatMap(interfaceDef -> interfaceDef.getOperationsMap().keySet().stream())
+                    .anyMatch(opName -> opName.equalsIgnoreCase(operationName)));
         if (!isOperationValidOnGlobalInterfaceType) {
             return Either.right(getResponseFormatManager()
-                    .getResponseFormat(ActionStatus.INTERFACE_OPERATION_INVALID_FOR_GLOBAL_TYPE,
-                            interfaceDefinition.getType()));
+                .getResponseFormat(ActionStatus.INTERFACE_OPERATION_INVALID_FOR_GLOBAL_TYPE, interfaceDefinition.getType()));
         }
         return Either.left(Boolean.TRUE);
     }
 
-    private Either<Boolean, ResponseFormat> validateOperationNameUniquenessInCollection(
-            Collection<Operation> operationList) {
+    private Either<Boolean, ResponseFormat> validateOperationNameUniquenessInCollection(Collection<Operation> operationList) {
         HashSet<String> operationNames = new HashSet<>();
         for (Operation operation : operationList) {
             if (!operationNames.add(operation.getName())) {
-                return Either.right(getResponseFormatManager()
-                                            .getResponseFormat(ActionStatus.INTERFACE_OPERATION_NAME_ALREADY_IN_USE,
-                                                    operation.getName()));
+                return Either
+                    .right(getResponseFormatManager().getResponseFormat(ActionStatus.INTERFACE_OPERATION_NAME_ALREADY_IN_USE, operation.getName()));
             }
         }
         return Either.left(Boolean.TRUE);
     }
 
-    private Either<Boolean, ResponseFormat> validateInterfaceOperation(Operation interfaceOperation,
-            InterfaceDefinition storedInterfaceDefinition, InterfaceDefinition inputInterfaceDefinition,
-            org.openecomp.sdc.be.model.Component component, boolean isUpdate) {
-
+    private Either<Boolean, ResponseFormat> validateInterfaceOperation(Operation interfaceOperation, InterfaceDefinition storedInterfaceDefinition,
+                                                                       InterfaceDefinition inputInterfaceDefinition,
+                                                                       org.openecomp.sdc.be.model.Component component, boolean isUpdate) {
         ResponseFormatManager responseFormatManager = getResponseFormatManager();
-        Either<Boolean, ResponseFormat> interfaceOperationTypeResponse =
-                isInterfaceOperationTypeValid(interfaceOperation, responseFormatManager, storedInterfaceDefinition,
-                        isUpdate);
+        Either<Boolean, ResponseFormat> interfaceOperationTypeResponse = isInterfaceOperationTypeValid(interfaceOperation, responseFormatManager,
+            storedInterfaceDefinition, isUpdate);
         if (interfaceOperationTypeResponse.isRight()) {
             return Either.right(interfaceOperationTypeResponse.right().value());
         }
-
-        if (null != interfaceOperation.getInputs()
-                && CollectionUtils.isNotEmpty(interfaceOperation.getInputs().getListToscaDataDefinition())) {
-            Either<Boolean, ResponseFormat> inputParametersResponse =
-                    validateInputParameters(interfaceOperation, responseFormatManager);
+        if (null != interfaceOperation.getInputs() && CollectionUtils.isNotEmpty(interfaceOperation.getInputs().getListToscaDataDefinition())) {
+            Either<Boolean, ResponseFormat> inputParametersResponse = validateInputParameters(interfaceOperation, responseFormatManager);
             if (inputParametersResponse.isRight()) {
                 return Either.right(inputParametersResponse.right().value());
             }
-
-            Either<Boolean, ResponseFormat> inputPropertyExistInComponent =
-                    validateInputPropertyExistInComponent(interfaceOperation,
-                            inputInterfaceDefinition, component, responseFormatManager);
+            Either<Boolean, ResponseFormat> inputPropertyExistInComponent = validateInputPropertyExistInComponent(interfaceOperation,
+                inputInterfaceDefinition, component, responseFormatManager);
             if (inputPropertyExistInComponent.isRight()) {
                 return Either.right(inputPropertyExistInComponent.right().value());
             }
         }
-
-        if (null != interfaceOperation.getOutputs()
-                && CollectionUtils.isNotEmpty(interfaceOperation.getOutputs().getListToscaDataDefinition())) {
-            Either<Boolean, ResponseFormat> outputParametersResponse =
-                    validateOutputParameters(interfaceOperation, responseFormatManager);
+        if (null != interfaceOperation.getOutputs() && CollectionUtils.isNotEmpty(interfaceOperation.getOutputs().getListToscaDataDefinition())) {
+            Either<Boolean, ResponseFormat> outputParametersResponse = validateOutputParameters(interfaceOperation, responseFormatManager);
             if (outputParametersResponse.isRight()) {
                 return Either.right(outputParametersResponse.right().value());
             }
         }
-
         if (MapUtils.isNotEmpty(component.getInterfaces()) && isUpdate) {
-            Either<Boolean, ResponseFormat> mappedOutputModifiedResponse =
-                    validateMappedOutputNotModified(interfaceOperation, component, inputInterfaceDefinition,
-                            responseFormatManager);
+            Either<Boolean, ResponseFormat> mappedOutputModifiedResponse = validateMappedOutputNotModified(interfaceOperation, component,
+                inputInterfaceDefinition, responseFormatManager);
             if (mappedOutputModifiedResponse.isRight()) {
                 return Either.right(mappedOutputModifiedResponse.right().value());
             }
         }
-
         return Either.left(Boolean.TRUE);
     }
 
-
     private Either<Boolean, ResponseFormat> validateMappedOutputNotModified(Operation interfaceOperation,
-            org.openecomp.sdc.be.model.Component component, InterfaceDefinition interfaceDefinition,
-            ResponseFormatManager responseFormatManager) {
-
-        List<OperationOutputDefinition> existingOperationOutputs =
-                getInterfaceOperationOutputs(interfaceOperation.getUniqueId(), component.getInterfaces());
+                                                                            org.openecomp.sdc.be.model.Component component,
+                                                                            InterfaceDefinition interfaceDefinition,
+                                                                            ResponseFormatManager responseFormatManager) {
+        List<OperationOutputDefinition> existingOperationOutputs = getInterfaceOperationOutputs(interfaceOperation.getUniqueId(),
+            component.getInterfaces());
         if (existingOperationOutputs.isEmpty()) {
             return Either.left(Boolean.TRUE);
         }
-        Set<String> existingOperationOutputNames = existingOperationOutputs.stream()
-                .map(OperationOutputDefinition::getName)
-                .collect(Collectors.toSet());
-
+        Set<String> existingOperationOutputNames = existingOperationOutputs.stream().map(OperationOutputDefinition::getName)
+            .collect(Collectors.toSet());
         ListDataDefinition<OperationOutputDefinition> currentOutputs = interfaceOperation.getOutputs();
         Set<String> currentOperationOutputNames = new HashSet<>();
         if (currentOutputs != null && !currentOutputs.isEmpty()) {
-            currentOperationOutputNames = currentOutputs.getListToscaDataDefinition().stream()
-                    .map(OperationOutputDefinition::getName)
-                    .collect(Collectors.toSet());
+            currentOperationOutputNames = currentOutputs.getListToscaDataDefinition().stream().map(OperationOutputDefinition::getName)
+                .collect(Collectors.toSet());
         }
         String mappedOutputPrefix = interfaceDefinition.getType() + "." + interfaceOperation.getName();
         //Get the deleted outputs (name changed also equivalent to deleted)
         Set<String> deletedOutputs = Sets.difference(existingOperationOutputNames, currentOperationOutputNames);
-        Set<String> deletedMappedOutputs = getModifiedMappedOutputs(deletedOutputs, mappedOutputPrefix,
-                component.getInterfaces());
-
+        Set<String> deletedMappedOutputs = getModifiedMappedOutputs(deletedOutputs, mappedOutputPrefix, component.getInterfaces());
         if (CollectionUtils.isNotEmpty(deletedMappedOutputs)) {
             return getMappedOutputErrorResponse(responseFormatManager, deletedMappedOutputs,
-                    "Cannot update or delete interface operation output(s) '{}' mapped to an operation input",
-                    ActionStatus.INTERFACE_OPERATION_MAPPED_OUTPUT_MODIFIED);
+                "Cannot update or delete interface operation output(s) '{}' mapped to an operation input",
+                ActionStatus.INTERFACE_OPERATION_MAPPED_OUTPUT_MODIFIED);
         }
-
         if (currentOutputs != null && !currentOutputs.isEmpty()) {
             //Get the unchanged outputs based on name to see if other attributes (type/mandatory) have not been changed
-            Set<String> unchangedOutputNames = Sets.intersection(existingOperationOutputNames,
-                    currentOperationOutputNames);
-            Set<String> modifiedOutputNames =
-                    getModifiedOutputNames(currentOutputs.getListToscaDataDefinition(),
-                            existingOperationOutputs, unchangedOutputNames);
-            Set<String> modifiedMappedOutputNames = getModifiedMappedOutputs(modifiedOutputNames, mappedOutputPrefix,
-                    component.getInterfaces());
+            Set<String> unchangedOutputNames = Sets.intersection(existingOperationOutputNames, currentOperationOutputNames);
+            Set<String> modifiedOutputNames = getModifiedOutputNames(currentOutputs.getListToscaDataDefinition(), existingOperationOutputs,
+                unchangedOutputNames);
+            Set<String> modifiedMappedOutputNames = getModifiedMappedOutputs(modifiedOutputNames, mappedOutputPrefix, component.getInterfaces());
             if (CollectionUtils.isNotEmpty(modifiedMappedOutputNames)) {
                 return getMappedOutputErrorResponse(responseFormatManager, modifiedMappedOutputNames,
-                        "Cannot update or delete interface operation output(s) '{}' mapped to an operation input",
-                        ActionStatus.INTERFACE_OPERATION_MAPPED_OUTPUT_MODIFIED);
+                    "Cannot update or delete interface operation output(s) '{}' mapped to an operation input",
+                    ActionStatus.INTERFACE_OPERATION_MAPPED_OUTPUT_MODIFIED);
             }
         }
-
         return Either.left(Boolean.TRUE);
     }
 
     private Set<String> getModifiedMappedOutputs(Set<String> modifiedOutputNames, String mappedOutputPrefix,
                                                  Map<String, InterfaceDefinition> componentInterfaces) {
         return modifiedOutputNames.stream()
-                .filter(modifiedOutputName -> isMappedOutputModified(mappedOutputPrefix, modifiedOutputName,
-                        componentInterfaces))
-                .map(InterfaceOperationUtils::getOperationOutputName)
-                .collect(Collectors.toSet());
+            .filter(modifiedOutputName -> isMappedOutputModified(mappedOutputPrefix, modifiedOutputName, componentInterfaces))
+            .map(InterfaceOperationUtils::getOperationOutputName).collect(Collectors.toSet());
     }
 
-    private boolean isMappedOutputModified(String mappedOutputPrefix, String outputName,
-                                           Map<String, InterfaceDefinition> componentInterfaces) {
-        List<OperationInputDefinition> interfaceOperationInputs =
-                getOtherOperationInputsOfComponent(mappedOutputPrefix, componentInterfaces);
+    private boolean isMappedOutputModified(String mappedOutputPrefix, String outputName, Map<String, InterfaceDefinition> componentInterfaces) {
+        List<OperationInputDefinition> interfaceOperationInputs = getOtherOperationInputsOfComponent(mappedOutputPrefix, componentInterfaces);
         return interfaceOperationInputs.stream()
-                .anyMatch(operationInputDefinition -> operationInputDefinition.getInputId()
-                        .equals(mappedOutputPrefix + "." + outputName));
+            .anyMatch(operationInputDefinition -> operationInputDefinition.getInputId().equals(mappedOutputPrefix + "." + outputName));
     }
 
     private static Set<String> getModifiedOutputNames(List<OperationOutputDefinition> currentOperationOutputs,
-                                                      List<OperationOutputDefinition> existingOperationOutputs,
-                                                      Set<String> unchangedOutputNames) {
+                                                      List<OperationOutputDefinition> existingOperationOutputs, Set<String> unchangedOutputNames) {
         Set<String> modifiedOutputDefinitionNames = new HashSet<>();
-        Map<String, OperationOutputDefinition> newOutputMap = currentOperationOutputs.stream()
-                .collect(Collectors.toMap(OperationOutputDefinition::getName,
-                        (OperationOutputDefinition operationOutputDefinition) -> operationOutputDefinition));
-
-        Map<String, OperationOutputDefinition> existingOutputMap = existingOperationOutputs.stream()
-                .collect(Collectors.toMap(OperationOutputDefinition::getName,
-                        (OperationOutputDefinition operationOutputDefinition) -> operationOutputDefinition));
-
+        Map<String, OperationOutputDefinition> newOutputMap = currentOperationOutputs.stream().collect(
+            Collectors.toMap(OperationOutputDefinition::getName, (OperationOutputDefinition operationOutputDefinition) -> operationOutputDefinition));
+        Map<String, OperationOutputDefinition> existingOutputMap = existingOperationOutputs.stream().collect(
+            Collectors.toMap(OperationOutputDefinition::getName, (OperationOutputDefinition operationOutputDefinition) -> operationOutputDefinition));
         for (String outputName : unchangedOutputNames) {
             OperationOutputDefinition existingOutputDefinition = existingOutputMap.get(outputName);
             OperationOutputDefinition newOutputDefinition = newOutputMap.get(outputName);
-            if (!existingOutputDefinition.getType().equals(newOutputDefinition.getType())
-                        || !existingOutputDefinition.isRequired().equals(newOutputDefinition.isRequired())) {
+            if (!existingOutputDefinition.getType().equals(newOutputDefinition.getType()) || !existingOutputDefinition.isRequired()
+                .equals(newOutputDefinition.isRequired())) {
                 modifiedOutputDefinitionNames.add(outputName);
             }
         }
@@ -298,8 +246,7 @@ public class InterfaceOperationValidation {
     }
 
     private Either<Boolean, ResponseFormat> getMappedOutputErrorResponse(ResponseFormatManager responseFormatManager,
-                                                                         Set<String> modifiedMappedOutputs,
-                                                                         String message,
+                                                                         Set<String> modifiedMappedOutputs, String message,
                                                                          ActionStatus errorStatus) {
         String modifiedOutputNameList = String.join(",", modifiedMappedOutputs);
         LOGGER.error(message, modifiedOutputNameList);
@@ -307,152 +254,120 @@ public class InterfaceOperationValidation {
         return Either.right(errorResponse);
     }
 
-
     protected ResponseFormatManager getResponseFormatManager() {
         return ResponseFormatManager.getInstance();
     }
 
-    private Either<Boolean, ResponseFormat> isInterfaceOperationTypeValid(Operation interfaceOperation,
-                                                                          ResponseFormatManager responseFormatManager,
-                                                                          InterfaceDefinition interfaceDefinition,
-                                                                          boolean isUpdate) {
-
-        Either<Boolean, ResponseFormat> operationTypeEmptyEither =
-                isOperationTypeEmpty(responseFormatManager, interfaceOperation.getName());
+    private Either<Boolean, ResponseFormat> isInterfaceOperationTypeValid(Operation interfaceOperation, ResponseFormatManager responseFormatManager,
+                                                                          InterfaceDefinition interfaceDefinition, boolean isUpdate) {
+        Either<Boolean, ResponseFormat> operationTypeEmptyEither = isOperationTypeEmpty(responseFormatManager, interfaceOperation.getName());
         if (operationTypeEmptyEither.isRight()) {
             return Either.right(operationTypeEmptyEither.right().value());
         }
-
-        Either<Boolean, ResponseFormat> operationTypeRegexValidationResponse =
-                isOperationTypeRegexValid(responseFormatManager, interfaceOperation.getName());
+        Either<Boolean, ResponseFormat> operationTypeRegexValidationResponse = isOperationTypeRegexValid(responseFormatManager,
+            interfaceOperation.getName());
         if (operationTypeRegexValidationResponse.isRight()) {
             return Either.right(operationTypeRegexValidationResponse.right().value());
         }
-
-        Either<Boolean, ResponseFormat> operationTypeUniqueResponse = validateOperationTypeUnique(interfaceOperation,
-                interfaceDefinition, isUpdate);
+        Either<Boolean, ResponseFormat> operationTypeUniqueResponse = validateOperationTypeUnique(interfaceOperation, interfaceDefinition, isUpdate);
         if (operationTypeUniqueResponse.isRight()) {
             return Either.right(operationTypeUniqueResponse.right().value());
         }
         if (!operationTypeUniqueResponse.left().value()) {
             LOGGER.error("Interface Operation type  {} already in use ", interfaceOperation.getName());
-            ResponseFormat errorResponse = responseFormatManager.getResponseFormat(
-                    ActionStatus.INTERFACE_OPERATION_NAME_ALREADY_IN_USE, interfaceOperation.getName());
+            ResponseFormat errorResponse = responseFormatManager
+                .getResponseFormat(ActionStatus.INTERFACE_OPERATION_NAME_ALREADY_IN_USE, interfaceOperation.getName());
             return Either.right(errorResponse);
         }
         return Either.left(Boolean.TRUE);
     }
 
-    private Either<Boolean, ResponseFormat> validateInputParameters(Operation interfaceOperation,
-                                                                    ResponseFormatManager responseFormatManager) {
+    private Either<Boolean, ResponseFormat> validateInputParameters(Operation interfaceOperation, ResponseFormatManager responseFormatManager) {
         if (isInputParameterNameEmpty(interfaceOperation)) {
             LOGGER.error("Interface operation input parameter name can't be empty");
-            ResponseFormat inputResponse =
-                    responseFormatManager.getResponseFormat(ActionStatus.INTERFACE_OPERATION_INPUT_NAME_MANDATORY);
+            ResponseFormat inputResponse = responseFormatManager.getResponseFormat(ActionStatus.INTERFACE_OPERATION_INPUT_NAME_MANDATORY);
             return Either.right(inputResponse);
         }
-
-        Either<Boolean, Set<String>> validateInputParametersUniqueResponse =
-                isInputParametersUnique(interfaceOperation);
+        Either<Boolean, Set<String>> validateInputParametersUniqueResponse = isInputParametersUnique(interfaceOperation);
         if (validateInputParametersUniqueResponse.isRight()) {
-            LOGGER.error("Interface operation input parameter names {} already in use",
-                    validateInputParametersUniqueResponse.right().value());
-            ResponseFormat inputResponse =
-                    responseFormatManager.getResponseFormat(ActionStatus.INTERFACE_OPERATION_INPUT_NAME_ALREADY_IN_USE,
-                            validateInputParametersUniqueResponse.right().value().toString());
+            LOGGER.error("Interface operation input parameter names {} already in use", validateInputParametersUniqueResponse.right().value());
+            ResponseFormat inputResponse = responseFormatManager.getResponseFormat(ActionStatus.INTERFACE_OPERATION_INPUT_NAME_ALREADY_IN_USE,
+                validateInputParametersUniqueResponse.right().value().toString());
             return Either.right(inputResponse);
         }
         return Either.left(Boolean.TRUE);
     }
 
-    private Either<Boolean, ResponseFormat> validateOutputParameters(Operation interfaceOperation,
-                                                                     ResponseFormatManager responseFormatManager) {
+    private Either<Boolean, ResponseFormat> validateOutputParameters(Operation interfaceOperation, ResponseFormatManager responseFormatManager) {
         if (isOutputParameterNameEmpty(interfaceOperation)) {
             LOGGER.error("Interface operation output parameter name can't be empty");
-            ResponseFormat inputResponse =
-                    responseFormatManager.getResponseFormat(ActionStatus.INTERFACE_OPERATION_OUTPUT_NAME_MANDATORY);
+            ResponseFormat inputResponse = responseFormatManager.getResponseFormat(ActionStatus.INTERFACE_OPERATION_OUTPUT_NAME_MANDATORY);
             return Either.right(inputResponse);
         }
-
-        Either<Boolean, Set<String>> validateOutputParametersUniqueResponse =
-                isOutputParametersUnique(interfaceOperation);
+        Either<Boolean, Set<String>> validateOutputParametersUniqueResponse = isOutputParametersUnique(interfaceOperation);
         if (validateOutputParametersUniqueResponse.isRight()) {
-            LOGGER.error("Interface operation output parameter names {} already in use",
-                    validateOutputParametersUniqueResponse.right().value());
-            ResponseFormat inputResponse =
-                    responseFormatManager.getResponseFormat(ActionStatus.INTERFACE_OPERATION_OUTPUT_NAME_ALREADY_IN_USE,
-                            validateOutputParametersUniqueResponse.right().value().toString());
+            LOGGER.error("Interface operation output parameter names {} already in use", validateOutputParametersUniqueResponse.right().value());
+            ResponseFormat inputResponse = responseFormatManager.getResponseFormat(ActionStatus.INTERFACE_OPERATION_OUTPUT_NAME_ALREADY_IN_USE,
+                validateOutputParametersUniqueResponse.right().value().toString());
             return Either.right(inputResponse);
         }
         return Either.left(Boolean.TRUE);
     }
 
-    private Either<Boolean, ResponseFormat> isOperationTypeEmpty(ResponseFormatManager responseFormatManager,
-            String operationType) {
+    private Either<Boolean, ResponseFormat> isOperationTypeEmpty(ResponseFormatManager responseFormatManager, String operationType) {
         if (StringUtils.isEmpty(operationType)) {
             LOGGER.error("Interface Operation type is mandatory");
-            ResponseFormat errorResponse =
-                    responseFormatManager.getResponseFormat(ActionStatus.INTERFACE_OPERATION_NAME_MANDATORY);
+            ResponseFormat errorResponse = responseFormatManager.getResponseFormat(ActionStatus.INTERFACE_OPERATION_NAME_MANDATORY);
             return Either.right(errorResponse);
         }
         return Either.left(Boolean.TRUE);
     }
 
-    private Either<Boolean, ResponseFormat> isOperationTypeRegexValid(ResponseFormatManager responseFormatManager,
-            String operationType) {
+    private Either<Boolean, ResponseFormat> isOperationTypeRegexValid(ResponseFormatManager responseFormatManager, String operationType) {
         if (!isValidOperationType(operationType)) {
             LOGGER.error("Interface Operation type {} is invalid, Operation type should not contain"
-                                 + "Special character, space, numbers and  should not be greater than 200 characters",
-                    operationType);
-            ResponseFormat errorResponse = responseFormatManager
-                                                   .getResponseFormat(ActionStatus.INTERFACE_OPERATION_NAME_INVALID,
-                                                           operationType);
+                + "Special character, space, numbers and  should not be greater than 200 characters", operationType);
+            ResponseFormat errorResponse = responseFormatManager.getResponseFormat(ActionStatus.INTERFACE_OPERATION_NAME_INVALID, operationType);
             return Either.right(errorResponse);
         }
         return Either.left(Boolean.TRUE);
     }
 
-    private Either<Boolean, ResponseFormat> validateOperationTypeUnique(Operation interfaceOperation,
-            InterfaceDefinition interfaceDefinition, boolean isUpdate) {
+    private Either<Boolean, ResponseFormat> validateOperationTypeUnique(Operation interfaceOperation, InterfaceDefinition interfaceDefinition,
+                                                                        boolean isUpdate) {
         boolean isOperationTypeUnique = false;
-
         if (interfaceDefinition == null || CollectionUtils.isEmpty(interfaceDefinition.getOperationsMap().values())) {
             return Either.left(true);
         }
-
         Map<String, String> operationTypes = new HashMap<>();
         interfaceDefinition.getOperationsMap().values()
-                .forEach(operationType -> operationTypes.put(operationType.getUniqueId(), operationType.getName()));
-
+            .forEach(operationType -> operationTypes.put(operationType.getUniqueId(), operationType.getName()));
         if (!operationTypes.values().contains(interfaceOperation.getName())) {
             isOperationTypeUnique = true;
         }
         if (!isOperationTypeUnique && isUpdate) {
-            Optional<String> id = operationTypes.entrySet().stream().filter(entry -> Objects.equals(entry.getValue(),
-                    interfaceOperation.getName())).map(Map.Entry::getKey).findAny();
+            Optional<String> id = operationTypes.entrySet().stream().filter(entry -> Objects.equals(entry.getValue(), interfaceOperation.getName()))
+                .map(Map.Entry::getKey).findAny();
             if (id.isPresent() && id.get().equalsIgnoreCase(interfaceOperation.getUniqueId())) {
                 isOperationTypeUnique = true;
             }
         }
-
         return Either.left(isOperationTypeUnique);
     }
 
     private Boolean isInputParameterNameEmpty(Operation operationDataDefinition) {
-        return operationDataDefinition.getInputs().getListToscaDataDefinition().stream().anyMatch(
-                inputParam -> inputParam.getName() == null || inputParam.getName().trim().equals(StringUtils.EMPTY));
+        return operationDataDefinition.getInputs().getListToscaDataDefinition().stream()
+            .anyMatch(inputParam -> inputParam.getName() == null || inputParam.getName().trim().equals(StringUtils.EMPTY));
     }
 
-
     private Either<Boolean, Set<String>> isInputParametersUnique(Operation operationDataDefinition) {
         Set<String> inputParamNamesSet = new HashSet<>();
         Set<String> duplicateParamNamesToReturn = new HashSet<>();
-        operationDataDefinition.getInputs().getListToscaDataDefinition()
-                               .forEach(inputParam -> {
-                                   if (!inputParamNamesSet.add(inputParam.getName().trim())) {
-                                       duplicateParamNamesToReturn.add(inputParam.getName().trim());
-                                   }
-                               });
+        operationDataDefinition.getInputs().getListToscaDataDefinition().forEach(inputParam -> {
+            if (!inputParamNamesSet.add(inputParam.getName().trim())) {
+                duplicateParamNamesToReturn.add(inputParam.getName().trim());
+            }
+        });
         if (!duplicateParamNamesToReturn.isEmpty()) {
             return Either.right(duplicateParamNamesToReturn);
         }
@@ -460,89 +375,80 @@ public class InterfaceOperationValidation {
     }
 
     private Boolean isOutputParameterNameEmpty(Operation operationDataDefinition) {
-        return operationDataDefinition.getOutputs().getListToscaDataDefinition().stream().anyMatch(
-                outputParam -> outputParam.getName() == null || outputParam.getName().trim().equals(StringUtils.EMPTY));
+        return operationDataDefinition.getOutputs().getListToscaDataDefinition().stream()
+            .anyMatch(outputParam -> outputParam.getName() == null || outputParam.getName().trim().equals(StringUtils.EMPTY));
     }
 
     private Either<Boolean, Set<String>> isOutputParametersUnique(Operation operationDataDefinition) {
         Set<String> outputParamNamesSet = new HashSet<>();
         Set<String> duplicateParamNamesToReturn = new HashSet<>();
-        operationDataDefinition.getOutputs().getListToscaDataDefinition()
-                               .forEach(outputParam -> {
-                                   if (!outputParamNamesSet.add(outputParam.getName().trim())) {
-                                       duplicateParamNamesToReturn.add(outputParam.getName().trim());
-                                   }
-                               });
+        operationDataDefinition.getOutputs().getListToscaDataDefinition().forEach(outputParam -> {
+            if (!outputParamNamesSet.add(outputParam.getName().trim())) {
+                duplicateParamNamesToReturn.add(outputParam.getName().trim());
+            }
+        });
         if (!duplicateParamNamesToReturn.isEmpty()) {
             return Either.right(duplicateParamNamesToReturn);
         }
         return Either.left(Boolean.TRUE);
     }
 
-    private  Either<Boolean, ResponseFormat> validateInputPropertyExistInComponent(Operation operation,
-            InterfaceDefinition inputInterfaceDefinition, org.openecomp.sdc.be.model.Component component,
-            ResponseFormatManager responseFormatManager) {
-
+    private Either<Boolean, ResponseFormat> validateInputPropertyExistInComponent(Operation operation, InterfaceDefinition inputInterfaceDefinition,
+                                                                                  org.openecomp.sdc.be.model.Component component,
+                                                                                  ResponseFormatManager responseFormatManager) {
         boolean isOperationInputToInputPropertyMappingValid = false;
         boolean isOperationInputToOtherOperationOutputMappingValid = false;
         String mappingName = "";
-        List<OperationInputDefinition> inputListToscaDataDefinition =
-                operation.getInputs().getListToscaDataDefinition();
+        List<OperationInputDefinition> inputListToscaDataDefinition = operation.getInputs().getListToscaDataDefinition();
         for (OperationInputDefinition inputDefinition : inputListToscaDataDefinition) {
-            if (isOperationInputMappedToComponentInput(inputDefinition, component.getInputs())
-                    || isCapabilityProperty(inputDefinition.getInputId(), component).isPresent()) {
+            if (isOperationInputMappedToComponentInput(inputDefinition, component.getInputs()) || isCapabilityProperty(inputDefinition.getInputId(),
+                component).isPresent()) {
                 isOperationInputToInputPropertyMappingValid = true;
             } else {
-                mappingName = inputDefinition.getInputId().contains(".")
-                        ? inputDefinition.getInputId().substring(inputDefinition.getInputId().lastIndexOf('.') + 1)
-                        : inputDefinition.getInputId();
+                mappingName = inputDefinition.getInputId().contains(".") ? inputDefinition.getInputId()
+                    .substring(inputDefinition.getInputId().lastIndexOf('.') + 1) : inputDefinition.getInputId();
                 break;
             }
         }
         if (isOperationInputToInputPropertyMappingValid) {
             return Either.left(Boolean.TRUE);
         }
-
         //Mapped property not found in the component properties.. Check in other operation output parameters of
+
         // component (other operation => not having the same full name)
         String actualOperationIdentifier = inputInterfaceDefinition.getType() + "." + operation.getName();
-        ListDataDefinition<OperationOutputDefinition> outputListDataDefinition =
-                getOtherOperationOutputsOfComponent(actualOperationIdentifier, component.getInterfaces());
-
-        List<OperationOutputDefinition> componentOutputsFromOtherOperations =
-                outputListDataDefinition.getListToscaDataDefinition();
+        ListDataDefinition<OperationOutputDefinition> outputListDataDefinition = getOtherOperationOutputsOfComponent(actualOperationIdentifier,
+            component.getInterfaces());
+        List<OperationOutputDefinition> componentOutputsFromOtherOperations = outputListDataDefinition.getListToscaDataDefinition();
         if (validateOutputExistsInComponent(mappingName, componentOutputsFromOtherOperations)) {
             isOperationInputToOtherOperationOutputMappingValid = true;
         } else {
             //Get the output parameter display name from the full name
             mappingName = getOperationOutputName(mappingName);
         }
-
         if (!isOperationInputToOtherOperationOutputMappingValid) {
             LOGGER.error("Interface operation input parameter property {} not found in component input properties or"
-                   + "capability properties or  outputs of other operations.", mappingName);
+                + "capability properties or  outputs of other operations.", mappingName);
             ResponseFormat inputResponse = responseFormatManager
-                    .getResponseFormat(ActionStatus.INTERFACE_OPERATION_INPUT_PROPERTY_NOT_FOUND_IN_COMPONENT,
-                            mappingName, component.getComponentType().getValue());
+                .getResponseFormat(ActionStatus.INTERFACE_OPERATION_INPUT_PROPERTY_NOT_FOUND_IN_COMPONENT, mappingName,
+                    component.getComponentType().getValue());
             return Either.right(inputResponse);
         }
         return Either.left(Boolean.TRUE);
     }
 
-    private boolean validateOutputExistsInComponent(String mappedOutputName,
-                                                    List<OperationOutputDefinition> outputs) {
-        return outputs.stream()
-                .anyMatch(output -> output.getName().equals(mappedOutputName));
+    private boolean validateOutputExistsInComponent(String mappedOutputName, List<OperationOutputDefinition> outputs) {
+        return outputs.stream().anyMatch(output -> output.getName().equals(mappedOutputName));
     }
 
     /**
      * Get the input definitions of other operations of the component from current as well as other interfaces.
+     *
      * @param currentOperationIdentifier Identifier for the request operation (interface_name.operation_name)
-     * @param componentInterfaces Interfaces of the component
+     * @param componentInterfaces        Interfaces of the component
      */
     private List<OperationInputDefinition> getOtherOperationInputsOfComponent(String currentOperationIdentifier,
-                                                                              Map<String, InterfaceDefinition>
-                                                                                      componentInterfaces) {
+                                                                              Map<String, InterfaceDefinition> componentInterfaces) {
         List<OperationInputDefinition> otherOperationInputs = new ArrayList<>();
         if (MapUtils.isEmpty(componentInterfaces)) {
             return otherOperationInputs;
@@ -554,8 +460,7 @@ public class InterfaceOperationValidation {
             }
             for (Map.Entry<String, OperationDataDefinition> operationEntry : operations.entrySet()) {
                 ListDataDefinition<OperationInputDefinition> inputs = operationEntry.getValue().getInputs();
-                String expectedOperationIdentifier =
-                        interfaceDefinitionEntry.getValue().getType() + "." + operationEntry.getValue().getName();
+                String expectedOperationIdentifier = interfaceDefinitionEntry.getValue().getType() + "." + operationEntry.getValue().getName();
                 if (!currentOperationIdentifier.equals(expectedOperationIdentifier) && Objects.nonNull(inputs) && !inputs.isEmpty()) {
                     otherOperationInputs.addAll(inputs.getListToscaDataDefinition());
                 }
@@ -566,12 +471,12 @@ public class InterfaceOperationValidation {
 
     /**
      * Get the output of an operation in an interface.
-     * @param inputOperationId Unique identifier for the request operation
+     *
+     * @param inputOperationId    Unique identifier for the request operation
      * @param componentInterfaces Interfaces of the component
      */
     private List<OperationOutputDefinition> getInterfaceOperationOutputs(String inputOperationId,
-                                                                         Map<String, InterfaceDefinition>
-                                                                                 componentInterfaces) {
+                                                                         Map<String, InterfaceDefinition> componentInterfaces) {
         List<OperationOutputDefinition> operationOutputDefinitions = new ArrayList<>();
         if (MapUtils.isEmpty(componentInterfaces)) {
             return operationOutputDefinitions;
@@ -584,11 +489,9 @@ public class InterfaceOperationValidation {
             for (Map.Entry<String, OperationDataDefinition> operationEntry : operations.entrySet()) {
                 String expectedOperationId = operationEntry.getValue().getUniqueId();
                 if (expectedOperationId.equals(inputOperationId)) {
-                    ListDataDefinition<OperationOutputDefinition> operationOutputs =
-                            operationEntry.getValue().getOutputs();
-                    return (Objects.isNull(operationOutputs) || operationOutputs.isEmpty())
-                            ? operationOutputDefinitions
-                            : operationOutputs.getListToscaDataDefinition();
+                    ListDataDefinition<OperationOutputDefinition> operationOutputs = operationEntry.getValue().getOutputs();
+                    return (Objects.isNull(operationOutputs) || operationOutputs.isEmpty()) ? operationOutputDefinitions
+                        : operationOutputs.getListToscaDataDefinition();
                 }
             }
         }
@@ -598,5 +501,4 @@ public class InterfaceOperationValidation {
     private boolean isValidOperationType(String operationType) {
         return Pattern.matches(TYPE_VALIDATION_REGEX, operationType);
     }
-
 }
index 8c27396..6bfe26a 100644 (file)
@@ -17,7 +17,6 @@
  * limitations under the License.
  * ============LICENSE_END=========================================================
  */
-
 package org.openecomp.sdc.be.components.validation;
 
 import com.google.common.collect.ImmutableSet;
@@ -55,34 +54,28 @@ import org.springframework.util.CollectionUtils;
 public class NodeFilterValidator {
 
     private static final String SOURCE = "Source";
-    public static final Set<String> comparableTypes = ImmutableSet.of(ToscaPropertyType.STRING.getType(),
-        ToscaPropertyType.INTEGER.getType(), ToscaPropertyType.FLOAT.getType());
-    public static final Set<String> schemableTypes =
-        ImmutableSet.of(ToscaPropertyType.MAP.getType(), ToscaPropertyType.LIST.getType());
-    public static final Set<String> comparableConstraintsOperators =
-        ImmutableSet.of(ConstraintConvertor.GREATER_THAN_OPERATOR, ConstraintConvertor.LESS_THAN_OPERATOR);
-
+    public static final Set<String> comparableTypes = ImmutableSet
+        .of(ToscaPropertyType.STRING.getType(), ToscaPropertyType.INTEGER.getType(), ToscaPropertyType.FLOAT.getType());
+    public static final Set<String> schemableTypes = ImmutableSet.of(ToscaPropertyType.MAP.getType(), ToscaPropertyType.LIST.getType());
+    public static final Set<String> comparableConstraintsOperators = ImmutableSet
+        .of(ConstraintConvertor.GREATER_THAN_OPERATOR, ConstraintConvertor.LESS_THAN_OPERATOR);
     protected final ToscaOperationFacade toscaOperationFacade;
     protected final ComponentsUtils componentsUtils;
-
     private static final Logger LOGGER = LoggerFactory.getLogger(NodeFilterValidator.class);
 
     @Autowired
-    public NodeFilterValidator(final ToscaOperationFacade toscaOperationFacade,
-                               final ComponentsUtils componentsUtils) {
+    public NodeFilterValidator(final ToscaOperationFacade toscaOperationFacade, final ComponentsUtils componentsUtils) {
         this.toscaOperationFacade = toscaOperationFacade;
         this.componentsUtils = componentsUtils;
     }
 
-    public Either<Boolean, ResponseFormat> validateComponentInstanceExist(final Component component,
-                                                                          final String componentInstanceId) {
+    public Either<Boolean, ResponseFormat> validateComponentInstanceExist(final Component component, final String componentInstanceId) {
         if (component == null || StringUtils.isEmpty(componentInstanceId)) {
             LOGGER.error("Input data cannot be empty");
             return getErrorResponse(ActionStatus.FILTER_NOT_FOUND);
         }
-        if (CollectionUtils.isEmpty(component.getComponentInstances()) ||
-            component.getComponentInstances().stream()
-                .noneMatch(ci -> ci.getUniqueId().equals(componentInstanceId))) {
+        if (CollectionUtils.isEmpty(component.getComponentInstances()) || component.getComponentInstances().stream()
+            .noneMatch(ci -> ci.getUniqueId().equals(componentInstanceId))) {
             LOGGER.error("Component Instance list is empty");
             return getErrorResponse(ActionStatus.FILTER_NOT_FOUND);
         }
@@ -94,31 +87,26 @@ public class NodeFilterValidator {
         return Either.right(errorResponse);
     }
 
-    public Either<Boolean, ResponseFormat> validateFilter(final Component parentComponent,
-                                                          final String componentInstanceId,
-                                                          final List<String> uiConstraints,
-                                                          final NodeFilterConstraintAction action,
+    public Either<Boolean, ResponseFormat> validateFilter(final Component parentComponent, final String componentInstanceId,
+                                                          final List<String> uiConstraints, final NodeFilterConstraintAction action,
                                                           final NodeFilterConstraintType nodeFilterConstraintType) {
         try {
             if (NodeFilterConstraintAction.ADD == action || NodeFilterConstraintAction.UPDATE == action) {
                 for (final String uiConstraint : uiConstraints) {
                     final UIConstraint constraint = new ConstraintConvertor().convert(uiConstraint);
                     if (ConstraintConvertor.PROPERTY_CONSTRAINT.equals(constraint.getSourceType())) {
-                        final Either<Boolean, ResponseFormat> booleanResponseFormatEither =
-                            validatePropertyConstraint(parentComponent, componentInstanceId, constraint);
+                        final Either<Boolean, ResponseFormat> booleanResponseFormatEither = validatePropertyConstraint(parentComponent,
+                            componentInstanceId, constraint);
                         if (booleanResponseFormatEither.isRight()) {
                             return booleanResponseFormatEither;
                         }
                     } else if (ConstraintConvertor.STATIC_CONSTRAINT.equals(constraint.getSourceType())) {
                         Either<Boolean, ResponseFormat> booleanResponseFormatEither;
                         if (NodeFilterConstraintType.PROPERTIES.equals(nodeFilterConstraintType)) {
-                            booleanResponseFormatEither = isComponentPropertyFilterValid(
-                                parentComponent, componentInstanceId, constraint);
+                            booleanResponseFormatEither = isComponentPropertyFilterValid(parentComponent, componentInstanceId, constraint);
                         } else {
-                            booleanResponseFormatEither = isComponentCapabilityPropertyFilterValid(
-                                parentComponent, componentInstanceId, constraint);
+                            booleanResponseFormatEither = isComponentCapabilityPropertyFilterValid(parentComponent, componentInstanceId, constraint);
                         }
-
                         if (booleanResponseFormatEither.isRight()) {
                             return booleanResponseFormatEither;
                         }
@@ -129,75 +117,49 @@ public class NodeFilterValidator {
             LOGGER.debug("Provided constraint" + uiConstraints, e);
             return Either.right(componentsUtils.getResponseFormat(ActionStatus.CONSTRAINT_FORMAT_INCORRECT));
         }
-
         return Either.left(true);
     }
 
     private Either<Boolean, ResponseFormat> isComponentCapabilityPropertyFilterValid(final Component parentComponent,
                                                                                      final String componentInstanceId,
                                                                                      final UIConstraint uiConstraint) {
-
         return validateStaticValueAndOperatorOfCapabilityProperties(parentComponent, componentInstanceId, uiConstraint);
-
     }
 
-    private Either<Boolean, ResponseFormat> isComponentPropertyFilterValid(Component parentComponent,
-                                                                           String componentInstanceId,
+    private Either<Boolean, ResponseFormat> isComponentPropertyFilterValid(Component parentComponent, String componentInstanceId,
                                                                            UIConstraint constraint) {
-
         return validateStaticValueAndOperator(parentComponent, componentInstanceId, constraint);
     }
 
-    private Either<Boolean, ResponseFormat> validatePropertyConstraint(final Component parentComponent,
-                                                                       final String componentInstanceId,
+    private Either<Boolean, ResponseFormat> validatePropertyConstraint(final Component parentComponent, final String componentInstanceId,
                                                                        final UIConstraint uiConstraint) {
         String source = SOURCE;
         final Optional<ComponentInstance> optionalComponentInstance;
-
         final List<PropertyDefinition> propertyDefinitions = parentComponent.getProperties();
         List<? extends PropertyDefinition> sourcePropertyDefinition =
-            parentComponent.getName().equals(uiConstraint.getSourceName()) &&
-                propertyDefinitions != null ? propertyDefinitions : Collections.emptyList();
-
+            parentComponent.getName().equals(uiConstraint.getSourceName()) && propertyDefinitions != null ? propertyDefinitions
+                : Collections.emptyList();
         if (sourcePropertyDefinition.isEmpty() && !parentComponent.getName().equals(uiConstraint.getSourceName())) {
             optionalComponentInstance = parentComponent.getComponentInstances().stream()
-                .filter(componentInstance -> uiConstraint.getSourceName()
-                    .equals(componentInstance
-                        .getName()))
-                .findFirst();
-
+                .filter(componentInstance -> uiConstraint.getSourceName().equals(componentInstance.getName())).findFirst();
             if (optionalComponentInstance.isPresent()) {
-                final List<ComponentInstanceProperty> componentInstanceProperties =
-                    parentComponent.getComponentInstancesProperties()
-                        .get(optionalComponentInstance.get().getUniqueId());
-                sourcePropertyDefinition =
-                    componentInstanceProperties == null ? new ArrayList<>() : componentInstanceProperties;
+                final List<ComponentInstanceProperty> componentInstanceProperties = parentComponent.getComponentInstancesProperties()
+                    .get(optionalComponentInstance.get().getUniqueId());
+                sourcePropertyDefinition = componentInstanceProperties == null ? new ArrayList<>() : componentInstanceProperties;
             }
         }
-
         if (!CollectionUtils.isEmpty(sourcePropertyDefinition)) {
             final Optional<? extends PropertyDefinition> sourceSelectedProperty = sourcePropertyDefinition.stream()
-                .filter(property -> uiConstraint
-                    .getValue()
-                    .equals(property.getName()))
-                .findFirst();
-
-            final Optional<? extends PropertyDefinition> targetComponentInstanceProperty =
-                parentComponent.getComponentInstancesProperties().get(componentInstanceId).stream()
-                    .filter(property -> uiConstraint.getServicePropertyName().equals(property.getName()))
-                    .findFirst();
-
+                .filter(property -> uiConstraint.getValue().equals(property.getName())).findFirst();
+            final Optional<? extends PropertyDefinition> targetComponentInstanceProperty = parentComponent.getComponentInstancesProperties()
+                .get(componentInstanceId).stream().filter(property -> uiConstraint.getServicePropertyName().equals(property.getName())).findFirst();
             source = !targetComponentInstanceProperty.isPresent() ? "Target" : SOURCE;
             if (sourceSelectedProperty.isPresent() && targetComponentInstanceProperty.isPresent()) {
                 return validatePropertyData(uiConstraint, sourceSelectedProperty, targetComponentInstanceProperty);
             }
         }
-
-        final String missingProperty =
-            source.equals(SOURCE) ? uiConstraint.getValue().toString() : uiConstraint.getServicePropertyName();
-
-        return Either.right(
-            componentsUtils.getResponseFormat(ActionStatus.MAPPED_PROPERTY_NOT_FOUND, source, missingProperty));
+        final String missingProperty = source.equals(SOURCE) ? uiConstraint.getValue().toString() : uiConstraint.getServicePropertyName();
+        return Either.right(componentsUtils.getResponseFormat(ActionStatus.MAPPED_PROPERTY_NOT_FOUND, source, missingProperty));
     }
 
     private Either<Boolean, ResponseFormat> validatePropertyData(UIConstraint uiConstraint,
@@ -213,122 +175,105 @@ public class NodeFilterValidator {
                     final SchemaDefinition sourceSchemaDefinition = sourcePropDefinition.getSchema();
                     final SchemaDefinition targetSchemaDefinition = targetPropDefinition.getSchema();
                     if (!sourceSchemaDefinition.equals(targetSchemaDefinition)) {
-                        return Either
-                            .right(componentsUtils.getResponseFormat(ActionStatus.SOURCE_TARGET_SCHEMA_MISMATCH,
-                                uiConstraint.getServicePropertyName(), uiConstraint.getValue().toString()));
+                        return Either.right(componentsUtils
+                            .getResponseFormat(ActionStatus.SOURCE_TARGET_SCHEMA_MISMATCH, uiConstraint.getServicePropertyName(),
+                                uiConstraint.getValue().toString()));
                     }
                 }
                 return Either.left(Boolean.TRUE);
             } else {
-                return Either.right(componentsUtils.getResponseFormat(ActionStatus.SOURCE_TARGET_PROPERTY_TYPE_MISMATCH,
-                    uiConstraint.getServicePropertyName(), uiConstraint.getValue().toString()));
+                return Either.right(componentsUtils
+                    .getResponseFormat(ActionStatus.SOURCE_TARGET_PROPERTY_TYPE_MISMATCH, uiConstraint.getServicePropertyName(),
+                        uiConstraint.getValue().toString()));
             }
         } else {
-            LOGGER.debug(
-                "Null value passed to `validatePropertyData` - sourceSelectedProperty: '{}' - targetComponentInstanceProperty: '{}'",
+            LOGGER.debug("Null value passed to `validatePropertyData` - sourceSelectedProperty: '{}' - targetComponentInstanceProperty: '{}'",
                 sourceSelectedProperty, targetComponentInstanceProperty);
             return Either.right(componentsUtils
-                .getResponseFormat(ActionStatus.GENERAL_ERROR, uiConstraint.getServicePropertyName(),
-                    uiConstraint.getValue().toString()));
+                .getResponseFormat(ActionStatus.GENERAL_ERROR, uiConstraint.getServicePropertyName(), uiConstraint.getValue().toString()));
         }
     }
 
-    private Either<Boolean, ResponseFormat> validateStaticValueAndOperator(
-        final Component parentComponent,
-        final String componentInstanceId, final UIConstraint uiConstraint) {
+    private Either<Boolean, ResponseFormat> validateStaticValueAndOperator(final Component parentComponent, final String componentInstanceId,
+                                                                           final UIConstraint uiConstraint) {
         if (!(Objects.nonNull(uiConstraint) && uiConstraint.getValue() instanceof String)) {
             return Either.left(false);
         }
         //TODO: get capabilities properties when constraint type is capabilities
-        final Optional<ComponentInstanceProperty> componentInstanceProperty =
-            parentComponent.getComponentInstancesProperties().get(componentInstanceId).stream()
-                .filter(property -> uiConstraint.getServicePropertyName().equals(property.getName()))
-                .findFirst();
-
+        final Optional<ComponentInstanceProperty> componentInstanceProperty = parentComponent.getComponentInstancesProperties()
+            .get(componentInstanceId).stream().filter(property -> uiConstraint.getServicePropertyName().equals(property.getName())).findFirst();
         if (!componentInstanceProperty.isPresent()) {
-            return Either.right(componentsUtils.getResponseFormat(ActionStatus.SELECTED_PROPERTY_NOT_PRESENT,
-                uiConstraint.getServicePropertyName()));
+            return Either.right(componentsUtils.getResponseFormat(ActionStatus.SELECTED_PROPERTY_NOT_PRESENT, uiConstraint.getServicePropertyName()));
         }
-        if (comparableConstraintsOperators.contains(uiConstraint.getConstraintOperator()) && !comparableTypes.contains(
-            componentInstanceProperty.get().getType())) {
-            return Either.right(componentsUtils.getResponseFormat(ActionStatus.UNSUPPORTED_OPERATOR_PROVIDED,
-                uiConstraint.getServicePropertyName(), uiConstraint.getConstraintOperator()));
+        if (comparableConstraintsOperators.contains(uiConstraint.getConstraintOperator()) && !comparableTypes
+            .contains(componentInstanceProperty.get().getType())) {
+            return Either.right(componentsUtils.getResponseFormat(ActionStatus.UNSUPPORTED_OPERATOR_PROVIDED, uiConstraint.getServicePropertyName(),
+                uiConstraint.getConstraintOperator()));
         }
-
         return isValidValueCheck(componentInstanceProperty.get().getType(), String.valueOf(uiConstraint.getValue()),
             uiConstraint.getServicePropertyName());
     }
 
-    private Either<Boolean, ResponseFormat> validateStaticValueAndOperatorOfCapabilityProperties(
-        final Component parentComponent, final String componentInstanceId, final UIConstraint uiConstraint) {
+    private Either<Boolean, ResponseFormat> validateStaticValueAndOperatorOfCapabilityProperties(final Component parentComponent,
+                                                                                                 final String componentInstanceId,
+                                                                                                 final UIConstraint uiConstraint) {
         if (!(Objects.nonNull(uiConstraint) && uiConstraint.getValue() instanceof String)) {
             return Either.left(false);
         }
         Optional<ComponentInstanceProperty> optionalComponentInstanceProperty = Optional.empty();
         final Optional<ComponentInstance> optionalComponentInstances = parentComponent.getComponentInstances().stream()
-            .filter(componentInstance -> componentInstanceId.equalsIgnoreCase(componentInstance.getUniqueId()))
-            .findFirst();
+            .filter(componentInstance -> componentInstanceId.equalsIgnoreCase(componentInstance.getUniqueId())).findFirst();
         if (optionalComponentInstances.isPresent()) {
-            final Optional<List<CapabilityDefinition>> optionalCapabilityDefinitionList = optionalComponentInstances.get()
-                .getCapabilities().values().stream()
-                .filter(capabilityDefinitions -> capabilityDefinitions
-                    .stream().allMatch(capabilityDefinition -> capabilityDefinition.getProperties() != null))
-                .collect(Collectors.toList())
-                .stream().filter(capabilityDefinitions -> capabilityDefinitions.stream().allMatch(
-                    capabilityDefinition -> capabilityDefinition.getProperties().stream().anyMatch(
-                        componentInstanceProperty -> uiConstraint.getServicePropertyName()
-                            .equalsIgnoreCase(componentInstanceProperty.getName())))).findFirst();
-
+            final Optional<List<CapabilityDefinition>> optionalCapabilityDefinitionList = optionalComponentInstances.get().getCapabilities().values()
+                .stream().filter(capabilityDefinitions -> capabilityDefinitions.stream()
+                    .allMatch(capabilityDefinition -> capabilityDefinition.getProperties() != null)).collect(Collectors.toList()).stream().filter(
+                    capabilityDefinitions -> capabilityDefinitions.stream().allMatch(
+                        capabilityDefinition -> capabilityDefinition.getProperties().stream().anyMatch(
+                            componentInstanceProperty -> uiConstraint.getServicePropertyName()
+                                .equalsIgnoreCase(componentInstanceProperty.getName())))).findFirst();
             if (optionalCapabilityDefinitionList.isPresent()) {
                 optionalComponentInstanceProperty = optionalCapabilityDefinitionList.get().stream().findAny()
                     .map(capabilityDefinition -> capabilityDefinition.getProperties().get(0));
             }
         }
-
         if (optionalComponentInstanceProperty.isEmpty()) {
-            return Either.right(componentsUtils.getResponseFormat(ActionStatus.SELECTED_PROPERTY_NOT_PRESENT,
-                uiConstraint.getServicePropertyName()));
+            return Either.right(componentsUtils.getResponseFormat(ActionStatus.SELECTED_PROPERTY_NOT_PRESENT, uiConstraint.getServicePropertyName()));
         }
-        if (comparableConstraintsOperators.contains(uiConstraint.getConstraintOperator()) && !comparableTypes.contains(
-            optionalComponentInstanceProperty.get().getType())) {
-            return Either.right(componentsUtils.getResponseFormat(ActionStatus.UNSUPPORTED_OPERATOR_PROVIDED,
-                uiConstraint.getServicePropertyName(), uiConstraint.getConstraintOperator()));
+        if (comparableConstraintsOperators.contains(uiConstraint.getConstraintOperator()) && !comparableTypes
+            .contains(optionalComponentInstanceProperty.get().getType())) {
+            return Either.right(componentsUtils.getResponseFormat(ActionStatus.UNSUPPORTED_OPERATOR_PROVIDED, uiConstraint.getServicePropertyName(),
+                uiConstraint.getConstraintOperator()));
         }
-
         return isValidValueCheck(optionalComponentInstanceProperty.get().getType(), String.valueOf(uiConstraint.getValue()),
             uiConstraint.getServicePropertyName());
     }
 
     private Either<Boolean, ResponseFormat> isValidValueCheck(String type, String value, String propertyName) {
-
         ToscaPropertyType toscaPropertyType = ToscaPropertyType.isValidType(type);
         if (Objects.isNull(toscaPropertyType)) {
-            return Either.right(
-                componentsUtils.getResponseFormat(ActionStatus.UNSUPPORTED_PROPERTY_TYPE, type, propertyName));
+            return Either.right(componentsUtils.getResponseFormat(ActionStatus.UNSUPPORTED_PROPERTY_TYPE, type, propertyName));
         }
         if (toscaPropertyType.getValidator().isValid(value, null)) {
             return Either.left(Boolean.TRUE);
         }
-        return Either.right(
-            componentsUtils.getResponseFormat(ActionStatus.UNSUPPORTED_VALUE_PROVIDED, type, propertyName, value));
+        return Either.right(componentsUtils.getResponseFormat(ActionStatus.UNSUPPORTED_VALUE_PROVIDED, type, propertyName, value));
     }
 
-    public Either<Boolean, ResponseFormat> validateComponentFilter(final Component component,
-                                                                   final List<String> uiConstraints,
+    public Either<Boolean, ResponseFormat> validateComponentFilter(final Component component, final List<String> uiConstraints,
                                                                    final NodeFilterConstraintAction action) {
         try {
             if (NodeFilterConstraintAction.ADD == action || NodeFilterConstraintAction.UPDATE == action) {
                 for (final String uiConstraint : uiConstraints) {
                     final UIConstraint constraint = new ConstraintConvertor().convert(uiConstraint);
                     if (ConstraintConvertor.PROPERTY_CONSTRAINT.equals(constraint.getSourceType())) {
-                        final Either<Boolean, ResponseFormat> booleanResponseFormatEither =
-                                validateComponentPropertyConstraint(component, constraint);
+                        final Either<Boolean, ResponseFormat> booleanResponseFormatEither = validateComponentPropertyConstraint(component,
+                            constraint);
                         if (booleanResponseFormatEither.isRight()) {
                             return booleanResponseFormatEither;
                         }
                     } else if (ConstraintConvertor.STATIC_CONSTRAINT.equals(constraint.getSourceType())) {
-                        final Either<Boolean, ResponseFormat> booleanResponseFormatEither =
-                                validateComponentStaticValueAndOperator(component, constraint);
+                        final Either<Boolean, ResponseFormat> booleanResponseFormatEither = validateComponentStaticValueAndOperator(component,
+                            constraint);
                         if (booleanResponseFormatEither.isRight()) {
                             return booleanResponseFormatEither;
                         }
@@ -339,66 +284,42 @@ public class NodeFilterValidator {
             LOGGER.debug("Provided constraint" + uiConstraints, e);
             return Either.right(componentsUtils.getResponseFormat(ActionStatus.CONSTRAINT_FORMAT_INCORRECT));
         }
-
         return Either.left(true);
     }
 
-    private Either<Boolean, ResponseFormat> validateComponentPropertyConstraint(final Component component,
-                                                                                final UIConstraint uiConstraint) {
+    private Either<Boolean, ResponseFormat> validateComponentPropertyConstraint(final Component component, final UIConstraint uiConstraint) {
         String source = SOURCE;
-
         final List<PropertyDefinition> propertyDefinitions = component.getProperties();
         List<? extends PropertyDefinition> sourcePropertyDefinition =
-                component.getName().equals(uiConstraint.getSourceName()) &&
-                        propertyDefinitions != null ? propertyDefinitions : Collections.emptyList();
-
+            component.getName().equals(uiConstraint.getSourceName()) && propertyDefinitions != null ? propertyDefinitions : Collections.emptyList();
         if (!CollectionUtils.isEmpty(sourcePropertyDefinition)) {
             final Optional<? extends PropertyDefinition> sourceSelectedProperty = sourcePropertyDefinition.stream()
-                    .filter(property -> uiConstraint
-                            .getValue()
-                            .equals(property.getName()))
-                    .findFirst();
-
-            final Optional<? extends PropertyDefinition> targetComponentProperty =
-                    component.getProperties().stream()
-                            .filter(property -> uiConstraint.getServicePropertyName().equals(property.getName()))
-                            .findFirst();
-
+                .filter(property -> uiConstraint.getValue().equals(property.getName())).findFirst();
+            final Optional<? extends PropertyDefinition> targetComponentProperty = component.getProperties().stream()
+                .filter(property -> uiConstraint.getServicePropertyName().equals(property.getName())).findFirst();
             source = !targetComponentProperty.isPresent() ? "Target" : SOURCE;
             if (sourceSelectedProperty.isPresent() && targetComponentProperty.isPresent()) {
                 return validatePropertyData(uiConstraint, sourceSelectedProperty, targetComponentProperty);
             }
         }
-
-        final String missingProperty =
-                source.equals(SOURCE) ? uiConstraint.getValue().toString() : uiConstraint.getServicePropertyName();
-
-        return Either.right(
-                componentsUtils.getResponseFormat(ActionStatus.MAPPED_PROPERTY_NOT_FOUND, source, missingProperty));
+        final String missingProperty = source.equals(SOURCE) ? uiConstraint.getValue().toString() : uiConstraint.getServicePropertyName();
+        return Either.right(componentsUtils.getResponseFormat(ActionStatus.MAPPED_PROPERTY_NOT_FOUND, source, missingProperty));
     }
 
-    private Either<Boolean, ResponseFormat> validateComponentStaticValueAndOperator(
-            final Component component, final UIConstraint uiConstraint) {
+    private Either<Boolean, ResponseFormat> validateComponentStaticValueAndOperator(final Component component, final UIConstraint uiConstraint) {
         if (!(Objects.nonNull(uiConstraint) && uiConstraint.getValue() instanceof String)) {
             return Either.left(false);
         }
-        final Optional<PropertyDefinition> componentProperty =
-                component.getProperties().stream()
-                        .filter(property -> uiConstraint.getServicePropertyName().equals(property.getName()))
-                        .findFirst();
-
+        final Optional<PropertyDefinition> componentProperty = component.getProperties().stream()
+            .filter(property -> uiConstraint.getServicePropertyName().equals(property.getName())).findFirst();
         if (componentProperty.isEmpty()) {
-            return Either.right(componentsUtils.getResponseFormat(ActionStatus.SELECTED_PROPERTY_NOT_PRESENT,
-                    uiConstraint.getServicePropertyName()));
+            return Either.right(componentsUtils.getResponseFormat(ActionStatus.SELECTED_PROPERTY_NOT_PRESENT, uiConstraint.getServicePropertyName()));
         }
-        if (comparableConstraintsOperators.contains(uiConstraint.getConstraintOperator()) && !comparableTypes.contains(
-                componentProperty.get().getType())) {
-            return Either.right(componentsUtils.getResponseFormat(ActionStatus.UNSUPPORTED_OPERATOR_PROVIDED,
-                    uiConstraint.getServicePropertyName(), uiConstraint.getConstraintOperator()));
+        if (comparableConstraintsOperators.contains(uiConstraint.getConstraintOperator()) && !comparableTypes
+            .contains(componentProperty.get().getType())) {
+            return Either.right(componentsUtils.getResponseFormat(ActionStatus.UNSUPPORTED_OPERATOR_PROVIDED, uiConstraint.getServicePropertyName(),
+                uiConstraint.getConstraintOperator()));
         }
-
-        return isValidValueCheck(componentProperty.get().getType(), String.valueOf(uiConstraint.getValue()),
-                uiConstraint.getServicePropertyName());
+        return isValidValueCheck(componentProperty.get().getType(), String.valueOf(uiConstraint.getValue()), uiConstraint.getServicePropertyName());
     }
-
 }
index 7947cbc..b1bc10b 100644 (file)
@@ -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.
  * limitations under the License.
  * ============LICENSE_END=========================================================
  */
-
 package org.openecomp.sdc.be.components.validation;
 
+import static org.apache.commons.collections.MapUtils.isEmpty;
+import static org.apache.commons.collections.MapUtils.isNotEmpty;
+import static org.apache.commons.lang3.StringUtils.isEmpty;
+import static org.apache.commons.lang3.StringUtils.isNotEmpty;
+import static org.openecomp.sdc.common.api.Constants.GROUP_POLICY_NAME_DELIMETER;
+
 import fj.data.Either;
+import java.util.Collections;
+import java.util.Map;
+import java.util.Optional;
+import java.util.Set;
 import org.openecomp.sdc.be.config.ConfigurationManager;
 import org.openecomp.sdc.be.dao.api.ActionStatus;
 import org.openecomp.sdc.be.datatypes.enums.ComponentTypeEnum;
@@ -34,17 +43,6 @@ import org.openecomp.sdc.common.api.Constants;
 import org.openecomp.sdc.common.log.wrappers.Logger;
 import org.openecomp.sdc.common.util.ValidationUtils;
 
-import java.util.Collections;
-import java.util.Map;
-import java.util.Optional;
-import java.util.Set;
-
-import static org.apache.commons.collections.MapUtils.isEmpty;
-import static org.apache.commons.collections.MapUtils.isNotEmpty;
-import static org.apache.commons.lang3.StringUtils.isEmpty;
-import static org.apache.commons.lang3.StringUtils.isNotEmpty;
-import static org.openecomp.sdc.common.api.Constants.GROUP_POLICY_NAME_DELIMETER;
-
 /**
  * Provides specific functionality for policy
  */
@@ -65,16 +63,10 @@ public class PolicyUtils {
     public static int getNextPolicyCounter(Map<String, PolicyDefinition> policies) {
         int nextCounter = 0;
         if (isNotEmpty(policies)) {
-            int nextCounterFromIds = policies.values()
-                                             .stream()
-                                             .map(p -> extractNextPolicyCounterFromUniqueId(p.getUniqueId()))
-                                             .max(Integer::compareTo)
-                                             .orElse(0);
-            int nextCounterFromNames = policies.values()
-                                               .stream()
-                                               .map(p -> extractNextPolicyCounterFromName(p.getName()))
-                                               .max(Integer::compareTo)
-                                               .orElse(0);
+            int nextCounterFromIds = policies.values().stream().map(p -> extractNextPolicyCounterFromUniqueId(p.getUniqueId()))
+                .max(Integer::compareTo).orElse(0);
+            int nextCounterFromNames = policies.values().stream().map(p -> extractNextPolicyCounterFromName(p.getName())).max(Integer::compareTo)
+                .orElse(0);
             nextCounter = nextCounterFromIds > nextCounterFromNames ? nextCounterFromIds : nextCounterFromNames;
         }
         return nextCounter;
@@ -88,7 +80,8 @@ public class PolicyUtils {
      * @param policies       all the polices related to the component
      * @return validated and updated policy or an error as action status
      */
-    public static Either<PolicyDefinition, ActionStatus> validatePolicyFields(PolicyDefinition recievedPolicy, PolicyDefinition validPolicy, Map<String, PolicyDefinition> policies) {
+    public static Either<PolicyDefinition, ActionStatus> validatePolicyFields(PolicyDefinition recievedPolicy, PolicyDefinition validPolicy,
+                                                                              Map<String, PolicyDefinition> policies) {
         validateImmutablePolicyFields(recievedPolicy, validPolicy);
         return validateUpdateMutablePolicyFields(recievedPolicy, validPolicy, policies);
     }
@@ -99,28 +92,21 @@ public class PolicyUtils {
      * @return the set of the policies
      */
     public static Set<String> getExcludedPolicyTypesByComponent(Component component) {
-        if (isEmpty(ConfigurationManager.getConfigurationManager()
-                                        .getConfiguration()
-                                        .getExcludedPolicyTypesMapping())) {
+        if (isEmpty(ConfigurationManager.getConfigurationManager().getConfiguration().getExcludedPolicyTypesMapping())) {
             return Collections.emptySet();
         }
         if (component.getComponentType() == ComponentTypeEnum.SERVICE) {
-            return ConfigurationManager.getConfigurationManager()
-                                       .getConfiguration()
-                                       .getExcludedPolicyTypesMapping()
-                                       .get(component.getComponentType().name());
+            return ConfigurationManager.getConfigurationManager().getConfiguration().getExcludedPolicyTypesMapping()
+                .get(component.getComponentType().name());
         }
-        return ConfigurationManager.getConfigurationManager()
-                                   .getConfiguration()
-                                   .getExcludedPolicyTypesMapping()
-                                   .get(((Resource) component).getResourceType().getValue());
+        return ConfigurationManager.getConfigurationManager().getConfiguration().getExcludedPolicyTypesMapping()
+            .get(((Resource) component).getResourceType().getValue());
     }
 
     public static PolicyDefinition getDeclaredPolicyDefinition(String componentInstanceId, ComponentInstanceProperty property) {
         PolicyDefinition policyDefinition = new PolicyDefinition(property);
         policyDefinition.setUniqueId(UniqueIdBuilder.buildPolicyUniqueId(componentInstanceId, property.getName()));
         policyDefinition.setInstanceUniqueId(componentInstanceId);
-
         return policyDefinition;
     }
 
@@ -146,14 +132,15 @@ public class PolicyUtils {
             int beginIndex = policyName.lastIndexOf(GROUP_POLICY_NAME_DELIMETER) + GROUP_POLICY_NAME_DELIMETER.length();
             String counterStr = policyName.substring(beginIndex, endIndex);
             counter = Integer.valueOf(counterStr) + 1;
-        }
-        catch (NumberFormatException | IndexOutOfBoundsException e) {
+        } catch (NumberFormatException | IndexOutOfBoundsException e) {
             log.error("#extractNextPolicyCounter - An error occurred when attempting to extract counter from policy name [{}]. ", policyName, e);
         }
         return counter;
     }
 
-    private static Either<PolicyDefinition, ActionStatus> validateUpdateMutablePolicyFields(PolicyDefinition recievedPolicy, PolicyDefinition validPolicy, Map<String, PolicyDefinition> policies) {
+    private static Either<PolicyDefinition, ActionStatus> validateUpdateMutablePolicyFields(PolicyDefinition recievedPolicy,
+                                                                                            PolicyDefinition validPolicy,
+                                                                                            Map<String, PolicyDefinition> policies) {
         return validateUpdatePolicyName(recievedPolicy, validPolicy, policies);
     }
 
@@ -168,15 +155,15 @@ public class PolicyUtils {
         logImmutableFieldUpdateWarning(receivedPolicy.getPolicyTypeUid(), validPolicy.getPolicyTypeUid(), JsonPresentationFields.TYPE_UNIQUE_ID);
         logImmutableFieldUpdateWarning(receivedPolicy.getPolicyUUID(), validPolicy.getPolicyUUID(), JsonPresentationFields.UUID);
         logImmutableFieldUpdateWarning(receivedPolicy.getVersion(), validPolicy.getVersion(), JsonPresentationFields.VERSION);
-        logImmutableFieldUpdateWarning(receivedPolicy.getIsFromCsar().toString(), validPolicy.getIsFromCsar().toString(), JsonPresentationFields.IS_FROM_CSAR);
+        logImmutableFieldUpdateWarning(receivedPolicy.getIsFromCsar().toString(), validPolicy.getIsFromCsar().toString(),
+            JsonPresentationFields.IS_FROM_CSAR);
     }
 
     private static boolean isUpdatedField(String oldField, String newField) {
         boolean isUpdatedField = false;
         if (isEmpty(oldField) && isNotEmpty(newField)) {
             isUpdatedField = true;
-        }
-        else if (isNotEmpty(oldField) && isNotEmpty(newField) && !oldField.equals(newField)) {
+        } else if (isNotEmpty(oldField) && isNotEmpty(newField) && !oldField.equals(newField)) {
             isUpdatedField = true;
         }
         return isUpdatedField;
@@ -184,27 +171,28 @@ public class PolicyUtils {
 
     private static void logImmutableFieldUpdateWarning(String oldValue, String newValue, JsonPresentationFields field) {
         if (isUpdatedField(oldValue, newValue)) {
-            log.warn("#logImmutableFieldUpdateWarning - Update of the field {} of a policy not allowed. The change will be ignored. The old value is {} , the new value is {}. ", field, oldValue, newValue);
+            log.warn(
+                "#logImmutableFieldUpdateWarning - Update of the field {} of a policy not allowed. The change will be ignored. The old value is {} , the new value is {}. ",
+                field, oldValue, newValue);
         }
     }
 
-    private static Either<PolicyDefinition, ActionStatus> validateUpdatePolicyName(PolicyDefinition receivedPolicy, PolicyDefinition validPolicy, Map<String, PolicyDefinition> policies) {
+    private static Either<PolicyDefinition, ActionStatus> validateUpdatePolicyName(PolicyDefinition receivedPolicy, PolicyDefinition validPolicy,
+                                                                                   Map<String, PolicyDefinition> policies) {
         Either<PolicyDefinition, ActionStatus> result = null;
         Optional<PolicyDefinition> sameNamePolicy = Optional.empty();
-        if (isEmpty(receivedPolicy.getName()) || !ValidationUtils.POLICY_NAME_PATTERN.matcher(receivedPolicy
-                .getName()).matches()) {
-            log.error("#validateUpdatePolicyName - Failed to validate the name {} of the policy {}. ", receivedPolicy.getName(), receivedPolicy.getUniqueId());
+        if (isEmpty(receivedPolicy.getName()) || !ValidationUtils.POLICY_NAME_PATTERN.matcher(receivedPolicy.getName()).matches()) {
+            log.error("#validateUpdatePolicyName - Failed to validate the name {} of the policy {}. ", receivedPolicy.getName(),
+                receivedPolicy.getUniqueId());
             result = Either.right(ActionStatus.INVALID_POLICY_NAME);
         }
         if (result == null && isNotEmpty(policies)) {
-            sameNamePolicy = policies.values()
-                                     .stream()
-                                     .filter(p -> p.getName().equals(receivedPolicy.getName()))
-                                     .findFirst();
+            sameNamePolicy = policies.values().stream().filter(p -> p.getName().equals(receivedPolicy.getName())).findFirst();
         }
         if (sameNamePolicy.isPresent()) {
-            log.error("#validateUpdatePolicyName - Failed to validate the name {} of the policy {}. The policy {} with the same name already exists. ", receivedPolicy
-                    .getName(), receivedPolicy.getUniqueId(), sameNamePolicy.get().getUniqueId());
+            log.error(
+                "#validateUpdatePolicyName - Failed to validate the name {} of the policy {}. The policy {} with the same name already exists. ",
+                receivedPolicy.getName(), receivedPolicy.getUniqueId(), sameNamePolicy.get().getUniqueId());
             result = Either.right(ActionStatus.POLICY_NAME_ALREADY_EXIST);
         }
         if (result == null) {
index ecbb039..bdb6799 100644 (file)
@@ -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.
  * limitations under the License.
  * ============LICENSE_END=========================================================
  */
-
 package org.openecomp.sdc.be.components.validation;
 
 import fj.data.Either;
+import java.util.List;
+import java.util.Map;
+import java.util.Optional;
 import org.apache.commons.lang3.tuple.ImmutablePair;
 import org.openecomp.sdc.be.components.impl.ResourceBusinessLogic;
 import org.openecomp.sdc.be.components.impl.utils.ExceptionUtils;
@@ -39,10 +41,6 @@ import org.slf4j.Logger;
 import org.slf4j.LoggerFactory;
 import org.springframework.stereotype.Component;
 
-import java.util.List;
-import java.util.Map;
-import java.util.Optional;
-
 @Component
 public class PropertyValidator {
 
@@ -52,94 +50,84 @@ public class PropertyValidator {
     private final ExceptionUtils exceptionUtils;
     private static final Logger log = LoggerFactory.getLogger(ResourceBusinessLogic.class);
 
-    public PropertyValidator(PropertyOperation propertyOperation, ComponentsUtils componentsUtils,
-                             ApplicationDataTypeCache applicationDataTypeCache, ExceptionUtils exceptionUtils) {
+    public PropertyValidator(PropertyOperation propertyOperation, ComponentsUtils componentsUtils, ApplicationDataTypeCache applicationDataTypeCache,
+                             ExceptionUtils exceptionUtils) {
         this.exceptionUtils = exceptionUtils;
         this.propertyOperation = propertyOperation;
         this.componentsUtils = componentsUtils;
         this.applicationDataTypeCache = applicationDataTypeCache;
     }
 
-    public void thinPropertiesValidator(List<PropertyDefinition> properties,
-                                        List<PropertyDefinition> dbAnnotationTypeDefinitionProperties,
-                                        Map<String, DataTypeDefinition> allDataTypes){
+    public void thinPropertiesValidator(List<PropertyDefinition> properties, List<PropertyDefinition> dbAnnotationTypeDefinitionProperties,
+                                        Map<String, DataTypeDefinition> allDataTypes) {
         for (PropertyDefinition property : properties) {
-            PropertyDefinition annotationTypeSpecificProperty = isPropertyInsideAnnotationTypeProperties(
-                    dbAnnotationTypeDefinitionProperties, property);
-            if(annotationTypeSpecificProperty!=null){
+            PropertyDefinition annotationTypeSpecificProperty = isPropertyInsideAnnotationTypeProperties(dbAnnotationTypeDefinitionProperties,
+                property);
+            if (annotationTypeSpecificProperty != null) {
                 verifyPropertyIsOfDefinedType(property, annotationTypeSpecificProperty, allDataTypes);
             }
         }
     }
 
-    private void verifyPropertyIsOfDefinedType(PropertyDefinition property,
-                                               PropertyDefinition typeSpecificProperty,
+    private void verifyPropertyIsOfDefinedType(PropertyDefinition property, PropertyDefinition typeSpecificProperty,
                                                Map<String, DataTypeDefinition> allDataTypes) {
-            propertyOperation.validateAndUpdatePropertyValue(typeSpecificProperty.getType(),
-                    property.getValue(), typeSpecificProperty.getSchemaType(), allDataTypes)
-                    .left()
-                    .on( error ->
-                    exceptionUtils.rollBackAndThrow(
-                            ActionStatus.INVALID_PROPERTY_TYPE, property.getType(), property.getName())
-            );
+        propertyOperation
+            .validateAndUpdatePropertyValue(typeSpecificProperty.getType(), property.getValue(), typeSpecificProperty.getSchemaType(), allDataTypes)
+            .left().on(error -> exceptionUtils.rollBackAndThrow(ActionStatus.INVALID_PROPERTY_TYPE, property.getType(), property.getName()));
     }
 
-    private PropertyDefinition isPropertyInsideAnnotationTypeProperties(
-            List<PropertyDefinition> dbAnnotationTypeDefinitionProperties, PropertyDefinition property) {
+    private PropertyDefinition isPropertyInsideAnnotationTypeProperties(List<PropertyDefinition> dbAnnotationTypeDefinitionProperties,
+                                                                        PropertyDefinition property) {
         Optional<PropertyDefinition> optionalResult = dbAnnotationTypeDefinitionProperties.stream()
-                .filter(prop -> prop.getName()
-                        .equals(property.getName()))
-                .findFirst();
-        if (optionalResult.isPresent()){
+            .filter(prop -> prop.getName().equals(property.getName())).findFirst();
+        if (optionalResult.isPresent()) {
             return optionalResult.get();
         }
-        ResponseFormat responseFormat = componentsUtils.getResponseFormat(
-                ActionStatus.PROPERTY_NOT_FOUND, property.getType(), property.getName());
+        ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.PROPERTY_NOT_FOUND, property.getType(), property.getName());
         exceptionUtils.rollBackAndThrow(responseFormat);
         return null;
     }
 
-    public Either<Boolean, ResponseFormat> iterateOverProperties(List<PropertyDefinition> properties){
+    public Either<Boolean, ResponseFormat> iterateOverProperties(List<PropertyDefinition> properties) {
         Either<Boolean, ResponseFormat> eitherResult = Either.left(true);
         String type = null;
         String innerType = null;
         for (PropertyDefinition property : properties) {
             if (!propertyOperation.isPropertyTypeValid(property)) {
                 log.info("Invalid type for property {}", property);
-                ResponseFormat responseFormat = componentsUtils.getResponseFormat(
-                        ActionStatus.INVALID_PROPERTY_TYPE, property.getType(), property.getName());
+                ResponseFormat responseFormat = componentsUtils
+                    .getResponseFormat(ActionStatus.INVALID_PROPERTY_TYPE, property.getType(), property.getName());
                 eitherResult = Either.right(responseFormat);
                 break;
             }
-
             Either<Map<String, DataTypeDefinition>, JanusGraphOperationStatus> allDataTypes = applicationDataTypeCache.getAll();
             if (allDataTypes.isRight()) {
                 JanusGraphOperationStatus status = allDataTypes.right().value();
-                BeEcompErrorManager.getInstance().logInternalFlowError("AddPropertyToGroup", "Failed to validate property. Status is " + status, BeEcompErrorManager.ErrorSeverity.ERROR);
-                return Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(DaoStatusConverter.convertJanusGraphStatusToStorageStatus(status))));
+                BeEcompErrorManager.getInstance().logInternalFlowError("AddPropertyToGroup", "Failed to validate property. Status is " + status,
+                    BeEcompErrorManager.ErrorSeverity.ERROR);
+                return Either.right(componentsUtils.getResponseFormat(
+                    componentsUtils.convertFromStorageResponse(DaoStatusConverter.convertJanusGraphStatusToStorageStatus(status))));
             }
-
             type = property.getType();
-
             if (type.equals(ToscaPropertyType.LIST.getType()) || type.equals(ToscaPropertyType.MAP.getType())) {
                 ResponseFormat responseFormat = validateMapOrListPropertyType(property, allDataTypes.left().value());
-                if(responseFormat != null)
-                    break;
+             if (responseFormat != null) {
+              break;
+             }
             }
-
             if (!propertyOperation.isPropertyDefaultValueValid(property, allDataTypes.left().value())) {
                 log.info("Invalid default value for property {}", property);
                 ResponseFormat responseFormat;
                 if (type.equals(ToscaPropertyType.LIST.getType()) || type.equals(ToscaPropertyType.MAP.getType())) {
-                    responseFormat = componentsUtils.getResponseFormat(ActionStatus.INVALID_COMPLEX_DEFAULT_VALUE,
-                            property.getName(), type, innerType, property.getDefaultValue());
+                    responseFormat = componentsUtils
+                        .getResponseFormat(ActionStatus.INVALID_COMPLEX_DEFAULT_VALUE, property.getName(), type, innerType,
+                            property.getDefaultValue());
                 } else {
-                    responseFormat = componentsUtils.getResponseFormat(ActionStatus.INVALID_DEFAULT_VALUE,
-                            property.getName(), type, property.getDefaultValue());
+                    responseFormat = componentsUtils
+                        .getResponseFormat(ActionStatus.INVALID_DEFAULT_VALUE, property.getName(), type, property.getDefaultValue());
                 }
                 eitherResult = Either.right(responseFormat);
                 break;
-
             }
         }
         return eitherResult;
@@ -147,15 +135,12 @@ public class PropertyValidator {
 
     private ResponseFormat validateMapOrListPropertyType(PropertyDefinition property, Map<String, DataTypeDefinition> allDataTypes) {
         ResponseFormat responseFormat = null;
-        ImmutablePair<String, Boolean> propertyInnerTypeValid = propertyOperation
-                .isPropertyInnerTypeValid(property, allDataTypes);
+        ImmutablePair<String, Boolean> propertyInnerTypeValid = propertyOperation.isPropertyInnerTypeValid(property, allDataTypes);
         String propertyInnerType = propertyInnerTypeValid.getLeft();
         if (!propertyInnerTypeValid.getRight().booleanValue()) {
             log.info("Invalid inner type for property {}", property);
-            responseFormat = componentsUtils.getResponseFormat(
-                    ActionStatus.INVALID_PROPERTY_INNER_TYPE, propertyInnerType, property.getName());
+            responseFormat = componentsUtils.getResponseFormat(ActionStatus.INVALID_PROPERTY_INNER_TYPE, propertyInnerType, property.getName());
         }
         return responseFormat;
     }
-
 }
index 030684e..7dd38bb 100644 (file)
  * See the License for the specific language governing permissions and
  * limitations under the License.
  */
-
 package org.openecomp.sdc.be.components.validation;
 
 import fj.data.Either;
+import java.util.Collection;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+import java.util.regex.Pattern;
+import java.util.stream.Collectors;
 import org.apache.commons.collections.CollectionUtils;
 import org.apache.commons.collections.MapUtils;
 import org.apache.commons.lang.StringUtils;
@@ -28,13 +33,6 @@ import org.slf4j.Logger;
 import org.slf4j.LoggerFactory;
 import org.springframework.stereotype.Component;
 
-import java.util.Collection;
-import java.util.HashMap;
-import java.util.List;
-import java.util.Map;
-import java.util.regex.Pattern;
-import java.util.stream.Collectors;
-
 @Component("requirementValidation")
 public class RequirementValidation {
 
@@ -42,13 +40,10 @@ public class RequirementValidation {
     private static final String REQUIREMENT_NOT_FOUND_IN_COMPONENT = "Requirement not found in component {} ";
     private static final Pattern NAME_VALIDATION_REGEX_PATTERN = Pattern.compile("^[a-zA-Z0-9_.]*$");
 
-    public Either<Boolean, ResponseFormat> validateRequirements(
-            Collection<RequirementDefinition> requirements,
-            org.openecomp.sdc.be.model.Component component, boolean isUpdate) {
-
-        for(RequirementDefinition requirementDefinition : requirements) {
-            Either<Boolean, ResponseFormat> requirementValidationResponse
-                    = validateRequirement(requirementDefinition, component, isUpdate);
+    public Either<Boolean, ResponseFormat> validateRequirements(Collection<RequirementDefinition> requirements,
+                                                                org.openecomp.sdc.be.model.Component component, boolean isUpdate) {
+        for (RequirementDefinition requirementDefinition : requirements) {
+            Either<Boolean, ResponseFormat> requirementValidationResponse = validateRequirement(requirementDefinition, component, isUpdate);
             if (requirementValidationResponse.isRight()) {
                 return requirementValidationResponse;
             }
@@ -56,34 +51,27 @@ public class RequirementValidation {
         return Either.left(Boolean.TRUE);
     }
 
-    private Either<Boolean, ResponseFormat> validateRequirement(
-            RequirementDefinition requirementDefinition,
-            org.openecomp.sdc.be.model.Component component,
-            boolean isUpdate) {
+    private Either<Boolean, ResponseFormat> validateRequirement(RequirementDefinition requirementDefinition,
+                                                                org.openecomp.sdc.be.model.Component component, boolean isUpdate) {
         ResponseFormatManager responseFormatManager = getResponseFormatManager();
-        if(isUpdate) {
-            Either<Boolean, ResponseFormat> requirementExistValidationEither
-                    = isRequirementExist(requirementDefinition, responseFormatManager, component);
+        if (isUpdate) {
+            Either<Boolean, ResponseFormat> requirementExistValidationEither = isRequirementExist(requirementDefinition, responseFormatManager,
+                component);
             if (requirementExistValidationEither.isRight()) {
                 return Either.right(requirementExistValidationEither.right().value());
             }
         }
-
-        Either<Boolean, ResponseFormat> requirementNameValidationResponse
-                = isRequirementNameValid(requirementDefinition, responseFormatManager,
-                component, isUpdate);
+        Either<Boolean, ResponseFormat> requirementNameValidationResponse = isRequirementNameValid(requirementDefinition, responseFormatManager,
+            component, isUpdate);
         if (requirementNameValidationResponse.isRight()) {
             return Either.right(requirementNameValidationResponse.right().value());
         }
-
-        Either<Boolean, ResponseFormat> requirementTypeEmptyEither =
-                isRequirementCapabilityEmpty(responseFormatManager,
-                        requirementDefinition.getCapability());
+        Either<Boolean, ResponseFormat> requirementTypeEmptyEither = isRequirementCapabilityEmpty(responseFormatManager,
+            requirementDefinition.getCapability());
         if (requirementTypeEmptyEither.isRight()) {
             return Either.right(requirementTypeEmptyEither.right().value());
         }
-        Either<Boolean, ResponseFormat> requirementOccurrencesValidationEither =
-                validateOccurrences(requirementDefinition, responseFormatManager);
+        Either<Boolean, ResponseFormat> requirementOccurrencesValidationEither = validateOccurrences(requirementDefinition, responseFormatManager);
         if (requirementOccurrencesValidationEither.isRight()) {
             return Either.right(requirementOccurrencesValidationEither.right().value());
         }
@@ -94,10 +82,9 @@ public class RequirementValidation {
                                                                 ResponseFormatManager responseFormatManager) {
         String maxOccurrences = requirementDefinition.getMaxOccurrences();
         String minOccurrences = requirementDefinition.getMinOccurrences();
-        if(maxOccurrences != null && minOccurrences !=null) {
-            Either<Boolean, ResponseFormat> requirementOccurrencesValidationEither =
-                    validateOccurrences(responseFormatManager, minOccurrences,
-                            maxOccurrences);
+        if (maxOccurrences != null && minOccurrences != null) {
+            Either<Boolean, ResponseFormat> requirementOccurrencesValidationEither = validateOccurrences(responseFormatManager, minOccurrences,
+                maxOccurrences);
             if (requirementOccurrencesValidationEither.isRight()) {
                 return Either.right(requirementOccurrencesValidationEither.right().value());
             }
@@ -105,55 +92,44 @@ public class RequirementValidation {
         return Either.left(Boolean.TRUE);
     }
 
-    private Either<Boolean, ResponseFormat> isRequirementNameValid(
-            RequirementDefinition requirementDefinition,
-            ResponseFormatManager responseFormatManager,
-            org.openecomp.sdc.be.model.Component component, boolean isUpdate) {
-        Either<Boolean, ResponseFormat> requirementNameEmptyEither =
-                isRequirementNameEmpty(responseFormatManager, requirementDefinition.getName());
+    private Either<Boolean, ResponseFormat> isRequirementNameValid(RequirementDefinition requirementDefinition,
+                                                                   ResponseFormatManager responseFormatManager,
+                                                                   org.openecomp.sdc.be.model.Component component, boolean isUpdate) {
+        Either<Boolean, ResponseFormat> requirementNameEmptyEither = isRequirementNameEmpty(responseFormatManager, requirementDefinition.getName());
         if (requirementNameEmptyEither.isRight()) {
             return Either.right(requirementNameEmptyEither.right().value());
         }
-
-        Either<Boolean, ResponseFormat> requirementNameRegexValidationResponse =
-                isRequirementNameRegexValid(responseFormatManager, requirementDefinition.getName());
+        Either<Boolean, ResponseFormat> requirementNameRegexValidationResponse = isRequirementNameRegexValid(responseFormatManager,
+            requirementDefinition.getName());
         if (requirementNameRegexValidationResponse.isRight()) {
             return Either.right(requirementNameRegexValidationResponse.right().value());
         }
-
-        Either<Boolean, ResponseFormat> requirementNameUniqueResponse
-                = validateRequirementNameUnique(requirementDefinition,
-                component, isUpdate );
-        if(requirementNameUniqueResponse.isRight()) {
+        Either<Boolean, ResponseFormat> requirementNameUniqueResponse = validateRequirementNameUnique(requirementDefinition, component, isUpdate);
+        if (requirementNameUniqueResponse.isRight()) {
             return Either.right(requirementNameUniqueResponse.right().value());
         }
         if (!requirementNameUniqueResponse.left().value()) {
             LOGGER.error("Requirement name  {} already in use ", requirementDefinition.getName());
-            ResponseFormat errorResponse = responseFormatManager.getResponseFormat(ActionStatus
-                    .REQUIREMENT_NAME_ALREADY_IN_USE, requirementDefinition.getName());
+            ResponseFormat errorResponse = responseFormatManager
+                .getResponseFormat(ActionStatus.REQUIREMENT_NAME_ALREADY_IN_USE, requirementDefinition.getName());
             return Either.right(errorResponse);
         }
         return Either.left(Boolean.TRUE);
     }
 
-    private Either<Boolean, ResponseFormat> isRequirementNameEmpty(
-            ResponseFormatManager responseFormatManager,
-            String requirementName) {
+    private Either<Boolean, ResponseFormat> isRequirementNameEmpty(ResponseFormatManager responseFormatManager, String requirementName) {
         if (StringUtils.isEmpty(requirementName)) {
             LOGGER.error("Requirement Name is mandatory");
-            ResponseFormat errorResponse = responseFormatManager.getResponseFormat(ActionStatus
-                    .REQUIREMENT_NAME_MANDATORY);
+            ResponseFormat errorResponse = responseFormatManager.getResponseFormat(ActionStatus.REQUIREMENT_NAME_MANDATORY);
             return Either.right(errorResponse);
         }
         return Either.left(Boolean.TRUE);
     }
 
-    private Either<Boolean, ResponseFormat> validateOccurrences        (
-            ResponseFormatManager responseFormatManager,
-            String minOccurrences, String maxOccurrences ) {
+    private Either<Boolean, ResponseFormat> validateOccurrences(ResponseFormatManager responseFormatManager, String minOccurrences,
+                                                                String maxOccurrences) {
         try {
-            if (StringUtils.isNotEmpty(maxOccurrences) && "UNBOUNDED".equalsIgnoreCase(maxOccurrences)
-                    && Integer.parseInt(minOccurrences) >= 0) {
+            if (StringUtils.isNotEmpty(maxOccurrences) && "UNBOUNDED".equalsIgnoreCase(maxOccurrences) && Integer.parseInt(minOccurrences) >= 0) {
                 return Either.left(Boolean.TRUE);
             } else if (Integer.parseInt(minOccurrences) < 0) {
                 LOGGER.debug("Invalid occurrences format.low_bound occurrence negative {}", minOccurrences);
@@ -161,8 +137,8 @@ public class RequirementValidation {
                 return Either.right(responseFormat);
             } else if (Integer.parseInt(maxOccurrences) < Integer.parseInt(minOccurrences)) {
                 LOGGER.error("Requirement maxOccurrences should be greater than minOccurrences");
-                ResponseFormat errorResponse = responseFormatManager.getResponseFormat(ActionStatus
-                        .MAX_OCCURRENCES_SHOULD_BE_GREATER_THAN_MIN_OCCURRENCES);
+                ResponseFormat errorResponse = responseFormatManager
+                    .getResponseFormat(ActionStatus.MAX_OCCURRENCES_SHOULD_BE_GREATER_THAN_MIN_OCCURRENCES);
                 return Either.right(errorResponse);
             }
         } catch (NumberFormatException ex) {
@@ -172,94 +148,72 @@ public class RequirementValidation {
         }
         return Either.left(Boolean.TRUE);
     }
-    private Either<Boolean, ResponseFormat> isRequirementCapabilityEmpty(
-            ResponseFormatManager responseFormatManager,
-            String requirementCapability) {
+
+    private Either<Boolean, ResponseFormat> isRequirementCapabilityEmpty(ResponseFormatManager responseFormatManager, String requirementCapability) {
         if (StringUtils.isEmpty(requirementCapability)) {
             LOGGER.error("Requirement capability is mandatory");
-            ResponseFormat errorResponse = responseFormatManager.getResponseFormat(ActionStatus
-                    .REQUIREMENT_CAPABILITY_MANDATORY);
+            ResponseFormat errorResponse = responseFormatManager.getResponseFormat(ActionStatus.REQUIREMENT_CAPABILITY_MANDATORY);
             return Either.right(errorResponse);
         }
         return Either.left(Boolean.TRUE);
     }
 
-    private Either<Boolean, ResponseFormat> validateRequirementNameUnique(
-            RequirementDefinition requirementDefinition,
-            org.openecomp.sdc.be.model.Component component,
-            boolean isUpdate) {
+    private Either<Boolean, ResponseFormat> validateRequirementNameUnique(RequirementDefinition requirementDefinition,
+                                                                          org.openecomp.sdc.be.model.Component component, boolean isUpdate) {
         boolean isRequirementNameUnique = false;
-
         Map<String, List<RequirementDefinition>> componentRequirements = component.getRequirements();
-        if(MapUtils.isEmpty(componentRequirements)){
+        if (MapUtils.isEmpty(componentRequirements)) {
             return Either.left(true);
         }
-        List<RequirementDefinition> requirementDefinitionList = componentRequirements.values()
-                .stream().flatMap(Collection::stream).collect(Collectors.toList());
-
-        if(CollectionUtils.isEmpty(requirementDefinitionList)){
+        List<RequirementDefinition> requirementDefinitionList = componentRequirements.values().stream().flatMap(Collection::stream)
+            .collect(Collectors.toList());
+        if (CollectionUtils.isEmpty(requirementDefinitionList)) {
             return Either.left(true);
         }
-
         Map<String, String> requirementNameMap = new HashMap<>();
-        requirementDefinitionList.forEach(requirement -> requirementNameMap
-                .put(requirement.getUniqueId(), requirement.getName()));
-
-        if (!requirementNameMap.values().contains(requirementDefinition.getName())){
+        requirementDefinitionList.forEach(requirement -> requirementNameMap.put(requirement.getUniqueId(), requirement.getName()));
+        if (!requirementNameMap.values().contains(requirementDefinition.getName())) {
             isRequirementNameUnique = true;
         }
-        if (!isRequirementNameUnique && isUpdate){
-            List<Map.Entry<String, String>> reqNamesEntry = requirementNameMap.entrySet()
-                    .stream().filter(entry -> entry.getValue().equalsIgnoreCase(requirementDefinition.getName()))
-                    .collect(Collectors.toList());
-            if(reqNamesEntry.size() == 1 && reqNamesEntry.get(0).getKey()
-                    .equals(requirementDefinition.getUniqueId())) {
+        if (!isRequirementNameUnique && isUpdate) {
+            List<Map.Entry<String, String>> reqNamesEntry = requirementNameMap.entrySet().stream()
+                .filter(entry -> entry.getValue().equalsIgnoreCase(requirementDefinition.getName())).collect(Collectors.toList());
+            if (reqNamesEntry.size() == 1 && reqNamesEntry.get(0).getKey().equals(requirementDefinition.getUniqueId())) {
                 isRequirementNameUnique = true;
             }
         }
         return Either.left(isRequirementNameUnique);
     }
 
-    private Either<Boolean, ResponseFormat> isRequirementExist(
-            RequirementDefinition definition,
-            ResponseFormatManager responseFormatManager,
-            org.openecomp.sdc.be.model.Component component) {
+    private Either<Boolean, ResponseFormat> isRequirementExist(RequirementDefinition definition, ResponseFormatManager responseFormatManager,
+                                                               org.openecomp.sdc.be.model.Component component) {
         Map<String, List<RequirementDefinition>> componentRequirements = component.getRequirements();
-        if(MapUtils.isEmpty(componentRequirements)){
+        if (MapUtils.isEmpty(componentRequirements)) {
             LOGGER.error(REQUIREMENT_NOT_FOUND_IN_COMPONENT, component.getUniqueId());
-            ResponseFormat errorResponse = responseFormatManager.getResponseFormat(ActionStatus
-                    .REQUIREMENT_NOT_FOUND, component.getUniqueId());
+            ResponseFormat errorResponse = responseFormatManager.getResponseFormat(ActionStatus.REQUIREMENT_NOT_FOUND, component.getUniqueId());
             return Either.right(errorResponse);
         }
-
-        List<RequirementDefinition> requirementDefinitionList = componentRequirements.values()
-                .stream().flatMap(Collection::stream).collect(Collectors.toList());
-        if(CollectionUtils.isEmpty(requirementDefinitionList)){
+        List<RequirementDefinition> requirementDefinitionList = componentRequirements.values().stream().flatMap(Collection::stream)
+            .collect(Collectors.toList());
+        if (CollectionUtils.isEmpty(requirementDefinitionList)) {
             LOGGER.error(REQUIREMENT_NOT_FOUND_IN_COMPONENT, component.getUniqueId());
-            ResponseFormat errorResponse = responseFormatManager.getResponseFormat(ActionStatus
-                    .REQUIREMENT_NOT_FOUND, component.getUniqueId());
+            ResponseFormat errorResponse = responseFormatManager.getResponseFormat(ActionStatus.REQUIREMENT_NOT_FOUND, component.getUniqueId());
             return Either.right(errorResponse);
         }
         boolean isRequirementExist = requirementDefinitionList.stream()
-                .anyMatch(requirementDefinition -> requirementDefinition.getUniqueId()
-                        .equalsIgnoreCase(definition.getUniqueId()));
-
-        if(!isRequirementExist) {
+            .anyMatch(requirementDefinition -> requirementDefinition.getUniqueId().equalsIgnoreCase(definition.getUniqueId()));
+        if (!isRequirementExist) {
             LOGGER.error(REQUIREMENT_NOT_FOUND_IN_COMPONENT, component.getUniqueId());
-            ResponseFormat errorResponse = responseFormatManager.getResponseFormat(ActionStatus
-                    .REQUIREMENT_NOT_FOUND, component.getUniqueId());
+            ResponseFormat errorResponse = responseFormatManager.getResponseFormat(ActionStatus.REQUIREMENT_NOT_FOUND, component.getUniqueId());
             return Either.right(errorResponse);
         }
         return Either.left(Boolean.TRUE);
     }
 
-    private Either<Boolean, ResponseFormat> isRequirementNameRegexValid(ResponseFormatManager responseFormatManager,
-                                                                        String requirementName) {
+    private Either<Boolean, ResponseFormat> isRequirementNameRegexValid(ResponseFormatManager responseFormatManager, String requirementName) {
         if (!isValidRequirementName(requirementName)) {
-            LOGGER.error("Requirement name {} is invalid, Only alphanumeric chars, underscore and dot allowed",
-                    requirementName);
-            ResponseFormat errorResponse = responseFormatManager
-                    .getResponseFormat(ActionStatus.INVALID_REQUIREMENT_NAME, requirementName);
+            LOGGER.error("Requirement name {} is invalid, Only alphanumeric chars, underscore and dot allowed", requirementName);
+            ResponseFormat errorResponse = responseFormatManager.getResponseFormat(ActionStatus.INVALID_REQUIREMENT_NAME, requirementName);
             return Either.right(errorResponse);
         }
         return Either.left(Boolean.TRUE);
@@ -272,6 +226,4 @@ public class RequirementValidation {
     protected ResponseFormatManager getResponseFormatManager() {
         return ResponseFormatManager.getInstance();
     }
-
 }
-
index 695ee58..b8ef79e 100644 (file)
@@ -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.
  * limitations under the License.
  * ============LICENSE_END=========================================================
  */
-
 package org.openecomp.sdc.be.components.validation;
 
 import fj.data.Either;
+import java.util.Arrays;
+import java.util.List;
+import javax.annotation.Resource;
 import org.apache.commons.lang.StringUtils;
 import org.openecomp.sdc.be.components.distribution.engine.IDistributionEngine;
 import org.openecomp.sdc.be.components.impl.ActivationRequestInformation;
@@ -38,15 +40,12 @@ import org.openecomp.sdc.be.resources.data.OperationalEnvironmentEntry;
 import org.openecomp.sdc.common.log.wrappers.Logger;
 import org.openecomp.sdc.exception.ResponseFormat;
 
-import javax.annotation.Resource;
-import java.util.Arrays;
-import java.util.List;
-
 /**
  * Created by chaya on 10/18/2017.
  */
 @org.springframework.stereotype.Component("serviceDistributionValidation")
 public class ServiceDistributionValidation {
+
     private static final Logger log = Logger.getLogger(ServiceDistributionValidation.class);
     @Resource
     private ComponentsUtils componentsUtils;
@@ -57,14 +56,16 @@ public class ServiceDistributionValidation {
     @Resource
     private IDistributionEngine distributionEngine;
 
-    public Either<ActivationRequestInformation, ResponseFormat> validateActivateServiceRequest(String serviceUUID, String opEnvId, User modifier, ServiceDistributionReqInfo data) {
+    public Either<ActivationRequestInformation, ResponseFormat> validateActivateServiceRequest(String serviceUUID, String opEnvId, User modifier,
+                                                                                               ServiceDistributionReqInfo data) {
         try {
             validateUserExists(modifier.getUserId());
             Service serviceToActivate = validateServiceExists(serviceUUID);
             validateDistributionServiceLifeCycleState(serviceToActivate);
             OperationalEnvironmentEntry operationalEnvironmentEntry = validateOperationalEnvExists(opEnvId);
             String workloadContext = validateWorkloadContext(data);
-            ActivationRequestInformation activationRequestInformation = new ActivationRequestInformation(serviceToActivate, workloadContext, operationalEnvironmentEntry.getTenant());
+            ActivationRequestInformation activationRequestInformation = new ActivationRequestInformation(serviceToActivate, workloadContext,
+                operationalEnvironmentEntry.getTenant());
             return Either.left(activationRequestInformation);
         } catch (ValidationException e) {
             log.error("failed while validating activate service UUID {} request. error {}", serviceUUID, e.getExceptionResponseFormat(), e);
@@ -77,7 +78,7 @@ public class ServiceDistributionValidation {
         Service abstractService = validateServiceExists(serviceUUID);
         validateDistributionServiceLifeCycleState(abstractService);
     }
-       
+
     private Service validateServiceExists(String serviceUUID) {
         if (StringUtils.isEmpty(serviceUUID.trim())) {
             ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.BAD_REQUEST_MISSING_RESOURCE);
@@ -86,10 +87,11 @@ public class ServiceDistributionValidation {
         Either<Component, StorageOperationStatus> latestComponentByUuid = toscaOperationFacade.getLatestServiceByUuid(serviceUUID);
         if (latestComponentByUuid.isRight()) {
             log.error("failed retrieving service {}", serviceUUID);
-            ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.API_RESOURCE_NOT_FOUND, ApiResourceEnum.SERVICE_ID.getValue());
+            ResponseFormat responseFormat = componentsUtils
+                .getResponseFormat(ActionStatus.API_RESOURCE_NOT_FOUND, ApiResourceEnum.SERVICE_ID.getValue());
             throw new ValidationException(responseFormat);
         }
-        return (Service)latestComponentByUuid.left().value();
+        return (Service) latestComponentByUuid.left().value();
     }
 
     private String validateWorkloadContext(ServiceDistributionReqInfo data) {
@@ -112,15 +114,19 @@ public class ServiceDistributionValidation {
             return failOnEnvNotExist(opEnvId);
         }
         if (!operationalEnvironment.getStatus().equals(EnvironmentStatusEnum.COMPLETED.getName())) {
-            log.error("the operational environment is not ready to receive distributions. environment status: {}", operationalEnvironment.getStatus());
-            ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.API_RESOURCE_NOT_FOUND , ApiResourceEnum.ENVIRONMENT_ID.getValue());
+            log.error("the operational environment is not ready to receive distributions. environment status: {}",
+                operationalEnvironment.getStatus());
+            ResponseFormat responseFormat = componentsUtils
+                .getResponseFormat(ActionStatus.API_RESOURCE_NOT_FOUND, ApiResourceEnum.ENVIRONMENT_ID.getValue());
             throw new ValidationException(responseFormat);
         }
         return operationalEnvironment;
     }
 
     private OperationalEnvironmentEntry failOnEnvNotExist(String opEnvId) {
-        return ValidationUtils.throwValidationException(componentsUtils.getResponseFormat(ActionStatus.API_RESOURCE_NOT_FOUND, ApiResourceEnum.ENVIRONMENT_ID.getValue()), "failed to get operational environment {}", opEnvId);
+        return ValidationUtils.throwValidationException(
+            componentsUtils.getResponseFormat(ActionStatus.API_RESOURCE_NOT_FOUND, ApiResourceEnum.ENVIRONMENT_ID.getValue()),
+            "failed to get operational environment {}", opEnvId);
     }
 
     private void validateServiceState(Service service, List<LifecycleStateEnum> allowedStates) {
@@ -131,12 +137,12 @@ public class ServiceDistributionValidation {
             throw new ValidationException(responseFormat);
         }
     }
+
     private void validateUserExists(String userId) {
         userValidations.validateUserExists(userId);
     }
 
     private void validateDistributionServiceLifeCycleState(Service serviceToActivate) {
-        validateServiceState(serviceToActivate,
-                Arrays.asList(LifecycleStateEnum.CERTIFIED));
+        validateServiceState(serviceToActivate, Arrays.asList(LifecycleStateEnum.CERTIFIED));
     }
 }
index 29ed858..cf4f848 100644 (file)
@@ -40,51 +40,46 @@ import org.springframework.stereotype.Component;
 public class UserValidations {
 
     private static final Logger log = Logger.getLogger(UserValidations.class);
-       private final UserBusinessLogic userAdmin;
+    private final UserBusinessLogic userAdmin;
 
     public UserValidations(final UserBusinessLogic userAdmin) {
-               this.userAdmin = userAdmin;
+        this.userAdmin = userAdmin;
     }
 
     public void validateUserRole(final User user, final List<Role> roles) {
-               final Role userRole = Role.valueOf(user.getRole());
-               if (roles != null && !roles.contains(userRole)) {
-                       log.error(EcompLoggerErrorCode.PERMISSION_ERROR, this.getClass().getName(),
-                               "user is not in appropriate role to perform action");
-                       throw new ByActionStatusComponentException(ActionStatus.RESTRICTED_OPERATION);
-               }
-       }
+        final Role userRole = Role.valueOf(user.getRole());
+        if (roles != null && !roles.contains(userRole)) {
+            log.error(EcompLoggerErrorCode.PERMISSION_ERROR, this.getClass().getName(), "user is not in appropriate role to perform action");
+            throw new ByActionStatusComponentException(ActionStatus.RESTRICTED_OPERATION);
+        }
+    }
 
-       public ActionStatus validateUserExistsActionStatus(final String userId) {
-           if (!userAdmin.hasActiveUser(userId)) {
-                       return ActionStatus.RESTRICTED_OPERATION;
-               }
-               return ActionStatus.OK;
-       }
+    public ActionStatus validateUserExistsActionStatus(final String userId) {
+        if (!userAdmin.hasActiveUser(userId)) {
+            return ActionStatus.RESTRICTED_OPERATION;
+        }
+        return ActionStatus.OK;
+    }
 
-    public User validateUserNotEmpty(final User user,
-                                                                        final String ecompErrorContext) {
-               final String userId = user.getUserId();
-               if (StringUtils.isEmpty(userId)) {
-                       log.error(EcompLoggerErrorCode.PERMISSION_ERROR, this.getClass().getName(),
-                               "User header is missing ");
-                       BeEcompErrorManager.getInstance().logBeUserMissingError(ecompErrorContext, user.getUserId());
+    public User validateUserNotEmpty(final User user, final String ecompErrorContext) {
+        final String userId = user.getUserId();
+        if (StringUtils.isEmpty(userId)) {
+            log.error(EcompLoggerErrorCode.PERMISSION_ERROR, this.getClass().getName(), "User header is missing ");
+            BeEcompErrorManager.getInstance().logBeUserMissingError(ecompErrorContext, user.getUserId());
             throw new ByActionStatusComponentException(ActionStatus.MISSING_USER_ID);
-               }
+        }
         return user;
-       }
-
-       public User validateUserExists(final String userId) {
-               final User user = userAdmin.getUser(userId);
-               if (UserStatusEnum.INACTIVE == user.getStatus()) {
-                       throw new ByActionStatusComponentException(USER_INACTIVE, userId);
-               }
-               return user;
-       }
-
-       public User validateUserExists(final User user) {
-               return validateUserExists(user.getUserId());
-       }
+    }
 
+    public User validateUserExists(final String userId) {
+        final User user = userAdmin.getUser(userId);
+        if (UserStatusEnum.INACTIVE == user.getStatus()) {
+            throw new ByActionStatusComponentException(USER_INACTIVE, userId);
+        }
+        return user;
+    }
 
+    public User validateUserExists(final User user) {
+        return validateUserExists(user.getUserId());
+    }
 }
index d65551a..e2fed1e 100644 (file)
@@ -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.
@@ -17,7 +17,6 @@
  * limitations under the License.
  * ============LICENSE_END=========================================================
  */
-
 package org.openecomp.sdc.be.components.validation;
 
 import org.openecomp.sdc.exception.ResponseFormat;
@@ -37,5 +36,4 @@ public class ValidationException extends RuntimeException {
     public ResponseFormat getExceptionResponseFormat() {
         return exceptionResponseFormat;
     }
-
 }
index 085001f..51603f6 100644 (file)
@@ -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.
@@ -17,7 +17,6 @@
  * limitations under the License.
  * ============LICENSE_END=========================================================
  */
-
 package org.openecomp.sdc.be.components.validation;
 
 import org.openecomp.sdc.common.log.wrappers.Logger;
@@ -27,9 +26,8 @@ public class ValidationUtils {
 
     private static final Logger log = Logger.getLogger(ValidationUtils.class);
 
-    public static  <T> T throwValidationException(ResponseFormat responseFormat, String logMessage, Object ... logParams){
+    public static <T> T throwValidationException(ResponseFormat responseFormat, String logMessage, Object... logParams) {
         log.error(logMessage, logParams);
         throw new ValidationException(responseFormat);
     }
-
 }
index 0c1face..2a177c6 100644 (file)
@@ -17,7 +17,6 @@
  * limitations under the License.
  * ============LICENSE_END=========================================================
  */
-
 package org.openecomp.sdc.be.components.validation.component;
 
 import org.openecomp.sdc.be.components.impl.exceptions.ByActionStatusComponentException;
@@ -46,7 +45,6 @@ public class ComponentContactIdValidator implements ComponentFieldValidator {
         log.debug("validate component contactId");
         ComponentTypeEnum type = component.getComponentType();
         String contactId = component.getContactId();
-
         if (!ValidationUtils.validateStringNotEmpty(contactId)) {
             log.info("contact is missing.");
             ResponseFormat errorResponse = componentsUtils.getResponseFormat(ActionStatus.COMPONENT_MISSING_CONTACT, type.getValue());
@@ -56,7 +54,8 @@ public class ComponentContactIdValidator implements ComponentFieldValidator {
         validateContactId(contactId, user, component, actionEnum, type);
     }
 
-    private void validateContactId(String contactId, User user, org.openecomp.sdc.be.model.Component component, AuditingActionEnum actionEnum, ComponentTypeEnum type) {
+    private void validateContactId(String contactId, User user, org.openecomp.sdc.be.model.Component component, AuditingActionEnum actionEnum,
+                                   ComponentTypeEnum type) {
         if (contactId != null && !ValidationUtils.validateContactId(contactId)) {
             log.info("contact is invalid.");
             ResponseFormat errorResponse = componentsUtils.getResponseFormat(ActionStatus.COMPONENT_INVALID_CONTACT, type.getValue());
index 47d9f8b..8cf985f 100644 (file)
@@ -17,7 +17,6 @@
  * limitations under the License.
  * ============LICENSE_END=========================================================
  */
-
 package org.openecomp.sdc.be.components.validation.component;
 
 import org.openecomp.sdc.be.components.impl.exceptions.ByActionStatusComponentException;
@@ -47,13 +46,12 @@ public class ComponentDescriptionValidator implements ComponentFieldValidator {
         ComponentTypeEnum type = component.getComponentType();
         String description = component.getDescription();
         if (!ValidationUtils.validateStringNotEmpty(description)) {
-            auditErrorAndThrow(user,component, actionEnum, ActionStatus.COMPONENT_MISSING_DESCRIPTION);
+            auditErrorAndThrow(user, component, actionEnum, ActionStatus.COMPONENT_MISSING_DESCRIPTION);
         }
-
         description = ValidationUtils.cleanUpText(description);
-        try{
+        try {
             validateComponentDescription(description, type);
-        } catch(ComponentException e){
+        } catch (ComponentException e) {
             ResponseFormat errorResponse = componentsUtils.getResponseFormat(e.getActionStatus(), component.getComponentType().getValue());
             componentsUtils.auditComponentAdmin(errorResponse, user, component, actionEnum, component.getComponentType());
             throw e;
@@ -61,7 +59,8 @@ public class ComponentDescriptionValidator implements ComponentFieldValidator {
         component.setDescription(description);
     }
 
-    private void auditErrorAndThrow(User user, org.openecomp.sdc.be.model.Component component, AuditingActionEnum actionEnum, ActionStatus actionStatus) {
+    private void auditErrorAndThrow(User user, org.openecomp.sdc.be.model.Component component, AuditingActionEnum actionEnum,
+                                    ActionStatus actionStatus) {
         ResponseFormat errorResponse = componentsUtils.getResponseFormat(actionStatus, component.getComponentType().getValue());
         componentsUtils.auditComponentAdmin(errorResponse, user, component, actionEnum, component.getComponentType());
         throw new ByActionStatusComponentException(actionStatus, component.getComponentType().getValue());
@@ -70,9 +69,9 @@ public class ComponentDescriptionValidator implements ComponentFieldValidator {
     private void validateComponentDescription(String description, ComponentTypeEnum type) {
         if (description != null) {
             if (!ValidationUtils.validateDescriptionLength(description)) {
-                throw new ByActionStatusComponentException(ActionStatus.COMPONENT_DESCRIPTION_EXCEEDS_LIMIT, type.getValue(), "" + ValidationUtils.COMPONENT_DESCRIPTION_MAX_LENGTH);
+                throw new ByActionStatusComponentException(ActionStatus.COMPONENT_DESCRIPTION_EXCEEDS_LIMIT, type.getValue(),
+                    "" + ValidationUtils.COMPONENT_DESCRIPTION_MAX_LENGTH);
             }
-
             if (!ValidationUtils.validateCommentPattern(description)) {
                 throw new ByActionStatusComponentException(ActionStatus.COMPONENT_INVALID_DESCRIPTION, type.getValue());
             }
index b8d6117..c0bea45 100644 (file)
  * limitations under the License.
  * ============LICENSE_END=========================================================
  */
-
 package org.openecomp.sdc.be.components.validation.component;
 
 import org.openecomp.sdc.be.model.User;
 import org.openecomp.sdc.be.resources.data.auditing.AuditingActionEnum;
 
-
 public interface ComponentFieldValidator {
 
     void validateAndCorrectField(User user, org.openecomp.sdc.be.model.Component component, AuditingActionEnum actionEnum);
index 432ff41..6bda4ea 100644 (file)
@@ -17,9 +17,9 @@
  * limitations under the License.
  * ============LICENSE_END=========================================================
  */
-
 package org.openecomp.sdc.be.components.validation.component;
 
+import java.util.Arrays;
 import org.apache.commons.lang3.StringUtils;
 import org.openecomp.sdc.be.components.impl.exceptions.ByActionStatusComponentException;
 import org.openecomp.sdc.be.components.impl.exceptions.ComponentException;
@@ -33,8 +33,6 @@ import org.openecomp.sdc.common.log.wrappers.Logger;
 import org.openecomp.sdc.common.util.ValidationUtils;
 import org.openecomp.sdc.exception.ResponseFormat;
 
-import java.util.Arrays;
-
 @org.springframework.stereotype.Component
 public class ComponentIconValidator implements ComponentFieldValidator {
 
@@ -59,12 +57,11 @@ public class ComponentIconValidator implements ComponentFieldValidator {
             if (component.getComponentType().equals(ComponentTypeEnum.SERVICE)) {
                 validateAndSetDefaultIcon(icon, component);
             } else {
-                validateIcon(icon,component.getComponentType());
+                validateIcon(icon, component.getComponentType());
             }
-
-        } catch(ComponentException e){
-            ResponseFormat responseFormat = e.getResponseFormat() != null ? e.getResponseFormat()
-                    : componentsUtils.getResponseFormat(e.getActionStatus(), e.getParams());
+        } catch (ComponentException e) {
+            ResponseFormat responseFormat =
+                e.getResponseFormat() != null ? e.getResponseFormat() : componentsUtils.getResponseFormat(e.getActionStatus(), e.getParams());
             componentsUtils.auditComponentAdmin(responseFormat, user, component, actionEnum, type);
             throw e;
         }
@@ -81,8 +78,7 @@ public class ComponentIconValidator implements ComponentFieldValidator {
                 }
             }
         } catch (NullPointerException exp) {
-            throw new ByActionStatusComponentException(ActionStatus.COMPONENT_MISSING_CATEGORY,
-                    ComponentTypeEnum.SERVICE.getValue());
+            throw new ByActionStatusComponentException(ActionStatus.COMPONENT_MISSING_CATEGORY, ComponentTypeEnum.SERVICE.getValue());
         }
         componnet.setIcon(DEFAULT_ICON);
     }
@@ -91,9 +87,9 @@ public class ComponentIconValidator implements ComponentFieldValidator {
         if (icon != null) {
             if (!ValidationUtils.validateIconLength(icon)) {
                 log.debug("icon exceeds max length");
-                throw new ByActionStatusComponentException(ActionStatus.COMPONENT_ICON_EXCEEDS_LIMIT, type.getValue(), "" + ValidationUtils.ICON_MAX_LENGTH);
+                throw new ByActionStatusComponentException(ActionStatus.COMPONENT_ICON_EXCEEDS_LIMIT, type.getValue(),
+                    "" + ValidationUtils.ICON_MAX_LENGTH);
             }
-
             if (!ValidationUtils.validateIcon(icon)) {
                 log.info("icon is invalid.");
                 throw new ByActionStatusComponentException(ActionStatus.COMPONENT_INVALID_ICON, type.getValue());
index 7b13d2e..c9aa5fb 100644 (file)
@@ -17,7 +17,6 @@
  * limitations under the License.
  * ============LICENSE_END=========================================================
  */
-
 package org.openecomp.sdc.be.components.validation.component;
 
 import fj.data.Either;
@@ -56,20 +55,18 @@ public class ComponentNameValidator implements ComponentFieldValidator {
         String componentName = component.getName();
         if (StringUtils.isEmpty(componentName)) {
             log.debug("component name is empty");
-            auditErrorAndThrow(user,component, actionEnum, ActionStatus.MISSING_COMPONENT_NAME);
+            auditErrorAndThrow(user, component, actionEnum, ActionStatus.MISSING_COMPONENT_NAME);
         }
-
         if (!ValidationUtils.validateComponentNameLength(componentName)) {
             log.debug("Component name exceeds max length {} ", ValidationUtils.COMPONENT_NAME_MAX_LENGTH);
-            auditErrorAndThrow(user,component, actionEnum, ActionStatus.COMPONENT_NAME_EXCEEDS_LIMIT);
+            auditErrorAndThrow(user, component, actionEnum, ActionStatus.COMPONENT_NAME_EXCEEDS_LIMIT);
         }
-
         if (!ValidationUtils.validateComponentNamePattern(componentName)) {
             log.debug("Component name {} has invalid format", componentName);
-            auditErrorAndThrow(user,component, actionEnum, ActionStatus.INVALID_COMPONENT_NAME);
+            auditErrorAndThrow(user, component, actionEnum, ActionStatus.INVALID_COMPONENT_NAME);
         }
         if (component.getComponentType().equals(ComponentTypeEnum.SERVICE)) {
-            validateComponentNameUnique(user,component,actionEnum);
+            validateComponentNameUnique(user, component, actionEnum);
         }
         //TODO remove assignment here
         component.setNormalizedName(ValidationUtils.normaliseComponentName(componentName));
@@ -80,15 +77,16 @@ public class ComponentNameValidator implements ComponentFieldValidator {
         log.debug("validate component name uniqueness for: {}", component.getName());
         ComponentTypeEnum type = component.getComponentType();
         ResourceTypeEnum resourceType = null;
-        if(component instanceof Resource){
-            resourceType = ((Resource)component).getResourceType();
+        if (component instanceof Resource) {
+            resourceType = ((Resource) component).getResourceType();
         }
-        Either<Boolean, StorageOperationStatus> dataModelResponse = toscaOperationFacade.validateComponentNameExists(component.getName(), resourceType, type);
-
+        Either<Boolean, StorageOperationStatus> dataModelResponse = toscaOperationFacade
+            .validateComponentNameExists(component.getName(), resourceType, type);
         if (dataModelResponse.isLeft()) {
             if (dataModelResponse.left().value()) {
                 log.info("Component with name {} already exists", component.getName());
-                ResponseFormat errorResponse = componentsUtils.getResponseFormat(ActionStatus.COMPONENT_NAME_ALREADY_EXIST, type.getValue(), component.getName());
+                ResponseFormat errorResponse = componentsUtils
+                    .getResponseFormat(ActionStatus.COMPONENT_NAME_ALREADY_EXIST, type.getValue(), component.getName());
                 componentsUtils.auditComponentAdmin(errorResponse, user, component, actionEnum, type);
                 throw new ByResponseFormatComponentException(errorResponse);
             }
@@ -101,7 +99,8 @@ public class ComponentNameValidator implements ComponentFieldValidator {
         throw new ByResponseFormatComponentException(errorResponse);
     }
 
-    private void auditErrorAndThrow(User user, org.openecomp.sdc.be.model.Component component, AuditingActionEnum actionEnum, ActionStatus actionStatus) {
+    private void auditErrorAndThrow(User user, org.openecomp.sdc.be.model.Component component, AuditingActionEnum actionEnum,
+                                    ActionStatus actionStatus) {
         ResponseFormat errorResponse = componentsUtils.getResponseFormat(actionStatus, component.getComponentType().getValue());
         componentsUtils.auditComponentAdmin(errorResponse, user, component, actionEnum, component.getComponentType());
         throw new ByActionStatusComponentException(actionStatus, component.getComponentType().getValue());
index 8d0fdf1..29b4fda 100644 (file)
@@ -17,7 +17,6 @@
  * limitations under the License.
  * ============LICENSE_END=========================================================
  */
-
 package org.openecomp.sdc.be.components.validation.component;
 
 import org.openecomp.sdc.be.components.impl.exceptions.ByResponseFormatComponentException;
@@ -34,7 +33,7 @@ import org.openecomp.sdc.common.util.ValidationUtils;
 import org.openecomp.sdc.exception.ResponseFormat;
 
 @org.springframework.stereotype.Component
-public class ComponentProjectCodeValidator implements  ComponentFieldValidator{
+public class ComponentProjectCodeValidator implements ComponentFieldValidator {
 
     private static final Logger log = Logger.getLogger(ComponentProjectCodeValidator.class.getName());
     private ComponentsUtils componentsUtils;
@@ -50,22 +49,18 @@ public class ComponentProjectCodeValidator implements  ComponentFieldValidator{
         }
         log.debug("validate ProjectCode name ");
         String projectCode = component.getProjectCode();
-
         if (!ValidationUtils.validateStringNotEmpty(projectCode)) {
             log.info("projectCode is empty is allowed CR.");
             return;
         }
-
         try {
             validateProjectCode(projectCode);
         } catch (ComponentException exp) {
             ResponseFormat responseFormat = exp.getResponseFormat();
             componentsUtils.auditComponentAdmin(responseFormat, user, component, actionEnum, component.getComponentType(),
-                    ResourceVersionInfo.newBuilder()
-                            .build());
+                ResourceVersionInfo.newBuilder().build());
             throw exp;
         }
-
     }
 
     private void validateProjectCode(String projectCode) {
index 243e040..c1c785e 100644 (file)
  * limitations under the License.
  * ============LICENSE_END=========================================================
  */
-
 package org.openecomp.sdc.be.components.validation.component;
 
+import java.util.ArrayList;
+import java.util.List;
 import org.openecomp.sdc.be.components.impl.exceptions.ByActionStatusComponentException;
 import org.openecomp.sdc.be.components.impl.exceptions.ComponentException;
 import org.openecomp.sdc.be.dao.api.ActionStatus;
@@ -32,9 +33,6 @@ import org.openecomp.sdc.common.log.wrappers.Logger;
 import org.openecomp.sdc.common.util.ValidationUtils;
 import org.openecomp.sdc.exception.ResponseFormat;
 
-import java.util.ArrayList;
-import java.util.List;
-
 @org.springframework.stereotype.Component
 public class ComponentTagsValidator implements ComponentFieldValidator {
 
@@ -51,16 +49,17 @@ public class ComponentTagsValidator implements ComponentFieldValidator {
         List<String> tagsList = component.getTags();
         try {
             validateComponentTags(tagsList, component.getName(), component.getComponentType(), user, component, actionEnum);
-        } catch(ComponentException e){
-            ResponseFormat responseFormat = e.getResponseFormat() != null ? e.getResponseFormat()
-                    : componentsUtils.getResponseFormat(e.getActionStatus(), e.getParams());
+        } catch (ComponentException e) {
+            ResponseFormat responseFormat =
+                e.getResponseFormat() != null ? e.getResponseFormat() : componentsUtils.getResponseFormat(e.getActionStatus(), e.getParams());
             componentsUtils.auditComponentAdmin(responseFormat, user, component, actionEnum, component.getComponentType());
             throw e;
         }
         ValidationUtils.removeDuplicateFromList(component.getTags());
     }
 
-    protected void validateComponentTags(List<String> tags, String name, ComponentTypeEnum componentType, User user, org.openecomp.sdc.be.model.Component component, AuditingActionEnum action) {
+    protected void validateComponentTags(List<String> tags, String name, ComponentTypeEnum componentType, User user,
+                                         org.openecomp.sdc.be.model.Component component, AuditingActionEnum action) {
         log.debug("validate component tags");
         boolean includesComponentName = false;
         int tagListSize = 0;
@@ -81,7 +80,6 @@ public class ComponentTagsValidator implements ComponentFieldValidator {
             if (tagListSize > 0) {
                 tagListSize--;
             }
-
             if (!includesComponentName) {
                 log.debug("tags must include component name");
                 responseFormat = componentsUtils.getResponseFormat(ActionStatus.COMPONENT_INVALID_TAGS_NO_COMP_NAME);
@@ -90,7 +88,8 @@ public class ComponentTagsValidator implements ComponentFieldValidator {
             }
             if (!ValidationUtils.validateTagListLength(tagListSize)) {
                 log.debug("overall tags length exceeds limit {}", ValidationUtils.TAG_LIST_MAX_LENGTH);
-                responseFormat = componentsUtils.getResponseFormat(ActionStatus.COMPONENT_TAGS_EXCEED_LIMIT, "" + ValidationUtils.TAG_LIST_MAX_LENGTH);
+                responseFormat = componentsUtils
+                    .getResponseFormat(ActionStatus.COMPONENT_TAGS_EXCEED_LIMIT, "" + ValidationUtils.TAG_LIST_MAX_LENGTH);
                 componentsUtils.auditComponentAdmin(responseFormat, user, component, action, componentType);
                 throw new ByActionStatusComponentException(ActionStatus.COMPONENT_TAGS_EXCEED_LIMIT, "" + ValidationUtils.TAG_LIST_MAX_LENGTH);
             }
@@ -108,7 +107,8 @@ public class ComponentTagsValidator implements ComponentFieldValidator {
         return includesComponentName;
     }
 
-    private void validateTagLength(ComponentTypeEnum componentType, User user, org.openecomp.sdc.be.model.Component component, AuditingActionEnum action, String tag) {
+    private void validateTagLength(ComponentTypeEnum componentType, User user, org.openecomp.sdc.be.model.Component component,
+                                   AuditingActionEnum action, String tag) {
         ResponseFormat responseFormat;
         if (!ValidationUtils.validateTagLength(tag)) {
             log.debug("tag length exceeds limit {}", ValidationUtils.TAG_MAX_LENGTH);
index 3f300af..25072e9 100644 (file)
  * limitations under the License.
  * ============LICENSE_END=========================================================
  */
-
 package org.openecomp.sdc.be.components.validation.component;
 
+import java.util.List;
 import org.openecomp.sdc.be.impl.ComponentsUtils;
 import org.openecomp.sdc.be.model.User;
 import org.openecomp.sdc.be.resources.data.auditing.AuditingActionEnum;
 import org.openecomp.sdc.common.log.wrappers.Logger;
 import org.springframework.stereotype.Component;
 
-import java.util.List;
-
 @Component
 public class ComponentValidator {
 
@@ -41,8 +39,6 @@ public class ComponentValidator {
     }
 
     public void validate(User user, org.openecomp.sdc.be.model.Component component, AuditingActionEnum actionEnum) {
-        componentFieldValidators.stream().forEach(validator ->
-                validator.validateAndCorrectField(user,component,actionEnum));
+        componentFieldValidators.stream().forEach(validator -> validator.validateAndCorrectField(user, component, actionEnum));
     }
-
 }
index 1fe14c3..f8b3fff 100644 (file)
  * limitations under the License.
  * ============LICENSE_END=========================================================
  */
-
 package org.openecomp.sdc.be.components.validation.service;
 
+import static org.apache.commons.collections.CollectionUtils.isEmpty;
+
 import fj.data.Either;
+import java.util.List;
 import org.openecomp.sdc.be.components.impl.exceptions.ByActionStatusComponentException;
 import org.openecomp.sdc.be.components.impl.exceptions.ByResponseFormatComponentException;
 import org.openecomp.sdc.be.dao.api.ActionStatus;
@@ -35,16 +37,12 @@ import org.openecomp.sdc.common.log.wrappers.Logger;
 import org.openecomp.sdc.common.util.ValidationUtils;
 import org.openecomp.sdc.exception.ResponseFormat;
 
-import java.util.List;
-
-import static org.apache.commons.collections.CollectionUtils.isEmpty;
-
 @org.springframework.stereotype.Component
 public class ServiceCategoryValidator implements ServiceFieldValidator {
 
     private static final Logger log = Logger.getLogger(ServiceCategoryValidator.class.getName());
-    private ComponentsUtils componentsUtils;
     protected IElementOperation elementDao;
+    private ComponentsUtils componentsUtils;
 
     public ServiceCategoryValidator(ComponentsUtils componentsUtils, IElementOperation elementDao) {
         this.componentsUtils = componentsUtils;
@@ -55,7 +53,8 @@ public class ServiceCategoryValidator implements ServiceFieldValidator {
     public void validateAndCorrectField(User user, Service service, AuditingActionEnum actionEnum) {
         log.debug("validate Service category");
         if (isEmpty(service.getCategories())) {
-            ResponseFormat errorResponse = componentsUtils.getResponseFormat(ActionStatus.COMPONENT_MISSING_CATEGORY, ComponentTypeEnum.SERVICE.getValue());
+            ResponseFormat errorResponse = componentsUtils
+                .getResponseFormat(ActionStatus.COMPONENT_MISSING_CATEGORY, ComponentTypeEnum.SERVICE.getValue());
             componentsUtils.auditComponentAdmin(errorResponse, user, service, actionEnum, ComponentTypeEnum.SERVICE);
             throw new ByActionStatusComponentException(ActionStatus.COMPONENT_MISSING_CATEGORY, ComponentTypeEnum.SERVICE.getValue());
         }
@@ -65,14 +64,14 @@ public class ServiceCategoryValidator implements ServiceFieldValidator {
             componentsUtils.auditComponentAdmin(responseFormat, user, service, actionEnum, ComponentTypeEnum.SERVICE);
             throw new ByResponseFormatComponentException(responseFormat);
         }
-
     }
 
     private Either<Boolean, ResponseFormat> validateServiceCategory(List<CategoryDefinition> list) {
         if (list != null) {
             if (list.size() > 1) {
                 log.debug("Must be only one category for service");
-                ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.COMPONENT_TOO_MUCH_CATEGORIES, ComponentTypeEnum.SERVICE.getValue());
+                ResponseFormat responseFormat = componentsUtils
+                    .getResponseFormat(ActionStatus.COMPONENT_TOO_MUCH_CATEGORIES, ComponentTypeEnum.SERVICE.getValue());
                 return Either.right(responseFormat);
             }
             CategoryDefinition category = list.get(0);
@@ -83,10 +82,10 @@ public class ServiceCategoryValidator implements ServiceFieldValidator {
             }
             if (!ValidationUtils.validateStringNotEmpty(category.getName())) {
                 log.debug("Resource category is empty");
-                ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.COMPONENT_MISSING_CATEGORY, ComponentTypeEnum.SERVICE.getValue());
+                ResponseFormat responseFormat = componentsUtils
+                    .getResponseFormat(ActionStatus.COMPONENT_MISSING_CATEGORY, ComponentTypeEnum.SERVICE.getValue());
                 return Either.right(responseFormat);
             }
-
             log.debug("validating service category {} against valid categories list", list);
             Either<List<CategoryDefinition>, ActionStatus> categorys = elementDao.getAllServiceCategories();
             if (categorys.isRight()) {
index 6120673..9a4468b 100644 (file)
@@ -17,9 +17,9 @@
  * limitations under the License.
  * ============LICENSE_END=========================================================
  */
-
 package org.openecomp.sdc.be.components.validation.service;
 
+import java.util.List;
 import org.openecomp.sdc.be.components.impl.exceptions.ByActionStatusComponentException;
 import org.openecomp.sdc.be.config.ConfigurationManager;
 import org.openecomp.sdc.be.dao.api.ActionStatus;
@@ -27,10 +27,9 @@ import org.openecomp.sdc.be.model.Service;
 import org.openecomp.sdc.be.model.User;
 import org.openecomp.sdc.be.resources.data.auditing.AuditingActionEnum;
 
-import java.util.List;
-
 @org.springframework.stereotype.Component
 public class ServiceEnvironmentContextValidator implements ServiceFieldValidator {
+
     @Override
     public void validateAndCorrectField(User user, Service service, AuditingActionEnum actionEnum) {
         String environmentContext = service.getEnvironmentContext();
@@ -38,15 +37,16 @@ public class ServiceEnvironmentContextValidator implements ServiceFieldValidator
             setDefaultEnvironmentContextFromConfiguration(service);
             return;
         }
-        List<String> environmentContextValidValues =
-                ConfigurationManager.getConfigurationManager().getConfiguration().getEnvironmentContext().getValidValues();
-        if (!environmentContextValidValues.contains(environmentContext))
+        List<String> environmentContextValidValues = ConfigurationManager.getConfigurationManager().getConfiguration().getEnvironmentContext()
+            .getValidValues();
+        if (!environmentContextValidValues.contains(environmentContext)) {
             throw new ByActionStatusComponentException(ActionStatus.INVALID_ENVIRONMENT_CONTEXT, environmentContext);
+        }
     }
 
     private void setDefaultEnvironmentContextFromConfiguration(Service service) {
-        String defaultEnvironmentContext =
-                ConfigurationManager.getConfigurationManager().getConfiguration().getEnvironmentContext().getDefaultValue();
+        String defaultEnvironmentContext = ConfigurationManager.getConfigurationManager().getConfiguration().getEnvironmentContext()
+            .getDefaultValue();
         service.setEnvironmentContext(defaultEnvironmentContext);
     }
 }
index 24d91c2..4ff95a4 100644 (file)
  * limitations under the License.
  * ============LICENSE_END=========================================================
  */
-
 package org.openecomp.sdc.be.components.validation.service;
 
 import org.openecomp.sdc.be.model.Service;
 import org.openecomp.sdc.be.model.User;
 import org.openecomp.sdc.be.resources.data.auditing.AuditingActionEnum;
 
-
 public interface ServiceFieldValidator {
+
     void validateAndCorrectField(User user, Service service, AuditingActionEnum actionEnum);
 }
index ff11629..a9ea944 100644 (file)
@@ -17,7 +17,6 @@
  * limitations under the License.
  * ============LICENSE_END=========================================================
  */
-
 package org.openecomp.sdc.be.components.validation.service;
 
 import org.apache.commons.lang3.StringUtils;
@@ -47,7 +46,7 @@ public class ServiceFunctionValidator implements ServiceFieldValidator {
     public void validateAndCorrectField(User user, Service service, AuditingActionEnum actionEnum) {
         log.debug("validate service function");
         String serviceFunction = service.getServiceFunction();
-        if(serviceFunction == null) {
+        if (serviceFunction == null) {
             log.info("service function is null, assigned to empty value.");
             service.setServiceFunction("");
             return;
@@ -56,7 +55,7 @@ public class ServiceFunctionValidator implements ServiceFieldValidator {
     }
 
     private void validateServiceFunction(String serviceFunction) {
-        if (StringUtils.isEmpty(serviceFunction)){
+        if (StringUtils.isEmpty(serviceFunction)) {
             return;
         } else {
             if (!ValidationUtils.validateServiceFunctionLength(serviceFunction)) {
@@ -64,7 +63,6 @@ public class ServiceFunctionValidator implements ServiceFieldValidator {
                 ResponseFormat errorResponse = componentsUtils.getResponseFormat(ActionStatus.PROPERTY_EXCEEDS_LIMIT, "" + SERVICE_FUNCTION);
                 throw new ByResponseFormatComponentException(errorResponse);
             }
-
             if (!ValidationUtils.validateServiceMetadata(serviceFunction)) {
                 log.info("service function is not valid.");
                 ResponseFormat errorResponse = componentsUtils.getResponseFormat(ActionStatus.INVALID_PROPERY, "" + SERVICE_FUNCTION);
index baa59a1..7a34528 100644 (file)
@@ -17,7 +17,6 @@
  * limitations under the License.
  * ============LICENSE_END=========================================================
  */
-
 package org.openecomp.sdc.be.components.validation.service;
 
 import org.apache.commons.lang3.StringUtils;
@@ -34,6 +33,7 @@ import org.openecomp.sdc.exception.ResponseFormat;
 
 @org.springframework.stereotype.Component
 public class ServiceInstantiationTypeValidator implements ServiceFieldValidator {
+
     private static final Logger log = Logger.getLogger(ServiceInstantiationTypeValidator.class.getName());
     private ComponentsUtils componentsUtils;
 
@@ -48,7 +48,7 @@ public class ServiceInstantiationTypeValidator implements ServiceFieldValidator
         if (StringUtils.isEmpty(instantiationType)) {
             service.setInstantiationType(InstantiationTypes.A_LA_CARTE.getValue());
         }
-        if (!InstantiationTypes.containsName(service.getInstantiationType())){
+        if (!InstantiationTypes.containsName(service.getInstantiationType())) {
             log.error("Recieved Instantiation type {} is not valid.", instantiationType);
             ResponseFormat errorResponse = componentsUtils.getResponseFormat(ActionStatus.INVALID_INSTANTIATION_TYPE, instantiationType);
             componentsUtils.auditComponentAdmin(errorResponse, user, service, actionEnum, ComponentTypeEnum.SERVICE);
index 5a76542..73acf20 100644 (file)
@@ -17,7 +17,6 @@
  * limitations under the License.
  * ============LICENSE_END=========================================================
  */
-
 package org.openecomp.sdc.be.components.validation.service;
 
 import org.apache.commons.lang3.StringUtils;
@@ -41,6 +40,7 @@ public class ServiceNamingPolicyValidator implements ServiceFieldValidator {
     public ServiceNamingPolicyValidator(ComponentsUtils componentsUtils) {
         this.componentsUtils = componentsUtils;
     }
+
     @Override
     public void validateAndCorrectField(User user, Service service, AuditingActionEnum actionEnum) {
         Boolean isEcompGeneratedCurr = service.isEcompGeneratedNaming();
@@ -50,7 +50,8 @@ public class ServiceNamingPolicyValidator implements ServiceFieldValidator {
         }
         if (isEcompGeneratedCurr) {
             if (!ValidationUtils.validateServiceNamingPolicyLength(namingPolicyUpdate)) {
-                ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.NAMING_POLICY_EXCEEDS_LIMIT, "" + ValidationUtils.SERVICE_NAMING_POLICY_MAX_SIZE);
+                ResponseFormat responseFormat = componentsUtils
+                    .getResponseFormat(ActionStatus.NAMING_POLICY_EXCEEDS_LIMIT, "" + ValidationUtils.SERVICE_NAMING_POLICY_MAX_SIZE);
                 throw new ByResponseFormatComponentException(responseFormat);
             }
             if (StringUtils.isEmpty(namingPolicyUpdate)) {
index 59d2e83..10c831b 100644 (file)
@@ -17,7 +17,6 @@
  * limitations under the License.
  * ============LICENSE_END=========================================================
  */
-
 package org.openecomp.sdc.be.components.validation.service;
 
 import org.apache.commons.lang3.StringUtils;
@@ -47,26 +46,23 @@ public class ServiceRoleValidator implements ServiceFieldValidator {
     public void validateAndCorrectField(User user, Service service, AuditingActionEnum actionEnum) {
         log.debug("validate service role");
         String serviceRole = service.getServiceRole();
-        if (serviceRole != null){
-        validateServiceRole(serviceRole);
-            }
-
+        if (serviceRole != null) {
+            validateServiceRole(serviceRole);
+        }
     }
 
     private void validateServiceRole(String serviceRole) {
-        if (StringUtils.isEmpty(serviceRole)){
+        if (StringUtils.isEmpty(serviceRole)) {
             return;
         } else {
-
             if (!ValidationUtils.validateServiceRoleLength(serviceRole)) {
                 log.info("service role exceeds limit.");
                 ResponseFormat errorResponse = componentsUtils.getResponseFormat(ActionStatus.PROPERTY_EXCEEDS_LIMIT, "" + SERVICE_ROLE);
                 throw new ByResponseFormatComponentException(errorResponse);
             }
-
             if (!ValidationUtils.validateServiceMetadata(serviceRole)) {
                 log.info("service role is not valid.");
-                ResponseFormat errorResponse = componentsUtils.getResponseFormat(ActionStatus.INVALID_PROPERY, ""+ SERVICE_ROLE);
+                ResponseFormat errorResponse = componentsUtils.getResponseFormat(ActionStatus.INVALID_PROPERY, "" + SERVICE_ROLE);
                 throw new ByResponseFormatComponentException(errorResponse);
             }
         }
index e5e2f0a..2b592d8 100644 (file)
@@ -17,7 +17,6 @@
  * limitations under the License.
  * ============LICENSE_END=========================================================
  */
-
 package org.openecomp.sdc.be.components.validation.service;
 
 import org.openecomp.sdc.be.components.impl.exceptions.ByActionStatusComponentException;
@@ -62,7 +61,7 @@ public class ServiceTypeValidator implements ServiceFieldValidator {
         }
         if (!ValidationUtils.validateServiceMetadata(serviceType)) {
             log.info("service type is not valid.");
-            throw new ByActionStatusComponentException(ActionStatus.INVALID_PROPERY,"" + SERVICE_TYPE);
+            throw new ByActionStatusComponentException(ActionStatus.INVALID_PROPERY, "" + SERVICE_TYPE);
         }
     }
 }
index 5cf490d..984e03d 100644 (file)
@@ -17,9 +17,9 @@
  * limitations under the License.
  * ============LICENSE_END=========================================================
  */
-
 package org.openecomp.sdc.be.components.validation.service;
 
+import java.util.List;
 import org.openecomp.sdc.be.components.validation.component.ComponentFieldValidator;
 import org.openecomp.sdc.be.components.validation.component.ComponentValidator;
 import org.openecomp.sdc.be.impl.ComponentsUtils;
@@ -28,14 +28,13 @@ import org.openecomp.sdc.be.model.User;
 import org.openecomp.sdc.be.resources.data.auditing.AuditingActionEnum;
 import org.springframework.stereotype.Component;
 
-import java.util.List;
-
 @Component
 public class ServiceValidator extends ComponentValidator {
 
     private List<ServiceFieldValidator> serviceFieldValidators;
 
-    public ServiceValidator(ComponentsUtils componentsUtils, List<ComponentFieldValidator> componentFieldValidators, List<ServiceFieldValidator> serviceFieldValidators) {
+    public ServiceValidator(ComponentsUtils componentsUtils, List<ComponentFieldValidator> componentFieldValidators,
+                            List<ServiceFieldValidator> serviceFieldValidators) {
         super(componentsUtils, componentFieldValidators);
         this.serviceFieldValidators = serviceFieldValidators;
     }
@@ -43,7 +42,6 @@ public class ServiceValidator extends ComponentValidator {
     @Override
     public void validate(User user, org.openecomp.sdc.be.model.Component component, AuditingActionEnum actionEnum) {
         super.validate(user, component, actionEnum);
-        serviceFieldValidators.forEach(validator ->
-                validator.validateAndCorrectField(user,(Service)component,actionEnum));
+        serviceFieldValidators.forEach(validator -> validator.validateAndCorrectField(user, (Service) component, actionEnum));
     }
 }
index 156b73c..bc1d9f4 100644 (file)
@@ -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.
  * limitations under the License.
  * ============LICENSE_END=========================================================
  */
-
 package org.openecomp.sdc.be.datamodel;
 
 import java.util.Set;
 
 public class ForwardingPaths {
 
-  public ForwardingPaths() {
-  }
+    private Set<String> forwardingPathToDelete;
+
+    public ForwardingPaths() {
+    }
 
-  private Set<String> forwardingPathToDelete;
-  public Set<String> getForwardingPathToDelete() {
-    return forwardingPathToDelete;
-  }
+    public Set<String> getForwardingPathToDelete() {
+        return forwardingPathToDelete;
+    }
 
-  public void setForwardingPathToDelete(Set<String> forwardingPathToDelete) {
-    this.forwardingPathToDelete = forwardingPathToDelete;
-  }
+    public void setForwardingPathToDelete(Set<String> forwardingPathToDelete) {
+        this.forwardingPathToDelete = forwardingPathToDelete;
+    }
 }
index 8985c60..6feab9e 100644 (file)
@@ -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.
@@ -17,7 +17,6 @@
  * limitations under the License.
  * ============LICENSE_END=========================================================
  */
-
 package org.openecomp.sdc.be.datamodel;
 
 import java.util.HashMap;
@@ -43,13 +42,16 @@ public class NameIdPair extends HashMap<String, Object> {
         if (!Objects.isNull(ownerId)) {
             setOwnerId(ownerId);
         }
-
     }
 
     public NameIdPair(NameIdPair nameIdPair) {
         super(nameIdPair);
     }
 
+    public static final NameIdPair create(String name, String id) {
+        return new NameIdPair(name, id);
+    }
+
     public String getName() {
         return get(NAME).toString();
     }
@@ -91,8 +93,12 @@ public class NameIdPair extends HashMap<String, Object> {
 
     @Override
     public boolean equals(Object o) {
-        if (this == o) return true;
-        if (!(o instanceof NameIdPair)) return false;
+        if (this == o) {
+            return true;
+        }
+        if (!(o instanceof NameIdPair)) {
+            return false;
+        }
         NameIdPair that = (NameIdPair) o;
         return Objects.equals(getId(), that.getId());
     }
@@ -101,10 +107,4 @@ public class NameIdPair extends HashMap<String, Object> {
     public int hashCode() {
         return Objects.hash(getId());
     }
-
-    public static final NameIdPair create(String name, String id) {
-        return new NameIdPair(name, id);
-    }
-
-
 }
index e26c3f5..81cc46a 100644 (file)
@@ -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.
  * limitations under the License.
  * ============LICENSE_END=========================================================
  */
-
 package org.openecomp.sdc.be.datamodel;
 
 import java.util.HashMap;
 
 public class NameIdPairWrapper extends HashMap<String, Object> {
+
     public static final String ID = "id";
     public static final String DATA = "data";
 
@@ -33,6 +33,7 @@ public class NameIdPairWrapper extends HashMap<String, Object> {
         super();
         init(nameIdPair);
     }
+
     public void init(NameIdPair nameIdPair) {
         setId(nameIdPair.getId());
         setData(new NameIdPair(nameIdPair));
@@ -54,9 +55,7 @@ public class NameIdPairWrapper extends HashMap<String, Object> {
         put(DATA, data);
     }
 
-    public NameIdPair getNameIdPair(){
-        return new NameIdPair(getData().getName(),getData().getId());
+    public NameIdPair getNameIdPair() {
+        return new NameIdPair(getData().getName(), getData().getId());
     }
-
-
 }
index cb1ddef..c55e155 100644 (file)
@@ -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.
@@ -17,7 +17,6 @@
  * limitations under the License.
  * ============LICENSE_END=========================================================
  */
-
 package org.openecomp.sdc.be.datamodel;
 
 import java.util.Set;
index 33aee95..5b3f90c 100644 (file)
@@ -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.
  * limitations under the License.
  * ============LICENSE_END=========================================================
  */
-
 package org.openecomp.sdc.be.datamodel.api;
 
 public enum CategoryTypeEnum {
-
     CATEGORY("category"), SUBCATEGORY("subcategory"), GROUPING("grouping");
-
     private String value;
 
     CategoryTypeEnum(String value) {
@@ -33,5 +30,4 @@ public enum CategoryTypeEnum {
     public String getValue() {
         return value;
     }
-
 }
index fc98400..b134ed0 100644 (file)
@@ -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.
  * limitations under the License.
  * ============LICENSE_END=========================================================
  */
-
 package org.openecomp.sdc.be.datamodel.api;
 
 public enum HighestFilterEnum {
-
     ALL, HIGHEST_ONLY, NON_HIGHEST_ONLY;
-
 }
index 9479c80..01da5a2 100644 (file)
@@ -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.
  * limitations under the License.
  * ============LICENSE_END=========================================================
  */
-
 package org.openecomp.sdc.be.datamodel.utils;
 
+import java.util.ArrayList;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+import java.util.Map.Entry;
+import java.util.stream.Collectors;
 import org.apache.commons.codec.binary.Base64;
 import org.openecomp.sdc.be.info.ArtifactTemplateInfo;
 import org.openecomp.sdc.be.model.ArtifactDefinition;
@@ -28,23 +33,16 @@ import org.openecomp.sdc.common.api.ArtifactTypeEnum;
 import org.openecomp.sdc.common.api.Constants;
 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.Map.Entry;
-import java.util.stream.Collectors;
-
 public class ArtifactUtils {
 
-    public static ArtifactDefinition findMasterArtifact(Map<String, ArtifactDefinition> deplymentArtifact, List<ArtifactDefinition> artifacts, List<String> artifactsList) {
+    public static ArtifactDefinition findMasterArtifact(Map<String, ArtifactDefinition> deplymentArtifact, List<ArtifactDefinition> artifacts,
+                                                        List<String> artifactsList) {
         for (String artifactUid : artifactsList) {
             for (Entry<String, ArtifactDefinition> entry : deplymentArtifact.entrySet()) {
                 ArtifactDefinition artifact = entry.getValue();
                 if (artifactUid.equalsIgnoreCase(artifact.getUniqueId())) {
                     artifacts.add(artifact);
                 }
-
             }
         }
         if (artifacts.size() == 1) {
@@ -53,7 +51,8 @@ public class ArtifactUtils {
         ArtifactDefinition masterArtifact = null;
         for (ArtifactDefinition artifactInfo : artifacts) {
             String atrifactType = artifactInfo.getArtifactType();
-            if (atrifactType.equalsIgnoreCase(ArtifactTypeEnum.HEAT_VOL.getType()) || atrifactType.equalsIgnoreCase(ArtifactTypeEnum.HEAT_NET.getType())) {
+            if (atrifactType.equalsIgnoreCase(ArtifactTypeEnum.HEAT_VOL.getType()) || atrifactType
+                .equalsIgnoreCase(ArtifactTypeEnum.HEAT_NET.getType())) {
                 masterArtifact = artifactInfo;
                 continue;
             }
@@ -66,61 +65,52 @@ public class ArtifactUtils {
     }
 
     public static Map<String, Object> buildJsonForUpdateArtifact(String artifactId, String artifactName, String artifactType,
-                                                                 ArtifactGroupTypeEnum artifactGroupType, String label, String displayName, String description,
-                                                                 byte[] artifactContentent, List<ArtifactTemplateInfo> updatedRequiredArtifacts, boolean isFromCsar) {
-
+                                                                 ArtifactGroupTypeEnum artifactGroupType, String label, String displayName,
+                                                                 String description, byte[] artifactContentent,
+                                                                 List<ArtifactTemplateInfo> updatedRequiredArtifacts, boolean isFromCsar) {
         Map<String, Object> json = new HashMap<>();
-        if (artifactId != null && !artifactId.isEmpty())
+        if (artifactId != null && !artifactId.isEmpty()) {
             json.put(Constants.ARTIFACT_ID, artifactId);
-
+        }
         json.put(Constants.ARTIFACT_NAME, artifactName);
         json.put(Constants.ARTIFACT_TYPE, artifactType);
         json.put(Constants.ARTIFACT_DESCRIPTION, description);
         json.put(Constants.IS_FROM_CSAR, isFromCsar);
-
         String encodedPayload = Base64.encodeBase64String(artifactContentent);
-
         json.put(Constants.ARTIFACT_PAYLOAD_DATA, encodedPayload);
         json.put(Constants.ARTIFACT_DISPLAY_NAME, displayName);
         json.put(Constants.ARTIFACT_LABEL, label);
         json.put(Constants.ARTIFACT_GROUP_TYPE, artifactGroupType.getType());
-        json.put(Constants.REQUIRED_ARTIFACTS,
-                (updatedRequiredArtifacts == null || updatedRequiredArtifacts.isEmpty()) ? new ArrayList<>()
-                        : updatedRequiredArtifacts.stream()
-                                                  .filter(e -> e.getType().equals(ArtifactTypeEnum.HEAT_ARTIFACT.getType())
-                                        || e.getType().equals(ArtifactTypeEnum.HEAT_NESTED.getType()))
-                                                  .map(ArtifactTemplateInfo::getFileName).collect(Collectors.toList()));
+        json.put(Constants.REQUIRED_ARTIFACTS, (updatedRequiredArtifacts == null || updatedRequiredArtifacts.isEmpty()) ? new ArrayList<>()
+            : updatedRequiredArtifacts.stream().filter(
+                e -> e.getType().equals(ArtifactTypeEnum.HEAT_ARTIFACT.getType()) || e.getType().equals(ArtifactTypeEnum.HEAT_NESTED.getType()))
+                .map(ArtifactTemplateInfo::getFileName).collect(Collectors.toList()));
         return json;
     }
 
-    public static Map<String, Object> buildJsonForArtifact(ArtifactTemplateInfo artifactTemplateInfo,
-                       byte[] artifactContentent, int atrifactLabelCounter, boolean isFromcsar) {
-
+    public static Map<String, Object> buildJsonForArtifact(ArtifactTemplateInfo artifactTemplateInfo, byte[] artifactContentent,
+                                                           int atrifactLabelCounter, boolean isFromcsar) {
         Map<String, Object> json = new HashMap<>();
         String artifactName = artifactTemplateInfo.getFileName();
-
         json.put(Constants.ARTIFACT_NAME, artifactTemplateInfo.getFileName());
         json.put(Constants.ARTIFACT_TYPE, artifactTemplateInfo.getType());
         json.put(Constants.ARTIFACT_DESCRIPTION, "created from csar");
-               json.put(Constants.IS_FROM_CSAR, isFromcsar);
-
+        json.put(Constants.IS_FROM_CSAR, isFromcsar);
         String encodedPayload = Base64.encodeBase64String(artifactContentent);
-
         json.put(Constants.ARTIFACT_PAYLOAD_DATA, encodedPayload);
         String displayName = artifactName;
-        if (artifactName.lastIndexOf(".") > 0)
+        if (artifactName.lastIndexOf(".") > 0) {
             displayName = artifactName.substring(0, artifactName.lastIndexOf("."));
+        }
         json.put(Constants.ARTIFACT_DISPLAY_NAME, displayName);
         String label = ValidationUtils.normalizeArtifactLabel(artifactTemplateInfo.getType() + atrifactLabelCounter);
         json.put(Constants.ARTIFACT_LABEL, label);
         json.put(Constants.ARTIFACT_GROUP_TYPE, ArtifactGroupTypeEnum.DEPLOYMENT.getType());
         List<ArtifactTemplateInfo> requiredArtifacts = artifactTemplateInfo.getRelatedArtifactsInfo();
-        json.put(Constants.REQUIRED_ARTIFACTS,
-                (requiredArtifacts == null || requiredArtifacts.isEmpty()) ? new ArrayList<>()
-                        : requiredArtifacts.stream()
-                                           .filter(e -> e.getType().equals(ArtifactTypeEnum.HEAT_ARTIFACT.getType())
-                                        || e.getType().equals(ArtifactTypeEnum.HEAT_NESTED.getType()))
-                                           .map(ArtifactTemplateInfo::getFileName).collect(Collectors.toList()));
+        json.put(Constants.REQUIRED_ARTIFACTS, (requiredArtifacts == null || requiredArtifacts.isEmpty()) ? new ArrayList<>()
+            : requiredArtifacts.stream().filter(
+                e -> e.getType().equals(ArtifactTypeEnum.HEAT_ARTIFACT.getType()) || e.getType().equals(ArtifactTypeEnum.HEAT_NESTED.getType()))
+                .map(ArtifactTemplateInfo::getFileName).collect(Collectors.toList()));
         return json;
     }
 
index 7a6697e..877f8c4 100644 (file)
@@ -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.
@@ -17,7 +17,6 @@
  * limitations under the License.
  * ============LICENSE_END=========================================================
  */
-
 package org.openecomp.sdc.be.datamodel.utils;
 
 import com.google.common.collect.ImmutableMap;
@@ -37,8 +36,6 @@ import org.yaml.snakeyaml.Yaml;
 
 public class ConstraintConvertor {
 
-    private static final Logger logger = LoggerFactory.getLogger(ConstraintConvertor.class);
-
     public static final String EQUAL_OPERATOR = ConstraintType.EQUAL.getTypes().get(1);
     public static final String GREATER_THAN_OPERATOR = ConstraintType.GREATER_THAN.getTypes().get(1);
     public static final String LESS_THAN_OPERATOR = ConstraintType.LESS_THAN.getTypes().get(1);
@@ -46,11 +43,10 @@ public class ConstraintConvertor {
     public static final String PROPERTY_CONSTRAINT = "property";
     public static final String SERVICE_INPUT_CONSTRAINT = "service_input";
     public static final String SELF = "SELF";
-    private static Set<String> SUPPORTED_CONSTRAINT_LIST =
-            ImmutableSet.of(EQUAL_OPERATOR, GREATER_THAN_OPERATOR, LESS_THAN_OPERATOR);
-
-    private static Set<String> SUPPORTED_FUNCTIONS =
-            ImmutableSet.of(ToscaFunctions.GET_INPUT.getFunctionName(), ToscaFunctions.GET_PROPERTY.getFunctionName());
+    private static final Logger logger = LoggerFactory.getLogger(ConstraintConvertor.class);
+    private static Set<String> SUPPORTED_CONSTRAINT_LIST = ImmutableSet.of(EQUAL_OPERATOR, GREATER_THAN_OPERATOR, LESS_THAN_OPERATOR);
+    private static Set<String> SUPPORTED_FUNCTIONS = ImmutableSet
+        .of(ToscaFunctions.GET_INPUT.getFunctionName(), ToscaFunctions.GET_PROPERTY.getFunctionName());
 
     public UIConstraint convert(String inConstraint) {
         Yaml yamlSource = new Yaml();
@@ -109,7 +105,7 @@ public class ConstraintConvertor {
             uiConstraint.setValue(value.get(1));
             return uiConstraint;
         }
-       return null;
+        return null;
     }
 
     public List<String> convertToList(List<UIConstraint> uiConstraints) {
@@ -127,7 +123,6 @@ public class ConstraintConvertor {
         try {
             Map map1 = new HashMap();
             Map map2 = new HashMap();
-
             map1.put(uiConstraint.getServicePropertyName(), map2);
             if (uiConstraint.getSourceType().equals(STATIC_CONSTRAINT)) {
                 Object value = uiConstraint.getValue();
@@ -143,7 +138,6 @@ public class ConstraintConvertor {
                 Map map3 = ImmutableMap.of(ToscaFunctions.GET_INPUT.getFunctionName(), uiConstraint.getValue());
                 map2.put(uiConstraint.getConstraintOperator(), map3);
             }
-
             Yaml yamlSource = new Yaml();
             return yamlSource.dump(map1);
         } catch (NullPointerException ex) {
@@ -186,6 +180,5 @@ public class ConstraintConvertor {
             return handleMap(uiConstraint, constraintValue);
         }
         return null;
-
     }
 }
index cd6351c..d1220b9 100644 (file)
@@ -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.
@@ -17,7 +17,6 @@
  * limitations under the License.
  * ============LICENSE_END=========================================================
  */
-
 package org.openecomp.sdc.be.datamodel.utils;
 
 import org.openecomp.sdc.be.datamodel.api.CategoryTypeEnum;
@@ -25,52 +24,51 @@ import org.openecomp.sdc.be.datatypes.enums.ComponentTypeEnum;
 import org.openecomp.sdc.be.datatypes.enums.NodeTypeEnum;
 
 public class NodeTypeConvertUtils {
+
     public static NodeTypeEnum getCategoryNodeTypeByComponentParam(ComponentTypeEnum componentTypeEnum, CategoryTypeEnum categoryType) {
         NodeTypeEnum res = null;
         if (componentTypeEnum != null) {
             switch (componentTypeEnum) {
-            case SERVICE:
-                switch (categoryType) {
-                case CATEGORY:
-                    res = NodeTypeEnum.ServiceNewCategory;
-                    break;
-
-                default:
-                    // doesn't support subcategories or grouping
+                case SERVICE:
+                    switch (categoryType) {
+                        case CATEGORY:
+                            res = NodeTypeEnum.ServiceNewCategory;
+                            break;
+                        default:
+                            // doesn't support subcategories or grouping
+                            break;
+                    }
                     break;
-                }
-                break;
-            case RESOURCE:
-                switch (categoryType) {
-                case CATEGORY:
-                    res = NodeTypeEnum.ResourceNewCategory;
+                case RESOURCE:
+                    switch (categoryType) {
+                        case CATEGORY:
+                            res = NodeTypeEnum.ResourceNewCategory;
+                            break;
+                        case SUBCATEGORY:
+                            res = NodeTypeEnum.ResourceSubcategory;
+                            break;
+                        default:
+                            // doesn't support grouping
+                            break;
+                    }
                     break;
-                case SUBCATEGORY:
-                    res = NodeTypeEnum.ResourceSubcategory;
+                case PRODUCT:
+                    switch (categoryType) {
+                        case CATEGORY:
+                            res = NodeTypeEnum.ProductCategory;
+                            break;
+                        case SUBCATEGORY:
+                            res = NodeTypeEnum.ProductSubcategory;
+                            break;
+                        case GROUPING:
+                            res = NodeTypeEnum.ProductGrouping;
+                            break;
+                    }
                     break;
                 default:
-                    // doesn't support grouping
                     break;
-                }
-                break;
-            case PRODUCT:
-                switch (categoryType) {
-                case CATEGORY:
-                    res = NodeTypeEnum.ProductCategory;
-                    break;
-                case SUBCATEGORY:
-                    res = NodeTypeEnum.ProductSubcategory;
-                    break;
-                case GROUPING:
-                    res = NodeTypeEnum.ProductGrouping;
-                    break;
-                }
-                break;
-            default:
-                break;
             }
         }
         return res;
     }
-
 }
index 24d4b2f..9569247 100644 (file)
  * See the License for the specific language governing permissions and
  * limitations under the License.
  */
-
 package org.openecomp.sdc.be.datamodel.utils;
 
 import com.fasterxml.jackson.core.type.TypeReference;
 import com.fasterxml.jackson.databind.ObjectMapper;
 import fj.data.Either;
+import java.io.IOException;
+import java.util.ArrayList;
+import java.util.Collection;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+import java.util.Objects;
 import org.apache.commons.collections4.CollectionUtils;
 import org.apache.commons.collections4.ListUtils;
 import org.apache.commons.collections4.MapUtils;
@@ -40,47 +46,34 @@ import org.openecomp.sdc.exception.ResponseFormat;
 import org.slf4j.Logger;
 import org.slf4j.LoggerFactory;
 
-import java.io.IOException;
-import java.util.ArrayList;
-import java.util.Collection;
-import java.util.HashMap;
-import java.util.List;
-import java.util.Map;
-import java.util.Objects;
-
 public class PropertyValueConstraintValidationUtil {
 
     private static final String UNDERSCORE = "_";
-    private static final String VALUE_PROVIDED_IN_INVALID_FORMAT_FOR_PROPERTY =
-            "%nValue provided in invalid format for %s property";
-    private Map<String, DataTypeDefinition> dataTypeDefinitionCache;
+    private static final String VALUE_PROVIDED_IN_INVALID_FORMAT_FOR_PROPERTY = "%nValue provided in invalid format for %s property";
     private static final Logger logger = LoggerFactory.getLogger(PropertyValueConstraintValidationUtil.class);
+    private static final String IGNORE_PROPERTY_VALUE_START_WITH = "{\"get_input\":";
+    private Map<String, DataTypeDefinition> dataTypeDefinitionCache;
     private ObjectMapper objectMapper = new ObjectMapper();
     private List<String> errorMessages = new ArrayList<>();
     private StringBuilder completePropertyName;
     private String completeInputName;
-    private static final String IGNORE_PROPERTY_VALUE_START_WITH = "{\"get_input\":";
 
     public static PropertyValueConstraintValidationUtil getInstance() {
         return new PropertyValueConstraintValidationUtil();
     }
 
-    public Either<Boolean, ResponseFormat> validatePropertyConstraints(
-            Collection<? extends PropertyDefinition> propertyDefinitionList,
-            ApplicationDataTypeCache applicationDataTypeCache) {
+    public Either<Boolean, ResponseFormat> validatePropertyConstraints(Collection<? extends PropertyDefinition> propertyDefinitionList,
+                                                                       ApplicationDataTypeCache applicationDataTypeCache) {
         ResponseFormatManager responseFormatManager = getResponseFormatManager();
         dataTypeDefinitionCache = applicationDataTypeCache.getAll().left().value();
-        CollectionUtils.emptyIfNull(propertyDefinitionList).stream()
-                .filter(this::isValuePresent)
-                .forEach(this::evaluatePropertyTypeForConstraintValidation);
-
+        CollectionUtils.emptyIfNull(propertyDefinitionList).stream().filter(this::isValuePresent)
+            .forEach(this::evaluatePropertyTypeForConstraintValidation);
         if (CollectionUtils.isNotEmpty(errorMessages)) {
             logger.error("Properties with Invalid Data:", errorMessages);
-            ResponseFormat inputResponse = responseFormatManager.getResponseFormat(ActionStatus
-                    .INVALID_PROPERTY_VALUES, String.join(",", errorMessages));
+            ResponseFormat inputResponse = responseFormatManager
+                .getResponseFormat(ActionStatus.INVALID_PROPERTY_VALUES, String.join(",", errorMessages));
             return Either.right(inputResponse);
         }
-
         return Either.left(Boolean.TRUE);
     }
 
@@ -88,69 +81,60 @@ public class PropertyValueConstraintValidationUtil {
         if (propertyDefinition instanceof InputDefinition) {
             return StringUtils.isNotEmpty(propertyDefinition.getDefaultValue());
         }
-
         return StringUtils.isNotEmpty(propertyDefinition.getValue());
     }
 
     private void evaluatePropertyTypeForConstraintValidation(PropertyDefinition propertyDefinition) {
-        if (Objects.nonNull(propertyDefinition.getType())
-                && dataTypeDefinitionCache.containsKey(propertyDefinition.getType())) {
-
+        if (Objects.nonNull(propertyDefinition.getType()) && dataTypeDefinitionCache.containsKey(propertyDefinition.getType())) {
             completeInputName = "";
             completePropertyName = new StringBuilder();
             if (propertyDefinition instanceof InputDefinition) {
                 completeInputName = propertyDefinition.getName();
                 propertyDefinition = getPropertyDefinitionObjectFromInputs(propertyDefinition);
             }
-
             if (Objects.nonNull(propertyDefinition)) {
-                               if (ToscaType.isPrimitiveType(propertyDefinition.getType())) {
-                                       propertyDefinition.setConstraints(
-                                                       org.openecomp.sdc.be.dao.utils.CollectionUtils.merge(propertyDefinition.safeGetConstraints(),
-                                                                       dataTypeDefinitionCache.get(propertyDefinition.getType()).safeGetConstraints()));
-                                       evaluateConstraintsOnProperty(propertyDefinition);
-                               } else if (ToscaType.isCollectionType(propertyDefinition.getType())) {
-                                       propertyDefinition.setConstraints(
-                                                       org.openecomp.sdc.be.dao.utils.CollectionUtils.merge(propertyDefinition.safeGetConstraints(),
-                                                                       dataTypeDefinitionCache.get(propertyDefinition.getType()).safeGetConstraints()));
-                                       evaluateConstraintsOnProperty(propertyDefinition);
-                                       evaluateCollectionTypeProperties(propertyDefinition);
-                               } else {
-                                       setCompletePropertyName(propertyDefinition);
-                                       evaluateComplexTypeProperties(propertyDefinition);
-                               }
-                       }
+                if (ToscaType.isPrimitiveType(propertyDefinition.getType())) {
+                    propertyDefinition.setConstraints(org.openecomp.sdc.be.dao.utils.CollectionUtils.merge(propertyDefinition.safeGetConstraints(),
+                        dataTypeDefinitionCache.get(propertyDefinition.getType()).safeGetConstraints()));
+                    evaluateConstraintsOnProperty(propertyDefinition);
+                } else if (ToscaType.isCollectionType(propertyDefinition.getType())) {
+                    propertyDefinition.setConstraints(org.openecomp.sdc.be.dao.utils.CollectionUtils.merge(propertyDefinition.safeGetConstraints(),
+                        dataTypeDefinitionCache.get(propertyDefinition.getType()).safeGetConstraints()));
+                    evaluateConstraintsOnProperty(propertyDefinition);
+                    evaluateCollectionTypeProperties(propertyDefinition);
+                } else {
+                    setCompletePropertyName(propertyDefinition);
+                    evaluateComplexTypeProperties(propertyDefinition);
+                }
+            }
         } else {
             errorMessages.add("\nUnsupported datatype found for property " + getCompletePropertyName(propertyDefinition));
         }
     }
 
     private void setCompletePropertyName(PropertyDefinition propertyDefinition) {
-        if(StringUtils.isNotBlank(propertyDefinition.getUniqueId())) {
-            completePropertyName.append(
-                    propertyDefinition.getUniqueId().substring(propertyDefinition.getUniqueId().lastIndexOf('.') + 1));
+        if (StringUtils.isNotBlank(propertyDefinition.getUniqueId())) {
+            completePropertyName.append(propertyDefinition.getUniqueId().substring(propertyDefinition.getUniqueId().lastIndexOf('.') + 1));
         }
     }
 
     private void evaluateConstraintsOnProperty(PropertyDefinition propertyDefinition) {
         ToscaType toscaType = ToscaType.isValidType(propertyDefinition.getType());
-        if (isPropertyNotMappedAsInput(propertyDefinition)
-                && CollectionUtils.isNotEmpty(propertyDefinition.getConstraints())
-                && isValidValueConstraintPresent(propertyDefinition.getConstraints())) {
+        if (isPropertyNotMappedAsInput(propertyDefinition) && CollectionUtils.isNotEmpty(propertyDefinition.getConstraints())
+            && isValidValueConstraintPresent(propertyDefinition.getConstraints())) {
             for (PropertyConstraint propertyConstraint : propertyDefinition.getConstraints()) {
                 try {
                     propertyConstraint.initialize(toscaType);
                     propertyConstraint.validate(toscaType, propertyDefinition.getValue());
                 } catch (ConstraintValueDoNotMatchPropertyTypeException | ConstraintViolationException exception) {
-                    errorMessages.add("\n" + propertyConstraint.getErrorMessage(
-                            toscaType, exception, getCompletePropertyName(propertyDefinition)));
+                    errorMessages.add("\n" + propertyConstraint.getErrorMessage(toscaType, exception, getCompletePropertyName(propertyDefinition)));
                 }
             }
-        } else if (isPropertyNotMappedAsInput(propertyDefinition)
-                && ToscaType.isPrimitiveType(propertyDefinition.getType())
-                && !toscaType.isValidValue(propertyDefinition.getValue())) {
-            errorMessages.add(String.format("\nUnsupported value provided for %s property supported value "
-                    + "type is %s.", getCompletePropertyName(propertyDefinition), toscaType.getType()));
+        } else if (isPropertyNotMappedAsInput(propertyDefinition) && ToscaType.isPrimitiveType(propertyDefinition.getType()) && !toscaType
+            .isValidValue(propertyDefinition.getValue())) {
+            errorMessages.add(String
+                .format("\nUnsupported value provided for %s property supported value " + "type is %s.", getCompletePropertyName(propertyDefinition),
+                    toscaType.getType()));
         }
     }
 
@@ -158,66 +142,49 @@ public class PropertyValueConstraintValidationUtil {
         return !propertyDefinition.getValue().startsWith(IGNORE_PROPERTY_VALUE_START_WITH);
     }
 
-    private void checkAndEvaluatePrimitiveProperty(PropertyDefinition propertyDefinition,
-                                                                                                  DataTypeDefinition dataTypeDefinition) {
-        if (ToscaType.isPrimitiveType(dataTypeDefinition.getName())
-                && CollectionUtils.isNotEmpty(dataTypeDefinition.getConstraints())) {
-
+    private void checkAndEvaluatePrimitiveProperty(PropertyDefinition propertyDefinition, DataTypeDefinition dataTypeDefinition) {
+        if (ToscaType.isPrimitiveType(dataTypeDefinition.getName()) && CollectionUtils.isNotEmpty(dataTypeDefinition.getConstraints())) {
             PropertyDefinition definition = new PropertyDefinition();
             definition.setValue(propertyDefinition.getValue());
             definition.setType(dataTypeDefinition.getName());
             definition.setConstraints(dataTypeDefinition.getConstraints());
-
             evaluateConstraintsOnProperty(propertyDefinition);
         }
     }
 
     private void evaluateComplexTypeProperties(PropertyDefinition propertyDefinition) {
-        List<PropertyDefinition> propertyDefinitions =
-                dataTypeDefinitionCache.get(propertyDefinition.getType()).getProperties();
-               try {
-                       Map<String, Object> valueMap =
-                                       MapUtils.emptyIfNull(ConstraintUtil.parseToCollection(propertyDefinition.getValue(),
-                                                       new TypeReference<Map<String, Object>>() {}));
-
-                       if (CollectionUtils.isEmpty(propertyDefinitions)) {
-                               checkAndEvaluatePrimitiveProperty(propertyDefinition,
-                                               dataTypeDefinitionCache.get(propertyDefinition.getType()));
-                       } else {
-                               ListUtils.emptyIfNull(propertyDefinitions)
-                                               .forEach(prop -> evaluateRegularComplexType(propertyDefinition, prop, valueMap));
-                       }
-               } catch (ConstraintValueDoNotMatchPropertyTypeException e) {
-                       logger.debug(e.getMessage(), e);
-                       errorMessages.add(String.format(VALUE_PROVIDED_IN_INVALID_FORMAT_FOR_PROPERTY,
-                                       getCompletePropertyName(propertyDefinition)));
-               }
+        List<PropertyDefinition> propertyDefinitions = dataTypeDefinitionCache.get(propertyDefinition.getType()).getProperties();
+        try {
+            Map<String, Object> valueMap = MapUtils
+                .emptyIfNull(ConstraintUtil.parseToCollection(propertyDefinition.getValue(), new TypeReference<Map<String, Object>>() {
+                }));
+            if (CollectionUtils.isEmpty(propertyDefinitions)) {
+                checkAndEvaluatePrimitiveProperty(propertyDefinition, dataTypeDefinitionCache.get(propertyDefinition.getType()));
+            } else {
+                ListUtils.emptyIfNull(propertyDefinitions).forEach(prop -> evaluateRegularComplexType(propertyDefinition, prop, valueMap));
+            }
+        } catch (ConstraintValueDoNotMatchPropertyTypeException e) {
+            logger.debug(e.getMessage(), e);
+            errorMessages.add(String.format(VALUE_PROVIDED_IN_INVALID_FORMAT_FOR_PROPERTY, getCompletePropertyName(propertyDefinition)));
+        }
     }
 
-    private void evaluateRegularComplexType(PropertyDefinition propertyDefinition,
-                                                                                       PropertyDefinition prop,
-                                                                                       Map<String, Object> valueMap) {
+    private void evaluateRegularComplexType(PropertyDefinition propertyDefinition, PropertyDefinition prop, Map<String, Object> valueMap) {
         try {
             if (valueMap.containsKey(prop.getName())) {
                 if (ToscaType.isPrimitiveType(prop.getType())) {
-                    evaluateConstraintsOnProperty(createPropertyDefinition(prop,
-                            String.valueOf(valueMap.get(prop.getName()))));
+                    evaluateConstraintsOnProperty(createPropertyDefinition(prop, String.valueOf(valueMap.get(prop.getName()))));
                 } else if (ToscaType.isCollectionType(prop.getType())) {
-
-                    evaluateCollectionTypeProperties(createPropertyDefinition(prop,
-                            objectMapper.writeValueAsString(valueMap.get(prop.getName()))));
+                    evaluateCollectionTypeProperties(createPropertyDefinition(prop, objectMapper.writeValueAsString(valueMap.get(prop.getName()))));
                 } else {
                     completePropertyName.append(UNDERSCORE);
                     completePropertyName.append(prop.getName());
-                    evaluateComplexTypeProperties(
-                            createPropertyDefinition(prop, objectMapper.writeValueAsString(
-                                    valueMap.get(prop.getName()))));
+                    evaluateComplexTypeProperties(createPropertyDefinition(prop, objectMapper.writeValueAsString(valueMap.get(prop.getName()))));
                 }
             }
         } catch (IOException e) {
             logger.error(e.getMessage(), e);
-            errorMessages.add(String.format(VALUE_PROVIDED_IN_INVALID_FORMAT_FOR_PROPERTY,
-                    getCompletePropertyName(propertyDefinition)));
+            errorMessages.add(String.format(VALUE_PROVIDED_IN_INVALID_FORMAT_FOR_PROPERTY, getCompletePropertyName(propertyDefinition)));
         }
     }
 
@@ -233,45 +200,37 @@ public class PropertyValueConstraintValidationUtil {
     private void evaluateListType(PropertyDefinition propertyDefinition) {
         try {
             String schemaType = propertyDefinition.getSchemaType();
-            List list = ConstraintUtil.parseToCollection(propertyDefinition.getValue(),
-                    new TypeReference<List<Object>>() {});
+            List list = ConstraintUtil.parseToCollection(propertyDefinition.getValue(), new TypeReference<List<Object>>() {
+            });
             evaluateCollectionType(propertyDefinition, list, schemaType);
         } catch (ConstraintValueDoNotMatchPropertyTypeException e) {
             logger.debug(e.getMessage(), e);
-            errorMessages.add(String.format(VALUE_PROVIDED_IN_INVALID_FORMAT_FOR_PROPERTY,
-                    getCompletePropertyName(propertyDefinition)));
+            errorMessages.add(String.format(VALUE_PROVIDED_IN_INVALID_FORMAT_FOR_PROPERTY, getCompletePropertyName(propertyDefinition)));
         }
     }
 
     private void evaluateMapType(PropertyDefinition propertyDefinition) {
         try {
             String schemaType = propertyDefinition.getSchemaType();
-            Map map = ConstraintUtil.parseToCollection(propertyDefinition.getValue(),
-                    new TypeReference<Map<String, Object>>() {
+            Map map = ConstraintUtil.parseToCollection(propertyDefinition.getValue(), new TypeReference<Map<String, Object>>() {
             });
             evaluateCollectionType(propertyDefinition, map.values(), schemaType);
         } catch (ConstraintValueDoNotMatchPropertyTypeException e) {
             logger.debug(e.getMessage(), e);
-            errorMessages.add(String.format(VALUE_PROVIDED_IN_INVALID_FORMAT_FOR_PROPERTY,
-                    getCompletePropertyName(propertyDefinition)));
+            errorMessages.add(String.format(VALUE_PROVIDED_IN_INVALID_FORMAT_FOR_PROPERTY, getCompletePropertyName(propertyDefinition)));
         }
     }
 
-    private void evaluateCollectionPrimitiveSchemaType(PropertyDefinition propertyDefinition,
-                                                                                                          Object value,
-                                                                                                          String schemaType) {
-        if (Objects.nonNull(propertyDefinition.getSchema())
-                && propertyDefinition.getSchema().getProperty() instanceof PropertyDefinition) {
-            propertyDefinition.setConstraints(((PropertyDefinition) propertyDefinition.getSchema()
-                    .getProperty()).getConstraints());
+    private void evaluateCollectionPrimitiveSchemaType(PropertyDefinition propertyDefinition, Object value, String schemaType) {
+        if (Objects.nonNull(propertyDefinition.getSchema()) && propertyDefinition.getSchema().getProperty() instanceof PropertyDefinition) {
+            propertyDefinition.setConstraints(((PropertyDefinition) propertyDefinition.getSchema().getProperty()).getConstraints());
             propertyDefinition.setValue(String.valueOf(value));
             propertyDefinition.setType(schemaType);
             evaluateConstraintsOnProperty(propertyDefinition);
         }
     }
-    private void evaluateCollectionType(PropertyDefinition propertyDefinition,
-                                                                               Collection valueList,
-                                                                               String schemaType) {
+
+    private void evaluateCollectionType(PropertyDefinition propertyDefinition, Collection valueList, String schemaType) {
         for (Object value : valueList) {
             try {
                 if (ToscaType.isPrimitiveType(schemaType)) {
@@ -289,16 +248,15 @@ public class PropertyValueConstraintValidationUtil {
                 }
             } catch (IOException e) {
                 logger.debug(e.getMessage(), e);
-                errorMessages.add(String.format(VALUE_PROVIDED_IN_INVALID_FORMAT_FOR_PROPERTY,
-                        getCompletePropertyName(propertyDefinition)));
+                errorMessages.add(String.format(VALUE_PROVIDED_IN_INVALID_FORMAT_FOR_PROPERTY, getCompletePropertyName(propertyDefinition)));
             }
         }
     }
 
     private String getCompletePropertyName(PropertyDefinition propertyDefinition) {
-        return StringUtils.isNotBlank(completeInputName) ? completeInputName :
-                StringUtils.isBlank(completePropertyName) ?
-                        propertyDefinition.getName() : completePropertyName + UNDERSCORE + propertyDefinition.getName();
+        return StringUtils.isNotBlank(completeInputName) ? completeInputName
+            : StringUtils.isBlank(completePropertyName) ? propertyDefinition.getName()
+                : completePropertyName + UNDERSCORE + propertyDefinition.getName();
     }
 
     private PropertyDefinition createPropertyDefinition(PropertyDefinition prop, String value) {
@@ -308,30 +266,24 @@ public class PropertyValueConstraintValidationUtil {
         propertyDefinition.setType(prop.getType());
         propertyDefinition.setConstraints(prop.getConstraints());
         propertyDefinition.setSchema(prop.getSchema());
-
         return propertyDefinition;
     }
 
     private boolean isValidValueConstraintPresent(List<PropertyConstraint> propertyConstraints) {
-        return propertyConstraints.stream()
-                .anyMatch(propertyConstraint -> propertyConstraint instanceof ValidValuesConstraint);
+        return propertyConstraints.stream().anyMatch(propertyConstraint -> propertyConstraint instanceof ValidValuesConstraint);
     }
 
-    private PropertyDefinition getPropertyDefinitionObjectFromInputs(
-            PropertyDefinition property) {
+    private PropertyDefinition getPropertyDefinitionObjectFromInputs(PropertyDefinition property) {
         InputDefinition inputDefinition = (InputDefinition) property;
         PropertyDefinition propertyDefinition = null;
-
-        if (CollectionUtils.isEmpty(inputDefinition.getProperties())
-                || ToscaType.isPrimitiveType(inputDefinition.getProperties().get(0).getType())) {
-               propertyDefinition  = new PropertyDefinition();
+        if (CollectionUtils.isEmpty(inputDefinition.getProperties()) || ToscaType.isPrimitiveType(inputDefinition.getProperties().get(0).getType())) {
+            propertyDefinition = new PropertyDefinition();
             propertyDefinition.setType(inputDefinition.getType());
             propertyDefinition.setValue(inputDefinition.getDefaultValue());
             propertyDefinition.setName(inputDefinition.getName());
         } else if (Objects.nonNull(inputDefinition.getInputPath())) {
             propertyDefinition = evaluateComplexTypeInputs(inputDefinition);
         }
-
         return propertyDefinition;
     }
 
@@ -342,10 +294,9 @@ public class PropertyValueConstraintValidationUtil {
         if (inputPathArr.length > 1) {
             inputPathArr = ArrayUtils.remove(inputPathArr, 0);
         }
-
         try {
             Map<String, Object> presentMap = inputMap;
-            for (int i = 0; i < inputPathArr.length ; i++) {
+            for (int i = 0; i < inputPathArr.length; i++) {
                 if (i == inputPathArr.length - 1) {
                     presentMap.computeIfAbsent(inputPathArr[i], k -> inputDefinition.getDefaultValue());
                 } else {
@@ -353,7 +304,6 @@ public class PropertyValueConstraintValidationUtil {
                     presentMap = (Map<String, Object>) presentMap.get(inputPathArr[i]);
                 }
             }
-
             if (CollectionUtils.isNotEmpty(inputDefinition.getProperties())) {
                 propertyDefinition.setType(inputDefinition.getProperties().get(0).getType());
             }
@@ -361,10 +311,8 @@ public class PropertyValueConstraintValidationUtil {
             propertyDefinition.setValue(objectMapper.writeValueAsString(inputMap));
         } catch (IOException e) {
             logger.error(e.getMessage(), e);
-            errorMessages.add(String.format(VALUE_PROVIDED_IN_INVALID_FORMAT_FOR_PROPERTY,
-                    inputDefinition.getName()));
+            errorMessages.add(String.format(VALUE_PROVIDED_IN_INVALID_FORMAT_FOR_PROPERTY, inputDefinition.getName()));
         }
-
         return propertyDefinition;
     }
 
index e4a1187..5bbf849 100644 (file)
@@ -17,7 +17,6 @@
  * limitations under the License.
  * ============LICENSE_END=========================================================
  */
-
 package org.openecomp.sdc.be.datamodel.utils;
 
 import static java.util.stream.Collectors.groupingBy;
@@ -63,19 +62,35 @@ import org.openecomp.sdc.common.log.wrappers.Logger;
 @org.springframework.stereotype.Component("uiComponentDataConverter")
 public class UiComponentDataConverter {
 
-    private static final Logger log = Logger.getLogger(UiComponentDataConverter.class);
     public static final String INVALID_INPUT_GIVEN_TO_DATA_CONVERTER = "Invalid input given to data converter: {}";
+    private static final Logger log = Logger.getLogger(UiComponentDataConverter.class);
     private final GroupTypeBusinessLogic groupTypeBusinessLogic;
     private final PolicyTypeBusinessLogic policyTypeBusinessLogic;
 
-    public UiComponentDataConverter(GroupTypeBusinessLogic groupTypeBusinessLogic,
-                                    PolicyTypeBusinessLogic policyTypeBusinessLogic) {
+    public UiComponentDataConverter(GroupTypeBusinessLogic groupTypeBusinessLogic, PolicyTypeBusinessLogic policyTypeBusinessLogic) {
         this.groupTypeBusinessLogic = groupTypeBusinessLogic;
         this.policyTypeBusinessLogic = policyTypeBusinessLogic;
     }
 
-    private void setUiTranferDataByFieldName(UiComponentDataTransfer dataTransfer, Component component,
-                                             String fieldName) {
+    public static UiComponentMetadata convertToUiComponentMetadata(Component component) {
+        UiComponentMetadata uiComponentMetadata = null;
+        switch (component.getComponentType()) {
+            case RESOURCE:
+                Resource resource = (Resource) component;
+                uiComponentMetadata = new UiResourceMetadata(component.getCategories(), resource.getDerivedFrom(),
+                    (ResourceMetadataDataDefinition) resource.getComponentMetadataDefinition().getMetadataDataDefinition());
+                break;
+            case SERVICE:
+                uiComponentMetadata = new UiServiceMetadata(component.getCategories(),
+                    (ServiceMetadataDataDefinition) component.getComponentMetadataDefinition().getMetadataDataDefinition());
+                break;
+            default:
+                break;
+        }
+        return uiComponentMetadata;
+    }
+
+    private void setUiTranferDataByFieldName(UiComponentDataTransfer dataTransfer, Component component, String fieldName) {
         ComponentFieldsEnum field = ComponentFieldsEnum.findByValue(fieldName);
         if (field == null) {
             log.error(INVALID_INPUT_GIVEN_TO_DATA_CONVERTER, fieldName);
@@ -161,8 +176,7 @@ public class UiComponentDataConverter {
         }
     }
 
-    private void setSubstitutionFilter(final UiComponentDataTransfer dataTransfer,
-                                       final Component component) {
+    private void setSubstitutionFilter(final UiComponentDataTransfer dataTransfer, final Component component) {
         if (component.getSubstitutionFilterComponents() == null) {
             dataTransfer.setSubstitutionFilter(null);
         } else {
@@ -172,34 +186,25 @@ public class UiComponentDataConverter {
 
     private void setPolicies(UiComponentDataTransfer dataTransfer, Component component) {
         Map<String, PolicyDefinition> policies = component.getPolicies();
-        Set<PolicyDefinition> policyDefinitions =
-            MapUtils.isEmpty(policies) ? new HashSet<>() : new HashSet<>(policies.values());
-
+        Set<PolicyDefinition> policyDefinitions = MapUtils.isEmpty(policies) ? new HashSet<>() : new HashSet<>(policies.values());
         policyDefinitions.addAll(getDeclaredPolicies(component.getComponentInstancesProperties()));
-
         dataTransfer.setPolicies(new ArrayList<>(policyDefinitions));
     }
 
-    private Set<PolicyDefinition> getDeclaredPolicies(
-        Map<String, List<ComponentInstanceProperty>> componentInstanceProperties) {
+    private Set<PolicyDefinition> getDeclaredPolicies(Map<String, List<ComponentInstanceProperty>> componentInstanceProperties) {
         if (MapUtils.isEmpty(componentInstanceProperties)) {
             return new HashSet<>();
         }
-
         Set<PolicyDefinition> declaredPolicies = new HashSet<>();
-        for (Map.Entry<String, List<ComponentInstanceProperty>> instancePropertyEntry : componentInstanceProperties
-            .entrySet()) {
-            declaredPolicies.addAll(instancePropertyEntry.getValue().stream()
-                .filter(property -> CollectionUtils.isNotEmpty(property.getGetPolicyValues()))
-                .map(instanceProperty -> PolicyUtils
-                    .getDeclaredPolicyDefinition(instancePropertyEntry.getKey(), instanceProperty))
-                .collect(Collectors.toSet()));
+        for (Map.Entry<String, List<ComponentInstanceProperty>> instancePropertyEntry : componentInstanceProperties.entrySet()) {
+            declaredPolicies.addAll(
+                instancePropertyEntry.getValue().stream().filter(property -> CollectionUtils.isNotEmpty(property.getGetPolicyValues()))
+                    .map(instanceProperty -> PolicyUtils.getDeclaredPolicyDefinition(instancePropertyEntry.getKey(), instanceProperty))
+                    .collect(Collectors.toSet()));
         }
-
         return declaredPolicies;
     }
 
-
     private void setComponentInstanceRelation(UiComponentDataTransfer dataTransfer, Component component) {
         if (component.getComponentInstancesRelations() == null) {
             dataTransfer.setComponentInstancesRelations(new ArrayList<>());
@@ -278,9 +283,7 @@ public class UiComponentDataConverter {
 
     private Map<String, List<CapabilityDefinition>> getFilteredCapabilities(Component component) {
         if (component.getComponentType() != ComponentTypeEnum.SERVICE) {
-            return component.getCapabilities().values()
-                .stream()
-                .flatMap(Collection::stream)
+            return component.getCapabilities().values().stream().flatMap(Collection::stream)
                 .filter(c -> c.getOwnerType() != CapabilityDataDefinition.OwnerType.GROUP)
                 .collect(groupingBy(CapabilityDefinition::getType, toList()));
         }
@@ -348,31 +351,23 @@ public class UiComponentDataConverter {
         if (groups == null) {
             dataTransfer.setGroups(new ArrayList<>());
         } else {
-            Set<String> nonExcludedGroupTypes = groupTypeBusinessLogic
-                .getExcludedGroupTypes(component.getActualComponentType());
-            List<GroupDefinition> nonExcludedGroups = groups.stream()
-                .filter(gd -> !nonExcludedGroupTypes.contains(gd.getType()))
-                .collect(toList());
+            Set<String> nonExcludedGroupTypes = groupTypeBusinessLogic.getExcludedGroupTypes(component.getActualComponentType());
+            List<GroupDefinition> nonExcludedGroups = groups.stream().filter(gd -> !nonExcludedGroupTypes.contains(gd.getType())).collect(toList());
             dataTransfer.setGroups(nonExcludedGroups);
         }
     }
 
     private void setNonExcludedPolicies(UiComponentDataTransfer dataTransfer, Component component) {
         List<PolicyDefinition> policyDefinitions = component.resolvePoliciesList();
-        Set<String> nonExcludedPolicyTypes = policyTypeBusinessLogic
-            .getExcludedPolicyTypes(component.getActualComponentType());
-        List<PolicyDefinition> nonExcludedPolicies = policyDefinitions.stream()
-            .filter(pd -> !nonExcludedPolicyTypes.contains(pd.getPolicyTypeName()))
+        Set<String> nonExcludedPolicyTypes = policyTypeBusinessLogic.getExcludedPolicyTypes(component.getActualComponentType());
+        List<PolicyDefinition> nonExcludedPolicies = policyDefinitions.stream().filter(pd -> !nonExcludedPolicyTypes.contains(pd.getPolicyTypeName()))
             .collect(toList());
         dataTransfer.setPolicies(nonExcludedPolicies);
     }
 
-    public UiComponentDataTransfer getUiDataTransferFromResourceByParams(Resource resource,
-                                                                         List<String> paramsToReturn) {
+    public UiComponentDataTransfer getUiDataTransferFromResourceByParams(Resource resource, List<String> paramsToReturn) {
         UiResourceDataTransfer dataTransfer = new UiResourceDataTransfer();
-
         for (String fieldName : paramsToReturn) {
-
             ComponentFieldsEnum field = ComponentFieldsEnum.findByValue(fieldName);
             if (field == null) {
                 log.error(INVALID_INPUT_GIVEN_TO_DATA_CONVERTER, fieldName);
@@ -386,10 +381,8 @@ public class UiComponentDataConverter {
                     setAdditionalInfo(resource, dataTransfer);
                     break;
                 case METADATA:
-                    UiResourceMetadata metadata = new UiResourceMetadata(resource.getCategories(),
-                        resource.getDerivedFrom(),
-                        (ResourceMetadataDataDefinition) resource.getComponentMetadataDefinition()
-                            .getMetadataDataDefinition());
+                    UiResourceMetadata metadata = new UiResourceMetadata(resource.getCategories(), resource.getDerivedFrom(),
+                        (ResourceMetadataDataDefinition) resource.getComponentMetadataDefinition().getMetadataDataDefinition());
                     dataTransfer.setMetadata(metadata);
                     break;
                 case SUBSTITUTION_FILTER:
@@ -398,27 +391,22 @@ public class UiComponentDataConverter {
                     } else {
                         final SubstitutionFilterConverter substitutionFilterConverter = new SubstitutionFilterConverter();
                         final Map<String, UINodeFilter> filterUiMap = new HashMap<>();
-                        filterUiMap.put(resource.getUniqueId(),
-                            substitutionFilterConverter.convertToUi(resource.getSubstitutionFilter()));
+                        filterUiMap.put(resource.getUniqueId(), substitutionFilterConverter.convertToUi(resource.getSubstitutionFilter()));
                         dataTransfer.setSubstitutionFilterForTopologyTemplate(filterUiMap);
                     }
                     break;
-
                 case NODE_FILTER:
                     if (resource.getNodeFilterComponents() == null) {
                         dataTransfer.setNodeFilterforNode(null);
                     } else {
                         final NodeFilterConverter nodeFilterConverter = new NodeFilterConverter();
-                        dataTransfer.setNodeFilterforNode(
-                            nodeFilterConverter.convertDataMapToUI(resource.getNodeFilterComponents()));
+                        dataTransfer.setNodeFilterforNode(nodeFilterConverter.convertDataMapToUI(resource.getNodeFilterComponents()));
                     }
                     break;
-
                 default:
                     setUiTranferDataByFieldName(dataTransfer, resource, fieldName);
             }
         }
-
         return dataTransfer;
     }
 
@@ -455,8 +443,7 @@ public class UiComponentDataConverter {
                     break;
                 case METADATA:
                     UiServiceMetadata metadata = new UiServiceMetadata(service.getCategories(),
-                        (ServiceMetadataDataDefinition) service.getComponentMetadataDefinition()
-                            .getMetadataDataDefinition());
+                        (ServiceMetadataDataDefinition) service.getComponentMetadataDefinition().getMetadataDataDefinition());
                     dataTransfer.setMetadata(metadata);
                     break;
                 case NODE_FILTER:
@@ -464,8 +451,7 @@ public class UiComponentDataConverter {
                         dataTransfer.setNodeFilterforNode(null);
                     } else {
                         final NodeFilterConverter nodeFilterConverter = new NodeFilterConverter();
-                        dataTransfer.setNodeFilterforNode(
-                            nodeFilterConverter.convertDataMapToUI(service.getNodeFilterComponents()));
+                        dataTransfer.setNodeFilterforNode(nodeFilterConverter.convertDataMapToUI(service.getNodeFilterComponents()));
                     }
                     break;
                 case SUBSTITUTION_FILTER:
@@ -474,8 +460,7 @@ public class UiComponentDataConverter {
                     } else {
                         final SubstitutionFilterConverter substitutionFilterConverter = new SubstitutionFilterConverter();
                         final Map<String, UINodeFilter> filterUiMap = new HashMap<>();
-                        filterUiMap.put(service.getUniqueId(),
-                            substitutionFilterConverter.convertToUi(service.getSubstitutionFilter()));
+                        filterUiMap.put(service.getUniqueId(), substitutionFilterConverter.convertToUi(service.getSubstitutionFilter()));
                         dataTransfer.setSubstitutionFilterForTopologyTemplate(filterUiMap);
                     }
                     break;
@@ -501,25 +486,4 @@ public class UiComponentDataConverter {
             dataTransfer.setForwardingPaths(service.getForwardingPaths());
         }
     }
-
-    public static UiComponentMetadata convertToUiComponentMetadata(Component component) {
-
-        UiComponentMetadata uiComponentMetadata = null;
-        switch (component.getComponentType()) {
-            case RESOURCE:
-                Resource resource = (Resource) component;
-                uiComponentMetadata = new UiResourceMetadata(component.getCategories(), resource.getDerivedFrom(),
-                    (ResourceMetadataDataDefinition) resource.getComponentMetadataDefinition()
-                        .getMetadataDataDefinition());
-                break;
-            case SERVICE:
-                uiComponentMetadata = new UiServiceMetadata(component.getCategories(),
-                    (ServiceMetadataDataDefinition) component.getComponentMetadataDefinition()
-                        .getMetadataDataDefinition());
-                break;
-            default:
-                break;
-        }
-        return uiComponentMetadata;
-    }
 }
index c8c2d94..87355df 100644 (file)
@@ -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.
@@ -17,7 +17,6 @@
  * limitations under the License.
  * ============LICENSE_END=========================================================
  */
-
 package org.openecomp.sdc.be.distribution;
 
 import org.openecomp.sdc.be.components.distribution.engine.CambriaErrorResponse;
@@ -28,6 +27,7 @@ import org.openecomp.sdc.be.resources.data.auditing.AuditingActionEnum;
 import org.openecomp.sdc.be.resources.data.auditing.model.DistributionTopicData;
 
 public class AuditHandler {
+
     private ComponentsUtils componentsUtils;
     private String instanceID;
     private RegistrationRequest registrationRequest;
@@ -39,23 +39,30 @@ public class AuditHandler {
         this.registrationRequest = registrationRequest;
     }
 
-
-    public void auditRegisterACL(CambriaErrorResponse registerResponse, SubscriberTypeEnum subscriberRole , DistributionTopicData distributionTopicData) {
-        componentsUtils.auditDistributionEngine(AuditingActionEnum.ADD_KEY_TO_TOPIC_ACL, registrationRequest.getDistrEnvName(), distributionTopicData, subscriberRole.name(), registrationRequest.getApiPublicKey(), String.valueOf(registerResponse.getHttpCode()));
+    public void auditRegisterACL(CambriaErrorResponse registerResponse, SubscriberTypeEnum subscriberRole,
+                                 DistributionTopicData distributionTopicData) {
+        componentsUtils.auditDistributionEngine(AuditingActionEnum.ADD_KEY_TO_TOPIC_ACL, registrationRequest.getDistrEnvName(), distributionTopicData,
+            subscriberRole.name(), registrationRequest.getApiPublicKey(), String.valueOf(registerResponse.getHttpCode()));
     }
 
-    public void auditUnRegisterACL(CambriaErrorResponse registerResponse, SubscriberTypeEnum subscriberRole, DistributionTopicData distributionTopicData) {
-        componentsUtils.auditDistributionEngine(AuditingActionEnum.REMOVE_KEY_FROM_TOPIC_ACL, registrationRequest.getDistrEnvName(), distributionTopicData, subscriberRole.name(), registrationRequest.getApiPublicKey(), String.valueOf(registerResponse.getHttpCode()));
+    public void auditUnRegisterACL(CambriaErrorResponse registerResponse, SubscriberTypeEnum subscriberRole,
+                                   DistributionTopicData distributionTopicData) {
+        componentsUtils
+            .auditDistributionEngine(AuditingActionEnum.REMOVE_KEY_FROM_TOPIC_ACL, registrationRequest.getDistrEnvName(), distributionTopicData,
+                subscriberRole.name(), registrationRequest.getApiPublicKey(), String.valueOf(registerResponse.getHttpCode()));
     }
 
     public void auditRegisterRequest(CambriaErrorResponse registerResponse) {
-        componentsUtils.auditRegisterOrUnRegisterEvent(AuditingActionEnum.DISTRIBUTION_REGISTER, instanceID, registrationRequest.getApiPublicKey(), registrationRequest.getDistrEnvName(), String.valueOf(registerResponse.getHttpCode()),
-                registerResponse.getOperationStatus().name(), DistributionBusinessLogic.getNotificationTopicName(registrationRequest.getDistrEnvName()), DistributionBusinessLogic.getStatusTopicName(registrationRequest.getDistrEnvName()));
-
+        componentsUtils.auditRegisterOrUnRegisterEvent(AuditingActionEnum.DISTRIBUTION_REGISTER, instanceID, registrationRequest.getApiPublicKey(),
+            registrationRequest.getDistrEnvName(), String.valueOf(registerResponse.getHttpCode()), registerResponse.getOperationStatus().name(),
+            DistributionBusinessLogic.getNotificationTopicName(registrationRequest.getDistrEnvName()),
+            DistributionBusinessLogic.getStatusTopicName(registrationRequest.getDistrEnvName()));
     }
 
     public void auditUnRegisterRequest(CambriaErrorResponse registerResponse) {
-        componentsUtils.auditRegisterOrUnRegisterEvent(AuditingActionEnum.DISTRIBUTION_UN_REGISTER, instanceID, registrationRequest.getApiPublicKey(), registrationRequest.getDistrEnvName(), String.valueOf(registerResponse.getHttpCode()),
-                registerResponse.getOperationStatus().name(), DistributionBusinessLogic.getNotificationTopicName(registrationRequest.getDistrEnvName()), DistributionBusinessLogic.getStatusTopicName(registrationRequest.getDistrEnvName()));
+        componentsUtils.auditRegisterOrUnRegisterEvent(AuditingActionEnum.DISTRIBUTION_UN_REGISTER, instanceID, registrationRequest.getApiPublicKey(),
+            registrationRequest.getDistrEnvName(), String.valueOf(registerResponse.getHttpCode()), registerResponse.getOperationStatus().name(),
+            DistributionBusinessLogic.getNotificationTopicName(registrationRequest.getDistrEnvName()),
+            DistributionBusinessLogic.getStatusTopicName(registrationRequest.getDistrEnvName()));
     }
 }
index 81c41bc..d293e9b 100644 (file)
@@ -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.
  * limitations under the License.
  * ============LICENSE_END=========================================================
  */
-
 package org.openecomp.sdc.be.distribution;
 
+import static org.apache.commons.lang.BooleanUtils.isTrue;
+import static org.openecomp.sdc.be.components.distribution.engine.DistributionEngineInitTask.buildTopicName;
+import static org.openecomp.sdc.be.config.ConfigurationManager.getConfigurationManager;
+
 import com.google.gson.Gson;
 import com.google.gson.GsonBuilder;
 import fj.data.Either;
+import java.util.List;
+import javax.annotation.Resource;
+import javax.ws.rs.core.Response;
 import org.apache.commons.collections.CollectionUtils;
 import org.apache.http.HttpStatus;
 import org.openecomp.sdc.be.components.distribution.engine.CambriaErrorResponse;
@@ -47,29 +53,31 @@ import org.openecomp.sdc.common.log.wrappers.Logger;
 import org.openecomp.sdc.exception.ResponseFormat;
 import org.springframework.stereotype.Component;
 
-import javax.annotation.Resource;
-import javax.ws.rs.core.Response;
-import java.util.List;
-
-import static org.apache.commons.lang.BooleanUtils.isTrue;
-import static org.openecomp.sdc.be.components.distribution.engine.DistributionEngineInitTask.buildTopicName;
-import static org.openecomp.sdc.be.config.ConfigurationManager.getConfigurationManager;
-
 @Component("distributionBusinessLogic")
 public class DistributionBusinessLogic {
+
     public static final String REGISTER_IN_DISTRIBUTION_ENGINE = "registerInDistributionEngine";
     public static final String UN_REGISTER_IN_DISTRIBUTION_ENGINE = "unregisterInDistributionEngine";
-    private Gson gson = new GsonBuilder().setPrettyPrinting().create();
     private static final Logger log = Logger.getLogger(DistributionBusinessLogic.class);
+    private Gson gson = new GsonBuilder().setPrettyPrinting().create();
     @Resource
     private IDistributionEngine distributionEngine;
-
     private ResponseFormatManager responseFormatManager = ResponseFormatManager.getInstance();
     @Resource
     private ICambriaHandler cambriaHandler;
 
+    public static String getNotificationTopicName(String envName) {
+        DistributionEngineConfiguration config = ConfigurationManager.getConfigurationManager().getDistributionEngineConfiguration();
+        return DistributionEngineInitTask.buildTopicName(config.getDistributionNotifTopicName(), envName);
+    }
+
+    public static String getStatusTopicName(String envName) {
+        DistributionEngineConfiguration config = ConfigurationManager.getConfigurationManager().getDistributionEngineConfiguration();
+        return DistributionEngineInitTask.buildTopicName(config.getDistributionStatusTopicName(), envName);
+    }
+
     private void initRequestEnvEndPointsAndKeys(RegistrationRequest registrationRequest, DistributionEngineConfiguration config) {
-        if(CollectionUtils.isEmpty(registrationRequest.getDistEnvEndPoints())){
+        if (CollectionUtils.isEmpty(registrationRequest.getDistEnvEndPoints())) {
             registrationRequest.setDistEnvEndPoints(config.getUebServers());
             registrationRequest.setManagerApiPublicKey(config.getUebPublicKey());
             registrationRequest.setManagerApiSecretKey(config.getUebSecretKey());
@@ -79,210 +87,148 @@ public class DistributionBusinessLogic {
             registrationRequest.setManagerApiSecretKey(environment.getUebSecretKey());
         }
     }
-    public Either<ServerListResponse, ResponseFormat> getUebServerList() {
 
+    public Either<ServerListResponse, ResponseFormat> getUebServerList() {
         DistributionEngineConfiguration distributionEngineConfiguration = ConfigurationManager.getConfigurationManager()
-                .getDistributionEngineConfiguration();
-
+            .getDistributionEngineConfiguration();
         List<String> serverList = distributionEngineConfiguration.getUebServers();
-
         if (serverList != null && !serverList.isEmpty()) {
-
             ServerListResponse serverListResponse = new ServerListResponse();
-
             serverListResponse.setUebServerList(serverList);
-
             return Either.left(serverListResponse);
         } else {
-            ResponseFormat errorResponseWrapper = getResponseFormatManager()
-                    .getResponseFormat(ActionStatus.GENERAL_ERROR);
+            ResponseFormat errorResponseWrapper = getResponseFormatManager().getResponseFormat(ActionStatus.GENERAL_ERROR);
             return Either.right(errorResponseWrapper);
         }
-
     }
 
-    public void handleRegistration(Wrapper<Response> responseWrapper, RegistrationRequest registrationRequest,
-            AuditHandler auditHandler) {
+    public void handleRegistration(Wrapper<Response> responseWrapper, RegistrationRequest registrationRequest, AuditHandler auditHandler) {
         CambriaErrorResponse registerResponse = null;
         try {
             DistributionEngineConfiguration config = getConfigurationManager().getDistributionEngineConfiguration();
-            String statusTopicName = buildTopicName(config.getDistributionStatusTopicName(),
-                    registrationRequest.getDistrEnvName());
+            String statusTopicName = buildTopicName(config.getDistributionStatusTopicName(), registrationRequest.getDistrEnvName());
             initRequestEnvEndPointsAndKeys(registrationRequest, config);
-            registerResponse = registerDistributionClientToTopic(responseWrapper, registrationRequest,
-                    SubscriberTypeEnum.PRODUCER, statusTopicName);
-
+            registerResponse = registerDistributionClientToTopic(responseWrapper, registrationRequest, SubscriberTypeEnum.PRODUCER, statusTopicName);
             auditHandler.auditRegisterACL(registerResponse, SubscriberTypeEnum.PRODUCER,
-                    DistributionTopicData.newBuilder()
-                        .statusTopic(statusTopicName)
-                        .build());
+                DistributionTopicData.newBuilder().statusTopic(statusTopicName).build());
             boolean isRegisteredAsProducerOnStatusSuccess = responseWrapper.isEmpty();
-
             // Story [347698] Distribution Client Get Indication from
+
             // component whether to register as consumer and producer on
+
             // status topic
             boolean registeredAsConsumerOnStatus = false;
             if (isRegisteredAsProducerOnStatusSuccess && isTrue(registrationRequest.getIsConsumerToSdcDistrStatusTopic())) {
-                registerResponse = registerDistributionClientToTopic(responseWrapper, registrationRequest,
-                        SubscriberTypeEnum.CONSUMER, statusTopicName);
+                registerResponse = registerDistributionClientToTopic(responseWrapper, registrationRequest, SubscriberTypeEnum.CONSUMER,
+                    statusTopicName);
                 auditHandler.auditRegisterACL(registerResponse, SubscriberTypeEnum.CONSUMER,
-                        DistributionTopicData.newBuilder()
-                                .statusTopic(statusTopicName)
-                                .build());
+                    DistributionTopicData.newBuilder().statusTopic(statusTopicName).build());
                 registeredAsConsumerOnStatus = responseWrapper.isEmpty();
-
             }
-
             if (responseWrapper.isEmpty()) {
-                String notificationTopicName = buildTopicName(config.getDistributionNotifTopicName(),
-                        registrationRequest.getDistrEnvName());
-                registerResponse = registerDistributionClientToTopic(responseWrapper, registrationRequest,
-                        SubscriberTypeEnum.CONSUMER, notificationTopicName);
+                String notificationTopicName = buildTopicName(config.getDistributionNotifTopicName(), registrationRequest.getDistrEnvName());
+                registerResponse = registerDistributionClientToTopic(responseWrapper, registrationRequest, SubscriberTypeEnum.CONSUMER,
+                    notificationTopicName);
                 auditHandler.auditRegisterACL(registerResponse, SubscriberTypeEnum.CONSUMER,
-                        DistributionTopicData.newBuilder()
-                            .notificationTopic(notificationTopicName)
-                            .build());
+                    DistributionTopicData.newBuilder().notificationTopic(notificationTopicName).build());
             }
             // Unregister Rollback
             if (!responseWrapper.isEmpty()) {
                 if (isRegisteredAsProducerOnStatusSuccess) {
-                    CambriaErrorResponse unRegisterResponse = unRegisterDistributionClientFromTopic(registrationRequest,
-                            SubscriberTypeEnum.PRODUCER, statusTopicName);
+                    CambriaErrorResponse unRegisterResponse = unRegisterDistributionClientFromTopic(registrationRequest, SubscriberTypeEnum.PRODUCER,
+                        statusTopicName);
                     auditHandler.auditUnRegisterACL(unRegisterResponse, SubscriberTypeEnum.PRODUCER,
-                            DistributionTopicData.newBuilder()
-                                    .statusTopic(statusTopicName)
-                                    .build());
+                        DistributionTopicData.newBuilder().statusTopic(statusTopicName).build());
                 }
                 if (registeredAsConsumerOnStatus) {
-                    CambriaErrorResponse unRegisterResponse = unRegisterDistributionClientFromTopic(registrationRequest,
-                            SubscriberTypeEnum.CONSUMER, statusTopicName);
+                    CambriaErrorResponse unRegisterResponse = unRegisterDistributionClientFromTopic(registrationRequest, SubscriberTypeEnum.CONSUMER,
+                        statusTopicName);
                     auditHandler.auditUnRegisterACL(unRegisterResponse, SubscriberTypeEnum.CONSUMER,
-                            DistributionTopicData.newBuilder()
-                            .statusTopic(statusTopicName)
-                            .build());
+                        DistributionTopicData.newBuilder().statusTopic(statusTopicName).build());
                 }
             }
-
             if (responseWrapper.isEmpty()) {
                 TopicRegistrationResponse okTopicResponse = buildTopicResponse(registrationRequest);
                 responseWrapper.setInnerElement(Response.status(HttpStatus.SC_OK).entity(okTopicResponse).build());
             }
-
         } catch (Exception e) {
             log.error("registration to topic failed", e);
-            BeEcompErrorManager.getInstance().logBeDistributionEngineSystemError(REGISTER_IN_DISTRIBUTION_ENGINE,
-                    "registration of subscriber to topic");
-            Response errorResponse = buildErrorResponse(
-                    getResponseFormatManager().getResponseFormat(ActionStatus.GENERAL_ERROR));
+            BeEcompErrorManager.getInstance()
+                .logBeDistributionEngineSystemError(REGISTER_IN_DISTRIBUTION_ENGINE, "registration of subscriber to topic");
+            Response errorResponse = buildErrorResponse(getResponseFormatManager().getResponseFormat(ActionStatus.GENERAL_ERROR));
             responseWrapper.setInnerElement(errorResponse);
         } finally {
             auditHandler.auditRegisterRequest(registerResponse);
         }
     }
 
-    public void handleUnRegistration(Wrapper<Response> responseWrapper, RegistrationRequest unRegistrationRequest,
-            AuditHandler auditHandler) {
+    public void handleUnRegistration(Wrapper<Response> responseWrapper, RegistrationRequest unRegistrationRequest, AuditHandler auditHandler) {
         Wrapper<CambriaErrorResponse> cambriaResponseWrapper = new Wrapper<>();
         try {
             String statusTopicName = getStatusTopicName(unRegistrationRequest.getDistrEnvName());
-            DistributionEngineConfiguration config = ConfigurationManager.getConfigurationManager()
-                    .getDistributionEngineConfiguration();
+            DistributionEngineConfiguration config = ConfigurationManager.getConfigurationManager().getDistributionEngineConfiguration();
             initRequestEnvEndPointsAndKeys(unRegistrationRequest, config);
-            CambriaErrorResponse unregisterClientProducerTopicResponse = unRegisterDistributionClientFromTopic(
-                    unRegistrationRequest, SubscriberTypeEnum.PRODUCER, statusTopicName);
+            CambriaErrorResponse unregisterClientProducerTopicResponse = unRegisterDistributionClientFromTopic(unRegistrationRequest,
+                SubscriberTypeEnum.PRODUCER, statusTopicName);
             auditHandler.auditUnRegisterACL(unregisterClientProducerTopicResponse, SubscriberTypeEnum.PRODUCER,
-                    DistributionTopicData.newBuilder()
-                            .statusTopic(statusTopicName)
-                            .build());
+                DistributionTopicData.newBuilder().statusTopic(statusTopicName).build());
             updateResponseWrapper(cambriaResponseWrapper, unregisterClientProducerTopicResponse);
-
             String notificationTopicName = getNotificationTopicName(unRegistrationRequest.getDistrEnvName());
-            CambriaErrorResponse unregisterClientConsumerTopicResponse = unRegisterDistributionClientFromTopic(
-                    unRegistrationRequest, SubscriberTypeEnum.CONSUMER, notificationTopicName);
+            CambriaErrorResponse unregisterClientConsumerTopicResponse = unRegisterDistributionClientFromTopic(unRegistrationRequest,
+                SubscriberTypeEnum.CONSUMER, notificationTopicName);
             auditHandler.auditUnRegisterACL(unregisterClientConsumerTopicResponse, SubscriberTypeEnum.CONSUMER,
-                    DistributionTopicData.newBuilder()
-                            .notificationTopic(notificationTopicName)
-                            .build());
+                DistributionTopicData.newBuilder().notificationTopic(notificationTopicName).build());
             updateResponseWrapper(cambriaResponseWrapper, unregisterClientConsumerTopicResponse);
-
             // Success unregister both topics
             TopicUnregistrationResponse unregisterResponse = new TopicUnregistrationResponse(
-                    getNotificationTopicName(unRegistrationRequest.getDistrEnvName()),
-                    getStatusTopicName(unRegistrationRequest.getDistrEnvName()),
-                    unregisterClientConsumerTopicResponse.getOperationStatus(),
-                    unregisterClientProducerTopicResponse.getOperationStatus());
-
+                getNotificationTopicName(unRegistrationRequest.getDistrEnvName()), getStatusTopicName(unRegistrationRequest.getDistrEnvName()),
+                unregisterClientConsumerTopicResponse.getOperationStatus(), unregisterClientProducerTopicResponse.getOperationStatus());
             if (cambriaResponseWrapper.getInnerElement().getOperationStatus() == CambriaOperationStatus.OK) {
                 responseWrapper.setInnerElement(Response.status(HttpStatus.SC_OK).entity(unregisterResponse).build());
             } else {
-                BeEcompErrorManager.getInstance().logBeDistributionEngineSystemError(UN_REGISTER_IN_DISTRIBUTION_ENGINE,
-                        "unregistration failed");
-                responseWrapper.setInnerElement(
-                        Response.status(HttpStatus.SC_INTERNAL_SERVER_ERROR).entity(unregisterResponse).build());
+                BeEcompErrorManager.getInstance().logBeDistributionEngineSystemError(UN_REGISTER_IN_DISTRIBUTION_ENGINE, "unregistration failed");
+                responseWrapper.setInnerElement(Response.status(HttpStatus.SC_INTERNAL_SERVER_ERROR).entity(unregisterResponse).build());
             }
         } catch (Exception e) {
             log.error("unregistered to topic failed", e);
-            Response errorResponse = buildErrorResponse(
-                    getResponseFormatManager().getResponseFormat(ActionStatus.GENERAL_ERROR));
+            Response errorResponse = buildErrorResponse(getResponseFormatManager().getResponseFormat(ActionStatus.GENERAL_ERROR));
             responseWrapper.setInnerElement(errorResponse);
-
         } finally {
             auditHandler.auditUnRegisterRequest(cambriaResponseWrapper.getInnerElement());
         }
     }
 
-    private void updateResponseWrapper(Wrapper<CambriaErrorResponse> cambriaResponseWrapper,
-            CambriaErrorResponse currentResponse) {
+    private void updateResponseWrapper(Wrapper<CambriaErrorResponse> cambriaResponseWrapper, CambriaErrorResponse currentResponse) {
         if (cambriaResponseWrapper.isEmpty()) {
             cambriaResponseWrapper.setInnerElement(currentResponse);
         } else if (currentResponse.getOperationStatus() != CambriaOperationStatus.OK) {
             cambriaResponseWrapper.setInnerElement(currentResponse);
-
         }
-
     }
 
-    public static String getNotificationTopicName(String envName) {
-        DistributionEngineConfiguration config = ConfigurationManager.getConfigurationManager()
-                .getDistributionEngineConfiguration();
-        return DistributionEngineInitTask.buildTopicName(config.getDistributionNotifTopicName(), envName);
-
-    }
-
-    public static String getStatusTopicName(String envName) {
-        DistributionEngineConfiguration config = ConfigurationManager.getConfigurationManager()
-                .getDistributionEngineConfiguration();
-        return DistributionEngineInitTask.buildTopicName(config.getDistributionStatusTopicName(), envName);
-
-    }
-
-    protected CambriaErrorResponse unRegisterDistributionClientFromTopic(RegistrationRequest unRegistrationRequest,
-            SubscriberTypeEnum subscriberType, String topicName) {
-
-        log.debug("unregistering client as {} , from topic: {}, using DistEnvPoints: {}", subscriberType, topicName, unRegistrationRequest.getDistEnvEndPoints());
+    protected CambriaErrorResponse unRegisterDistributionClientFromTopic(RegistrationRequest unRegistrationRequest, SubscriberTypeEnum subscriberType,
+                                                                         String topicName) {
+        log.debug("unregistering client as {} , from topic: {}, using DistEnvPoints: {}", subscriberType, topicName,
+            unRegistrationRequest.getDistEnvEndPoints());
         return cambriaHandler.unRegisterFromTopic(unRegistrationRequest.getDistEnvEndPoints(), unRegistrationRequest.getManagerApiPublicKey(),
-                unRegistrationRequest.getManagerApiSecretKey(), unRegistrationRequest.getApiPublicKey(), subscriberType, topicName);
+            unRegistrationRequest.getManagerApiSecretKey(), unRegistrationRequest.getApiPublicKey(), subscriberType, topicName);
     }
 
     private TopicRegistrationResponse buildTopicResponse(RegistrationRequest registrationRequest) {
-        DistributionEngineConfiguration config = ConfigurationManager.getConfigurationManager()
-                .getDistributionEngineConfiguration();
-        String statusTopicName = DistributionEngineInitTask.buildTopicName(config.getDistributionStatusTopicName(),
-                registrationRequest.getDistrEnvName());
-        String notificationTopicName = DistributionEngineInitTask.buildTopicName(config.getDistributionNotifTopicName(),
-                registrationRequest.getDistrEnvName());
-
+        DistributionEngineConfiguration config = ConfigurationManager.getConfigurationManager().getDistributionEngineConfiguration();
+        String statusTopicName = DistributionEngineInitTask
+            .buildTopicName(config.getDistributionStatusTopicName(), registrationRequest.getDistrEnvName());
+        String notificationTopicName = DistributionEngineInitTask
+            .buildTopicName(config.getDistributionNotifTopicName(), registrationRequest.getDistrEnvName());
         TopicRegistrationResponse topicResponse = new TopicRegistrationResponse();
         topicResponse.setDistrNotificationTopicName(notificationTopicName);
         topicResponse.setDistrStatusTopicName(statusTopicName);
         return topicResponse;
     }
 
-    protected CambriaErrorResponse registerDistributionClientToTopic(Wrapper<Response> responseWrapper,
-            RegistrationRequest registrationRequest, SubscriberTypeEnum subscriberType, String topicName) {
-
+    protected CambriaErrorResponse registerDistributionClientToTopic(Wrapper<Response> responseWrapper, RegistrationRequest registrationRequest,
+                                                                     SubscriberTypeEnum subscriberType, String topicName) {
         String errorMsg;
-
         // Register for notifications as consumer
         if (subscriberType == SubscriberTypeEnum.CONSUMER) {
             errorMsg = "registration of subscriber to topic:" + topicName + " as consumer failed";
@@ -291,24 +237,21 @@ public class DistributionBusinessLogic {
         else {
             errorMsg = "registration of subscriber to topic:" + topicName + " as producer failed";
         }
-        log.debug("registering client as {} , from topic: {}, using DistEnvPoints: {}", subscriberType, topicName, registrationRequest.getDistEnvEndPoints());
-        CambriaErrorResponse registerToTopic = cambriaHandler.registerToTopic(registrationRequest.getDistEnvEndPoints(),
-                registrationRequest.getManagerApiPublicKey(), registrationRequest.getManagerApiSecretKey(), registrationRequest.getApiPublicKey(),
-                subscriberType, topicName);
-
+        log.debug("registering client as {} , from topic: {}, using DistEnvPoints: {}", subscriberType, topicName,
+            registrationRequest.getDistEnvEndPoints());
+        CambriaErrorResponse registerToTopic = cambriaHandler
+            .registerToTopic(registrationRequest.getDistEnvEndPoints(), registrationRequest.getManagerApiPublicKey(),
+                registrationRequest.getManagerApiSecretKey(), registrationRequest.getApiPublicKey(), subscriberType, topicName);
         if (registerToTopic.getOperationStatus() != CambriaOperationStatus.OK) {
-            Response failedRegistrationResponse = buildErrorResponse(
-                    getResponseFormatManager().getResponseFormat(ActionStatus.GENERAL_ERROR));
-            BeEcompErrorManager.getInstance().logBeDistributionEngineSystemError(REGISTER_IN_DISTRIBUTION_ENGINE,
-                    errorMsg);
+            Response failedRegistrationResponse = buildErrorResponse(getResponseFormatManager().getResponseFormat(ActionStatus.GENERAL_ERROR));
+            BeEcompErrorManager.getInstance().logBeDistributionEngineSystemError(REGISTER_IN_DISTRIBUTION_ENGINE, errorMsg);
             responseWrapper.setInnerElement(failedRegistrationResponse);
         }
         return registerToTopic;
     }
 
     protected Response buildErrorResponse(ResponseFormat requestErrorWrapper) {
-        return Response.status(requestErrorWrapper.getStatus())
-                .entity(gson.toJson(requestErrorWrapper.getRequestError())).build();
+        return Response.status(requestErrorWrapper.getStatus()).entity(gson.toJson(requestErrorWrapper.getRequestError())).build();
     }
 
     public ResponseFormatManager getResponseFormatManager() {
@@ -318,5 +261,4 @@ public class DistributionBusinessLogic {
     public IDistributionEngine getDistributionEngine() {
         return distributionEngine;
     }
-
 }
index 3edb3d8..6fccd8e 100644 (file)
@@ -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.
@@ -17,9 +17,8 @@
  * limitations under the License.
  * ============LICENSE_END=========================================================
  */
-
 package org.openecomp.sdc.be.distribution.api.client;
 
 public enum CambriaOperationStatus {
-    OK, CONNNECTION_ERROR, NOT_FOUND, TOPIC_ALREADY_EXIST, OBJECT_NOT_FOUND, INTERNAL_SERVER_ERROR, AUTHENTICATION_ERROR, UNKNOWN_HOST_ERROR,
+    OK, CONNNECTION_ERROR, NOT_FOUND, TOPIC_ALREADY_EXIST, OBJECT_NOT_FOUND, INTERNAL_SERVER_ERROR, AUTHENTICATION_ERROR, UNKNOWN_HOST_ERROR
 }
index 1ce3621..4385d4d 100644 (file)
@@ -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.
@@ -17,7 +17,6 @@
  * limitations under the License.
  * ============LICENSE_END=========================================================
  */
-
 package org.openecomp.sdc.be.distribution.api.client;
 
 import java.util.List;
@@ -27,6 +26,7 @@ import lombok.Setter;
 @Getter
 @Setter
 public class RegistrationRequest {
+
     private String apiPublicKey;
     private String distrEnvName;
     private Boolean isConsumerToSdcDistrStatusTopic;
@@ -39,7 +39,8 @@ public class RegistrationRequest {
         this.distrEnvName = distrEnvName;
         this.isConsumerToSdcDistrStatusTopic = isConsumerToSdcDistrStatusTopic;
     }
-    public RegistrationRequest(String apiPublicKey, String distrEnvName, List<String> distEnvEndPoints, boolean isConsumerToSdcDistrStatusTopic){
+
+    public RegistrationRequest(String apiPublicKey, String distrEnvName, List<String> distEnvEndPoints, boolean isConsumerToSdcDistrStatusTopic) {
         this.apiPublicKey = apiPublicKey;
         this.distrEnvName = distrEnvName;
         this.distEnvEndPoints = distEnvEndPoints;
index b0db19f..6062890 100644 (file)
@@ -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.
@@ -17,7 +17,6 @@
  * limitations under the License.
  * ============LICENSE_END=========================================================
  */
-
 package org.openecomp.sdc.be.distribution.api.client;
 
 import java.util.List;
@@ -29,5 +28,6 @@ import lombok.Setter;
 @Setter
 @NoArgsConstructor(force = true)
 public class ServerListResponse {
+
     private List<String> uebServerList;
 }
index 6b3e9e1..7612d1f 100644 (file)
@@ -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.
@@ -17,7 +17,6 @@
  * limitations under the License.
  * ============LICENSE_END=========================================================
  */
-
 package org.openecomp.sdc.be.distribution.api.client;
 
 import lombok.Getter;
@@ -28,6 +27,7 @@ import lombok.Setter;
 @Setter
 @NoArgsConstructor(force = true)
 public class TopicRegistrationResponse {
+
     String distrNotificationTopicName;
     String distrStatusTopicName;
 }
index 55c3bae..337b347 100644 (file)
@@ -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.
  * limitations under the License.
  * ============LICENSE_END=========================================================
  */
-
 package org.openecomp.sdc.be.distribution.api.client;
 
 import lombok.Getter;
 
 @Getter
 public class TopicUnregistrationResponse {
+
     String distrNotificationTopicName;
     String distrStatusTopicName;
     CambriaOperationStatus notificationUnregisterResult;
     CambriaOperationStatus statusUnregisterResult;
 
-    public TopicUnregistrationResponse(String distrNotificationTopicName, String distrStatusTopicName, CambriaOperationStatus notificationUnregisterResult, CambriaOperationStatus statusUnregisterResult) {
+    public TopicUnregistrationResponse(String distrNotificationTopicName, String distrStatusTopicName,
+                                       CambriaOperationStatus notificationUnregisterResult, CambriaOperationStatus statusUnregisterResult) {
         super();
         this.distrNotificationTopicName = distrNotificationTopicName;
         this.distrStatusTopicName = distrStatusTopicName;
index f0d329e..e0fb335 100644 (file)
@@ -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,7 +19,6 @@
  * Modifications copyright (c) 2019 Nokia
  * ================================================================================
  */
-
 package org.openecomp.sdc.be.distribution.servlet;
 
 import com.jcabi.aspects.Loggable;
@@ -33,6 +32,22 @@ import io.swagger.v3.oas.annotations.servers.Server;
 import io.swagger.v3.oas.annotations.servers.Servers;
 import io.swagger.v3.oas.annotations.tags.Tag;
 import io.swagger.v3.oas.annotations.tags.Tags;
+import java.io.ByteArrayInputStream;
+import java.io.InputStream;
+import java.util.HashMap;
+import java.util.Map;
+import javax.inject.Inject;
+import javax.inject.Singleton;
+import javax.servlet.http.HttpServletRequest;
+import javax.ws.rs.Consumes;
+import javax.ws.rs.GET;
+import javax.ws.rs.HeaderParam;
+import javax.ws.rs.Path;
+import javax.ws.rs.PathParam;
+import javax.ws.rs.Produces;
+import javax.ws.rs.core.Context;
+import javax.ws.rs.core.MediaType;
+import javax.ws.rs.core.Response;
 import org.openecomp.sdc.be.components.impl.ArtifactsBusinessLogic;
 import org.openecomp.sdc.be.components.impl.aaf.AafPermission;
 import org.openecomp.sdc.be.components.impl.aaf.PermissionAllowed;
@@ -48,30 +63,11 @@ import org.openecomp.sdc.common.datastructure.Wrapper;
 import org.openecomp.sdc.common.log.wrappers.Logger;
 import org.openecomp.sdc.exception.ResponseFormat;
 
-import javax.inject.Inject;
-import javax.inject.Singleton;
-import javax.servlet.http.HttpServletRequest;
-import javax.ws.rs.Consumes;
-import javax.ws.rs.GET;
-import javax.ws.rs.HeaderParam;
-import javax.ws.rs.Path;
-import javax.ws.rs.PathParam;
-import javax.ws.rs.Produces;
-import javax.ws.rs.core.Context;
-import javax.ws.rs.core.MediaType;
-import javax.ws.rs.core.Response;
-import java.io.ByteArrayInputStream;
-import java.io.InputStream;
-import java.util.HashMap;
-import java.util.Map;
-
 /**
  * This Servlet serves external users to download artifacts.
- * 
- * @author tgitelman
  *
+ * @author tgitelman
  */
-
 @Loggable(prepend = true, value = Loggable.DEBUG, trim = false)
 @Path("/v1/catalog")
 @Tags({@Tag(name = "SDC Distribution APIs")})
@@ -80,26 +76,22 @@ import java.util.Map;
 public class DistributionCatalogServlet extends BeGenericServlet {
 
     private static final String DOWNLOAD_ARTIFACT_FAILED_WITH_EXCEPTION = "download artifact failed with exception";
-       private static final String MISSING_X_ECOMP_INSTANCE_ID_HEADER = "Missing X-ECOMP-InstanceID header";
-       private static final Logger log = Logger.getLogger(DistributionCatalogServlet.class);
-       private final ArtifactsBusinessLogic artifactsBusinessLogic;
+    private static final String MISSING_X_ECOMP_INSTANCE_ID_HEADER = "Missing X-ECOMP-InstanceID header";
+    private static final Logger log = Logger.getLogger(DistributionCatalogServlet.class);
+    private final ArtifactsBusinessLogic artifactsBusinessLogic;
+    @Context
+    private HttpServletRequest request;
 
-       @Inject
-    public DistributionCatalogServlet(UserBusinessLogic userBusinessLogic,
-        ComponentsUtils componentsUtils,
-        ArtifactsBusinessLogic artifactsBusinessLogic) {
+    @Inject
+    public DistributionCatalogServlet(UserBusinessLogic userBusinessLogic, ComponentsUtils componentsUtils,
+                                      ArtifactsBusinessLogic artifactsBusinessLogic) {
         super(userBusinessLogic, componentsUtils);
         this.artifactsBusinessLogic = artifactsBusinessLogic;
     }
-
-    @Context
-    private HttpServletRequest request;
-
     // *******************************************************
     // Download (GET) artifacts
     // **********************************************************/
     /**
-     *
      * @param requestId
      * @param instanceIdHeader
      * @param accept
@@ -113,51 +105,39 @@ public class DistributionCatalogServlet extends BeGenericServlet {
     @Path("/services/{serviceName}/{serviceVersion}/artifacts/{artifactName}")
     @Consumes(MediaType.APPLICATION_JSON)
     @Produces(MediaType.APPLICATION_OCTET_STREAM)
-    @Operation(description = "Download service artifact", method = "GET", summary = "Returns downloaded artifact",
-            responses = {@ApiResponse(
-                    content = @Content(array = @ArraySchema(schema = @Schema(implementation = String.class)))),
-                    @ApiResponse(responseCode = "200", description = "The artifact is found and streamed.",
-                            content = @Content(array = @ArraySchema(schema = @Schema(implementation = String.class)))),
-                    @ApiResponse(responseCode = "400",
-                            description = "Missing  'X-ECOMP-InstanceID'  HTTP header - POL5001"),
-                    @ApiResponse(responseCode = "401",
-                            description = "ECOMP component  should authenticate itself  and  to  re-send  again  HTTP  request  with its Basic  Authentication credentials - POL5002"),
-                    @ApiResponse(responseCode = "403", description = "ECOMP component is not authorized - POL5003"),
-                    @ApiResponse(responseCode = "404", description = "Specified Service is not found - SVC4503"),
-                    @ApiResponse(responseCode = "404",
-                            description = "Specified Service Version is  not  found - SVC4504"),
-                    @ApiResponse(responseCode = "404", description = "Specified artifact is  not found - SVC4505"),
-                    @ApiResponse(responseCode = "405",
-                            description = "Method  Not Allowed: Invalid HTTP method type used (PUT,DELETE,POST will be rejected) - POL4050"),
-                    @ApiResponse(responseCode = "500",
-                            description = "The GET request failed either due to internal SDC problem or Cambria Service failure. ECOMP Component should continue the attempts to get the needed information - POL5000")})
+    @Operation(description = "Download service artifact", method = "GET", summary = "Returns downloaded artifact", responses = {
+        @ApiResponse(content = @Content(array = @ArraySchema(schema = @Schema(implementation = String.class)))),
+        @ApiResponse(responseCode = "200", description = "The artifact is found and streamed.", content = @Content(array = @ArraySchema(schema = @Schema(implementation = String.class)))),
+        @ApiResponse(responseCode = "400", description = "Missing  'X-ECOMP-InstanceID'  HTTP header - POL5001"),
+        @ApiResponse(responseCode = "401", description = "ECOMP component  should authenticate itself  and  to  re-send  again  HTTP  request  with its Basic  Authentication credentials - POL5002"),
+        @ApiResponse(responseCode = "403", description = "ECOMP component is not authorized - POL5003"),
+        @ApiResponse(responseCode = "404", description = "Specified Service is not found - SVC4503"),
+        @ApiResponse(responseCode = "404", description = "Specified Service Version is  not  found - SVC4504"),
+        @ApiResponse(responseCode = "404", description = "Specified artifact is  not found - SVC4505"),
+        @ApiResponse(responseCode = "405", description = "Method  Not Allowed: Invalid HTTP method type used (PUT,DELETE,POST will be rejected) - POL4050"),
+        @ApiResponse(responseCode = "500", description = "The GET request failed either due to internal SDC problem or Cambria Service failure. ECOMP Component should continue the attempts to get the needed information - POL5000")})
     @PermissionAllowed({AafPermission.PermNames.READ_VALUE})
     public Response downloadServiceArtifact(
-            @Parameter(description = "X-ECOMP-RequestID header", required = false)@HeaderParam(value = Constants.X_ECOMP_REQUEST_ID_HEADER) String requestId,
-            @Parameter(description = "X-ECOMP-InstanceID header", required = true)@HeaderParam(value = Constants.X_ECOMP_INSTANCE_ID_HEADER) final String instanceIdHeader,
-            @Parameter(description = "Determines the format of the body of the response", required = false)@HeaderParam(value = Constants.ACCEPT_HEADER) String accept,
-            @Parameter(description = "The username and password", required = true)@HeaderParam(value = Constants.AUTHORIZATION_HEADER) String authorization,
-            @PathParam("serviceName") final String serviceName,
-            @PathParam("serviceVersion") final String serviceVersion,
-            @PathParam("artifactName") final String artifactName) {
-
+        @Parameter(description = "X-ECOMP-RequestID header", required = false) @HeaderParam(value = Constants.X_ECOMP_REQUEST_ID_HEADER) String requestId,
+        @Parameter(description = "X-ECOMP-InstanceID header", required = true) @HeaderParam(value = Constants.X_ECOMP_INSTANCE_ID_HEADER) final String instanceIdHeader,
+        @Parameter(description = "Determines the format of the body of the response", required = false) @HeaderParam(value = Constants.ACCEPT_HEADER) String accept,
+        @Parameter(description = "The username and password", required = true) @HeaderParam(value = Constants.AUTHORIZATION_HEADER) String authorization,
+        @PathParam("serviceName") final String serviceName, @PathParam("serviceVersion") final String serviceVersion,
+        @PathParam("artifactName") final String artifactName) {
         String requestURI = request.getRequestURI();
         Wrapper<Response> responseWrapper = validateInstanceIdHeader(new Wrapper<>(), instanceIdHeader, requestURI);
-        if(!responseWrapper.isEmpty()) {
+        if (!responseWrapper.isEmpty()) {
             return responseWrapper.getInnerElement();
         }
-
         try {
             byte[] downloadRsrcArtifactEither = artifactsBusinessLogic.downloadServiceArtifactByNames(serviceName, serviceVersion, artifactName);
             byte[] value = downloadRsrcArtifactEither;
             InputStream is = new ByteArrayInputStream(value);
-
             Map<String, String> headers = new HashMap<>();
             headers.put(Constants.CONTENT_DISPOSITION_HEADER, getContentDispositionValue(artifactName));
             ResponseFormat responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.OK);
             getComponentsUtils().auditDistributionDownload(responseFormat, new DistributionData(instanceIdHeader, requestURI));
             return buildOkResponse(responseFormat, is, headers);
-
         } catch (ComponentException e) {
             getComponentsUtils().auditDistributionDownload(e.getResponseFormat(), new DistributionData(instanceIdHeader, requestURI));
             BeEcompErrorManager.getInstance().logBeRestApiGeneralError("download Murano package artifact for service - external API");
@@ -177,7 +157,6 @@ public class DistributionCatalogServlet extends BeGenericServlet {
     }
 
     /**
-     *
      * @param requestId
      * @param instanceIdHeader
      * @param accept
@@ -193,48 +172,36 @@ public class DistributionCatalogServlet extends BeGenericServlet {
     @Path("/services/{serviceName}/{serviceVersion}/resources/{resourceName}/{resourceVersion}/artifacts/{artifactName}")
     @Consumes(MediaType.APPLICATION_JSON)
     @Produces(MediaType.APPLICATION_OCTET_STREAM)
-    @Operation(description = "Download resource artifact", method = "GET", summary = "Returns downloaded artifact",
-            responses = {@ApiResponse(
-                    content = @Content(array = @ArraySchema(schema = @Schema(implementation = String.class)))),
-                    @ApiResponse(responseCode = "200", description = "The artifact is found and streamed.",
-                            content = @Content(array = @ArraySchema(schema = @Schema(implementation = String.class)))),
-                    @ApiResponse(responseCode = "400",
-                            description = "Missing  'X-ECOMP-InstanceID'  HTTP header - POL5001"),
-                    @ApiResponse(responseCode = "401",
-                            description = "ECOMP component  should authenticate itself  and  to  re-send  again  HTTP  request  with its Basic  Authentication credentials - POL5002"),
-                    @ApiResponse(responseCode = "403", description = "ECOMP component is not authorized - POL5003"),
-                    @ApiResponse(responseCode = "404", description = "Specified Service is not found - SVC4503"),
-                    @ApiResponse(responseCode = "404",
-                            description = "Specified Resource Instance  is not found - SVC4526"),
-                    @ApiResponse(responseCode = "404",
-                            description = "Specified Service Version is  not  found - SVC4504"),
-                    @ApiResponse(responseCode = "404", description = "Specified artifact is  not found - SVC4505"),
-                    @ApiResponse(responseCode = "405",
-                            description = "Method  Not Allowed: Invalid HTTP method type used (PUT,DELETE,POST will be rejected) - POL4050"),
-                    @ApiResponse(responseCode = "500",
-                            description = "The GET request failed either due to internal SDC problem or Cambria Service failure. ECOMP Component should continue the attempts to get the needed information - POL5000")})
+    @Operation(description = "Download resource artifact", method = "GET", summary = "Returns downloaded artifact", responses = {
+        @ApiResponse(content = @Content(array = @ArraySchema(schema = @Schema(implementation = String.class)))),
+        @ApiResponse(responseCode = "200", description = "The artifact is found and streamed.", content = @Content(array = @ArraySchema(schema = @Schema(implementation = String.class)))),
+        @ApiResponse(responseCode = "400", description = "Missing  'X-ECOMP-InstanceID'  HTTP header - POL5001"),
+        @ApiResponse(responseCode = "401", description = "ECOMP component  should authenticate itself  and  to  re-send  again  HTTP  request  with its Basic  Authentication credentials - POL5002"),
+        @ApiResponse(responseCode = "403", description = "ECOMP component is not authorized - POL5003"),
+        @ApiResponse(responseCode = "404", description = "Specified Service is not found - SVC4503"),
+        @ApiResponse(responseCode = "404", description = "Specified Resource Instance  is not found - SVC4526"),
+        @ApiResponse(responseCode = "404", description = "Specified Service Version is  not  found - SVC4504"),
+        @ApiResponse(responseCode = "404", description = "Specified artifact is  not found - SVC4505"),
+        @ApiResponse(responseCode = "405", description = "Method  Not Allowed: Invalid HTTP method type used (PUT,DELETE,POST will be rejected) - POL4050"),
+        @ApiResponse(responseCode = "500", description = "The GET request failed either due to internal SDC problem or Cambria Service failure. ECOMP Component should continue the attempts to get the needed information - POL5000")})
     @PermissionAllowed({AafPermission.PermNames.READ_VALUE})
     public Response downloadResourceArtifact(
-            @Parameter(description = "X-ECOMP-RequestID header", required = false)@HeaderParam(value = Constants.X_ECOMP_REQUEST_ID_HEADER) String requestId,
-            @Parameter(description = "X-ECOMP-InstanceID header", required = true)@HeaderParam(value = Constants.X_ECOMP_INSTANCE_ID_HEADER) final String instanceIdHeader,
-            @Parameter(description = "Determines the format of the body of the response", required = false)@HeaderParam(value = Constants.ACCEPT_HEADER) String accept,
-            @Parameter(description = "The username and password", required = true)@HeaderParam(value = Constants.AUTHORIZATION_HEADER) String authorization,
-            @PathParam("serviceName") final String serviceName,
-            @PathParam("serviceVersion") final String serviceVersion,
-            @PathParam("resourceName") final String resourceName,
-            @PathParam("resourceVersion") final String resourceVersion,
-            @PathParam("artifactName") final String artifactName) {
-
+        @Parameter(description = "X-ECOMP-RequestID header", required = false) @HeaderParam(value = Constants.X_ECOMP_REQUEST_ID_HEADER) String requestId,
+        @Parameter(description = "X-ECOMP-InstanceID header", required = true) @HeaderParam(value = Constants.X_ECOMP_INSTANCE_ID_HEADER) final String instanceIdHeader,
+        @Parameter(description = "Determines the format of the body of the response", required = false) @HeaderParam(value = Constants.ACCEPT_HEADER) String accept,
+        @Parameter(description = "The username and password", required = true) @HeaderParam(value = Constants.AUTHORIZATION_HEADER) String authorization,
+        @PathParam("serviceName") final String serviceName, @PathParam("serviceVersion") final String serviceVersion,
+        @PathParam("resourceName") final String resourceName, @PathParam("resourceVersion") final String resourceVersion,
+        @PathParam("artifactName") final String artifactName) {
         String requestURI = request.getRequestURI();
         Wrapper<Response> responseWrapper = validateInstanceIdHeader(new Wrapper<>(), instanceIdHeader, requestURI);
-
-        if(!responseWrapper.isEmpty()) {
+        if (!responseWrapper.isEmpty()) {
             return responseWrapper.getInnerElement();
         }
-
         try {
             ArtifactsBusinessLogic artifactsLogic = getArtifactBL(request.getSession().getServletContext());
-            byte[] downloadRsrcArtifactEither = artifactsLogic.downloadRsrcArtifactByNames(serviceName, serviceVersion, resourceName, resourceVersion, artifactName);
+            byte[] downloadRsrcArtifactEither = artifactsLogic
+                .downloadRsrcArtifactByNames(serviceName, serviceVersion, resourceName, resourceVersion, artifactName);
             byte[] value = downloadRsrcArtifactEither;
             // Returning 64-encoded as it was received during upload
             InputStream is = new ByteArrayInputStream(value);
@@ -243,7 +210,6 @@ public class DistributionCatalogServlet extends BeGenericServlet {
             ResponseFormat responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.OK);
             getComponentsUtils().auditDistributionDownload(responseFormat, new DistributionData(instanceIdHeader, requestURI));
             return buildOkResponse(responseFormat, is, headers);
-
         } catch (ComponentException e) {
             getComponentsUtils().auditDistributionDownload(e.getResponseFormat(), new DistributionData(instanceIdHeader, requestURI));
             BeEcompErrorManager.getInstance().logBeRestApiGeneralError("download interface artifact for resource - external API");
@@ -253,7 +219,6 @@ public class DistributionCatalogServlet extends BeGenericServlet {
     }
 
     /**
-     *
      * @param requestId
      * @param instanceIdHeader
      * @param accept
@@ -268,43 +233,34 @@ public class DistributionCatalogServlet extends BeGenericServlet {
     @Path("/services/{serviceName}/{serviceVersion}/resourceInstances/{resourceInstanceName}/artifacts/{artifactName}")
     @Consumes(MediaType.APPLICATION_JSON)
     @Produces(MediaType.APPLICATION_OCTET_STREAM)
-    @Operation(description = "Download resource instance artifact", method = "GET",
-            summary = "Returns downloaded artifact", responses = {
-            @ApiResponse(content = @Content(array = @ArraySchema(schema = @Schema(implementation = String.class)))),
-            @ApiResponse(responseCode = "200", description = "The artifact is found and streamed.",
-                    content = @Content(array = @ArraySchema(schema = @Schema(implementation = String.class)))),
-            @ApiResponse(responseCode = "400", description = "Missing  'X-ECOMP-InstanceID'  HTTP header - POL5001"),
-            @ApiResponse(responseCode = "401",
-                    description = "ECOMP component  should authenticate itself  and  to  re-send  again  HTTP  request  with its Basic  Authentication credentials - POL5002"),
-            @ApiResponse(responseCode = "403", description = "ECOMP component is not authorized - POL5003"),
-            @ApiResponse(responseCode = "404", description = "Specified Service is not found - SVC4503"),
-            @ApiResponse(responseCode = "404", description = "Specified Resource Instance  is not found - SVC4526"),
-            @ApiResponse(responseCode = "404", description = "Specified Service Version is  not  found - SVC4504"),
-            @ApiResponse(responseCode = "404", description = "Specified artifact is  not found - SVC4505"),
-            @ApiResponse(responseCode = "405",
-                    description = "Method  Not Allowed: Invalid HTTP method type used (PUT,DELETE,POST will be rejected) - POL4050"),
-            @ApiResponse(responseCode = "500",
-                    description = "The GET request failed either due to internal SDC problem or Cambria Service failure. ECOMP Component should continue the attempts to get the needed information - POL5000")})
+    @Operation(description = "Download resource instance artifact", method = "GET", summary = "Returns downloaded artifact", responses = {
+        @ApiResponse(content = @Content(array = @ArraySchema(schema = @Schema(implementation = String.class)))),
+        @ApiResponse(responseCode = "200", description = "The artifact is found and streamed.", content = @Content(array = @ArraySchema(schema = @Schema(implementation = String.class)))),
+        @ApiResponse(responseCode = "400", description = "Missing  'X-ECOMP-InstanceID'  HTTP header - POL5001"),
+        @ApiResponse(responseCode = "401", description = "ECOMP component  should authenticate itself  and  to  re-send  again  HTTP  request  with its Basic  Authentication credentials - POL5002"),
+        @ApiResponse(responseCode = "403", description = "ECOMP component is not authorized - POL5003"),
+        @ApiResponse(responseCode = "404", description = "Specified Service is not found - SVC4503"),
+        @ApiResponse(responseCode = "404", description = "Specified Resource Instance  is not found - SVC4526"),
+        @ApiResponse(responseCode = "404", description = "Specified Service Version is  not  found - SVC4504"),
+        @ApiResponse(responseCode = "404", description = "Specified artifact is  not found - SVC4505"),
+        @ApiResponse(responseCode = "405", description = "Method  Not Allowed: Invalid HTTP method type used (PUT,DELETE,POST will be rejected) - POL4050"),
+        @ApiResponse(responseCode = "500", description = "The GET request failed either due to internal SDC problem or Cambria Service failure. ECOMP Component should continue the attempts to get the needed information - POL5000")})
     @PermissionAllowed({AafPermission.PermNames.READ_VALUE})
     public Response downloadResourceInstanceArtifactByName(
-            @Parameter(description = "X-ECOMP-RequestID header", required = false)@HeaderParam(value = Constants.X_ECOMP_REQUEST_ID_HEADER) String requestId,
-            @Parameter(description = "X-ECOMP-InstanceID header", required = true)@HeaderParam(value = Constants.X_ECOMP_INSTANCE_ID_HEADER) final String instanceIdHeader,
-            @Parameter(description = "Determines the format of the body of the response", required = false)@HeaderParam(value = Constants.ACCEPT_HEADER) String accept,
-            @Parameter(description = "The username and password", required = true)@HeaderParam(value = Constants.AUTHORIZATION_HEADER) String authorization,
-            @PathParam("serviceName") final String serviceName,
-            @PathParam("serviceVersion") final String serviceVersion,
-            @PathParam("resourceInstanceName") final String resourceInstanceName,
-            @PathParam("artifactName") final String artifactName) {
-
+        @Parameter(description = "X-ECOMP-RequestID header", required = false) @HeaderParam(value = Constants.X_ECOMP_REQUEST_ID_HEADER) String requestId,
+        @Parameter(description = "X-ECOMP-InstanceID header", required = true) @HeaderParam(value = Constants.X_ECOMP_INSTANCE_ID_HEADER) final String instanceIdHeader,
+        @Parameter(description = "Determines the format of the body of the response", required = false) @HeaderParam(value = Constants.ACCEPT_HEADER) String accept,
+        @Parameter(description = "The username and password", required = true) @HeaderParam(value = Constants.AUTHORIZATION_HEADER) String authorization,
+        @PathParam("serviceName") final String serviceName, @PathParam("serviceVersion") final String serviceVersion,
+        @PathParam("resourceInstanceName") final String resourceInstanceName, @PathParam("artifactName") final String artifactName) {
         String requestURI = request.getRequestURI();
         Wrapper<Response> responseWrapper = validateInstanceIdHeader(new Wrapper<>(), instanceIdHeader, requestURI);
-
-        if(!responseWrapper.isEmpty()) {
+        if (!responseWrapper.isEmpty()) {
             return responseWrapper.getInnerElement();
         }
-
         try {
-            byte[] downloadRsrcArtifactEither = artifactsBusinessLogic.downloadRsrcInstArtifactByNames(serviceName, serviceVersion, resourceInstanceName, artifactName);
+            byte[] downloadRsrcArtifactEither = artifactsBusinessLogic
+                .downloadRsrcInstArtifactByNames(serviceName, serviceVersion, resourceInstanceName, artifactName);
             byte[] value = downloadRsrcArtifactEither;
             // Returning 64-encoded as it was received during upload
             InputStream is = new ByteArrayInputStream(value);
@@ -313,7 +269,6 @@ public class DistributionCatalogServlet extends BeGenericServlet {
             ResponseFormat responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.OK);
             getComponentsUtils().auditDistributionDownload(responseFormat, new DistributionData(instanceIdHeader, requestURI));
             return buildOkResponse(responseFormat, is, headers);
-
         } catch (ComponentException e) {
             getComponentsUtils().auditDistributionDownload(e.getResponseFormat(), new DistributionData(instanceIdHeader, requestURI));
             BeEcompErrorManager.getInstance().logBeRestApiGeneralError("download interface artifact for resource - external API");
index c6be01d..511e997 100644 (file)
@@ -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.
@@ -17,7 +17,6 @@
  * limitations under the License.
  * ============LICENSE_END=========================================================
  */
-
 package org.openecomp.sdc.be.distribution.servlet;
 
 import com.jcabi.aspects.Loggable;
@@ -33,6 +32,17 @@ import io.swagger.v3.oas.annotations.servers.Server;
 import io.swagger.v3.oas.annotations.servers.Servers;
 import io.swagger.v3.oas.annotations.tags.Tag;
 import io.swagger.v3.oas.annotations.tags.Tags;
+import javax.inject.Inject;
+import javax.servlet.http.HttpServletRequest;
+import javax.ws.rs.Consumes;
+import javax.ws.rs.GET;
+import javax.ws.rs.HeaderParam;
+import javax.ws.rs.POST;
+import javax.ws.rs.Path;
+import javax.ws.rs.Produces;
+import javax.ws.rs.core.Context;
+import javax.ws.rs.core.MediaType;
+import javax.ws.rs.core.Response;
 import org.openecomp.sdc.be.components.impl.aaf.AafPermission;
 import org.openecomp.sdc.be.components.impl.aaf.PermissionAllowed;
 import org.openecomp.sdc.be.config.BeEcompErrorManager;
@@ -56,25 +66,11 @@ import org.openecomp.sdc.common.util.HttpUtil;
 import org.openecomp.sdc.exception.ResponseFormat;
 import org.springframework.stereotype.Controller;
 
-import javax.inject.Inject;
-import javax.servlet.http.HttpServletRequest;
-import javax.ws.rs.Consumes;
-import javax.ws.rs.GET;
-import javax.ws.rs.HeaderParam;
-import javax.ws.rs.POST;
-import javax.ws.rs.Path;
-import javax.ws.rs.Produces;
-import javax.ws.rs.core.Context;
-import javax.ws.rs.core.MediaType;
-import javax.ws.rs.core.Response;
-
 /**
  * This Servlet serves external users for distribution purposes.
  *
  * @author tgitelman
- *
  */
-
 @Loggable(prepend = true, value = Loggable.DEBUG, trim = false)
 @Path("/v1")
 @Tags({@Tag(name = "SDC Distribution APIs")})
@@ -83,20 +79,18 @@ import javax.ws.rs.core.Response;
 public class DistributionServlet extends BeGenericServlet {
 
     private static final String START_HANDLE_REQUEST_OF = "Start handle request of {}";
-       private static final Logger log = Logger.getLogger(DistributionServlet.class);
+    private static final Logger log = Logger.getLogger(DistributionServlet.class);
     private final DistributionBusinessLogic distributionLogic;
     @Context
     private HttpServletRequest request;
 
     @Inject
-    public DistributionServlet(UserBusinessLogic userBusinessLogic,
-        ComponentsUtils componentsUtils, DistributionBusinessLogic distributionLogic) {
+    public DistributionServlet(UserBusinessLogic userBusinessLogic, ComponentsUtils componentsUtils, DistributionBusinessLogic distributionLogic) {
         super(userBusinessLogic, componentsUtils);
         this.distributionLogic = distributionLogic;
     }
 
     /**
-     *
      * @param requestId
      * @param instanceId
      * @param accept
@@ -107,46 +101,36 @@ public class DistributionServlet extends BeGenericServlet {
     @Path("/distributionUebCluster")
     @Consumes(MediaType.APPLICATION_JSON)
     @Produces(MediaType.APPLICATION_JSON)
-    @Operation(description = "UEB Server List", method = "GET", summary = "return the available UEB Server List",
-            responses = {@ApiResponse(responseCode = "200",
-                    description = "ECOMP component is authenticated and list of Cambria API server’s FQDNs is returned",
-                    content = @Content(
-                            array = @ArraySchema(schema = @Schema(implementation = ServerListResponse.class)))),
-                    @ApiResponse(responseCode = "400",
-                            description = "Missing  'X-ECOMP-InstanceID'  HTTP header - POL5001"),
-                    @ApiResponse(responseCode = "401",
-                            description = "ECOMP component  should authenticate itself  and  to  re-send  again  HTTP  request  with its credentials  for  Basic Authentication - POL5002"),
-                    @ApiResponse(responseCode = "403", description = "ECOMP component is not authorized - POL5003"),
-                    @ApiResponse(responseCode = "405",
-                            description = "Method  Not Allowed: Invalid HTTP method type used ( PUT,DELETE,POST will be rejected) - POL4050"),
-                    @ApiResponse(responseCode = "500",
-                            description = "The GET request failed either due to internal SDC problem or Cambria Service failure. ECOMP Component should continue the attempts to get the needed information - POL5000")})
+    @Operation(description = "UEB Server List", method = "GET", summary = "return the available UEB Server List", responses = {
+        @ApiResponse(responseCode = "200", description = "ECOMP component is authenticated and list of Cambria API server’s FQDNs is returned", content = @Content(array = @ArraySchema(schema = @Schema(implementation = ServerListResponse.class)))),
+        @ApiResponse(responseCode = "400", description = "Missing  'X-ECOMP-InstanceID'  HTTP header - POL5001"),
+        @ApiResponse(responseCode = "401", description = "ECOMP component  should authenticate itself  and  to  re-send  again  HTTP  request  with its credentials  for  Basic Authentication - POL5002"),
+        @ApiResponse(responseCode = "403", description = "ECOMP component is not authorized - POL5003"),
+        @ApiResponse(responseCode = "405", description = "Method  Not Allowed: Invalid HTTP method type used ( PUT,DELETE,POST will be rejected) - POL4050"),
+        @ApiResponse(responseCode = "500", description = "The GET request failed either due to internal SDC problem or Cambria Service failure. ECOMP Component should continue the attempts to get the needed information - POL5000")})
     //TODO Tal G fix response headers
+
     /*responseHeaders = {
             @ResponseHeader(name = Constants.CONTENT_TYPE_HEADER, description = "Determines the format of the response body", response = String.class),
             @ResponseHeader(name = "Content-Length", description = "Length of  the response body", response = String.class)})*/
     @PermissionAllowed({AafPermission.PermNames.READ_VALUE})
     public Response getUebServerList(
-            @Parameter(description = "X-ECOMP-RequestID header", required = false)@HeaderParam(value = Constants.X_ECOMP_REQUEST_ID_HEADER) String requestId,
-            @Parameter(description = "X-ECOMP-InstanceID header", required = true)@HeaderParam(value = Constants.X_ECOMP_INSTANCE_ID_HEADER) String instanceId,
-            @Parameter(description = "Determines the format of the body of the response", required = false)@HeaderParam(value = Constants.ACCEPT_HEADER) String accept,
-            @Parameter(description = "The username and password", required = true)@HeaderParam(value = Constants.AUTHORIZATION_HEADER) String authorization) {
-
+        @Parameter(description = "X-ECOMP-RequestID header", required = false) @HeaderParam(value = Constants.X_ECOMP_REQUEST_ID_HEADER) String requestId,
+        @Parameter(description = "X-ECOMP-InstanceID header", required = true) @HeaderParam(value = Constants.X_ECOMP_INSTANCE_ID_HEADER) String instanceId,
+        @Parameter(description = "Determines the format of the body of the response", required = false) @HeaderParam(value = Constants.ACCEPT_HEADER) String accept,
+        @Parameter(description = "The username and password", required = true) @HeaderParam(value = Constants.AUTHORIZATION_HEADER) String authorization) {
         String url = request.getMethod() + " " + request.getRequestURI();
         log.debug(START_HANDLE_REQUEST_OF, url);
         Response response = null;
         ResponseFormat responseFormat = null;
-
         if (instanceId == null) {
             responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.MISSING_X_ECOMP_INSTANCE_ID);
             response = buildErrorResponse(responseFormat);
             getComponentsUtils().auditGetUebCluster(null, responseFormat.getStatus().toString(), responseFormat.getFormattedMessage());
             return response;
         }
-
         try {
             Either<ServerListResponse, ResponseFormat> actionResponse = distributionLogic.getUebServerList();
-
             if (actionResponse.isRight()) {
                 responseFormat = actionResponse.right().value();
                 response = buildErrorResponse(responseFormat);
@@ -154,10 +138,8 @@ public class DistributionServlet extends BeGenericServlet {
                 responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.OK);
                 response = buildOkResponse(responseFormat, actionResponse.left().value());
             }
-
             getComponentsUtils().auditGetUebCluster(instanceId, responseFormat.getStatus().toString(), responseFormat.getFormattedMessage());
             return response;
-
         } catch (Exception e) {
             BeEcompErrorManager.getInstance().logBeRestApiGeneralError("failed to get ueb serbver list from cofiguration");
             log.debug("failed to get ueb serbver list from cofiguration", e);
@@ -165,11 +147,9 @@ public class DistributionServlet extends BeGenericServlet {
             getComponentsUtils().auditGetUebCluster(instanceId, responseFormat.getStatus().toString(), responseFormat.getFormattedMessage());
             return buildErrorResponse(responseFormat);
         }
-
     }
 
     /**
-     *
      * @param requestId
      * @param instanceId
      * @param accept
@@ -183,92 +163,72 @@ public class DistributionServlet extends BeGenericServlet {
     @Path("/registerForDistribution")
     @Consumes(MediaType.APPLICATION_JSON)
     @Produces(MediaType.APPLICATION_JSON)
-    @Operation(parameters = {@Parameter(name = "requestJson", required = true,
-            schema = @Schema(implementation = org.openecomp.sdc.be.distribution.api.client.RegistrationRequest.class))},
-            description = "Subscription status", method = "POST", summary = "Subscribes for distribution notifications",
-            responses = {@ApiResponse(responseCode = "200",
-                    description = "ECOMP component is successfully registered for distribution", content = @Content(
-                    array = @ArraySchema(schema = @Schema(implementation = TopicRegistrationResponse.class)))),
-                    @ApiResponse(responseCode = "400",
-                            description = "Missing  'X-ECOMP-InstanceID'  HTTP header - POL5001"),
-                    @ApiResponse(responseCode = "400", description = "Missing  Body - POL4500"),
-                    @ApiResponse(responseCode = "400",
-                            description = "Invalid  Body  : missing mandatory parameter 'apiPublicKey' - POL4501"),
-                    @ApiResponse(responseCode = "400",
-                            description = "Invalid  Body  : missing mandatory parameter 'distrEnvName' - POL4502"),
-                    @ApiResponse(responseCode = "400",
-                            description = "Invalid Body :  Specified 'distrEnvName' doesn’t exist - POL4137"),
-                    @ApiResponse(responseCode = "401",
-                            description = "ECOMP component  should authenticate itself  and  to  re-send  again  HTTP  request  with its Basic Authentication credentials - POL5002"),
-                    @ApiResponse(responseCode = "403", description = "ECOMP component is not authorized - POL5003"),
-                    @ApiResponse(responseCode = "405",
-                            description = "Method  Not Allowed  :  Invalid HTTP method type used to  register for  distribution ( PUT,DELETE,GET  will be rejected) - POL4050"),
-                    @ApiResponse(responseCode = "500",
-                            description = "The registration failed due to internal SDC problem or Cambria Service failure ECOMP Component  should  continue the attempts to  register for  distribution - POL5000")})
+    @Operation(parameters = {
+        @Parameter(name = "requestJson", required = true, schema = @Schema(implementation = org.openecomp.sdc.be.distribution.api.client.RegistrationRequest.class))}, description = "Subscription status", method = "POST", summary = "Subscribes for distribution notifications", responses = {
+        @ApiResponse(responseCode = "200", description = "ECOMP component is successfully registered for distribution", content = @Content(array = @ArraySchema(schema = @Schema(implementation = TopicRegistrationResponse.class)))),
+        @ApiResponse(responseCode = "400", description = "Missing  'X-ECOMP-InstanceID'  HTTP header - POL5001"),
+        @ApiResponse(responseCode = "400", description = "Missing  Body - POL4500"),
+        @ApiResponse(responseCode = "400", description = "Invalid  Body  : missing mandatory parameter 'apiPublicKey' - POL4501"),
+        @ApiResponse(responseCode = "400", description = "Invalid  Body  : missing mandatory parameter 'distrEnvName' - POL4502"),
+        @ApiResponse(responseCode = "400", description = "Invalid Body :  Specified 'distrEnvName' doesn’t exist - POL4137"),
+        @ApiResponse(responseCode = "401", description = "ECOMP component  should authenticate itself  and  to  re-send  again  HTTP  request  with its Basic Authentication credentials - POL5002"),
+        @ApiResponse(responseCode = "403", description = "ECOMP component is not authorized - POL5003"),
+        @ApiResponse(responseCode = "405", description = "Method  Not Allowed  :  Invalid HTTP method type used to  register for  distribution ( PUT,DELETE,GET  will be rejected) - POL4050"),
+        @ApiResponse(responseCode = "500", description = "The registration failed due to internal SDC problem or Cambria Service failure ECOMP Component  should  continue the attempts to  register for  distribution - POL5000")})
     @PermissionAllowed({AafPermission.PermNames.READ_VALUE})
     public Response registerForDistribution(
-            @Parameter(description = "X-ECOMP-RequestID header", required = false)@HeaderParam(value = Constants.X_ECOMP_REQUEST_ID_HEADER) String requestId,
-            @Parameter(description = "X-ECOMP-InstanceID header", required = true)@HeaderParam(value = Constants.X_ECOMP_INSTANCE_ID_HEADER) String instanceId,
-            @Parameter(description = "Determines the format of the body of the response", required = false)@HeaderParam(value = Constants.ACCEPT_HEADER) String accept,
-            @Parameter(description = "Determines the format of the body of the request", required = true)@HeaderParam(value = Constants.CONTENT_TYPE_HEADER) String contentType,
-            @Parameter(description = "Length  of  the request body", required = true)@HeaderParam(value = Constants.CONTENT_LENGTH_HEADER) String contenLength,
-            @Parameter(description = "The username and password", required = true)@HeaderParam(value = Constants.AUTHORIZATION_HEADER) String authorization,
-            @Parameter( hidden = true) String requestJson) {
+        @Parameter(description = "X-ECOMP-RequestID header", required = false) @HeaderParam(value = Constants.X_ECOMP_REQUEST_ID_HEADER) String requestId,
+        @Parameter(description = "X-ECOMP-InstanceID header", required = true) @HeaderParam(value = Constants.X_ECOMP_INSTANCE_ID_HEADER) String instanceId,
+        @Parameter(description = "Determines the format of the body of the response", required = false) @HeaderParam(value = Constants.ACCEPT_HEADER) String accept,
+        @Parameter(description = "Determines the format of the body of the request", required = true) @HeaderParam(value = Constants.CONTENT_TYPE_HEADER) String contentType,
+        @Parameter(description = "Length  of  the request body", required = true) @HeaderParam(value = Constants.CONTENT_LENGTH_HEADER) String contenLength,
+        @Parameter(description = "The username and password", required = true) @HeaderParam(value = Constants.AUTHORIZATION_HEADER) String authorization,
+        @Parameter(hidden = true) String requestJson) {
         String url = request.getMethod() + " " + request.getRequestURI();
         log.debug(START_HANDLE_REQUEST_OF, url);
-
         Wrapper<Response> responseWrapper = new Wrapper<>();
         Wrapper<RegistrationRequest> registrationRequestWrapper = new Wrapper<>();
-
         validateHeaders(responseWrapper, request, AuditingActionEnum.ADD_KEY_TO_TOPIC_ACL);
-
         if (responseWrapper.isEmpty()) {
             validateJson(responseWrapper, registrationRequestWrapper, requestJson);
         }
         if (responseWrapper.isEmpty()) {
             validateEnv(responseWrapper);
         }
-
         if (responseWrapper.isEmpty()) {
-            distributionLogic.handleRegistration(responseWrapper, registrationRequestWrapper.getInnerElement(), buildAuditHandler(request, registrationRequestWrapper.getInnerElement()));
+            distributionLogic.handleRegistration(responseWrapper, registrationRequestWrapper.getInnerElement(),
+                buildAuditHandler(request, registrationRequestWrapper.getInnerElement()));
         } else {
-            BeEcompErrorManager.getInstance().logBeDistributionEngineSystemError(DistributionBusinessLogic.REGISTER_IN_DISTRIBUTION_ENGINE, "registration validation failed");
+            BeEcompErrorManager.getInstance()
+                .logBeDistributionEngineSystemError(DistributionBusinessLogic.REGISTER_IN_DISTRIBUTION_ENGINE, "registration validation failed");
         }
-
         return responseWrapper.getInnerElement();
     }
 
     /**
-     * Returns list of valid artifact types for validation done in the distribution client.<br>
-     * The list is the representation of the values of the enum ArtifactTypeEnum.
+     * Returns list of valid artifact types for validation done in the distribution client.<br> The list is the representation of the values of the
+     * enum ArtifactTypeEnum.
      */
     @GET
     @Path("/artifactTypes")
     @Consumes(MediaType.APPLICATION_JSON)
     @Produces(MediaType.APPLICATION_JSON)
-    @Operation(description = "Artifact types list", method = "GET", summary = "Fetches available artifact types list",
-            responses = {@ApiResponse(responseCode = "200", description = "Artifact types list fetched successfully",
-                    content = @Content(array = @ArraySchema(schema = @Schema(implementation = String.class)))),
-                    @ApiResponse(responseCode = "400",
-                            description = "Missing  'X-ECOMP-InstanceID'  HTTP header - POL5001"),
-                    @ApiResponse(responseCode = "401",
-                            description = "ECOMP component  should authenticate itself  and  to  re-send  again  HTTP  request  with its Basic Authentication credentials - POL5002"),
-                    @ApiResponse(responseCode = "403", description = "ECOMP component is not authorized - POL5003"),
-                    @ApiResponse(responseCode = "405",
-                            description = "Method  Not Allowed  :  Invalid HTTP method type used to  register for  distribution ( POST,PUT,DELETE  will be rejected) - POL4050"),
-                    @ApiResponse(responseCode = "500",
-                            description = "The registration failed due to internal SDC problem or Cambria Service failure ECOMP Component  should  continue the attempts to  register for  distribution - POL5000")})
+    @Operation(description = "Artifact types list", method = "GET", summary = "Fetches available artifact types list", responses = {
+        @ApiResponse(responseCode = "200", description = "Artifact types list fetched successfully", content = @Content(array = @ArraySchema(schema = @Schema(implementation = String.class)))),
+        @ApiResponse(responseCode = "400", description = "Missing  'X-ECOMP-InstanceID'  HTTP header - POL5001"),
+        @ApiResponse(responseCode = "401", description = "ECOMP component  should authenticate itself  and  to  re-send  again  HTTP  request  with its Basic Authentication credentials - POL5002"),
+        @ApiResponse(responseCode = "403", description = "ECOMP component is not authorized - POL5003"),
+        @ApiResponse(responseCode = "405", description = "Method  Not Allowed  :  Invalid HTTP method type used to  register for  distribution ( POST,PUT,DELETE  will be rejected) - POL4050"),
+        @ApiResponse(responseCode = "500", description = "The registration failed due to internal SDC problem or Cambria Service failure ECOMP Component  should  continue the attempts to  register for  distribution - POL5000")})
     @PermissionAllowed({AafPermission.PermNames.READ_VALUE})
     public Response getValidArtifactTypes(
-            @Parameter(description = "X-ECOMP-RequestID header", required = false)@HeaderParam(value = Constants.X_ECOMP_REQUEST_ID_HEADER) String requestId,
-            @Parameter(description = "X-ECOMP-InstanceID header", required = true)@HeaderParam(value = Constants.X_ECOMP_INSTANCE_ID_HEADER) String instanceId,
-            @Parameter(description = "The username and password", required = true)@HeaderParam(value = Constants.AUTHORIZATION_HEADER) String authorization,
-            @Parameter(description = "The username and password", required = true)@HeaderParam(value = Constants.ACCEPT_HEADER) String accept) {
+        @Parameter(description = "X-ECOMP-RequestID header", required = false) @HeaderParam(value = Constants.X_ECOMP_REQUEST_ID_HEADER) String requestId,
+        @Parameter(description = "X-ECOMP-InstanceID header", required = true) @HeaderParam(value = Constants.X_ECOMP_INSTANCE_ID_HEADER) String instanceId,
+        @Parameter(description = "The username and password", required = true) @HeaderParam(value = Constants.AUTHORIZATION_HEADER) String authorization,
+        @Parameter(description = "The username and password", required = true) @HeaderParam(value = Constants.ACCEPT_HEADER) String accept) {
         String url = request.getMethod() + " " + request.getRequestURI();
         log.debug(START_HANDLE_REQUEST_OF, url);
-
         Wrapper<Response> responseWrapper = new Wrapper<>();
-
         //TODO check if in use
         validateHeaders(responseWrapper, request, AuditingActionEnum.GET_VALID_ARTIFACT_TYPES);
         if (responseWrapper.isEmpty()) {
@@ -294,46 +254,34 @@ public class DistributionServlet extends BeGenericServlet {
     @Path("/unRegisterForDistribution")
     @Consumes(MediaType.APPLICATION_JSON)
     @Produces(MediaType.APPLICATION_JSON)
-    @Operation(parameters = @Parameter(name = "requestJson", required = true), description = "Subscription status",
-            method = "POST", summary = "Removes from subscription for distribution notifications", responses = {
-            @ApiResponse(responseCode = "204", description = "ECOMP component is successfully unregistered",
-                    content = @Content(array = @ArraySchema(
-                            schema = @Schema(implementation = TopicUnregistrationResponse.class)))),
-            @ApiResponse(responseCode = "400", description = "Missing  'X-ECOMP-InstanceID'  HTTP header - POL5001"),
-            @ApiResponse(responseCode = "400", description = "Missing  Body - POL4500"),
-            @ApiResponse(responseCode = "400",
-                    description = "Invalid  Body  : missing mandatory parameter 'apiPublicKey' - POL4501"),
-            @ApiResponse(responseCode = "400",
-                    description = "Invalid  Body  : missing mandatory parameter 'distrEnvName' - SVC4506"),
-            @ApiResponse(responseCode = "400",
-                    description = "Invalid Body :  Specified 'distrEnvName' doesn’t exist - POL4137"),
-            @ApiResponse(responseCode = "401",
-                    description = "ECOMP component  should authenticate itself  and  to  re-send  again  HTTP  request  with its Basic Authentication credentials - POL5002"),
-            @ApiResponse(responseCode = "403", description = "ECOMP component is not authorized - POL5003"),
-            @ApiResponse(responseCode = "405",
-                    description = "Method  Not Allowed  :  Invalid HTTP method type used to  register for  distribution ( PUT,DELETE,GET will be rejected) - POL4050"),
-            @ApiResponse(responseCode = "500",
-                    description = "The registration failed due to internal SDC problem or Cambria Service failure ECOMP Component  should  continue the attempts to  register for  distribution - POL5000")})
+    @Operation(parameters = @Parameter(name = "requestJson", required = true), description = "Subscription status", method = "POST", summary = "Removes from subscription for distribution notifications", responses = {
+        @ApiResponse(responseCode = "204", description = "ECOMP component is successfully unregistered", content = @Content(array = @ArraySchema(schema = @Schema(implementation = TopicUnregistrationResponse.class)))),
+        @ApiResponse(responseCode = "400", description = "Missing  'X-ECOMP-InstanceID'  HTTP header - POL5001"),
+        @ApiResponse(responseCode = "400", description = "Missing  Body - POL4500"),
+        @ApiResponse(responseCode = "400", description = "Invalid  Body  : missing mandatory parameter 'apiPublicKey' - POL4501"),
+        @ApiResponse(responseCode = "400", description = "Invalid  Body  : missing mandatory parameter 'distrEnvName' - SVC4506"),
+        @ApiResponse(responseCode = "400", description = "Invalid Body :  Specified 'distrEnvName' doesn’t exist - POL4137"),
+        @ApiResponse(responseCode = "401", description = "ECOMP component  should authenticate itself  and  to  re-send  again  HTTP  request  with its Basic Authentication credentials - POL5002"),
+        @ApiResponse(responseCode = "403", description = "ECOMP component is not authorized - POL5003"),
+        @ApiResponse(responseCode = "405", description = "Method  Not Allowed  :  Invalid HTTP method type used to  register for  distribution ( PUT,DELETE,GET will be rejected) - POL4050"),
+        @ApiResponse(responseCode = "500", description = "The registration failed due to internal SDC problem or Cambria Service failure ECOMP Component  should  continue the attempts to  register for  distribution - POL5000")})
     //TODO Edit the responses
-    @Parameters({@Parameter(name = "requestJson", required = true, schema = @Schema(implementation = org.openecomp.sdc.be.distribution.api.client.RegistrationRequest.class) , description = "json describe the artifact")})
+    @Parameters({
+        @Parameter(name = "requestJson", required = true, schema = @Schema(implementation = org.openecomp.sdc.be.distribution.api.client.RegistrationRequest.class), description = "json describe the artifact")})
     @PermissionAllowed({AafPermission.PermNames.READ_VALUE})
     public Response unRegisterForDistribution(
-            @Parameter(description = "X-ECOMP-RequestID header", required = false)@HeaderParam(value = Constants.X_ECOMP_REQUEST_ID_HEADER) String requestId,
-            @Parameter(description = "X-ECOMP-InstanceID header", required = true)@HeaderParam(value = Constants.X_ECOMP_INSTANCE_ID_HEADER) String instanceId,
-            @Parameter(description = "Determines the format of the body of the response", required = false)@HeaderParam(value = Constants.ACCEPT_HEADER) String accept,
-            @Parameter(description = "Determines the format of the body of the request", required = true)@HeaderParam(value = Constants.CONTENT_TYPE_HEADER) String contentType,
-            @Parameter(description = "Length  of  the request body", required = true)@HeaderParam(value = Constants.CONTENT_LENGTH_HEADER) String contenLength,
-            @Parameter(description = "The username and password", required = true)@HeaderParam(value = Constants.AUTHORIZATION_HEADER) String authorization,
-            @Parameter( hidden = true) String requestJson) {
-
+        @Parameter(description = "X-ECOMP-RequestID header", required = false) @HeaderParam(value = Constants.X_ECOMP_REQUEST_ID_HEADER) String requestId,
+        @Parameter(description = "X-ECOMP-InstanceID header", required = true) @HeaderParam(value = Constants.X_ECOMP_INSTANCE_ID_HEADER) String instanceId,
+        @Parameter(description = "Determines the format of the body of the response", required = false) @HeaderParam(value = Constants.ACCEPT_HEADER) String accept,
+        @Parameter(description = "Determines the format of the body of the request", required = true) @HeaderParam(value = Constants.CONTENT_TYPE_HEADER) String contentType,
+        @Parameter(description = "Length  of  the request body", required = true) @HeaderParam(value = Constants.CONTENT_LENGTH_HEADER) String contenLength,
+        @Parameter(description = "The username and password", required = true) @HeaderParam(value = Constants.AUTHORIZATION_HEADER) String authorization,
+        @Parameter(hidden = true) String requestJson) {
         String url = request.getMethod() + " " + request.getRequestURI();
         log.debug(START_HANDLE_REQUEST_OF, url);
-
         Wrapper<Response> responseWrapper = new Wrapper<>();
         Wrapper<RegistrationRequest> unRegistrationRequestWrapper = new Wrapper<>();
-
         validateHeaders(responseWrapper, request, AuditingActionEnum.REMOVE_KEY_FROM_TOPIC_ACL);
-
         if (responseWrapper.isEmpty()) {
             validateJson(responseWrapper, unRegistrationRequestWrapper, requestJson);
         }
@@ -341,65 +289,67 @@ public class DistributionServlet extends BeGenericServlet {
             validateEnv(responseWrapper);
         }
         if (responseWrapper.isEmpty()) {
-            distributionLogic.handleUnRegistration(responseWrapper, unRegistrationRequestWrapper.getInnerElement(), buildAuditHandler(request, unRegistrationRequestWrapper.getInnerElement()));
+            distributionLogic.handleUnRegistration(responseWrapper, unRegistrationRequestWrapper.getInnerElement(),
+                buildAuditHandler(request, unRegistrationRequestWrapper.getInnerElement()));
         } else {
-            BeEcompErrorManager.getInstance().logBeDistributionEngineSystemError(DistributionBusinessLogic.UN_REGISTER_IN_DISTRIBUTION_ENGINE, "unregistration validation failed");
+            BeEcompErrorManager.getInstance()
+                .logBeDistributionEngineSystemError(DistributionBusinessLogic.UN_REGISTER_IN_DISTRIBUTION_ENGINE, "unregistration validation failed");
         }
-
         return responseWrapper.getInnerElement();
     }
 
     private void validateEnv(Wrapper<Response> responseWrapper) {
-
         // DE194021
         StorageOperationStatus environmentStatus = distributionLogic.getDistributionEngine().isEnvironmentAvailable();
         if (environmentStatus != StorageOperationStatus.OK) {
             if (environmentStatus == StorageOperationStatus.DISTR_ENVIRONMENT_NOT_FOUND) {
-                Response missingHeaderResponse = buildErrorResponse(distributionLogic.getResponseFormatManager().getResponseFormat(ActionStatus.DISTRIBUTION_ENV_DOES_NOT_EXIST));
+                Response missingHeaderResponse = buildErrorResponse(
+                    distributionLogic.getResponseFormatManager().getResponseFormat(ActionStatus.DISTRIBUTION_ENV_DOES_NOT_EXIST));
                 responseWrapper.setInnerElement(missingHeaderResponse);
             } else {
-                Response missingHeaderResponse = buildErrorResponse(distributionLogic.getResponseFormatManager().getResponseFormat(ActionStatus.GENERAL_ERROR));
+                Response missingHeaderResponse = buildErrorResponse(
+                    distributionLogic.getResponseFormatManager().getResponseFormat(ActionStatus.GENERAL_ERROR));
                 responseWrapper.setInnerElement(missingHeaderResponse);
             }
         }
-
     }
 
     private void validateHeaders(Wrapper<Response> responseWrapper, HttpServletRequest request, AuditingActionEnum auditingAction) {
         if (request.getHeader(Constants.X_ECOMP_INSTANCE_ID_HEADER) == null) {
-            Response missingHeaderResponse = buildErrorResponse(distributionLogic.getResponseFormatManager().getResponseFormat(ActionStatus.MISSING_X_ECOMP_INSTANCE_ID));
+            Response missingHeaderResponse = buildErrorResponse(
+                distributionLogic.getResponseFormatManager().getResponseFormat(ActionStatus.MISSING_X_ECOMP_INSTANCE_ID));
             responseWrapper.setInnerElement(missingHeaderResponse);
             ResponseFormat responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.MISSING_X_ECOMP_INSTANCE_ID);
             getComponentsUtils().auditMissingInstanceIdAsDistributionEngineEvent(auditingAction, responseFormat.getStatus().toString());
-
         }
-
     }
 
     private void validateJson(Wrapper<Response> responseWrapper, Wrapper<RegistrationRequest> registrationRequestWrapper, String requestJson) {
         if (requestJson == null || requestJson.isEmpty()) {
-            Response missingBodyResponse = buildErrorResponse(distributionLogic.getResponseFormatManager().getResponseFormat(ActionStatus.MISSING_BODY));
+            Response missingBodyResponse = buildErrorResponse(
+                distributionLogic.getResponseFormatManager().getResponseFormat(ActionStatus.MISSING_BODY));
             responseWrapper.setInnerElement(missingBodyResponse);
         } else {
             Either<RegistrationRequest, Exception> eitherRegistration = HttpUtil.convertJsonStringToObject(requestJson, RegistrationRequest.class);
             if (eitherRegistration.isLeft()) {
                 RegistrationRequest registrationRequest = eitherRegistration.left().value();
                 if (registrationRequest.getApiPublicKey() == null) {
-                    Response missingBodyResponse = buildErrorResponse(distributionLogic.getResponseFormatManager().getResponseFormat(ActionStatus.MISSING_PUBLIC_KEY));
+                    Response missingBodyResponse = buildErrorResponse(
+                        distributionLogic.getResponseFormatManager().getResponseFormat(ActionStatus.MISSING_PUBLIC_KEY));
                     responseWrapper.setInnerElement(missingBodyResponse);
-
                 } else if (registrationRequest.getDistrEnvName() == null) {
-                    Response missingBodyResponse = buildErrorResponse(distributionLogic.getResponseFormatManager().getResponseFormat(ActionStatus.MISSING_ENV_NAME));
+                    Response missingBodyResponse = buildErrorResponse(
+                        distributionLogic.getResponseFormatManager().getResponseFormat(ActionStatus.MISSING_ENV_NAME));
                     responseWrapper.setInnerElement(missingBodyResponse);
                 } else {
                     registrationRequestWrapper.setInnerElement(registrationRequest);
                 }
             } else {
-                Response missingBodyResponse = buildErrorResponse(distributionLogic.getResponseFormatManager().getResponseFormat(ActionStatus.MISSING_BODY));
+                Response missingBodyResponse = buildErrorResponse(
+                    distributionLogic.getResponseFormatManager().getResponseFormat(ActionStatus.MISSING_BODY));
                 responseWrapper.setInnerElement(missingBodyResponse);
             }
         }
-
     }
 
     private AuditHandler buildAuditHandler(HttpServletRequest request, RegistrationRequest registrationRequest) {
index 69b50e0..c67594f 100644 (file)
@@ -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.
@@ -17,7 +17,6 @@
  * limitations under the License.
  * ============LICENSE_END=========================================================
  */
-
 package org.openecomp.sdc.be.dto;
 
 import com.fasterxml.jackson.annotation.JsonInclude;
@@ -34,7 +33,7 @@ import lombok.Setter;
 @Getter
 @Setter
 public class ExternalRefDTO {
+
     @JsonInclude
     private String referenceUUID;
-
 }
index 783d1fc..636c7ce 100644 (file)
@@ -17,7 +17,6 @@
  * limitations under the License.
  * ============LICENSE_END=========================================================
  */
-
 package org.openecomp.sdc.be.ecomp;
 
 import fj.data.Either;
@@ -49,10 +48,11 @@ import org.springframework.context.ApplicationContext;
 import org.springframework.web.context.ContextLoader;
 
 public class EcompIntImpl implements IPortalRestAPIService {
-    private static final String FAILED_TO_CONVERT_ROLES = "Failed to convert Roles";
+
     public static final String FAILED_TO_GET_ROLES = "Failed to get Roles";
-    private static final String GET_USER_ROLES = "GetUserRoles";
     public static final String ERROR_FAILED_TO_GET_ROLES = "Error: Failed to get Roles";
+    private static final String FAILED_TO_CONVERT_ROLES = "Failed to convert Roles";
+    private static final String GET_USER_ROLES = "GetUserRoles";
     private static final String PUSH_USER_ROLE = "PushUserRole";
     private static final String FAILED_TO_FETCH_ROLES = "Failed to fetch roles";
     private static final String FAILED_TO_CONVERT_USER2 = "Failed to convert User {}";
@@ -79,17 +79,13 @@ public class EcompIntImpl implements IPortalRestAPIService {
         log.debug("Start handle request of ECOMP pushUser");
         try {
             if (user == null) {
-                BeEcompErrorManager.getInstance()
-                        .logInvalidInputError(PUSH_USER, RECEIVED_NULL_FOR_ARGUMENT_USER, ErrorSeverity.INFO);
+                BeEcompErrorManager.getInstance().logInvalidInputError(PUSH_USER, RECEIVED_NULL_FOR_ARGUMENT_USER, ErrorSeverity.INFO);
                 log.debug(RECEIVED_NULL_FOR_ARGUMENT_USER);
                 throw new PortalAPIException(RECEIVED_NULL_FOR_ARGUMENT_USER);
             }
-
             UserBusinessLogic userBusinessLogic = getUserBusinessLogic();
-
             final String modifierAttId = JH0003;
             log.debug("modifier id is {}", modifierAttId);
-
             User convertedAsdcUser = EcompUserConverter.convertEcompUserToUser(user);
             userBusinessLogic.createUser(modifierAttId, convertedAsdcUser);
             log.debug("User created {}", user);
@@ -98,14 +94,12 @@ public class EcompIntImpl implements IPortalRestAPIService {
                 log.debug("User already exist {}", user);
             } else {
                 log.debug(FAILED_TO_CREATE_USER, user);
-                BeEcompErrorManager.getInstance()
-                        .logInvalidInputError(PUSH_USER, FAILED_TO_CREATE_USER, ErrorSeverity.ERROR);
+                BeEcompErrorManager.getInstance().logInvalidInputError(PUSH_USER, FAILED_TO_CREATE_USER, ErrorSeverity.ERROR);
                 throw new PortalAPIException(FAILED_TO_CREATE_USER + ce.getActionStatus());
             }
         } catch (Exception e) {
             log.debug(FAILED_TO_CREATE_USER, user, e);
-            BeEcompErrorManager.getInstance()
-                    .logInvalidInputError(PUSH_USER, FAILED_TO_CREATE_USER, ErrorSeverity.ERROR);
+            BeEcompErrorManager.getInstance().logInvalidInputError(PUSH_USER, FAILED_TO_CREATE_USER, ErrorSeverity.ERROR);
             throw new PortalAPIException(FAILED_TO_CREATE_USER, e);
         }
     }
@@ -120,46 +114,35 @@ public class EcompIntImpl implements IPortalRestAPIService {
     @Override
     public void editUser(String loginId, EcompUser user) throws PortalAPIException {
         log.debug("Start handle request of ECOMP editUser");
-
         try {
             if (user == null) {
                 log.debug(RECEIVED_NULL_FOR_ARGUMENT_USER);
-                BeEcompErrorManager.getInstance()
-                        .logInvalidInputError(EDIT_USER, RECEIVED_NULL_FOR_ARGUMENT_USER, ErrorSeverity.INFO);
+                BeEcompErrorManager.getInstance().logInvalidInputError(EDIT_USER, RECEIVED_NULL_FOR_ARGUMENT_USER, ErrorSeverity.INFO);
                 throw new PortalAPIException(RECEIVED_NULL_FOR_ARGUMENT_USER);
             } else if (loginId == null) {
                 log.debug(RECEIVED_NULL_FOR_ARGUMENT_LOGIN_ID);
-                BeEcompErrorManager.getInstance()
-                        .logInvalidInputError(EDIT_USER, RECEIVED_NULL_FOR_ARGUMENT_LOGIN_ID, ErrorSeverity.INFO);
+                BeEcompErrorManager.getInstance().logInvalidInputError(EDIT_USER, RECEIVED_NULL_FOR_ARGUMENT_LOGIN_ID, ErrorSeverity.INFO);
                 throw new PortalAPIException(RECEIVED_NULL_FOR_ARGUMENT_LOGIN_ID);
             }
-
             UserBusinessLogic userBusinessLogic = getUserBusinessLogic();
-
             if (user.getLoginId() != null && !user.getLoginId().equals(loginId)) {
                 log.debug("loginId and user loginId not equal");
-                BeEcompErrorManager.getInstance()
-                        .logInvalidInputError(EDIT_USER, "loginId and user loginId not equal", ErrorSeverity.INFO);
+                BeEcompErrorManager.getInstance().logInvalidInputError(EDIT_USER, "loginId and user loginId not equal", ErrorSeverity.INFO);
                 throw new PortalAPIException("loginId not equals to the user loginId field");
             } else if (user.getLoginId() == null) {
                 user.setLoginId(loginId);
             }
-
             User asdcUser = EcompUserConverter.convertEcompUserToUser(user);
-            Either<User, ResponseFormat> updateUserCredentialsResponse =
-                    userBusinessLogic.updateUserCredentials(asdcUser);
-
+            Either<User, ResponseFormat> updateUserCredentialsResponse = userBusinessLogic.updateUserCredentials(asdcUser);
             if (updateUserCredentialsResponse.isRight()) {
                 log.debug(FAILED_TO_UPDATE_USER_CREDENTIALS);
-                BeEcompErrorManager.getInstance()
-                        .logInvalidInputError(EDIT_USER, FAILED_TO_UPDATE_USER_CREDENTIALS, ErrorSeverity.ERROR);
+                BeEcompErrorManager.getInstance().logInvalidInputError(EDIT_USER, FAILED_TO_UPDATE_USER_CREDENTIALS, ErrorSeverity.ERROR);
                 throw new PortalAPIException(FAILED_TO_EDIT_USER + updateUserCredentialsResponse.right().value());
             }
         } catch (Exception e) {
             log.debug(FAILED_TO_UPDATE_USER_CREDENTIALS);
             throw new PortalAPIException(FAILED_TO_EDIT_USER, e);
         }
-
     }
 
     @Override
@@ -168,8 +151,7 @@ public class EcompIntImpl implements IPortalRestAPIService {
         try {
             if (loginId == null) {
                 log.debug(RECEIVED_NULL_FOR_ARGUMENT_LOGIN_ID);
-                BeEcompErrorManager.getInstance()
-                        .logInvalidInputError(GET_USER, RECEIVED_NULL_FOR_ARGUMENT_LOGIN_ID, ErrorSeverity.INFO);
+                BeEcompErrorManager.getInstance().logInvalidInputError(GET_USER, RECEIVED_NULL_FOR_ARGUMENT_LOGIN_ID, ErrorSeverity.INFO);
                 throw new PortalAPIException(RECEIVED_NULL_FOR_ARGUMENT_LOGIN_ID);
             }
             UserBusinessLogic userBusinessLogic = getUserBusinessLogic();
@@ -179,15 +161,13 @@ public class EcompIntImpl implements IPortalRestAPIService {
                 return ecompUser.left().value();
             } else {
                 log.debug(FAILED_TO_GET_USER);
-                BeEcompErrorManager.getInstance()
-                        .logInvalidInputError(GET_USER, FAILED_TO_GET_USER, ErrorSeverity.INFO);
+                BeEcompErrorManager.getInstance().logInvalidInputError(GET_USER, FAILED_TO_GET_USER, ErrorSeverity.INFO);
                 throw new PortalAPIException(ecompUser.right().value());
             }
         } catch (ComponentException ce) {
             log.debug(FAILED_TO_GET_USER);
             BeEcompErrorManager.getInstance().logInvalidInputError(GET_USER, FAILED_TO_GET_USER, ErrorSeverity.INFO);
             throw new PortalAPIException(FAILED_TO_GET_USER + ce.getActionStatus());
-
         } catch (Exception e) {
             log.debug(FAILED_TO_GET_USER);
             throw new PortalAPIException(FAILED_TO_GET_USER, e);
@@ -197,7 +177,6 @@ public class EcompIntImpl implements IPortalRestAPIService {
     @Override
     public List<EcompUser> getUsers() throws PortalAPIException {
         log.debug("Start handle request of ECOMP getUsers");
-
         try {
             UserBusinessLogic userBusinessLogic = getUserBusinessLogic();
             List<User> users = userBusinessLogic.getUsersList(JH0003, null, null);
@@ -207,8 +186,7 @@ public class EcompIntImpl implements IPortalRestAPIService {
                 if (ecompUser.isRight() || ecompUser.left().value() == null) {
                     log.debug(FAILED_TO_CONVERT_USER2, user);
                     BeEcompErrorManager.getInstance()
-                            .logInvalidInputError(GET_USERS, "Failed to convert User" + user.toString(),
-                                                  ErrorSeverity.WARNING);
+                        .logInvalidInputError(GET_USERS, "Failed to convert User" + user.toString(), ErrorSeverity.WARNING);
                     continue;
                 }
                 ecompUserList.add(ecompUser.left().value());
@@ -232,19 +210,15 @@ public class EcompIntImpl implements IPortalRestAPIService {
                 ecompRole.setName(role.name());
                 ecompRolesList.add(ecompRole);
             }
-
             if (ecompRolesList.isEmpty()) {
                 throw new PortalAPIException();
             }
-
             return ecompRolesList;
         } catch (Exception e) {
             log.debug(FAILED_TO_FETCH_ROLES);
-            BeEcompErrorManager.getInstance()
-                    .logInvalidInputError("GetAvailableRoles", FAILED_TO_FETCH_ROLES, ErrorSeverity.INFO);
+            BeEcompErrorManager.getInstance().logInvalidInputError("GetAvailableRoles", FAILED_TO_FETCH_ROLES, ErrorSeverity.INFO);
             throw new PortalAPIException("Roles fetching failed", e);
         }
-
     }
 
     /**
@@ -253,14 +227,10 @@ public class EcompIntImpl implements IPortalRestAPIService {
     @Override
     public void pushUserRole(String loginId, List<EcompRole> roles) throws PortalAPIException {
         log.debug("Start handle request of ECOMP pushUserRole");
-
         final String modifierAttId = JH0003;
         log.debug("modifier id is {}", modifierAttId);
-
         UserBusinessLogic userBusinessLogic = getUserBusinessLogic();
-
         String updatedRole;
-
         if (roles == null) {
             throw new PortalAPIException("Error: Received null for roles");
         } else if (roles.iterator().hasNext()) {
@@ -271,21 +241,18 @@ public class EcompIntImpl implements IPortalRestAPIService {
                 userBusinessLogic.updateUserRole(modifierAttId, loginId, updatedRole);
             } catch (Exception e) {
                 log.debug("Error: Failed to update role");
-                BeEcompErrorManager.getInstance()
-                        .logInvalidInputError(PUSH_USER_ROLE, "Failed to update role", ErrorSeverity.INFO);
+                BeEcompErrorManager.getInstance().logInvalidInputError(PUSH_USER_ROLE, "Failed to update role", ErrorSeverity.INFO);
                 throw new PortalAPIException("Failed to update role" + e);
             }
         } else {
             log.debug("Error: No roles in List");
-            BeEcompErrorManager.getInstance()
-                    .logInvalidInputError(PUSH_USER_ROLE, FAILED_TO_FETCH_ROLES, ErrorSeverity.INFO);
+            BeEcompErrorManager.getInstance().logInvalidInputError(PUSH_USER_ROLE, FAILED_TO_FETCH_ROLES, ErrorSeverity.INFO);
             //in this cases we want to deactivate the user
             try {
                 getUserBusinessLogicExt().deActivateUser(modifierAttId, loginId);
             } catch (Exception e) {
                 log.debug("Error: Failed to deactivate user {}", loginId);
-                BeEcompErrorManager.getInstance()
-                        .logInvalidInputError(PUSH_USER_ROLE, "Failed to deactivate user", ErrorSeverity.INFO);
+                BeEcompErrorManager.getInstance().logInvalidInputError(PUSH_USER_ROLE, "Failed to deactivate user", ErrorSeverity.INFO);
                 throw new PortalAPIException("Error: Failed to deactivate user" + e);
             }
         }
@@ -300,41 +267,34 @@ public class EcompIntImpl implements IPortalRestAPIService {
             Either<EcompUser, String> ecompUser = EcompUserConverter.convertUserToEcompUser(user);
             if (ecompUser.isRight()) {
                 log.debug("Error: Failed to convert Roles");
-                BeEcompErrorManager.getInstance()
-                        .logInvalidInputError(GET_USER_ROLES, FAILED_TO_CONVERT_ROLES, ErrorSeverity.ERROR);
+                BeEcompErrorManager.getInstance().logInvalidInputError(GET_USER_ROLES, FAILED_TO_CONVERT_ROLES, ErrorSeverity.ERROR);
                 throw new PortalAPIException(ecompUser.right().value());
             } else if (ecompUser.left().value() == null) {
                 log.debug("Error: Failed to convert Roles");
-                BeEcompErrorManager.getInstance()
-                        .logInvalidInputError(GET_USER_ROLES, FAILED_TO_CONVERT_ROLES, ErrorSeverity.ERROR);
+                BeEcompErrorManager.getInstance().logInvalidInputError(GET_USER_ROLES, FAILED_TO_CONVERT_ROLES, ErrorSeverity.ERROR);
                 throw new PortalAPIException();
             }
             return new LinkedList<>(ecompUser.left().value().getRoles());
         } catch (ComponentException ce) {
             log.debug(ERROR_FAILED_TO_GET_ROLES);
-            BeEcompErrorManager.getInstance()
-                    .logInvalidInputError(GET_USER_ROLES, FAILED_TO_GET_ROLES, ErrorSeverity.INFO);
+            BeEcompErrorManager.getInstance().logInvalidInputError(GET_USER_ROLES, FAILED_TO_GET_ROLES, ErrorSeverity.INFO);
             throw new PortalAPIException(FAILED_TO_GET_ROLES + ce.getActionStatus());
         } catch (Exception e) {
             log.debug(ERROR_FAILED_TO_GET_ROLES);
-            BeEcompErrorManager.getInstance()
-                    .logInvalidInputError(GET_USER_ROLES, FAILED_TO_GET_ROLES, ErrorSeverity.INFO);
+            BeEcompErrorManager.getInstance().logInvalidInputError(GET_USER_ROLES, FAILED_TO_GET_ROLES, ErrorSeverity.INFO);
             throw new PortalAPIException(FAILED_TO_GET_ROLES, e);
         }
     }
 
     @Override
-    public boolean isAppAuthenticated(HttpServletRequest request, Map<String, String> appCredentials)
-            throws PortalAPIException {
+    public boolean isAppAuthenticated(HttpServletRequest request, Map<String, String> appCredentials) throws PortalAPIException {
         final String portal_key = PortalApiProperties.getProperty("portal_pass");
         final String portal_user = PortalApiProperties.getProperty("portal_user");
         final String username = request.getHeader("username");
         final String password = request.getHeader("password");
-
         if (username != null && password != null) {
             try {
-                if (username.equals(CipherUtil.decryptPKC(portal_user))
-                        && password.equals(CipherUtil.decryptPKC(portal_key))) {
+                if (username.equals(CipherUtil.decryptPKC(portal_user)) && password.equals(CipherUtil.decryptPKC(portal_key))) {
                     log.debug("User authenticated - Username: {}", username);
                     return true;
                 }
@@ -358,13 +318,10 @@ public class EcompIntImpl implements IPortalRestAPIService {
     }
 
     /**
-     * Gets and returns the userId for the logged-in user based on the request.
-     * If any error occurs, the method should throw PortalApiException with an
-     * appropriate message. The FW library will catch the exception and send an
-     * appropriate response to Portal.
-     * However, the app can always choose to have a custom implementation of
-     * this method. For Open-source implementation, for example, the app will
-     * have a totally different implementation for this method.
+     * Gets and returns the userId for the logged-in user based on the request. If any error occurs, the method should throw PortalApiException with
+     * an appropriate message. The FW library will catch the exception and send an appropriate response to Portal. However, the app can always choose
+     * to have a custom implementation of this method. For Open-source implementation, for example, the app will have a totally different
+     * implementation for this method.
      *
      * @param request The HttpServletRequest
      * @return true if the request contains appropriate credentials, else false.
index b8ecbac..ddbbc92 100644 (file)
  * limitations under the License.
  * ============LICENSE_END=========================================================
  */
-
 package org.openecomp.sdc.be.ecomp;
 
 public enum PortalPropertiesEnum {
-    APP_NAME("portal_app_name"),
-    ECOMP_REST_URL("ecomp_rest_url"),
-    PASSWORD("portal_pass"),
-    UEB_APP_KEY("ueb_app_key"),
-    USER("portal_user");
-
+    APP_NAME("portal_app_name"), ECOMP_REST_URL("ecomp_rest_url"), PASSWORD("portal_pass"), UEB_APP_KEY("ueb_app_key"), USER("portal_user");
     private final String value;
 
     PortalPropertiesEnum(String value) {
@@ -36,4 +30,4 @@ public enum PortalPropertiesEnum {
     public String value() {
         return value;
     }
-}
\ No newline at end of file
+}
index 757eeb8..55ce879 100644 (file)
@@ -17,7 +17,6 @@
  * limitations under the License.
  * ============LICENSE_END=========================================================
  */
-
 package org.openecomp.sdc.be.ecomp;
 
 import fj.data.Either;
@@ -44,6 +43,7 @@ import org.springframework.context.ApplicationContext;
 import org.springframework.web.context.ContextLoader;
 
 public final class PortalRestApiCentralServiceImpl implements IPortalRestCentralService {
+
     private static final String FAILED_TO_UPDATE_USER_CREDENTIALS = "Failed to update user credentials";
     private static final String FAILED_TO_DEACTIVATE_USER = "Failed to deactivate user {}";
     private static final String FAILED_TO_EDIT_USER = "Failed to edit user";
@@ -69,8 +69,8 @@ public final class PortalRestApiCentralServiceImpl implements IPortalRestCentral
             userBusinessLogicExt = (UserBusinessLogicExt) ctx.getBean("userBusinessLogicExt");
         } catch (Exception e) {
             log.debug("Failed to get user UserBusinessLogic", e);
-            BeEcompErrorManager.getInstance().logInvalidInputError("constructor", "Exception thrown" + e.getMessage(),
-                                                                   BeEcompErrorManager.ErrorSeverity.ERROR);
+            BeEcompErrorManager.getInstance()
+                .logInvalidInputError("constructor", "Exception thrown" + e.getMessage(), BeEcompErrorManager.ErrorSeverity.ERROR);
             throw new PortalAPIException("SDC Internal server error");
         }
         log.debug("PortalRestApiCentralServiceImpl Class Instantiated");
@@ -82,6 +82,18 @@ public final class PortalRestApiCentralServiceImpl implements IPortalRestCentral
         this.userBusinessLogicExt = uble;
     }
 
+    public static void checkIfSingleRoleProvided(EcompUser user) throws PortalAPIException {
+        if (user.getRoles() == null) {
+            log.debug(RECEIVED_NULL_ROLES, user);
+            BeEcompErrorManager.getInstance().logInvalidInputError(CHECK_ROLES, RECEIVED_NULL_ROLES, BeEcompErrorManager.ErrorSeverity.ERROR);
+            throw new PortalAPIException(RECEIVED_NULL_ROLES + user);
+        } else if (user.getRoles().size() > 1) {
+            log.debug(RECEIVED_MULTIPLE_ROLES, user);
+            BeEcompErrorManager.getInstance().logInvalidInputError(CHECK_ROLES, RECEIVED_MULTIPLE_ROLES2, BeEcompErrorManager.ErrorSeverity.ERROR);
+            throw new PortalAPIException(RECEIVED_MULTIPLE_ROLES2 + user);
+        }
+    }
+
     @Override
     public Map<String, String> getAppCredentials() throws PortalAPIException {
         Map<String, String> credMap = new HashMap<>();
@@ -103,30 +115,24 @@ public final class PortalRestApiCentralServiceImpl implements IPortalRestCentral
     @Override
     public void pushUser(EcompUser user) throws PortalAPIException {
         log.debug("Start handle request of ECOMP pushUser");
-
         if (user == null) {
-            BeEcompErrorManager.getInstance().logInvalidInputError(PUSH_USER, RECEIVED_NULL_FOR_ARGUMENT_USER,
-                                                                   BeEcompErrorManager.ErrorSeverity.INFO);
+            BeEcompErrorManager.getInstance()
+                .logInvalidInputError(PUSH_USER, RECEIVED_NULL_FOR_ARGUMENT_USER, BeEcompErrorManager.ErrorSeverity.INFO);
             log.debug(RECEIVED_NULL_FOR_ARGUMENT_USER);
             throw new PortalAPIException(RECEIVED_NULL_FOR_ARGUMENT_USER);
         }
         checkIfSingleRoleProvided(user);
-
         final String modifierAttId = JH0003;
         log.debug("modifier id is {}", modifierAttId);
-
         User convertedAsdcUser = EcompUserConverter.convertEcompUserToUser(user);
-
         try {
             log.debug("Before creating ecomp user {} sdc user {}", user, convertedAsdcUser);
             userBusinessLogic.createUser(modifierAttId, convertedAsdcUser);
         } catch (Exception e) {
             log.debug(FAILED_TO_CREATE_USER, user, e);
-            BeEcompErrorManager.getInstance()
-                    .logInvalidInputError(PUSH_USER, FAILED_TO_CREATE_USER, BeEcompErrorManager.ErrorSeverity.ERROR);
+            BeEcompErrorManager.getInstance().logInvalidInputError(PUSH_USER, FAILED_TO_CREATE_USER, BeEcompErrorManager.ErrorSeverity.ERROR);
             throw new PortalAPIException(FAILED_TO_CREATE_USER + e.getMessage());
         }
-
         log.debug("User created ecomp user {} sdc user {}", user, convertedAsdcUser);
     }
 
@@ -134,31 +140,26 @@ public final class PortalRestApiCentralServiceImpl implements IPortalRestCentral
     public void editUser(String loginId, EcompUser user) throws PortalAPIException {
         if (user == null) {
             log.debug(RECEIVED_NULL_FOR_ARGUMENT_USER);
-            BeEcompErrorManager.getInstance().logInvalidInputError(EDIT_USER, RECEIVED_NULL_FOR_ARGUMENT_USER,
-                                                                   BeEcompErrorManager.ErrorSeverity.INFO);
+            BeEcompErrorManager.getInstance()
+                .logInvalidInputError(EDIT_USER, RECEIVED_NULL_FOR_ARGUMENT_USER, BeEcompErrorManager.ErrorSeverity.INFO);
             throw new PortalAPIException(RECEIVED_NULL_FOR_ARGUMENT_USER);
         } else if (loginId == null) {
             log.debug(RECEIVED_NULL_FOR_ARGUMENT_LOGIN_ID);
-            BeEcompErrorManager.getInstance().logInvalidInputError(EDIT_USER, RECEIVED_NULL_FOR_ARGUMENT_LOGIN_ID,
-                                                                   BeEcompErrorManager.ErrorSeverity.INFO);
+            BeEcompErrorManager.getInstance()
+                .logInvalidInputError(EDIT_USER, RECEIVED_NULL_FOR_ARGUMENT_LOGIN_ID, BeEcompErrorManager.ErrorSeverity.INFO);
             throw new PortalAPIException(RECEIVED_NULL_FOR_ARGUMENT_LOGIN_ID);
         }
-
-        log.debug("Start handle request of ECOMP editUser {} with loginId {} with follopwing roles {}", user, loginId,
-                  user.getRoles());
-
+        log.debug("Start handle request of ECOMP editUser {} with loginId {} with follopwing roles {}", user, loginId, user.getRoles());
         final String modifierAttId = JH0003;
         log.debug("modifier id is {}", modifierAttId);
-
         if (user.getLoginId() != null && !user.getLoginId().equals(loginId)) {
             log.debug("loginId and user loginId not equal");
-            BeEcompErrorManager.getInstance().logInvalidInputError(EDIT_USER, "loginId and user loginId not equal",
-                                                                   BeEcompErrorManager.ErrorSeverity.INFO);
+            BeEcompErrorManager.getInstance()
+                .logInvalidInputError(EDIT_USER, "loginId and user loginId not equal", BeEcompErrorManager.ErrorSeverity.INFO);
             throw new PortalAPIException("loginId not equals to the user loginId field");
         } else if (user.getLoginId() == null) {
             user.setLoginId(loginId);
         }
-
         Either<User, ActionStatus> verifyNewUser;
         try {
             verifyNewUser = userBusinessLogic.verifyNewUserForPortal(user.getLoginId());
@@ -166,26 +167,21 @@ public final class PortalRestApiCentralServiceImpl implements IPortalRestCentral
             log.debug("Failed to verify new user", e);
             throw new PortalAPIException(e.getCause());
         }
-
-        if (verifyNewUser.isRight()
-                && (ActionStatus.USER_NOT_FOUND.equals(verifyNewUser.right().value())
-                || ActionStatus.USER_INACTIVE.equals(verifyNewUser.right().value()))) {
+        if (verifyNewUser.isRight() && (ActionStatus.USER_NOT_FOUND.equals(verifyNewUser.right().value()) || ActionStatus.USER_INACTIVE
+            .equals(verifyNewUser.right().value()))) {
             log.debug("Edit user for user that not exist in DB, executing push user flow {}", user);
             pushUser(user);
             return;
         }
-
         User asdcUser = EcompUserConverter.convertEcompUserToUser(user);
         log.debug("Before editing ecomp user {} sdc user {}", user, asdcUser);
         Either<User, ResponseFormat> updateUserCredentialsResponse = userBusinessLogic.updateUserCredentials(asdcUser);
-
         if (updateUserCredentialsResponse.isRight()) {
             log.debug(FAILED_TO_UPDATE_USER_CREDENTIALS);
-            BeEcompErrorManager.getInstance().logInvalidInputError(EDIT_USER, FAILED_TO_UPDATE_USER_CREDENTIALS,
-                                                                   BeEcompErrorManager.ErrorSeverity.ERROR);
+            BeEcompErrorManager.getInstance()
+                .logInvalidInputError(EDIT_USER, FAILED_TO_UPDATE_USER_CREDENTIALS, BeEcompErrorManager.ErrorSeverity.ERROR);
             throw new PortalAPIException(FAILED_TO_EDIT_USER + updateUserCredentialsResponse.right().value());
         }
-
         if (user.getRoles() == null || user.getRoles().isEmpty()) {
             try {
                 log.debug("Before deactivating ecomp user {} sdc user {}", user, asdcUser);
@@ -193,8 +189,7 @@ public final class PortalRestApiCentralServiceImpl implements IPortalRestCentral
             } catch (Exception e) {
                 log.debug("Error: Failed to deactivate user {}", loginId);
                 BeEcompErrorManager.getInstance()
-                        .logInvalidInputError(FAILED_TO_DEACTIVATE_USER, "Failed to deactivate user",
-                                              BeEcompErrorManager.ErrorSeverity.INFO);
+                    .logInvalidInputError(FAILED_TO_DEACTIVATE_USER, "Failed to deactivate user", BeEcompErrorManager.ErrorSeverity.INFO);
                 throw new PortalAPIException("Error: Failed to deactivate user" + e);
             }
         } else {
@@ -205,8 +200,7 @@ public final class PortalRestApiCentralServiceImpl implements IPortalRestCentral
             } catch (Exception e) {
                 log.debug("Error: Failed to update user role {}", loginId);
                 BeEcompErrorManager.getInstance()
-                        .logInvalidInputError(FAILED_TO_EDIT_USER, "Failed to update user role",
-                                              BeEcompErrorManager.ErrorSeverity.INFO);
+                    .logInvalidInputError(FAILED_TO_EDIT_USER, "Failed to update user role", BeEcompErrorManager.ErrorSeverity.INFO);
                 throw new PortalAPIException("Error: Failed to update user role" + e);
             }
         }
@@ -218,27 +212,10 @@ public final class PortalRestApiCentralServiceImpl implements IPortalRestCentral
         String header = request.getHeader(Constants.USER_ID_HEADER);
         if (header == null) {
             log.debug(FAILED_TO_GET_USER_ID_HEADER);
-            BeEcompErrorManager.getInstance().logInvalidInputError("getUserId", FAILED_TO_GET_USER_ID_HEADER,
-                                                                   BeEcompErrorManager.ErrorSeverity.ERROR);
+            BeEcompErrorManager.getInstance()
+                .logInvalidInputError("getUserId", FAILED_TO_GET_USER_ID_HEADER, BeEcompErrorManager.ErrorSeverity.ERROR);
             throw new PortalAPIException(FAILED_TO_GET_USER_ID_HEADER);
         }
         return header;
     }
-
-
-    public static void checkIfSingleRoleProvided(EcompUser user) throws PortalAPIException {
-        if (user.getRoles() == null) {
-            log.debug(RECEIVED_NULL_ROLES, user);
-            BeEcompErrorManager.getInstance()
-                    .logInvalidInputError(CHECK_ROLES, RECEIVED_NULL_ROLES, BeEcompErrorManager.ErrorSeverity.ERROR);
-            throw new PortalAPIException(RECEIVED_NULL_ROLES + user);
-        } else if (user.getRoles().size() > 1) {
-            log.debug(RECEIVED_MULTIPLE_ROLES, user);
-            BeEcompErrorManager.getInstance().logInvalidInputError(CHECK_ROLES, RECEIVED_MULTIPLE_ROLES2,
-                                                                   BeEcompErrorManager.ErrorSeverity.ERROR);
-            throw new PortalAPIException(RECEIVED_MULTIPLE_ROLES2 + user);
-        }
-    }
-
-
 }
index 0729ee2..0d43082 100644 (file)
@@ -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.
  * limitations under the License.
  * ============LICENSE_END=========================================================
  */
-
 package org.openecomp.sdc.be.ecomp.converters;
 
 import fj.data.Either;
+import java.util.Collection;
+import java.util.HashMap;
+import java.util.LinkedList;
+import java.util.List;
+import java.util.Map;
 import org.apache.commons.collections.MapUtils;
 import org.apache.commons.lang3.tuple.ImmutablePair;
 import org.openecomp.sdc.be.dao.api.ActionStatus;
@@ -46,31 +50,24 @@ import org.openecomp.sdc.common.log.wrappers.Logger;
 import org.openecomp.sdc.exception.ResponseFormat;
 import org.springframework.beans.factory.annotation.Autowired;
 
-import java.util.Collection;
-import java.util.HashMap;
-import java.util.LinkedList;
-import java.util.List;
-import java.util.Map;
-
 @org.springframework.stereotype.Component("asset-metadata-utils")
 public class AssetMetadataConverter {
-    private static final Logger log = Logger.getLogger(DistributionCatalogServlet.class);
-
-    @Autowired
-    private ComponentsUtils componentsUtils;
 
+    private static final Logger log = Logger.getLogger(DistributionCatalogServlet.class);
     @Autowired
     protected ToscaOperationFacade toscaOperationFacade;
+    @Autowired
+    private ComponentsUtils componentsUtils;
 
     /*
      * Relative asset’s URL. Should be used in REST GET API to download the asset’s CSAR. https://{serverBaseURL}/{csarPath} can be obtained from (HttpServletRequest)request.getServerName()
      */
-    public Either<List<? extends AssetMetadata>, ResponseFormat> convertToAssetMetadata(List<? extends Component> componentList, String serverBaseURL, boolean detailed) {
+    public Either<List<? extends AssetMetadata>, ResponseFormat> convertToAssetMetadata(List<? extends Component> componentList, String serverBaseURL,
+                                                                                        boolean detailed) {
         if (componentList == null || componentList.isEmpty()) {
             return Either.left(new LinkedList<>());
         }
         List<AssetMetadata> retResList = new LinkedList<>();
-
         for (Component curr : componentList) {
             Either<? extends AssetMetadata, ResponseFormat> resMetaData = convertToSingleAssetMetadata(curr, serverBaseURL, detailed);
             if (resMetaData.isRight()) {
@@ -78,40 +75,30 @@ public class AssetMetadataConverter {
             }
             retResList.add(resMetaData.left().value());
         }
-
         return Either.left(retResList);
-
     }
 
-    public <T extends Component> Either<? extends AssetMetadata, ResponseFormat> convertToSingleAssetMetadata(T component, String serverBaseURL, boolean detailed) {
+    public <T extends Component> Either<? extends AssetMetadata, ResponseFormat> convertToSingleAssetMetadata(T component, String serverBaseURL,
+                                                                                                              boolean detailed) {
         ComponentTypeEnum componentType = component.getComponentType();
         Either<? extends AssetMetadata, ResponseFormat> resMetaData = convertToMetadata(componentType, serverBaseURL, detailed, component);
-
         if (resMetaData.isRight()) {
             return Either.right(resMetaData.right().value());
-        }
-        else{
+        } else {
             return Either.left(resMetaData.left().value());
         }
-
     }
 
-    private Either<? extends AssetMetadata, ResponseFormat> convertToMetadata(ComponentTypeEnum componentType, String serverBaseURL, boolean detailed, Component curr) {
-
+    private Either<? extends AssetMetadata, ResponseFormat> convertToMetadata(ComponentTypeEnum componentType, String serverBaseURL, boolean detailed,
+                                                                              Component curr) {
         switch (componentType) {
-
-        case RESOURCE:
-
-            return generateResourceMeatdata(serverBaseURL, detailed, curr);
-
-        case SERVICE:
-
-            return generateServiceMetadata(serverBaseURL, detailed, curr);
-
-        default:
-
-            ResponseFormat responseFormat = componentsUtils.getResponseFormatAdditionalProperty(ActionStatus.COMPONENT_INVALID_CATEGORY);
-            return Either.right(responseFormat);
+            case RESOURCE:
+                return generateResourceMeatdata(serverBaseURL, detailed, curr);
+            case SERVICE:
+                return generateServiceMetadata(serverBaseURL, detailed, curr);
+            default:
+                ResponseFormat responseFormat = componentsUtils.getResponseFormatAdditionalProperty(ActionStatus.COMPONENT_INVALID_CATEGORY);
+                return Either.right(responseFormat);
         }
     }
 
@@ -119,56 +106,53 @@ public class AssetMetadataConverter {
         AssetMetadata metaData;
         metaData = createMetadaObject(detailed, curr.getComponentType());
         metaData = convertToResourceMetadata((ResourceAssetMetadata) metaData, (Resource) curr, serverBaseURL, detailed);
-
         if (detailed) {
-            Either<ResourceAssetDetailedMetadata, StorageOperationStatus> converted = convertToResourceDetailedMetadata((ResourceAssetDetailedMetadata) metaData, (Resource) curr, serverBaseURL);
+            Either<ResourceAssetDetailedMetadata, StorageOperationStatus> converted = convertToResourceDetailedMetadata(
+                (ResourceAssetDetailedMetadata) metaData, (Resource) curr, serverBaseURL);
             if (converted.isRight()) {
                 ActionStatus storageResponse = componentsUtils.convertFromStorageResponse(converted.right().value(), ComponentTypeEnum.RESOURCE);
                 ResponseFormat responseFormat = componentsUtils.getResponseFormat(storageResponse);
                 return Either.right(responseFormat);
             }
         }
-
         return Either.left(metaData);
     }
 
     private AssetMetadata createMetadaObject(boolean detailed, ComponentTypeEnum type) {
         AssetMetadata metaData = null;
         switch (type) {
-        case SERVICE:
-            if (!detailed) {
-                metaData = new ServiceAssetMetadata();
-            } else {
-                metaData = new ServiceAssetDetailedMetadata();
-            }
-            break;
-        case RESOURCE:
-            if (!detailed) {
-                metaData = new ResourceAssetMetadata();
-            } else {
-                metaData = new ResourceAssetDetailedMetadata();
-            }
-            break;
-        default:
-            break;
+            case SERVICE:
+                if (!detailed) {
+                    metaData = new ServiceAssetMetadata();
+                } else {
+                    metaData = new ServiceAssetDetailedMetadata();
+                }
+                break;
+            case RESOURCE:
+                if (!detailed) {
+                    metaData = new ResourceAssetMetadata();
+                } else {
+                    metaData = new ResourceAssetDetailedMetadata();
+                }
+                break;
+            default:
+                break;
         }
         return metaData;
     }
 
     private Either<? extends AssetMetadata, ResponseFormat> generateServiceMetadata(String serverBaseURL, boolean detailed, Component curr) {
         AssetMetadata metaData = createMetadaObject(detailed, curr.getComponentType());
-
         metaData = convertToServiceAssetMetadata((ServiceAssetMetadata) metaData, (Service) curr, serverBaseURL, detailed);
-
         if (detailed) {
-            Either<ServiceAssetDetailedMetadata, StorageOperationStatus> converted = convertToServiceDetailedMetadata((ServiceAssetDetailedMetadata) metaData, (Service) curr);
+            Either<ServiceAssetDetailedMetadata, StorageOperationStatus> converted = convertToServiceDetailedMetadata(
+                (ServiceAssetDetailedMetadata) metaData, (Service) curr);
             if (converted.isRight()) {
                 ActionStatus storageResponse = componentsUtils.convertFromStorageResponse(converted.right().value(), ComponentTypeEnum.RESOURCE);
                 ResponseFormat responseFormat = componentsUtils.getResponseFormat(storageResponse);
                 return Either.right(responseFormat);
             }
         }
-
         return Either.left(metaData);
     }
 
@@ -183,13 +167,13 @@ public class AssetMetadataConverter {
             String toscaModelUrl = (new String(serverBaseURL)).replace("metadata", "toscaModel");
             asset.setToscaModelURL(toscaModelUrl);
         }
-
         return asset;
     }
 
-    private <T extends ResourceAssetMetadata> T convertToResourceMetadata(T assetToPopulate, Resource resource, String serverBaseURL, boolean detailed) {
+    private <T extends ResourceAssetMetadata> T convertToResourceMetadata(T assetToPopulate, Resource resource, String serverBaseURL,
+                                                                          boolean detailed) {
         assetToPopulate = convertToAsset(assetToPopulate, resource, serverBaseURL, detailed);
-        if(resource.getCategories() != null && !resource.getCategories().isEmpty()){
+        if (resource.getCategories() != null && !resource.getCategories().isEmpty()) {
             CategoryDefinition categoryDefinition = resource.getCategories().get(0);
             assetToPopulate.setCategory(categoryDefinition.getName());
             assetToPopulate.setSubCategory(categoryDefinition.getSubcategories().get(0).getName());
@@ -197,94 +181,81 @@ public class AssetMetadataConverter {
         assetToPopulate.setResourceType(resource.getResourceType().name());
         assetToPopulate.setLifecycleState(resource.getLifecycleState().name());
         assetToPopulate.setLastUpdaterUserId(resource.getLastUpdaterUserId());
-
         return (T) assetToPopulate;
     }
 
-    private <T extends ServiceAssetMetadata> T convertToServiceAssetMetadata(T assetToPopulate, Service service, String serverBaseURL, boolean detailed) {
+    private <T extends ServiceAssetMetadata> T convertToServiceAssetMetadata(T assetToPopulate, Service service, String serverBaseURL,
+                                                                             boolean detailed) {
         assetToPopulate = convertToAsset(assetToPopulate, service, serverBaseURL, detailed);
-
-        if(service.getCategories() != null && !service.getCategories().isEmpty()){
+        if (service.getCategories() != null && !service.getCategories().isEmpty()) {
             CategoryDefinition categoryDefinition = service.getCategories().get(0);
             assetToPopulate.setCategory(categoryDefinition.getName());
         }
-
         assetToPopulate.setLifecycleState(service.getLifecycleState().name());
         assetToPopulate.setLastUpdaterUserId(service.getLastUpdaterUserId());
         assetToPopulate.setDistributionStatus(service.getDistributionStatus().name());
-
         return (T) assetToPopulate;
     }
 
-    private <T extends ResourceAssetDetailedMetadata> Either<T, StorageOperationStatus> convertToResourceDetailedMetadata(T assetToPopulate, Resource resource, String serverBaseURL) {
-
+    private <T extends ResourceAssetDetailedMetadata> Either<T, StorageOperationStatus> convertToResourceDetailedMetadata(T assetToPopulate,
+                                                                                                                          Resource resource,
+                                                                                                                          String serverBaseURL) {
         List<ComponentInstance> componentInstances = resource.getComponentInstances();
-
         if (componentInstances != null) {
-            Either<List<ResourceInstanceMetadata>, StorageOperationStatus> resourceInstanceMetadata = convertToResourceInstanceMetadata(componentInstances, ComponentTypeEnum.RESOURCE_PARAM_NAME, resource.getUUID());
+            Either<List<ResourceInstanceMetadata>, StorageOperationStatus> resourceInstanceMetadata = convertToResourceInstanceMetadata(
+                componentInstances, ComponentTypeEnum.RESOURCE_PARAM_NAME, resource.getUUID());
             if (resourceInstanceMetadata.isRight()) {
                 return Either.right(resourceInstanceMetadata.right().value());
             }
-
             assetToPopulate.setResources(resourceInstanceMetadata.left().value());
         }
-
         Map<String, ArtifactDefinition> deploymentArtifacts = resource.getDeploymentArtifacts();
         assetToPopulate = populateResourceWithArtifacts(assetToPopulate, resource, deploymentArtifacts);
-
         assetToPopulate.setLastUpdaterFullName(resource.getLastUpdaterFullName());
         assetToPopulate.setToscaResourceName(resource.getToscaResourceName());
         assetToPopulate.setDescription(resource.getDescription());
         return Either.left(assetToPopulate);
     }
 
-    private <T extends ServiceAssetDetailedMetadata> Either<T, StorageOperationStatus> convertToServiceDetailedMetadata(T assetToPopulate, Service service) {
-
+    private <T extends ServiceAssetDetailedMetadata> Either<T, StorageOperationStatus> convertToServiceDetailedMetadata(T assetToPopulate,
+                                                                                                                        Service service) {
         List<ComponentInstance> componentInstances = service.getComponentInstances();
-
         if (componentInstances != null) {
-            Either<List<ResourceInstanceMetadata>, StorageOperationStatus> resourceInstanceMetadata = convertToResourceInstanceMetadata(componentInstances, ComponentTypeEnum.SERVICE_PARAM_NAME, service.getUUID());
+            Either<List<ResourceInstanceMetadata>, StorageOperationStatus> resourceInstanceMetadata = convertToResourceInstanceMetadata(
+                componentInstances, ComponentTypeEnum.SERVICE_PARAM_NAME, service.getUUID());
             if (resourceInstanceMetadata.isRight()) {
                 return Either.right(resourceInstanceMetadata.right().value());
             }
-
             assetToPopulate.setResources(resourceInstanceMetadata.left().value());
         }
-
         Map<String, ArtifactDefinition> deploymentArtifacts = service.getDeploymentArtifacts();
         assetToPopulate = populateServiceWithArtifacts(assetToPopulate, service, deploymentArtifacts);
-
         assetToPopulate.setLastUpdaterFullName(service.getLastUpdaterFullName());
-
         return Either.left(assetToPopulate);
     }
 
-    private <T extends ResourceAssetDetailedMetadata> T populateResourceWithArtifacts(T asset, Resource resource, Map<String, ArtifactDefinition> artifacts) {
-
+    private <T extends ResourceAssetDetailedMetadata> T populateResourceWithArtifacts(T asset, Resource resource,
+                                                                                      Map<String, ArtifactDefinition> artifacts) {
         List<ArtifactMetadata> artifactMetaList = populateAssetWithArtifacts(resource, artifacts);
-
         asset.setArtifacts(artifactMetaList);
-
         return asset;
     }
 
-    private <T extends ServiceAssetDetailedMetadata> T populateServiceWithArtifacts(T asset, Service service, Map<String, ArtifactDefinition> artifacts) {
-
+    private <T extends ServiceAssetDetailedMetadata> T populateServiceWithArtifacts(T asset, Service service,
+                                                                                    Map<String, ArtifactDefinition> artifacts) {
         List<ArtifactMetadata> artifactMetaList = populateAssetWithArtifacts(service, artifacts);
-
         asset.setArtifacts(artifactMetaList);
-
         return asset;
     }
 
     private List<ArtifactMetadata> populateAssetWithArtifacts(Component component, Map<String, ArtifactDefinition> artifacts) {
-        List<ArtifactMetadata> artifactMetaList =  new LinkedList<>();
+        List<ArtifactMetadata> artifactMetaList = new LinkedList<>();
         if (artifacts != null) {
             Collection<ArtifactDefinition> artefactDefList = artifacts.values();
-
             for (ArtifactDefinition artifactDefinition : artefactDefList) {
                 if (artifactDefinition.getEsId() != null && !artifactDefinition.getEsId().isEmpty()) {
-                    ArtifactMetadata convertedArtifactMetadata = convertToArtifactMetadata(artifactDefinition, ComponentTypeEnum.findParamByType(component.getComponentType()), component.getUUID(), null);
+                    ArtifactMetadata convertedArtifactMetadata = convertToArtifactMetadata(artifactDefinition,
+                        ComponentTypeEnum.findParamByType(component.getComponentType()), component.getUUID(), null);
                     artifactMetaList.add(convertedArtifactMetadata);
                 }
             }
@@ -292,22 +263,19 @@ public class AssetMetadataConverter {
         return artifactMetaList.isEmpty() ? null : artifactMetaList;
     }
 
-    private ArtifactMetadata convertToArtifactMetadata(ArtifactDefinition artifact, String componentType, String componentUUID, String resourceInstanceName) {
+    private ArtifactMetadata convertToArtifactMetadata(ArtifactDefinition artifact, String componentType, String componentUUID,
+                                                       String resourceInstanceName) {
         final String COMPONENT_ARTIFACT_URL = "/sdc/v1/catalog/%s/%s/artifacts/%s";
-
         final String RESOURCE_INSTANCE_ARTIFACT_URL = "/sdc/v1/catalog/%s/%s/resourceInstances/%s/artifacts/%s";
-
         ArtifactMetadata metadata = new ArtifactMetadata();
-
         metadata.setArtifactName(artifact.getArtifactName());
         metadata.setArtifactType(artifact.getArtifactType());
-
         if (resourceInstanceName == null || resourceInstanceName.isEmpty()) {
             metadata.setArtifactURL(String.format(COMPONENT_ARTIFACT_URL, componentType, componentUUID, artifact.getArtifactUUID()));
         } else {
-            metadata.setArtifactURL(String.format(RESOURCE_INSTANCE_ARTIFACT_URL, componentType, componentUUID, resourceInstanceName, artifact.getArtifactUUID()));
+            metadata.setArtifactURL(
+                String.format(RESOURCE_INSTANCE_ARTIFACT_URL, componentType, componentUUID, resourceInstanceName, artifact.getArtifactUUID()));
         }
-
         metadata.setArtifactDescription(artifact.getDescription());
         metadata.setArtifactTimeout(artifact.getTimeout() != null && artifact.getTimeout() > 0 ? artifact.getTimeout() : null);
         metadata.setArtifactChecksum(artifact.getArtifactChecksum());
@@ -319,15 +287,14 @@ public class AssetMetadataConverter {
         return metadata;
     }
 
-    private Either<List<ResourceInstanceMetadata>, StorageOperationStatus> convertToResourceInstanceMetadata(List<ComponentInstance> componentInstances, String componentType, String componentUUID) {
+    private Either<List<ResourceInstanceMetadata>, StorageOperationStatus> convertToResourceInstanceMetadata(
+        List<ComponentInstance> componentInstances, String componentType, String componentUUID) {
         List<ResourceInstanceMetadata> retList = new LinkedList<>();
         Map<String, ImmutablePair<String, String>> uuidDuplicatesMap = new HashMap<>();
-
         for (ComponentInstance componentInstance : componentInstances) {
             ResourceInstanceMetadata metadata = new ResourceInstanceMetadata();
             String componentUid = componentInstance.getComponentUid();
             String invariantUUID, resourceUUID;
-
             if (!uuidDuplicatesMap.containsKey(componentUid)) {
                 Either<Resource, StorageOperationStatus> eitherResource = toscaOperationFacade.getToscaElement(componentInstance.getComponentUid());
                 if (eitherResource.isRight()) {
@@ -342,21 +309,20 @@ public class AssetMetadataConverter {
                 }
             } else {
                 invariantUUID = uuidDuplicatesMap.get(componentUid).getRight();
-                resourceUUID =  uuidDuplicatesMap.get(componentUid).getLeft();
+                resourceUUID = uuidDuplicatesMap.get(componentUid).getLeft();
             }
-
             metadata.setResourceInvariantUUID(invariantUUID);
             metadata.setResourceUUID(resourceUUID);
             metadata.setResourceInstanceName(componentInstance.getName());
             metadata.setResourceName(componentInstance.getComponentName());
             metadata.setResourceVersion(componentInstance.getComponentVersion());
             metadata.setResoucreType(componentInstance.getOriginType().getValue());
-
-            if(MapUtils.isNotEmpty(componentInstance.getDeploymentArtifacts())){
+            if (MapUtils.isNotEmpty(componentInstance.getDeploymentArtifacts())) {
                 LinkedList<ArtifactMetadata> artifactMetaList = new LinkedList<>();
                 Collection<ArtifactDefinition> values = componentInstance.getDeploymentArtifacts().values();
                 for (ArtifactDefinition artifactDefinition : values) {
-                    ArtifactMetadata converted = convertToArtifactMetadata(artifactDefinition, componentType, componentUUID, componentInstance.getNormalizedName());
+                    ArtifactMetadata converted = convertToArtifactMetadata(artifactDefinition, componentType, componentUUID,
+                        componentInstance.getNormalizedName());
                     artifactMetaList.add(converted);
                 }
                 metadata.setArtifacts(artifactMetaList);
@@ -365,5 +331,4 @@ public class AssetMetadataConverter {
         }
         return Either.left(retList);
     }
-
 }
index d7beb14..df8e97f 100644 (file)
@@ -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.
@@ -17,7 +17,6 @@
  * limitations under the License.
  * ============LICENSE_END=========================================================
  */
-
 package org.openecomp.sdc.be.ecomp.converters;
 
 import org.onap.portalsdk.core.onboarding.exception.PortalAPIException;
@@ -27,6 +26,7 @@ import org.openecomp.sdc.be.user.Role;
 import org.openecomp.sdc.common.log.wrappers.Logger;
 
 public final class EcompRoleConverter {
+
     private static final String FAILED_TO_CONVERT_USER = "Failed to convert user";
     private static final String EDIT_USER = "EditUser";
     private static final Logger log = Logger.getLogger(EcompRoleConverter.class);
@@ -35,16 +35,14 @@ public final class EcompRoleConverter {
     }
 
     public static String convertEcompRoleToRole(EcompRole ecompRole) throws PortalAPIException {
-
         log.debug("converting role{}", ecompRole);
         if (ecompRole == null) {
             log.debug("recieved null for roles");
             return null;
         }
-
         for (Role role : Role.values()) {
-            if (role.name().toLowerCase().equals(ecompRole.getName().toLowerCase())){
-                return  role.name();
+            if (role.name().toLowerCase().equals(ecompRole.getName().toLowerCase())) {
+                return role.name();
             }
         }
         BeEcompErrorManager.getInstance().logInvalidInputError(EDIT_USER, FAILED_TO_CONVERT_USER, BeEcompErrorManager.ErrorSeverity.INFO);
index ce23c6e..0fb42d2 100644 (file)
@@ -17,7 +17,6 @@
  * limitations under the License.
  * ============LICENSE_END=========================================================
  */
-
 package org.openecomp.sdc.be.ecomp.converters;
 
 import fj.data.Either;
@@ -38,23 +37,19 @@ public final class EcompUserConverter {
 
     public static Either<EcompUser, String> convertUserToEcompUser(User asdcUser) {
         EcompUser convertedUser = new EcompUser();
-
         if (asdcUser == null) {
             return Either.right("User is null");
         }
-
         convertedUser.setFirstName(asdcUser.getFirstName());
         convertedUser.setLastName(asdcUser.getLastName());
         convertedUser.setLoginId(asdcUser.getUserId());
         convertedUser.setOrgUserId(asdcUser.getUserId());
         convertedUser.setEmail(asdcUser.getEmail());
-
         if (asdcUser.getStatus().equals(UserStatusEnum.ACTIVE)) {
             convertedUser.setActive(true);
         } else if (asdcUser.getStatus().equals(UserStatusEnum.INACTIVE)) {
             convertedUser.setActive(false);
         }
-
         EcompRole convertedRole = new EcompRole();
         for (Role role : Role.values()) {
             if (role.name().equals(asdcUser.getRole()) || role.toString().equals(asdcUser.getRole())) {
@@ -63,47 +58,37 @@ public final class EcompUserConverter {
                 break;
             }
         }
-
         Set<EcompRole> convertedRoleSet = new HashSet<>();
         convertedRoleSet.add(convertedRole);
         convertedUser.setRoles(convertedRoleSet);
-
         return Either.left(convertedUser);
     }
 
     public static User convertEcompUserToUser(EcompUser ecompUser) throws PortalAPIException {
         User convertedUser = new User();
-
         if (ecompUser == null) {
             throw new PortalAPIException("ecomp user is null");
         }
-
         convertedUser.setFirstName(ecompUser.getFirstName());
         convertedUser.setLastName(ecompUser.getLastName());
-
         if (ecompUser.getLoginId() != null && !ecompUser.getLoginId().isEmpty()) {
             convertedUser.setUserId(ecompUser.getLoginId());
         } else {
             convertedUser.setUserId(ecompUser.getOrgUserId());
         }
-
         convertedUser.setEmail(ecompUser.getEmail());
-
         if (ecompUser.getRoles() != null) {
             Iterator<EcompRole> iter = ecompUser.getRoles().iterator();
-
             if (iter.hasNext()) {
                 String updatedRole = EcompRoleConverter.convertEcompRoleToRole(iter.next());
                 convertedUser.setRole(updatedRole);
             }
         }
-
         if (ecompUser.isActive()) {
             convertedUser.setStatus(UserStatusEnum.ACTIVE);
         } else {
             convertedUser.setStatus(UserStatusEnum.INACTIVE);
         }
-
         return convertedUser;
     }
 }
index a25bf1a..c92779f 100644 (file)
  * limitations under the License.
  * ============LICENSE_END=========================================================
  */
-
 package org.openecomp.sdc.be.exception;
 
-public class RestrictionAccessFilterException extends RuntimeException{
-    
+public class RestrictionAccessFilterException extends RuntimeException {
+
     public RestrictionAccessFilterException(Exception exception) {
         super(exception);
     }
-
 }
index b47d355..f8936b1 100644 (file)
@@ -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.
@@ -17,7 +17,6 @@
  * limitations under the License.
  * ============LICENSE_END=========================================================
  */
-
 package org.openecomp.sdc.be.exception;
 
 import org.openecomp.sdc.be.dao.api.ActionStatus;
index 66357c1..d38f08f 100644 (file)
@@ -16,7 +16,6 @@
  *  SPDX-License-Identifier: Apache-2.0
  *  ============LICENSE_END=========================================================
  */
-
 package org.openecomp.sdc.be.exception;
 
 public class ToscaExportException extends Exception {
@@ -24,5 +23,4 @@ public class ToscaExportException extends Exception {
     public ToscaExportException(String message) {
         super(message);
     }
-
 }
index 6b24867..17819de 100644 (file)
@@ -13,7 +13,6 @@
  * See the License for the specific language governing permissions and
  * limitations under the License.
  */
-
 package org.openecomp.sdc.be.externalapi.servlet;
 
 import com.jcabi.aspects.Loggable;
@@ -26,18 +25,25 @@ import io.swagger.v3.oas.annotations.media.Schema;
 import io.swagger.v3.oas.annotations.responses.ApiResponse;
 import io.swagger.v3.oas.annotations.servers.Server;
 import io.swagger.v3.oas.annotations.tags.Tag;
-
 import java.io.IOException;
 import java.util.List;
 import javax.inject.Inject;
 import javax.servlet.http.HttpServletRequest;
-import javax.ws.rs.*;
+import javax.ws.rs.GET;
+import javax.ws.rs.HeaderParam;
+import javax.ws.rs.POST;
+import javax.ws.rs.Path;
+import javax.ws.rs.PathParam;
+import javax.ws.rs.Produces;
 import javax.ws.rs.core.Context;
 import javax.ws.rs.core.MediaType;
 import javax.ws.rs.core.Response;
-
-
-import org.openecomp.sdc.be.components.impl.*;
+import org.openecomp.sdc.be.components.impl.AbstractTemplateBusinessLogic;
+import org.openecomp.sdc.be.components.impl.ComponentInstanceBusinessLogic;
+import org.openecomp.sdc.be.components.impl.ElementBusinessLogic;
+import org.openecomp.sdc.be.components.impl.ResourceBusinessLogic;
+import org.openecomp.sdc.be.components.impl.ResourceImportManager;
+import org.openecomp.sdc.be.components.impl.ServiceBusinessLogic;
 import org.openecomp.sdc.be.components.impl.aaf.AafPermission;
 import org.openecomp.sdc.be.components.impl.aaf.PermissionAllowed;
 import org.openecomp.sdc.be.components.impl.exceptions.ByResponseFormatComponentException;
@@ -48,11 +54,14 @@ import org.openecomp.sdc.be.externalapi.servlet.representation.AbstractTemplateI
 import org.openecomp.sdc.be.externalapi.servlet.representation.CopyServiceInfo;
 import org.openecomp.sdc.be.impl.ComponentsUtils;
 import org.openecomp.sdc.be.impl.ServletUtils;
-import org.openecomp.sdc.be.model.*;
+import org.openecomp.sdc.be.model.Component;
+import org.openecomp.sdc.be.model.Service;
+import org.openecomp.sdc.be.model.User;
 import org.openecomp.sdc.be.resources.data.auditing.AuditingActionEnum;
 import org.openecomp.sdc.be.resources.data.auditing.model.DistributionData;
 import org.openecomp.sdc.be.resources.data.auditing.model.ResourceCommonInfo;
-import org.openecomp.sdc.be.servlets.*;
+import org.openecomp.sdc.be.servlets.AbstractValidationsServlet;
+import org.openecomp.sdc.be.servlets.RepresentationUtils;
 import org.openecomp.sdc.be.user.UserBusinessLogic;
 import org.openecomp.sdc.common.api.Constants;
 import org.openecomp.sdc.common.log.elements.LoggerSupportability;
@@ -67,33 +76,27 @@ import org.springframework.stereotype.Controller;
  *
  * @author hekeguang
  */
-
 @Loggable(prepend = true, value = Loggable.DEBUG, trim = false)
 @Path("/v1/catalog")
 @Tag(name = "SDC External APIs")
 @Server(url = "/sdc")
 @Controller
-
 public class AbstractTemplateServlet extends AbstractValidationsServlet {
 
-    @Context
-    private HttpServletRequest request;
-
+    private static final Logger log = Logger.getLogger(AbstractTemplateServlet.class);
+    private static final LoggerSupportability loggerSupportability = LoggerSupportability.getLogger(AbstractTemplateServlet.class.getName());
     private final ElementBusinessLogic elementBusinessLogic;
     private final AbstractTemplateBusinessLogic abstractTemplateBusinessLogic;
-
     private final ServiceBusinessLogic serviceBusinessLogic;
     private final ResourceBusinessLogic resourceBusinessLogic;
-
-    private static final Logger log = Logger.getLogger(AbstractTemplateServlet.class);
-    private static final LoggerSupportability loggerSupportability = LoggerSupportability.getLogger(AbstractTemplateServlet.class.getName());
+    @Context
+    private HttpServletRequest request;
 
     @Inject
-    public AbstractTemplateServlet(UserBusinessLogic userBusinessLogic,
-                                   ComponentInstanceBusinessLogic componentInstanceBL, ComponentsUtils componentsUtils,
-                                   ServletUtils servletUtils, ResourceImportManager resourceImportManager,
-                                   ElementBusinessLogic elementBusinessLogic,
-                                   AbstractTemplateBusinessLogic abstractTemplateBusinessLogic, ServiceBusinessLogic serviceBusinessLogic, ResourceBusinessLogic resourceBusinessLogic) {
+    public AbstractTemplateServlet(UserBusinessLogic userBusinessLogic, ComponentInstanceBusinessLogic componentInstanceBL,
+                                   ComponentsUtils componentsUtils, ServletUtils servletUtils, ResourceImportManager resourceImportManager,
+                                   ElementBusinessLogic elementBusinessLogic, AbstractTemplateBusinessLogic abstractTemplateBusinessLogic,
+                                   ServiceBusinessLogic serviceBusinessLogic, ResourceBusinessLogic resourceBusinessLogic) {
         super(userBusinessLogic, componentInstanceBL, componentsUtils, servletUtils, resourceImportManager);
         this.elementBusinessLogic = elementBusinessLogic;
         this.abstractTemplateBusinessLogic = abstractTemplateBusinessLogic;
@@ -112,39 +115,26 @@ public class AbstractTemplateServlet extends AbstractValidationsServlet {
     @GET
     @Path("/abstract/service/serviceUUID/{uuid}/status")
     @Produces(MediaType.APPLICATION_JSON)
-    @Operation(description = "Fetch abstract status of service", method = "GET",
-            summary = "Return whether the service is a virtual service", responses = {@ApiResponse(responseCode = "200",
-            description = "The check result of whether the service is an abstract service is returned",
-            content = @Content(array = @ArraySchema(schema = @Schema(implementation = AbstractTemplateInfo.class)))),
-            @ApiResponse(responseCode = "400", description = "Missing  'X-ECOMP-InstanceID'  HTTP header - POL5001"),
-            @ApiResponse(responseCode = "401",
-                    description = "ECOMP component  should authenticate itself  and  to  re-send  again  HTTP  request  with its Basic Authentication credentials - POL5002"),
-            @ApiResponse(responseCode = "403", description = "ECOMP component is not authorized - POL5003"),
-            @ApiResponse(responseCode = "404",
-                    description = "Error: Requested '%1' (uuid) resource was not found - SVC4063"),
-            @ApiResponse(responseCode = "405",
-                    description = "Method  Not Allowed  :  Invalid HTTP method type used ( PUT,DELETE,POST will be rejected) - POL4050"),
-            @ApiResponse(responseCode = "500",
-                    description = "The GET request failed either due to internal SDC problem. ECOMP Component should continue the attempts to get the needed information - POL5000")})
+    @Operation(description = "Fetch abstract status of service", method = "GET", summary = "Return whether the service is a virtual service", responses = {
+        @ApiResponse(responseCode = "200", description = "The check result of whether the service is an abstract service is returned", content = @Content(array = @ArraySchema(schema = @Schema(implementation = AbstractTemplateInfo.class)))),
+        @ApiResponse(responseCode = "400", description = "Missing  'X-ECOMP-InstanceID'  HTTP header - POL5001"),
+        @ApiResponse(responseCode = "401", description = "ECOMP component  should authenticate itself  and  to  re-send  again  HTTP  request  with its Basic Authentication credentials - POL5002"),
+        @ApiResponse(responseCode = "403", description = "ECOMP component is not authorized - POL5003"),
+        @ApiResponse(responseCode = "404", description = "Error: Requested '%1' (uuid) resource was not found - SVC4063"),
+        @ApiResponse(responseCode = "405", description = "Method  Not Allowed  :  Invalid HTTP method type used ( PUT,DELETE,POST will be rejected) - POL4050"),
+        @ApiResponse(responseCode = "500", description = "The GET request failed either due to internal SDC problem. ECOMP Component should continue the attempts to get the needed information - POL5000")})
     @PermissionAllowed(AafPermission.PermNames.READ_VALUE)
     public Response getServiceAbstractStatus(
-            @Parameter(description = "X-ECOMP-RequestID header",
-                    required = false) @HeaderParam(value = Constants.X_ECOMP_REQUEST_ID_HEADER) String requestId,
-            @Parameter(description = "X-ECOMP-InstanceID header", required = true) @HeaderParam(
-                    value = Constants.X_ECOMP_INSTANCE_ID_HEADER) final String instanceIdHeader,
-            @Parameter(description = "Determines the format of the body of the response",
-                    required = false) @HeaderParam(value = Constants.ACCEPT_HEADER) String accept,
-            @Parameter(description = "The username and password",
-                    required = true) @HeaderParam(value = Constants.AUTHORIZATION_HEADER) String authorization,
-            @Parameter(description = "The requested asset uuid",
-                    required = true) @PathParam("uuid") final String uuid) throws IOException {
-
+        @Parameter(description = "X-ECOMP-RequestID header", required = false) @HeaderParam(value = Constants.X_ECOMP_REQUEST_ID_HEADER) String requestId,
+        @Parameter(description = "X-ECOMP-InstanceID header", required = true) @HeaderParam(value = Constants.X_ECOMP_INSTANCE_ID_HEADER) final String instanceIdHeader,
+        @Parameter(description = "Determines the format of the body of the response", required = false) @HeaderParam(value = Constants.ACCEPT_HEADER) String accept,
+        @Parameter(description = "The username and password", required = true) @HeaderParam(value = Constants.AUTHORIZATION_HEADER) String authorization,
+        @Parameter(description = "The requested asset uuid", required = true) @PathParam("uuid") final String uuid) throws IOException {
         ResponseFormat responseFormat = null;
         AuditingActionEnum auditingActionEnum = AuditingActionEnum.GET_TEMPLATE_ABSTRACT_STATUS;
         String requestURI = request.getRequestURI();
         String url = request.getMethod() + " " + requestURI;
         log.debug("getServiceAbstractStatus: Start handle request of {}", url);
-
         String assetType = "services";
         ComponentTypeEnum componentType = ComponentTypeEnum.findByParamName(assetType);
         ResourceCommonInfo resourceCommonInfo = new ResourceCommonInfo(componentType.getValue());
@@ -153,39 +143,31 @@ public class AbstractTemplateServlet extends AbstractValidationsServlet {
         if (instanceIdHeader == null || instanceIdHeader.isEmpty()) {
             log.debug("getServiceAbstractStatus: Missing X-ECOMP-InstanceID header");
             responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.MISSING_X_ECOMP_INSTANCE_ID);
-            getComponentsUtils().auditExternalGetAsset(responseFormat, auditingActionEnum, distributionData,
-                    resourceCommonInfo, requestId, uuid);
+            getComponentsUtils().auditExternalGetAsset(responseFormat, auditingActionEnum, distributionData, resourceCommonInfo, requestId, uuid);
             return buildErrorResponse(responseFormat);
         }
-
         try {
-
-            Either<List<? extends Component>, ResponseFormat> assetTypeData = elementBusinessLogic.getCatalogComponentsByUuidAndAssetType(assetType, uuid);
-
+            Either<List<? extends Component>, ResponseFormat> assetTypeData = elementBusinessLogic
+                .getCatalogComponentsByUuidAndAssetType(assetType, uuid);
             if (assetTypeData.isRight()) {
                 log.debug("getServiceAbstractStatus: Service Fetching Failed");
                 responseFormat = assetTypeData.right().value();
-                getComponentsUtils().auditExternalGetAsset(responseFormat, auditingActionEnum, distributionData,
-                        resourceCommonInfo, requestId, uuid);
-
+                getComponentsUtils().auditExternalGetAsset(responseFormat, auditingActionEnum, distributionData, resourceCommonInfo, requestId, uuid);
                 return buildErrorResponse(responseFormat);
             }
             resourceCommonInfo.setResourceName(assetTypeData.left().value().iterator().next().getName());
             log.debug("getServiceAbstractStatus: Service Fetching Success");
-            Either<AbstractTemplateInfo, ResponseFormat> resMetadata = abstractTemplateBusinessLogic.getServiceAbstractStatus(assetTypeData.left().value());
+            Either<AbstractTemplateInfo, ResponseFormat> resMetadata = abstractTemplateBusinessLogic
+                .getServiceAbstractStatus(assetTypeData.left().value());
             if (resMetadata.isRight()) {
                 log.debug("getServiceAbstractStatus: Service abstract status get Failed");
                 responseFormat = resMetadata.right().value();
-
-                getComponentsUtils().auditExternalGetAsset(responseFormat, auditingActionEnum, distributionData,
-                        resourceCommonInfo, requestId, uuid);
+                getComponentsUtils().auditExternalGetAsset(responseFormat, auditingActionEnum, distributionData, resourceCommonInfo, requestId, uuid);
                 return buildErrorResponse(responseFormat);
             }
             Object result = RepresentationUtils.toRepresentation(resMetadata.left().value());
             responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.OK);
-            getComponentsUtils().auditExternalGetAsset(responseFormat, auditingActionEnum, distributionData,
-                    resourceCommonInfo, requestId, uuid);
-
+            getComponentsUtils().auditExternalGetAsset(responseFormat, auditingActionEnum, distributionData, resourceCommonInfo, requestId, uuid);
             return buildOkResponse(responseFormat, result);
         } catch (Exception e) {
             BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Fetch abstract status of service");
@@ -205,63 +187,44 @@ public class AbstractTemplateServlet extends AbstractValidationsServlet {
     @POST
     @Path("/abstract/service/serviceUUID/{uuid}/copy")
     @Produces(MediaType.APPLICATION_JSON)
-    @Operation(description = "Copy a new service based on the existing service", method = "POST",
-            summary = "Return whether the copy service is successful", responses = {@ApiResponse(responseCode = "200",
-            description = "ECOMP component is authenticated and list of Catalog Assets Metadata is returned",
-            content = @Content(array = @ArraySchema(schema = @Schema(implementation = AbstractTemplateInfo.class)))),
-            @ApiResponse(responseCode = "400", description = "Missing  'X-ECOMP-InstanceID'  HTTP header - POL5001"),
-            @ApiResponse(responseCode = "401",
-                    description = "ECOMP component  should authenticate itself  and  to  re-send  again  HTTP  request  with its Basic Authentication credentials - POL5002"),
-            @ApiResponse(responseCode = "403", description = "ECOMP component is not authorized - POL5003"),
-            @ApiResponse(responseCode = "404",
-                    description = "Error: Requested '%1' (uuid) resource was not found - SVC4063"),
-            @ApiResponse(responseCode = "405",
-                    description = "Method  Not Allowed  :  Invalid HTTP method type used ( PUT,DELETE,POST will be rejected) - POL4050"),
-            @ApiResponse(responseCode = "500",
-                    description = "The GET request failed either due to internal SDC problem. ECOMP Component should continue the attempts to get the needed information - POL5000"),
-            @ApiResponse(responseCode = "409", description = "Service already exist")})
+    @Operation(description = "Copy a new service based on the existing service", method = "POST", summary = "Return whether the copy service is successful", responses = {
+        @ApiResponse(responseCode = "200", description = "ECOMP component is authenticated and list of Catalog Assets Metadata is returned", content = @Content(array = @ArraySchema(schema = @Schema(implementation = AbstractTemplateInfo.class)))),
+        @ApiResponse(responseCode = "400", description = "Missing  'X-ECOMP-InstanceID'  HTTP header - POL5001"),
+        @ApiResponse(responseCode = "401", description = "ECOMP component  should authenticate itself  and  to  re-send  again  HTTP  request  with its Basic Authentication credentials - POL5002"),
+        @ApiResponse(responseCode = "403", description = "ECOMP component is not authorized - POL5003"),
+        @ApiResponse(responseCode = "404", description = "Error: Requested '%1' (uuid) resource was not found - SVC4063"),
+        @ApiResponse(responseCode = "405", description = "Method  Not Allowed  :  Invalid HTTP method type used ( PUT,DELETE,POST will be rejected) - POL4050"),
+        @ApiResponse(responseCode = "500", description = "The GET request failed either due to internal SDC problem. ECOMP Component should continue the attempts to get the needed information - POL5000"),
+        @ApiResponse(responseCode = "409", description = "Service already exist")})
     @PermissionAllowed(AafPermission.PermNames.WRITE_VALUE)
     public Response copyExistService(
-            @Parameter(description = "The user id",
-                    required = true) @HeaderParam(value = Constants.USER_ID_HEADER) final String userId,
-            @Parameter(description = "X-ECOMP-RequestID header",
-                    required = false) @HeaderParam(value = Constants.X_ECOMP_REQUEST_ID_HEADER) String requestId,
-            @Parameter(description = "X-ECOMP-InstanceID header", required = true) @HeaderParam(
-                    value = Constants.X_ECOMP_INSTANCE_ID_HEADER) final String instanceIdHeader,
-            @Parameter(description = "Determines the format of the body of the response",
-                    required = false) @HeaderParam(value = Constants.ACCEPT_HEADER) String accept,
-            @Parameter(description = "The username and password",
-                    required = true) @HeaderParam(value = Constants.AUTHORIZATION_HEADER) String authorization,
-            @Parameter(description = "The requested asset uuid",
-                    required = true) @PathParam("uuid") final String uuid,
-            @Parameter(hidden = true) String data) throws IOException {
-
-
+        @Parameter(description = "The user id", required = true) @HeaderParam(value = Constants.USER_ID_HEADER) final String userId,
+        @Parameter(description = "X-ECOMP-RequestID header", required = false) @HeaderParam(value = Constants.X_ECOMP_REQUEST_ID_HEADER) String requestId,
+        @Parameter(description = "X-ECOMP-InstanceID header", required = true) @HeaderParam(value = Constants.X_ECOMP_INSTANCE_ID_HEADER) final String instanceIdHeader,
+        @Parameter(description = "Determines the format of the body of the response", required = false) @HeaderParam(value = Constants.ACCEPT_HEADER) String accept,
+        @Parameter(description = "The username and password", required = true) @HeaderParam(value = Constants.AUTHORIZATION_HEADER) String authorization,
+        @Parameter(description = "The requested asset uuid", required = true) @PathParam("uuid") final String uuid,
+        @Parameter(hidden = true) String data) throws IOException {
         String url = request.getMethod() + " " + request.getRequestURI();
         log.debug("copyExistService: Start handle request of {}", url);
         User modifier = new User();
         modifier.setUserId(userId);
         log.debug("modifier id is {}", userId);
         loggerSupportability.log(LoggerSupportabilityActions.CREATE_SERVICE, StatusCode.STARTED, "Starting to create a service by user {} ", userId);
-
         validateNotEmptyBody(data);
-
         Either<CopyServiceInfo, ResponseFormat> convertResponse = parseToCopyServiceInfo(data, modifier);
         if (convertResponse.isRight()) {
             throw new ByResponseFormatComponentException(convertResponse.right().value());
         }
-
         String assetType = "services";
         CopyServiceInfo copyServiceInfo = convertResponse.left().value();
-        Either<List<? extends Component>, ResponseFormat> assetTypeData = elementBusinessLogic.getCatalogComponentsByUuidAndAssetType(assetType, uuid);
-
+        Either<List<? extends Component>, ResponseFormat> assetTypeData = elementBusinessLogic
+            .getCatalogComponentsByUuidAndAssetType(assetType, uuid);
         if (assetTypeData.isRight() || assetTypeData.left().value().size() != 1) {
             log.debug("getServiceAbstractStatus: Service Fetching Failed");
             throw new ByResponseFormatComponentException(assetTypeData.right().value());
         }
-
         log.debug("getServiceAbstractStatus: Service Fetching Success");
-
         Service service = (Service) assetTypeData.left().value().get(0);
         List<String> tags = service.getTags();
         if (tags != null && !tags.isEmpty()) {
@@ -275,20 +238,17 @@ public class AbstractTemplateServlet extends AbstractValidationsServlet {
         service.setName(copyServiceInfo.getNewServiceName());
         tags.add(copyServiceInfo.getNewServiceName());
         Either<Service, ResponseFormat> actionResponse = serviceBusinessLogic.createService(service, modifier);
-
         if (actionResponse.isRight()) {
             log.debug("Failed to create service");
             throw new ByResponseFormatComponentException(actionResponse.right().value());
         }
-
-        loggerSupportability.log(LoggerSupportabilityActions.CREATE_SERVICE, service.getComponentMetadataForSupportLog(), StatusCode.COMPLETE, "Service {} has been copyied by user {} ", service.getName(), userId);
-
+        loggerSupportability.log(LoggerSupportabilityActions.CREATE_SERVICE, service.getComponentMetadataForSupportLog(), StatusCode.COMPLETE,
+            "Service {} has been copyied by user {} ", service.getName(), userId);
         return buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.CREATED), actionResponse.left().value());
-
     }
 
     public Either<CopyServiceInfo, ResponseFormat> parseToCopyServiceInfo(String serviceJson, User user) {
-        return getComponentsUtils().convertJsonToObjectUsingObjectMapper(serviceJson, user, CopyServiceInfo.class, AuditingActionEnum.CREATE_RESOURCE, ComponentTypeEnum.SERVICE);
+        return getComponentsUtils().convertJsonToObjectUsingObjectMapper(serviceJson, user, CopyServiceInfo.class, AuditingActionEnum.CREATE_RESOURCE,
+            ComponentTypeEnum.SERVICE);
     }
-
 }
index 3955fdd..f4615ab 100644 (file)
@@ -17,7 +17,6 @@
  * limitations under the License.
  * ============LICENSE_END=========================================================
  */
-
 package org.openecomp.sdc.be.externalapi.servlet;
 
 import com.jcabi.aspects.Loggable;
@@ -79,7 +78,6 @@ import org.springframework.stereotype.Controller;
  * This Servlet serves external users operations on artifacts.
  *
  * @author mshitrit
- *
  */
 @Loggable(prepend = true, value = Loggable.DEBUG, trim = false)
 @Path("/v1/catalog")
@@ -90,21 +88,16 @@ public class ArtifactExternalServlet extends AbstractValidationsServlet {
 
     private static final String FAILED_TO_UPDATE_ARTIFACT = "failed to update artifact";
     private static final String DOUBLE_CURLY_BRACKETS = "{} {}";
-
-    @Context
-    private HttpServletRequest request;
-
-    private final ArtifactsBusinessLogic artifactsBusinessLogic;
-
     private static final Logger log = Logger.getLogger(ArtifactExternalServlet.class);
-
     private static String startLog = "Start handle request of ";
+    private final ArtifactsBusinessLogic artifactsBusinessLogic;
+    @Context
+    private HttpServletRequest request;
 
     @Inject
-    public ArtifactExternalServlet(UserBusinessLogic userBusinessLogic,
-            ComponentInstanceBusinessLogic componentInstanceBL, ComponentsUtils componentsUtils,
-            ServletUtils servletUtils, ResourceImportManager resourceImportManager,
-            ArtifactsBusinessLogic artifactsBusinessLogic) {
+    public ArtifactExternalServlet(UserBusinessLogic userBusinessLogic, ComponentInstanceBusinessLogic componentInstanceBL,
+                                   ComponentsUtils componentsUtils, ServletUtils servletUtils, ResourceImportManager resourceImportManager,
+                                   ArtifactsBusinessLogic artifactsBusinessLogic) {
         super(userBusinessLogic, componentInstanceBL, componentsUtils, servletUtils, resourceImportManager);
         this.artifactsBusinessLogic = artifactsBusinessLogic;
     }
@@ -112,57 +105,36 @@ public class ArtifactExternalServlet extends AbstractValidationsServlet {
     @POST
     @Path("/{assetType}/{uuid}/interfaces/{interfaceUUID}/operations/{operationUUID}/artifacts/{artifactUUID}")
     @Produces(MediaType.APPLICATION_JSON)
-    @Operation(parameters = {@Parameter(required = true,
-            schema = @Schema(implementation = org.openecomp.sdc.be.model.ArtifactDefinition.class))},
-            description = "uploads of artifact to VF operation workflow", method = "POST",
-            summary = "uploads of artifact to VF operation workflow", responses = {
-            @ApiResponse(responseCode = "200", description = "Artifact uploaded", content = @Content(
-                    array = @ArraySchema(schema = @Schema(implementation = ArtifactDefinition.class)))),
-            @ApiResponse(responseCode = "400", description = "Missing  'X-ECOMP-InstanceID'  HTTP header - POL5001"),
-            @ApiResponse(responseCode = "401",
-                    description = "ECOMP component  should authenticate itself  and  to  re-send  again  HTTP  request  with its Basic  Authentication credentials - POL5002"),
-            @ApiResponse(responseCode = "403", description = "ECOMP component is not authorized - POL5003"),
-            @ApiResponse(responseCode = "404", description = "Specified resource is not found - SVC4063"),
-            @ApiResponse(responseCode = "405",
-                    description = "Method  Not Allowed: Invalid HTTP method type used (PUT,DELETE,POST will be rejected) - POL4050"),
-            @ApiResponse(responseCode = "500",
-                    description = "The GET request failed either due to internal SDC problem or Cambria Service failure. ECOMP Component should continue the attempts to get the needed information - POL5000"),
-            @ApiResponse(responseCode = "400", description = "Invalid artifactType was defined as input - SVC4122"),
-            @ApiResponse(responseCode = "400",
-                    description = "Artifact type (mandatory field) is missing in request - SVC4124"),
-            @ApiResponse(responseCode = "400",
-                    description = "Artifact name given in input already exists in the context of the asset - SVC4125"),
-            @ApiResponse(responseCode = "400", description = "Invalid MD5 header - SVC4127"),
-            @ApiResponse(responseCode = "400", description = "Artifact name is missing in input - SVC4128"),
-            @ApiResponse(responseCode = "400",
-                    description = "Asset is being edited by different user. Only one user can checkout and edit an asset on given time. The asset will be available for checkout after the other user will checkin the asset - SVC4086"),
-            @ApiResponse(responseCode = "400",
-                    description = "Restricted Operation â€“ the user provided does not have role of Designer or the asset is being used by another designer - SVC4301")})
+    @Operation(parameters = {
+        @Parameter(required = true, schema = @Schema(implementation = org.openecomp.sdc.be.model.ArtifactDefinition.class))}, description = "uploads of artifact to VF operation workflow", method = "POST", summary = "uploads of artifact to VF operation workflow", responses = {
+        @ApiResponse(responseCode = "200", description = "Artifact uploaded", content = @Content(array = @ArraySchema(schema = @Schema(implementation = ArtifactDefinition.class)))),
+        @ApiResponse(responseCode = "400", description = "Missing  'X-ECOMP-InstanceID'  HTTP header - POL5001"),
+        @ApiResponse(responseCode = "401", description = "ECOMP component  should authenticate itself  and  to  re-send  again  HTTP  request  with its Basic  Authentication credentials - POL5002"),
+        @ApiResponse(responseCode = "403", description = "ECOMP component is not authorized - POL5003"),
+        @ApiResponse(responseCode = "404", description = "Specified resource is not found - SVC4063"),
+        @ApiResponse(responseCode = "405", description = "Method  Not Allowed: Invalid HTTP method type used (PUT,DELETE,POST will be rejected) - POL4050"),
+        @ApiResponse(responseCode = "500", description = "The GET request failed either due to internal SDC problem or Cambria Service failure. ECOMP Component should continue the attempts to get the needed information - POL5000"),
+        @ApiResponse(responseCode = "400", description = "Invalid artifactType was defined as input - SVC4122"),
+        @ApiResponse(responseCode = "400", description = "Artifact type (mandatory field) is missing in request - SVC4124"),
+        @ApiResponse(responseCode = "400", description = "Artifact name given in input already exists in the context of the asset - SVC4125"),
+        @ApiResponse(responseCode = "400", description = "Invalid MD5 header - SVC4127"),
+        @ApiResponse(responseCode = "400", description = "Artifact name is missing in input - SVC4128"),
+        @ApiResponse(responseCode = "400", description = "Asset is being edited by different user. Only one user can checkout and edit an asset on given time. The asset will be available for checkout after the other user will checkin the asset - SVC4086"),
+        @ApiResponse(responseCode = "400", description = "Restricted Operation â€“ the user provided does not have role of Designer or the asset is being used by another designer - SVC4301")})
     public Response uploadInterfaceOperationArtifact(
-            @Parameter(description = "Determines the format of the body of the request",
-                    required = true) @HeaderParam(value = HttpHeaders.CONTENT_TYPE) String contentType,
-            @Parameter(description = "The value for this header must be the MD5 checksum over the whole json body",
-                    required = true) @HeaderParam(value = Constants.MD5_HEADER) String checksum,
-            @Parameter(description = "The user ID of the DCAE Designer. This user must also have Designer role in SDC",
-                    required = true) @HeaderParam(value = Constants.USER_ID_HEADER) final String userId,
-            @Parameter(description = "X-ECOMP-RequestID header",
-                    required = false) @HeaderParam(value = Constants.X_ECOMP_REQUEST_ID_HEADER) String requestId,
-            @Parameter(description = "X-ECOMP-InstanceID header", required = true) @HeaderParam(
-                    value = Constants.X_ECOMP_INSTANCE_ID_HEADER) final String instanceIdHeader,
-            @Parameter(description = "Determines the format of the body of the response",
-                    required = false) @HeaderParam(value = Constants.ACCEPT_HEADER) String accept,
-            @Parameter(description = "The username and password",
-                    required = true) @HeaderParam(value = Constants.AUTHORIZATION_HEADER) String authorization,
-            @Parameter(description = "Asset type") @PathParam("assetType") String assetType,
-            @Parameter(description = "The uuid of the asset as published in the metadata",
-                    required = true) @PathParam("uuid") final String uuid,
-            @Parameter(description = "The uuid of the interface",
-                    required = true) @PathParam("interfaceUUID") final String interfaceUUID,
-            @Parameter(description = "The uuid of the operation",
-                    required = true) @PathParam("operationUUID") final String operationUUID,
-            @Parameter(description = "The uuid of the artifact",
-                    required = true) @PathParam("artifactUUID") final String artifactUUID,
-            @Parameter(hidden = true) String data) {
+        @Parameter(description = "Determines the format of the body of the request", required = true) @HeaderParam(value = HttpHeaders.CONTENT_TYPE) String contentType,
+        @Parameter(description = "The value for this header must be the MD5 checksum over the whole json body", required = true) @HeaderParam(value = Constants.MD5_HEADER) String checksum,
+        @Parameter(description = "The user ID of the DCAE Designer. This user must also have Designer role in SDC", required = true) @HeaderParam(value = Constants.USER_ID_HEADER) final String userId,
+        @Parameter(description = "X-ECOMP-RequestID header", required = false) @HeaderParam(value = Constants.X_ECOMP_REQUEST_ID_HEADER) String requestId,
+        @Parameter(description = "X-ECOMP-InstanceID header", required = true) @HeaderParam(value = Constants.X_ECOMP_INSTANCE_ID_HEADER) final String instanceIdHeader,
+        @Parameter(description = "Determines the format of the body of the response", required = false) @HeaderParam(value = Constants.ACCEPT_HEADER) String accept,
+        @Parameter(description = "The username and password", required = true) @HeaderParam(value = Constants.AUTHORIZATION_HEADER) String authorization,
+        @Parameter(description = "Asset type") @PathParam("assetType") String assetType,
+        @Parameter(description = "The uuid of the asset as published in the metadata", required = true) @PathParam("uuid") final String uuid,
+        @Parameter(description = "The uuid of the interface", required = true) @PathParam("interfaceUUID") final String interfaceUUID,
+        @Parameter(description = "The uuid of the operation", required = true) @PathParam("operationUUID") final String operationUUID,
+        @Parameter(description = "The uuid of the artifact", required = true) @PathParam("artifactUUID") final String artifactUUID,
+        @Parameter(hidden = true) String data) {
         Wrapper<Response> responseWrapper = new Wrapper<>();
         ResponseFormat responseFormat = null;
         String requestURI = request.getRequestURI();
@@ -170,7 +142,6 @@ public class ArtifactExternalServlet extends AbstractValidationsServlet {
         log.debug(DOUBLE_CURLY_BRACKETS, startLog, url);
         ResourceCommonInfo resourceCommonInfo = new ResourceCommonInfo(assetType);
         ArtifactDefinition artifactDefinition = null;
-
         if (responseWrapper.isEmpty() && (instanceIdHeader == null || instanceIdHeader.isEmpty())) {
             log.debug("updateArtifact: Missing X-ECOMP-InstanceID header");
             responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.MISSING_X_ECOMP_INSTANCE_ID);
@@ -184,20 +155,21 @@ public class ArtifactExternalServlet extends AbstractValidationsServlet {
         try {
             if (responseWrapper.isEmpty()) {
                 Either<ArtifactDefinition, ResponseFormat> uploadArtifactEither = artifactsBusinessLogic
-                        .updateArtifactOnInterfaceOperationByResourceUUID(data, request, ComponentTypeEnum
-                                        .findByParamName(assetType), uuid, interfaceUUID, operationUUID, artifactUUID,
-                                resourceCommonInfo, new ArtifactOperationInfo(true, false, ArtifactOperationEnum.UPDATE));
+                    .updateArtifactOnInterfaceOperationByResourceUUID(data, request, ComponentTypeEnum.findByParamName(assetType), uuid,
+                        interfaceUUID, operationUUID, artifactUUID, resourceCommonInfo,
+                        new ArtifactOperationInfo(true, false, ArtifactOperationEnum.UPDATE));
                 if (uploadArtifactEither.isRight()) {
                     log.debug(FAILED_TO_UPDATE_ARTIFACT);
                     responseFormat = uploadArtifactEither.right().value();
                     responseWrapper.setInnerElement(buildErrorResponse(responseFormat));
                 } else {
-                    artifactDefinition=uploadArtifactEither.left().value();
+                    artifactDefinition = uploadArtifactEither.left().value();
                     Object representation = RepresentationUtils.toRepresentation(artifactDefinition);
                     Map<String, String> headers = new HashMap<>();
                     headers.put(Constants.MD5_HEADER, GeneralUtility.calculateMD5Base64EncodedByString((String) representation));
                     responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.OK);
-                    responseWrapper.setInnerElement(buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), representation, headers));
+                    responseWrapper
+                        .setInnerElement(buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), representation, headers));
                 }
             }
         } catch (Exception e) {
@@ -206,8 +178,9 @@ public class ArtifactExternalServlet extends AbstractValidationsServlet {
             log.debug(message, e);
             responseWrapper.setInnerElement(buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR)));
         } finally {
-            getComponentsUtils().auditExternalCrudApi(responseFormat, AuditingActionEnum.ARTIFACT_UPLOAD_BY_API,
-                    resourceCommonInfo, request, artifactDefinition, null);
+            getComponentsUtils()
+                .auditExternalCrudApi(responseFormat, AuditingActionEnum.ARTIFACT_UPLOAD_BY_API, resourceCommonInfo, request, artifactDefinition,
+                    null);
         }
         return responseWrapper.getInnerElement();
     }
@@ -218,56 +191,36 @@ public class ArtifactExternalServlet extends AbstractValidationsServlet {
     @POST
     @Path("/{assetType}/{uuid}/artifacts")
     @Produces(MediaType.APPLICATION_JSON)
-    @Operation(parameters = {@Parameter(required = true,
-            schema = @Schema(implementation = org.openecomp.sdc.be.model.ArtifactDefinition.class))},
-            description = "uploads of artifact to a resource or service", method = "POST",
-            summary = "uploads of artifact to a resource or service", responses = {
-            @ApiResponse(responseCode = "200", description = "Artifact uploaded", content = @Content(
-                    array = @ArraySchema(schema = @Schema(implementation = ArtifactDefinition.class)))),
-            @ApiResponse(responseCode = "400", description = "Missing  'X-ECOMP-InstanceID'  HTTP header - POL5001"),
-            @ApiResponse(responseCode = "401",
-                    description = "ECOMP component  should authenticate itself  and  to  re-send  again  HTTP  request  with its Basic  Authentication credentials - POL5002"),
-            @ApiResponse(responseCode = "403", description = "ECOMP component is not authorized - POL5003"),
-            @ApiResponse(responseCode = "404", description = "Specified resource is not found - SVC4063"),
-            @ApiResponse(responseCode = "405",
-                    description = "Method  Not Allowed: Invalid HTTP method type used (PUT,DELETE,POST will be rejected) - POL4050"),
-            @ApiResponse(responseCode = "500",
-                    description = "The GET request failed either due to internal SDC problem or Cambria Service failure. ECOMP Component should continue the attempts to get the needed information - POL5000"),
-            @ApiResponse(responseCode = "400", description = "Invalid artifactType was defined as input - SVC4122"),
-            @ApiResponse(responseCode = "400",
-                    description = "Artifact type (mandatory field) is missing in request - SVC4124"),
-            @ApiResponse(responseCode = "400",
-                    description = "Artifact name given in input already exists in the context of the asset - SVC4125"),
-            @ApiResponse(responseCode = "400", description = "Invalid MD5 header - SVC4127"),
-            @ApiResponse(responseCode = "400", description = "Artifact name is missing in input - SVC4128"),
-            @ApiResponse(responseCode = "400",
-                    description = "Asset is being edited by different user. Only one user can checkout and edit an asset on given time. The asset will be available for checkout after the other user will checkin the asset - SVC4086"),
-            @ApiResponse(responseCode = "400",
-                    description = "Restricted Operation â€“ the user provided does not have role of Designer or the asset is being used by another designer - SVC4301")})
+    @Operation(parameters = {
+        @Parameter(required = true, schema = @Schema(implementation = org.openecomp.sdc.be.model.ArtifactDefinition.class))}, description = "uploads of artifact to a resource or service", method = "POST", summary = "uploads of artifact to a resource or service", responses = {
+        @ApiResponse(responseCode = "200", description = "Artifact uploaded", content = @Content(array = @ArraySchema(schema = @Schema(implementation = ArtifactDefinition.class)))),
+        @ApiResponse(responseCode = "400", description = "Missing  'X-ECOMP-InstanceID'  HTTP header - POL5001"),
+        @ApiResponse(responseCode = "401", description = "ECOMP component  should authenticate itself  and  to  re-send  again  HTTP  request  with its Basic  Authentication credentials - POL5002"),
+        @ApiResponse(responseCode = "403", description = "ECOMP component is not authorized - POL5003"),
+        @ApiResponse(responseCode = "404", description = "Specified resource is not found - SVC4063"),
+        @ApiResponse(responseCode = "405", description = "Method  Not Allowed: Invalid HTTP method type used (PUT,DELETE,POST will be rejected) - POL4050"),
+        @ApiResponse(responseCode = "500", description = "The GET request failed either due to internal SDC problem or Cambria Service failure. ECOMP Component should continue the attempts to get the needed information - POL5000"),
+        @ApiResponse(responseCode = "400", description = "Invalid artifactType was defined as input - SVC4122"),
+        @ApiResponse(responseCode = "400", description = "Artifact type (mandatory field) is missing in request - SVC4124"),
+        @ApiResponse(responseCode = "400", description = "Artifact name given in input already exists in the context of the asset - SVC4125"),
+        @ApiResponse(responseCode = "400", description = "Invalid MD5 header - SVC4127"),
+        @ApiResponse(responseCode = "400", description = "Artifact name is missing in input - SVC4128"),
+        @ApiResponse(responseCode = "400", description = "Asset is being edited by different user. Only one user can checkout and edit an asset on given time. The asset will be available for checkout after the other user will checkin the asset - SVC4086"),
+        @ApiResponse(responseCode = "400", description = "Restricted Operation â€“ the user provided does not have role of Designer or the asset is being used by another designer - SVC4301")})
     @PermissionAllowed({AafPermission.PermNames.WRITE_VALUE})
     public Response uploadArtifact(
-            @Parameter(description = "Determines the format of the body of the request",
-                    required = true) @HeaderParam(value = Constants.CONTENT_TYPE_HEADER) String contentType,
-            @Parameter(description = "The value for this header must be the MD5 checksum over the whole json body",
-                    required = true) @HeaderParam(value = Constants.MD5_HEADER) String checksum,
-            @Parameter(description = "The user ID of the DCAE Designer. This user must also have Designer role in SDC",
-                    required = true) @HeaderParam(value = Constants.USER_ID_HEADER) final String userId,
-            @Parameter(description = "X-ECOMP-RequestID header",
-                    required = false) @HeaderParam(value = Constants.X_ECOMP_REQUEST_ID_HEADER) String requestId,
-            @Parameter(description = "X-ECOMP-InstanceID header", required = true) @HeaderParam(
-                    value = Constants.X_ECOMP_INSTANCE_ID_HEADER) final String instanceIdHeader,
-            @Parameter(description = "Determines the format of the body of the response",
-                    required = false) @HeaderParam(value = Constants.ACCEPT_HEADER) String accept,
-            @Parameter(description = "The username and password",
-                    required = true) @HeaderParam(value = Constants.AUTHORIZATION_HEADER) String authorization,
-            @Parameter(schema = @Schema(allowableValues = {"resources,services"}),description = "The requested asset type",
-                    required = true) @PathParam("assetType") final String assetType,
-            @Parameter(description = "The uuid of the asset as published in the metadata",
-                    required = true) @PathParam("uuid") final String uuid,
-            @Parameter(hidden = true) String data) {
-
+        @Parameter(description = "Determines the format of the body of the request", required = true) @HeaderParam(value = Constants.CONTENT_TYPE_HEADER) String contentType,
+        @Parameter(description = "The value for this header must be the MD5 checksum over the whole json body", required = true) @HeaderParam(value = Constants.MD5_HEADER) String checksum,
+        @Parameter(description = "The user ID of the DCAE Designer. This user must also have Designer role in SDC", required = true) @HeaderParam(value = Constants.USER_ID_HEADER) final String userId,
+        @Parameter(description = "X-ECOMP-RequestID header", required = false) @HeaderParam(value = Constants.X_ECOMP_REQUEST_ID_HEADER) String requestId,
+        @Parameter(description = "X-ECOMP-InstanceID header", required = true) @HeaderParam(value = Constants.X_ECOMP_INSTANCE_ID_HEADER) final String instanceIdHeader,
+        @Parameter(description = "Determines the format of the body of the response", required = false) @HeaderParam(value = Constants.ACCEPT_HEADER) String accept,
+        @Parameter(description = "The username and password", required = true) @HeaderParam(value = Constants.AUTHORIZATION_HEADER) String authorization,
+        @Parameter(schema = @Schema(allowableValues = {
+            "resources,services"}), description = "The requested asset type", required = true) @PathParam("assetType") final String assetType,
+        @Parameter(description = "The uuid of the asset as published in the metadata", required = true) @PathParam("uuid") final String uuid,
+        @Parameter(hidden = true) String data) {
         init();
-
         Wrapper<ResponseFormat> responseWrapper = new Wrapper<>();
         String requestURI = request.getRequestURI();
         String url = request.getMethod() + " " + requestURI;
@@ -275,7 +228,6 @@ public class ArtifactExternalServlet extends AbstractValidationsServlet {
         ComponentTypeEnum componentType = ComponentTypeEnum.findByParamName(assetType);
         String componentTypeValue = componentType == null ? null : componentType.getValue();
         ResourceCommonInfo resourceCommonInfo = new ResourceCommonInfo(componentTypeValue);
-
         if (componentType == null) {
             log.debug("uploadArtifact: assetType parameter {} is not valid", assetType);
             responseWrapper.setInnerElement(getComponentsUtils().getResponseFormat(ActionStatus.INVALID_CONTENT));
@@ -283,15 +235,15 @@ public class ArtifactExternalServlet extends AbstractValidationsServlet {
         if (responseWrapper.isEmpty()) {
             validateXECOMPInstanceIDHeader(instanceIdHeader, responseWrapper);
         }
-        if (responseWrapper.isEmpty() ) {
+        if (responseWrapper.isEmpty()) {
             validateHttpCspUserIdHeader(userId, responseWrapper);
         }
         Response response = null;
         ArtifactDefinition artifactDefinition = null;
         try {
             if (responseWrapper.isEmpty()) {
-                artifactDefinition = artifactsBusinessLogic.uploadArtifactToComponentByUUID(data, request, componentType, uuid,
-                        resourceCommonInfo, new ArtifactOperationInfo(true, false, ArtifactOperationEnum.CREATE));
+                artifactDefinition = artifactsBusinessLogic.uploadArtifactToComponentByUUID(data, request, componentType, uuid, resourceCommonInfo,
+                    new ArtifactOperationInfo(true, false, ArtifactOperationEnum.CREATE));
                 Object representation = RepresentationUtils.toRepresentation(artifactDefinition);
                 Map<String, String> headers = new HashMap<>();
                 headers.put(Constants.MD5_HEADER, GeneralUtility.calculateMD5Base64EncodedByString((String) representation));
@@ -304,14 +256,15 @@ public class ArtifactExternalServlet extends AbstractValidationsServlet {
             log.debug(message, e);
             responseWrapper.setInnerElement(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR));
             response = buildErrorResponse(responseWrapper.getInnerElement());
-        }   catch (ComponentException e){
+        } catch (ComponentException e) {
             responseWrapper.setInnerElement(getComponentsUtils().getResponseFormat(e));
-        }finally {
-            if( response == null ){
+        } finally {
+            if (response == null) {
                 response = buildErrorResponse(responseWrapper.getInnerElement());
             }
-            getComponentsUtils().auditExternalCrudApi(responseWrapper.getInnerElement(), AuditingActionEnum.ARTIFACT_UPLOAD_BY_API,
-                    resourceCommonInfo, request, artifactDefinition, null);
+            getComponentsUtils()
+                .auditExternalCrudApi(responseWrapper.getInnerElement(), AuditingActionEnum.ARTIFACT_UPLOAD_BY_API, resourceCommonInfo, request,
+                    artifactDefinition, null);
         }
         return response;
     }
@@ -322,56 +275,37 @@ public class ArtifactExternalServlet extends AbstractValidationsServlet {
     @POST
     @Path("/{assetType}/{uuid}/resourceInstances/{resourceInstanceName}/artifacts")
     @Produces(MediaType.APPLICATION_JSON)
-    @Operation(parameters = {@Parameter(required = true,
-            schema = @Schema(implementation = org.openecomp.sdc.be.model.ArtifactDefinition.class),
-            description = "json describe the artifact")}, description = "uploads an artifact to a resource instance",
-            method = "POST", summary = "uploads an artifact to a resource instance", responses = {
-            @ApiResponse(responseCode = "200", description = "Artifact uploaded", content = @Content(
-                    array = @ArraySchema(schema = @Schema(implementation = ArtifactDefinition.class)))),
-            @ApiResponse(responseCode = "400", description = "Missing  'X-ECOMP-InstanceID'  HTTP header - POL5001"),
-            @ApiResponse(responseCode = "401",
-                    description = "ECOMP component  should authenticate itself  and  to  re-send  again  HTTP  request  with its Basic  Authentication credentials - POL5002"),
-            @ApiResponse(responseCode = "403", description = "ECOMP component is not authorized - POL5003"),
-            @ApiResponse(responseCode = "404", description = "Specified resource is not found - SVC4063"),
-            @ApiResponse(responseCode = "405",
-                    description = "Method  Not Allowed: Invalid HTTP method type used (PUT,DELETE,POST will be rejected) - POL4050"),
-            @ApiResponse(responseCode = "500",
-                    description = "The GET request failed either due to internal SDC problem or Cambria Service failure. ECOMP Component should continue the attempts to get the needed information - POL5000"),
-            @ApiResponse(responseCode = "400", description = "Invalid artifactType was defined as input - SVC4122"),
-            @ApiResponse(responseCode = "400",
-                    description = "Artifact type (mandatory field) is missing in request - SVC4124"),
-            @ApiResponse(responseCode = "400",
-                    description = "Artifact name given in input already exists in the context of the asset - SVC4125"),
-            @ApiResponse(responseCode = "400", description = "Invalid MD5 header - SVC4127"),
-            @ApiResponse(responseCode = "400", description = "Artifact name is missing in input - SVC4128"),
-            @ApiResponse(responseCode = "400",
-                    description = "Asset is being edited by different user. Only one user can checkout and edit an asset on given time. The asset will be available for checkout after the other user will checkin the asset - SVC4086"),
-            @ApiResponse(responseCode = "400",
-                    description = "Restricted Operation â€“ the user provided does not have role of Designer or the asset is being used by another designer - SVC4301")})
+    @Operation(parameters = {
+        @Parameter(required = true, schema = @Schema(implementation = org.openecomp.sdc.be.model.ArtifactDefinition.class), description = "json describe the artifact")}, description = "uploads an artifact to a resource instance", method = "POST", summary = "uploads an artifact to a resource instance", responses = {
+        @ApiResponse(responseCode = "200", description = "Artifact uploaded", content = @Content(array = @ArraySchema(schema = @Schema(implementation = ArtifactDefinition.class)))),
+        @ApiResponse(responseCode = "400", description = "Missing  'X-ECOMP-InstanceID'  HTTP header - POL5001"),
+        @ApiResponse(responseCode = "401", description = "ECOMP component  should authenticate itself  and  to  re-send  again  HTTP  request  with its Basic  Authentication credentials - POL5002"),
+        @ApiResponse(responseCode = "403", description = "ECOMP component is not authorized - POL5003"),
+        @ApiResponse(responseCode = "404", description = "Specified resource is not found - SVC4063"),
+        @ApiResponse(responseCode = "405", description = "Method  Not Allowed: Invalid HTTP method type used (PUT,DELETE,POST will be rejected) - POL4050"),
+        @ApiResponse(responseCode = "500", description = "The GET request failed either due to internal SDC problem or Cambria Service failure. ECOMP Component should continue the attempts to get the needed information - POL5000"),
+        @ApiResponse(responseCode = "400", description = "Invalid artifactType was defined as input - SVC4122"),
+        @ApiResponse(responseCode = "400", description = "Artifact type (mandatory field) is missing in request - SVC4124"),
+        @ApiResponse(responseCode = "400", description = "Artifact name given in input already exists in the context of the asset - SVC4125"),
+        @ApiResponse(responseCode = "400", description = "Invalid MD5 header - SVC4127"),
+        @ApiResponse(responseCode = "400", description = "Artifact name is missing in input - SVC4128"),
+        @ApiResponse(responseCode = "400", description = "Asset is being edited by different user. Only one user can checkout and edit an asset on given time. The asset will be available for checkout after the other user will checkin the asset - SVC4086"),
+        @ApiResponse(responseCode = "400", description = "Restricted Operation â€“ the user provided does not have role of Designer or the asset is being used by another designer - SVC4301")})
     @PermissionAllowed(AafPermission.PermNames.WRITE_VALUE)
     public Response uploadArtifactToInstance(
-            @Parameter(description = "Determines the format of the body of the request",
-                    required = true) @HeaderParam(value = Constants.CONTENT_TYPE_HEADER) String contentType,
-            @Parameter(description = "The value for this header must be the MD5 checksum over the whole json body",
-                    required = true) @HeaderParam(value = Constants.MD5_HEADER) String checksum,
-            @Parameter(description = "The user ID of the DCAE Designer. This user must also have Designer role in SDC",
-                    required = true) @HeaderParam(value = Constants.USER_ID_HEADER) final String userId,
-            @Parameter(description = "X-ECOMP-RequestID header",
-                    required = false) @HeaderParam(value = Constants.X_ECOMP_REQUEST_ID_HEADER) String requestId,
-            @Parameter(description = "X-ECOMP-InstanceID header", required = true) @HeaderParam(
-                    value = Constants.X_ECOMP_INSTANCE_ID_HEADER) final String instanceIdHeader,
-            @Parameter(description = "Determines the format of the body of the response",
-                    required = false) @HeaderParam(value = Constants.ACCEPT_HEADER) String accept,
-            @Parameter(description = "The username and password",
-                    required = true) @HeaderParam(value = Constants.AUTHORIZATION_HEADER) String authorization,
-            @Parameter(schema = @Schema(allowableValues = {"resources,services"}),description = "The requested asset type",
-                    required = true) @PathParam("assetType") final String assetType,
-            @Parameter(schema = @Schema(allowableValues = {"resources,services"}),description = "The uuid of the asset as published in the metadata",
-                    required = true) @PathParam("uuid") final String uuid,
-            @Parameter(description = "The component instance name (as publishedin the response of the detailed query)",
-                    required = true) @PathParam("resourceInstanceName") final String resourceInstanceName,
-            @Parameter(hidden = true) String data) {
-
+        @Parameter(description = "Determines the format of the body of the request", required = true) @HeaderParam(value = Constants.CONTENT_TYPE_HEADER) String contentType,
+        @Parameter(description = "The value for this header must be the MD5 checksum over the whole json body", required = true) @HeaderParam(value = Constants.MD5_HEADER) String checksum,
+        @Parameter(description = "The user ID of the DCAE Designer. This user must also have Designer role in SDC", required = true) @HeaderParam(value = Constants.USER_ID_HEADER) final String userId,
+        @Parameter(description = "X-ECOMP-RequestID header", required = false) @HeaderParam(value = Constants.X_ECOMP_REQUEST_ID_HEADER) String requestId,
+        @Parameter(description = "X-ECOMP-InstanceID header", required = true) @HeaderParam(value = Constants.X_ECOMP_INSTANCE_ID_HEADER) final String instanceIdHeader,
+        @Parameter(description = "Determines the format of the body of the response", required = false) @HeaderParam(value = Constants.ACCEPT_HEADER) String accept,
+        @Parameter(description = "The username and password", required = true) @HeaderParam(value = Constants.AUTHORIZATION_HEADER) String authorization,
+        @Parameter(schema = @Schema(allowableValues = {
+            "resources,services"}), description = "The requested asset type", required = true) @PathParam("assetType") final String assetType,
+        @Parameter(schema = @Schema(allowableValues = {
+            "resources,services"}), description = "The uuid of the asset as published in the metadata", required = true) @PathParam("uuid") final String uuid,
+        @Parameter(description = "The component instance name (as publishedin the response of the detailed query)", required = true) @PathParam("resourceInstanceName") final String resourceInstanceName,
+        @Parameter(hidden = true) String data) {
         Wrapper<Response> responseWrapper = new Wrapper<>();
         ResponseFormat responseFormat = null;
         String requestURI = request.getRequestURI();
@@ -381,7 +315,6 @@ public class ArtifactExternalServlet extends AbstractValidationsServlet {
         String componentTypeValue = componentType == null ? null : componentType.getValue();
         ResourceCommonInfo resourceCommonInfo = new ResourceCommonInfo(resourceInstanceName, componentTypeValue);
         ArtifactDefinition artifactDefinition = null;
-
         if (componentType == null) {
             log.debug("uploadArtifact: assetType parameter {} is not valid", assetType);
             responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.INVALID_CONTENT);
@@ -400,82 +333,62 @@ public class ArtifactExternalServlet extends AbstractValidationsServlet {
         try {
             if (responseWrapper.isEmpty()) {
                 artifactDefinition = artifactsBusinessLogic.uploadArtifactToRiByUUID(data, request, componentType, uuid, resourceInstanceName,
-                        new ArtifactOperationInfo(true, false, ArtifactOperationEnum.CREATE));
+                    new ArtifactOperationInfo(true, false, ArtifactOperationEnum.CREATE));
                 Object representation = RepresentationUtils.toRepresentation(artifactDefinition);
                 Map<String, String> headers = new HashMap<>();
                 headers.put(Constants.MD5_HEADER, GeneralUtility.calculateMD5Base64EncodedByString((String) representation));
                 responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.OK);
                 responseWrapper.setInnerElement(buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), representation, headers));
             }
-        }catch (IOException e) {
+        } catch (IOException e) {
             final String message = "failed to upload artifact to a resource instance";
             BeEcompErrorManager.getInstance().logBeRestApiGeneralError(message);
             log.debug(message, e);
             responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR);
             responseWrapper.setInnerElement(buildErrorResponse(responseFormat));
-        }catch (ComponentException e){
+        } catch (ComponentException e) {
             responseFormat = getComponentsUtils().getResponseFormat(e);
             throw e;
-        }finally {
-            getComponentsUtils().auditExternalCrudApi(responseFormat, AuditingActionEnum.ARTIFACT_UPLOAD_BY_API,
-                    resourceCommonInfo, request, artifactDefinition, null);
+        } finally {
+            getComponentsUtils()
+                .auditExternalCrudApi(responseFormat, AuditingActionEnum.ARTIFACT_UPLOAD_BY_API, resourceCommonInfo, request, artifactDefinition,
+                    null);
         }
         return responseWrapper.getInnerElement();
     }
 
-
     @POST
     @Path("/{assetType}/{uuid}/artifacts/{artifactUUID}")
     @Produces(MediaType.APPLICATION_JSON)
-    @Operation(parameters = {@Parameter(required = true,
-            schema = @Schema(implementation = org.openecomp.sdc.be.model.ArtifactDefinition.class),
-            description = "json describe the artifact")}, description = "updates an artifact on a resource or service",
-            method = "POST", summary = "uploads of artifact to a resource or service", responses = {
-            @ApiResponse(responseCode = "200", description = "Artifact updated", content = @Content(
-                    array = @ArraySchema(schema = @Schema(implementation = ArtifactDefinition.class)))),
-            @ApiResponse(responseCode = "400", description = "Missing  'X-ECOMP-InstanceID'  HTTP header - POL5001"),
-            @ApiResponse(responseCode = "401",
-                    description = "ECOMP component  should authenticate itself  and  to  re-send  again  HTTP  request  with its Basic  Authentication credentials - POL5002"),
-            @ApiResponse(responseCode = "403", description = "ECOMP component is not authorized - POL5003"),
-            @ApiResponse(responseCode = "404", description = "Specified resource is not found - SVC4063"),
-            @ApiResponse(responseCode = "405",
-                    description = "Method  Not Allowed: Invalid HTTP method type used (PUT,DELETE,POST will be rejected) - POL4050"),
-            @ApiResponse(responseCode = "500",
-                    description = "The GET request failed either due to internal SDC problem or Cambria Service failure. ECOMP Component should continue the attempts to get the needed information - POL5000"),
-            @ApiResponse(responseCode = "400", description = "Invalid artifactType was defined as input - SVC4122"),
-            @ApiResponse(responseCode = "400",
-                    description = "Artifact type (mandatory field) is missing in request - SVC4124"),
-            @ApiResponse(responseCode = "400", description = "Invalid MD5 header - SVC4127"),
-            @ApiResponse(responseCode = "400", description = "Artifact name is missing in input - SVC4128"),
-            @ApiResponse(responseCode = "403",
-                    description = "Asset is being edited by different user. Only one user can checkout and edit an asset on given time. The asset will be available for checkout after the other user will checkin the asset - SVC4086"),
-            @ApiResponse(responseCode = "409",
-                    description = "Restricted Operation â€“ the user provided does not have role of Designer or the asset is being used by another designer - SVC4301")})
+    @Operation(parameters = {
+        @Parameter(required = true, schema = @Schema(implementation = org.openecomp.sdc.be.model.ArtifactDefinition.class), description = "json describe the artifact")}, description = "updates an artifact on a resource or service", method = "POST", summary = "uploads of artifact to a resource or service", responses = {
+        @ApiResponse(responseCode = "200", description = "Artifact updated", content = @Content(array = @ArraySchema(schema = @Schema(implementation = ArtifactDefinition.class)))),
+        @ApiResponse(responseCode = "400", description = "Missing  'X-ECOMP-InstanceID'  HTTP header - POL5001"),
+        @ApiResponse(responseCode = "401", description = "ECOMP component  should authenticate itself  and  to  re-send  again  HTTP  request  with its Basic  Authentication credentials - POL5002"),
+        @ApiResponse(responseCode = "403", description = "ECOMP component is not authorized - POL5003"),
+        @ApiResponse(responseCode = "404", description = "Specified resource is not found - SVC4063"),
+        @ApiResponse(responseCode = "405", description = "Method  Not Allowed: Invalid HTTP method type used (PUT,DELETE,POST will be rejected) - POL4050"),
+        @ApiResponse(responseCode = "500", description = "The GET request failed either due to internal SDC problem or Cambria Service failure. ECOMP Component should continue the attempts to get the needed information - POL5000"),
+        @ApiResponse(responseCode = "400", description = "Invalid artifactType was defined as input - SVC4122"),
+        @ApiResponse(responseCode = "400", description = "Artifact type (mandatory field) is missing in request - SVC4124"),
+        @ApiResponse(responseCode = "400", description = "Invalid MD5 header - SVC4127"),
+        @ApiResponse(responseCode = "400", description = "Artifact name is missing in input - SVC4128"),
+        @ApiResponse(responseCode = "403", description = "Asset is being edited by different user. Only one user can checkout and edit an asset on given time. The asset will be available for checkout after the other user will checkin the asset - SVC4086"),
+        @ApiResponse(responseCode = "409", description = "Restricted Operation â€“ the user provided does not have role of Designer or the asset is being used by another designer - SVC4301")})
     @PermissionAllowed(AafPermission.PermNames.WRITE_VALUE)
     public Response updateArtifact(
-            @Parameter(description = "Determines the format of the body of the request",
-                    required = true) @HeaderParam(value = Constants.CONTENT_TYPE_HEADER) String contentType,
-            @Parameter(description = "The value for this header must be the MD5 checksum over the whole json body",
-                    required = true) @HeaderParam(value = Constants.MD5_HEADER) String checksum,
-            @Parameter(description = "The user ID of the DCAE Designer. This user must also have Designer role in SDC",
-                    required = true) @HeaderParam(value = Constants.USER_ID_HEADER) final String userId,
-            @Parameter(description = "X-ECOMP-RequestID header",
-                    required = false) @HeaderParam(value = Constants.X_ECOMP_REQUEST_ID_HEADER) String requestId,
-            @Parameter(description = "X-ECOMP-InstanceID header", required = true) @HeaderParam(
-                    value = Constants.X_ECOMP_INSTANCE_ID_HEADER) final String instanceIdHeader,
-            @Parameter(description = "Determines the format of the body of the response",
-                    required = false) @HeaderParam(value = Constants.ACCEPT_HEADER) String accept,
-            @Parameter(description = "The username and password",
-                    required = true) @HeaderParam(value = Constants.AUTHORIZATION_HEADER) String authorization,
-            @Parameter(schema = @Schema(allowableValues = {"resources,services"}),description = "The requested asset type",
-                    required = true) @PathParam("assetType") final String assetType,
-            @Parameter(description = "The uuid of the asset as published in the metadata",
-                    required = true) @PathParam("uuid") final String uuid,
-            @Parameter(
-                    description = "The uuid of the artifact as published in the asset detailed metadata or in the response of the upload / update operation",
-                    required = true) @PathParam("artifactUUID") final String artifactUUID,
-            @Parameter(hidden = true) String data) {
-
+        @Parameter(description = "Determines the format of the body of the request", required = true) @HeaderParam(value = Constants.CONTENT_TYPE_HEADER) String contentType,
+        @Parameter(description = "The value for this header must be the MD5 checksum over the whole json body", required = true) @HeaderParam(value = Constants.MD5_HEADER) String checksum,
+        @Parameter(description = "The user ID of the DCAE Designer. This user must also have Designer role in SDC", required = true) @HeaderParam(value = Constants.USER_ID_HEADER) final String userId,
+        @Parameter(description = "X-ECOMP-RequestID header", required = false) @HeaderParam(value = Constants.X_ECOMP_REQUEST_ID_HEADER) String requestId,
+        @Parameter(description = "X-ECOMP-InstanceID header", required = true) @HeaderParam(value = Constants.X_ECOMP_INSTANCE_ID_HEADER) final String instanceIdHeader,
+        @Parameter(description = "Determines the format of the body of the response", required = false) @HeaderParam(value = Constants.ACCEPT_HEADER) String accept,
+        @Parameter(description = "The username and password", required = true) @HeaderParam(value = Constants.AUTHORIZATION_HEADER) String authorization,
+        @Parameter(schema = @Schema(allowableValues = {
+            "resources,services"}), description = "The requested asset type", required = true) @PathParam("assetType") final String assetType,
+        @Parameter(description = "The uuid of the asset as published in the metadata", required = true) @PathParam("uuid") final String uuid,
+        @Parameter(description = "The uuid of the artifact as published in the asset detailed metadata or in the response of the upload / update operation", required = true) @PathParam("artifactUUID") final String artifactUUID,
+        @Parameter(hidden = true) String data) {
         Wrapper<Response> responseWrapper = new Wrapper<>();
         ResponseFormat responseFormat = null;
         String requestURI = request.getRequestURI();
@@ -484,7 +397,6 @@ public class ArtifactExternalServlet extends AbstractValidationsServlet {
         ComponentTypeEnum componentType = ComponentTypeEnum.findByParamName(assetType);
         String componentTypeValue = componentType == null ? null : componentType.getValue();
         ResourceCommonInfo resourceCommonInfo = new ResourceCommonInfo(componentTypeValue);
-
         if (componentType == null) {
             log.debug("updateArtifact: assetType parameter {} is not valid", assetType);
             responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.INVALID_CONTENT);
@@ -503,8 +415,9 @@ public class ArtifactExternalServlet extends AbstractValidationsServlet {
         ArtifactDefinition artifactDefinition = null;
         try {
             if (responseWrapper.isEmpty()) {
-                artifactDefinition = artifactsBusinessLogic.updateArtifactOnComponentByUUID(data, request, componentType, uuid, artifactUUID,
-                        resourceCommonInfo, new ArtifactOperationInfo(true, false, ArtifactOperationEnum.UPDATE));
+                artifactDefinition = artifactsBusinessLogic
+                    .updateArtifactOnComponentByUUID(data, request, componentType, uuid, artifactUUID, resourceCommonInfo,
+                        new ArtifactOperationInfo(true, false, ArtifactOperationEnum.UPDATE));
                 Object representation = RepresentationUtils.toRepresentation(artifactDefinition);
                 Map<String, String> headers = new HashMap<>();
                 headers.put(Constants.MD5_HEADER, GeneralUtility.calculateMD5Base64EncodedByString((String) representation));
@@ -517,13 +430,13 @@ public class ArtifactExternalServlet extends AbstractValidationsServlet {
             log.debug(message, e);
             responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR);
             responseWrapper.setInnerElement(buildErrorResponse(responseFormat));
-        }  catch (ComponentException e){
+        } catch (ComponentException e) {
             responseFormat = getComponentsUtils().getResponseFormat(e);
             throw e;
-        }
-        finally{
-            getComponentsUtils().auditExternalCrudApi(responseFormat, AuditingActionEnum.ARTIFACT_UPDATE_BY_API, resourceCommonInfo,
-                    request, artifactDefinition, artifactUUID);
+        } finally {
+            getComponentsUtils()
+                .auditExternalCrudApi(responseFormat, AuditingActionEnum.ARTIFACT_UPDATE_BY_API, resourceCommonInfo, request, artifactDefinition,
+                    artifactUUID);
         }
         return responseWrapper.getInnerElement();
     }
@@ -534,57 +447,36 @@ public class ArtifactExternalServlet extends AbstractValidationsServlet {
     @POST
     @Path("/{assetType}/{uuid}/resourceInstances/{resourceInstanceName}/artifacts/{artifactUUID}")
     @Produces(MediaType.APPLICATION_JSON)
-    @Operation(parameters = {@Parameter(required = true,
-            schema = @Schema(implementation = org.openecomp.sdc.be.model.ArtifactDefinition.class),
-            description = "json describe the artifact")}, description = "updates an artifact on a resource instance",
-            method = "POST", summary = "uploads of artifact to a resource or service", responses = {
-            @ApiResponse(responseCode = "200", description = "Artifact updated", content = @Content(
-                    array = @ArraySchema(schema = @Schema(implementation = ArtifactDefinition.class)))),
-            @ApiResponse(responseCode = "400", description = "Missing  'X-ECOMP-InstanceID'  HTTP header - POL5001"),
-            @ApiResponse(responseCode = "401",
-                    description = "ECOMP component  should authenticate itself  and  to  re-send  again  HTTP  request  with its Basic  Authentication credentials - POL5002"),
-            @ApiResponse(responseCode = "403", description = "ECOMP component is not authorized - POL5003"),
-            @ApiResponse(responseCode = "404", description = "Specified resource is not found - SVC4063"),
-            @ApiResponse(responseCode = "405",
-                    description = "Method  Not Allowed: Invalid HTTP method type used (PUT,DELETE,POST will be rejected) - POL4050"),
-            @ApiResponse(responseCode = "500",
-                    description = "The GET request failed either due to internal SDC problem or Cambria Service failure. ECOMP Component should continue the attempts to get the needed information - POL5000"),
-            @ApiResponse(responseCode = "400", description = "Invalid artifactType was defined as input - SVC4122"),
-            @ApiResponse(responseCode = "400",
-                    description = "Artifact type (mandatory field) is missing in request - SVC4124"),
-            @ApiResponse(responseCode = "400", description = "Invalid MD5 header - SVC4127"),
-            @ApiResponse(responseCode = "400", description = "Artifact name is missing in input - SVC4128"),
-            @ApiResponse(responseCode = "403",
-                    description = "Asset is being edited by different user. Only one user can checkout and edit an asset on given time. The asset will be available for checkout after the other user will checkin the asset - SVC4086"),
-            @ApiResponse(responseCode = "409",
-                    description = "Restricted Operation â€“ the user provided does not have role of Designer or the asset is being used by another designer - SVC4301")})
+    @Operation(parameters = {
+        @Parameter(required = true, schema = @Schema(implementation = org.openecomp.sdc.be.model.ArtifactDefinition.class), description = "json describe the artifact")}, description = "updates an artifact on a resource instance", method = "POST", summary = "uploads of artifact to a resource or service", responses = {
+        @ApiResponse(responseCode = "200", description = "Artifact updated", content = @Content(array = @ArraySchema(schema = @Schema(implementation = ArtifactDefinition.class)))),
+        @ApiResponse(responseCode = "400", description = "Missing  'X-ECOMP-InstanceID'  HTTP header - POL5001"),
+        @ApiResponse(responseCode = "401", description = "ECOMP component  should authenticate itself  and  to  re-send  again  HTTP  request  with its Basic  Authentication credentials - POL5002"),
+        @ApiResponse(responseCode = "403", description = "ECOMP component is not authorized - POL5003"),
+        @ApiResponse(responseCode = "404", description = "Specified resource is not found - SVC4063"),
+        @ApiResponse(responseCode = "405", description = "Method  Not Allowed: Invalid HTTP method type used (PUT,DELETE,POST will be rejected) - POL4050"),
+        @ApiResponse(responseCode = "500", description = "The GET request failed either due to internal SDC problem or Cambria Service failure. ECOMP Component should continue the attempts to get the needed information - POL5000"),
+        @ApiResponse(responseCode = "400", description = "Invalid artifactType was defined as input - SVC4122"),
+        @ApiResponse(responseCode = "400", description = "Artifact type (mandatory field) is missing in request - SVC4124"),
+        @ApiResponse(responseCode = "400", description = "Invalid MD5 header - SVC4127"),
+        @ApiResponse(responseCode = "400", description = "Artifact name is missing in input - SVC4128"),
+        @ApiResponse(responseCode = "403", description = "Asset is being edited by different user. Only one user can checkout and edit an asset on given time. The asset will be available for checkout after the other user will checkin the asset - SVC4086"),
+        @ApiResponse(responseCode = "409", description = "Restricted Operation â€“ the user provided does not have role of Designer or the asset is being used by another designer - SVC4301")})
     @PermissionAllowed(AafPermission.PermNames.WRITE_VALUE)
     public Response updateArtifactOnResourceInstance(
-            @Parameter(description = "Determines the format of the body of the request",
-                    required = true) @HeaderParam(value = Constants.CONTENT_TYPE_HEADER) String contentType,
-            @Parameter(description = "The value for this header must be the MD5 checksum over the whole json body",
-                    required = true) @HeaderParam(value = Constants.MD5_HEADER) String checksum,
-            @Parameter(description = "The user ID of the DCAE Designer. This user must also have Designer role in SDC",
-                    required = true) @HeaderParam(value = Constants.USER_ID_HEADER) final String userId,
-            @Parameter(description = "X-ECOMP-RequestID header",
-                    required = false) @HeaderParam(value = Constants.X_ECOMP_REQUEST_ID_HEADER) String requestId,
-            @Parameter(description = "X-ECOMP-InstanceID header", required = true) @HeaderParam(
-                    value = Constants.X_ECOMP_INSTANCE_ID_HEADER) final String instanceIdHeader,
-            @Parameter(description = "Determines the format of the body of the response",
-                    required = false) @HeaderParam(value = Constants.ACCEPT_HEADER) String accept,
-            @Parameter(description = "The username and password",
-                    required = true) @HeaderParam(value = Constants.AUTHORIZATION_HEADER) String authorization,
-            @Parameter(schema = @Schema(allowableValues = {"resources,services"}),description = "The requested asset type",
-                    required = true) @PathParam("assetType") final String assetType,
-            @Parameter(description = "The uuid of the asset as published in the metadata",
-                    required = true) @PathParam("uuid") final String uuid,
-            @Parameter(
-                    description = "The uuid of the artifact as published in the asset detailed metadata or in the response of the upload / update operation",
-                    required = true) @PathParam("artifactUUID") final String artifactUUID,
-            @Parameter(description = "The component instance name (as publishedin the response of the detailed query)",
-                    required = true) @PathParam("resourceInstanceName") final String resourceInstanceName,
-            @Parameter(hidden = true) String data) {
-
+        @Parameter(description = "Determines the format of the body of the request", required = true) @HeaderParam(value = Constants.CONTENT_TYPE_HEADER) String contentType,
+        @Parameter(description = "The value for this header must be the MD5 checksum over the whole json body", required = true) @HeaderParam(value = Constants.MD5_HEADER) String checksum,
+        @Parameter(description = "The user ID of the DCAE Designer. This user must also have Designer role in SDC", required = true) @HeaderParam(value = Constants.USER_ID_HEADER) final String userId,
+        @Parameter(description = "X-ECOMP-RequestID header", required = false) @HeaderParam(value = Constants.X_ECOMP_REQUEST_ID_HEADER) String requestId,
+        @Parameter(description = "X-ECOMP-InstanceID header", required = true) @HeaderParam(value = Constants.X_ECOMP_INSTANCE_ID_HEADER) final String instanceIdHeader,
+        @Parameter(description = "Determines the format of the body of the response", required = false) @HeaderParam(value = Constants.ACCEPT_HEADER) String accept,
+        @Parameter(description = "The username and password", required = true) @HeaderParam(value = Constants.AUTHORIZATION_HEADER) String authorization,
+        @Parameter(schema = @Schema(allowableValues = {
+            "resources,services"}), description = "The requested asset type", required = true) @PathParam("assetType") final String assetType,
+        @Parameter(description = "The uuid of the asset as published in the metadata", required = true) @PathParam("uuid") final String uuid,
+        @Parameter(description = "The uuid of the artifact as published in the asset detailed metadata or in the response of the upload / update operation", required = true) @PathParam("artifactUUID") final String artifactUUID,
+        @Parameter(description = "The component instance name (as publishedin the response of the detailed query)", required = true) @PathParam("resourceInstanceName") final String resourceInstanceName,
+        @Parameter(hidden = true) String data) {
         Wrapper<Response> responseWrapper = new Wrapper<>();
         ResponseFormat responseFormat = null;
         String requestURI = request.getRequestURI();
@@ -593,7 +485,6 @@ public class ArtifactExternalServlet extends AbstractValidationsServlet {
         ComponentTypeEnum componentType = ComponentTypeEnum.findByParamName(assetType);
         String componentTypeValue = componentType == null ? null : componentType.getValue();
         ResourceCommonInfo resourceCommonInfo = new ResourceCommonInfo(resourceInstanceName, componentTypeValue);
-
         if (componentType == null) {
             log.debug("updateArtifactOnResourceInstance: assetType parameter {} is not valid", assetType);
             responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.INVALID_CONTENT);
@@ -609,11 +500,11 @@ public class ArtifactExternalServlet extends AbstractValidationsServlet {
             responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.MISSING_USER_ID);
             responseWrapper.setInnerElement(buildErrorResponse(responseFormat));
         }
-
         ArtifactDefinition artifactDefinition = null;
         try {
             if (responseWrapper.isEmpty()) {
-                artifactDefinition = artifactsBusinessLogic.updateArtifactOnRiByUUID(data, request, componentType, uuid, resourceInstanceName, artifactUUID,
+                artifactDefinition = artifactsBusinessLogic
+                    .updateArtifactOnRiByUUID(data, request, componentType, uuid, resourceInstanceName, artifactUUID,
                         new ArtifactOperationInfo(true, false, ArtifactOperationEnum.UPDATE));
                 Object representation = RepresentationUtils.toRepresentation(artifactDefinition);
                 Map<String, String> headers = new HashMap<>();
@@ -627,13 +518,13 @@ public class ArtifactExternalServlet extends AbstractValidationsServlet {
             log.debug(message, e);
             responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR);
             responseWrapper.setInnerElement(buildErrorResponse(responseFormat));
-        }  catch (ComponentException e){
+        } catch (ComponentException e) {
             responseFormat = getComponentsUtils().getResponseFormat(e);
             throw e;
-        }
-        finally{
-            getComponentsUtils().auditExternalCrudApi(responseFormat, AuditingActionEnum.ARTIFACT_UPDATE_BY_API, resourceCommonInfo,
-                    request, artifactDefinition, artifactUUID);
+        } finally {
+            getComponentsUtils()
+                .auditExternalCrudApi(responseFormat, AuditingActionEnum.ARTIFACT_UPDATE_BY_API, resourceCommonInfo, request, artifactDefinition,
+                    artifactUUID);
         }
         return responseWrapper.getInnerElement();
     }
@@ -644,49 +535,32 @@ public class ArtifactExternalServlet extends AbstractValidationsServlet {
     @DELETE
     @Path("/{assetType}/{uuid}/artifacts/{artifactUUID}")
     @Produces(MediaType.APPLICATION_JSON)
-    @Operation(description = "deletes an artifact of a resource or service", method = "DELETE",
-            summary = "deletes an artifact of a resource or service", responses = {
-            @ApiResponse(content = @Content(array = @ArraySchema(schema = @Schema(implementation = Response.class)))),
-            @ApiResponse(responseCode = "200", description = "Artifact deleted", content = @Content(
-                    array = @ArraySchema(schema = @Schema(implementation = ArtifactDefinition.class)))),
-            @ApiResponse(responseCode = "400", description = "Missing  'X-ECOMP-InstanceID'  HTTP header - POL5001"),
-            @ApiResponse(responseCode = "401",
-                    description = "ECOMP component  should authenticate itself  and  to  re-send  again  HTTP  request  with its Basic  Authentication credentials - POL5002"),
-            @ApiResponse(responseCode = "403", description = "ECOMP component is not authorized - POL5003"),
-            @ApiResponse(responseCode = "404", description = "Specified resource is not found - SVC4063"),
-            @ApiResponse(responseCode = "405",
-                    description = "Method  Not Allowed: Invalid HTTP method type used (PUT,DELETE,POST will be rejected) - POL4050"),
-            @ApiResponse(responseCode = "500",
-                    description = "The GET request failed either due to internal SDC problem or Cambria Service failure. ECOMP Component should continue the attempts to get the needed information - POL5000"),
-            @ApiResponse(responseCode = "400", description = "Invalid artifactType was defined as input - SVC4122"),
-            @ApiResponse(responseCode = "400",
-                    description = "Artifact type (mandatory field) is missing in request - SVC4124"),
-            @ApiResponse(responseCode = "400", description = "Invalid MD5 header - SVC4127"),
-            @ApiResponse(responseCode = "400", description = "Artifact name is missing in input - SVC4128"),
-            @ApiResponse(responseCode = "403",
-                    description = "Asset is being edited by different user. Only one user can checkout and edit an asset on given time. The asset will be available for checkout after the other user will checkin the asset - SVC4086"),
-            @ApiResponse(responseCode = "409",
-                    description = "Restricted Operation â€“ the user provided does not have role of Designer or the asset is being used by another designer - SVC4301")})
+    @Operation(description = "deletes an artifact of a resource or service", method = "DELETE", summary = "deletes an artifact of a resource or service", responses = {
+        @ApiResponse(content = @Content(array = @ArraySchema(schema = @Schema(implementation = Response.class)))),
+        @ApiResponse(responseCode = "200", description = "Artifact deleted", content = @Content(array = @ArraySchema(schema = @Schema(implementation = ArtifactDefinition.class)))),
+        @ApiResponse(responseCode = "400", description = "Missing  'X-ECOMP-InstanceID'  HTTP header - POL5001"),
+        @ApiResponse(responseCode = "401", description = "ECOMP component  should authenticate itself  and  to  re-send  again  HTTP  request  with its Basic  Authentication credentials - POL5002"),
+        @ApiResponse(responseCode = "403", description = "ECOMP component is not authorized - POL5003"),
+        @ApiResponse(responseCode = "404", description = "Specified resource is not found - SVC4063"),
+        @ApiResponse(responseCode = "405", description = "Method  Not Allowed: Invalid HTTP method type used (PUT,DELETE,POST will be rejected) - POL4050"),
+        @ApiResponse(responseCode = "500", description = "The GET request failed either due to internal SDC problem or Cambria Service failure. ECOMP Component should continue the attempts to get the needed information - POL5000"),
+        @ApiResponse(responseCode = "400", description = "Invalid artifactType was defined as input - SVC4122"),
+        @ApiResponse(responseCode = "400", description = "Artifact type (mandatory field) is missing in request - SVC4124"),
+        @ApiResponse(responseCode = "400", description = "Invalid MD5 header - SVC4127"),
+        @ApiResponse(responseCode = "400", description = "Artifact name is missing in input - SVC4128"),
+        @ApiResponse(responseCode = "403", description = "Asset is being edited by different user. Only one user can checkout and edit an asset on given time. The asset will be available for checkout after the other user will checkin the asset - SVC4086"),
+        @ApiResponse(responseCode = "409", description = "Restricted Operation â€“ the user provided does not have role of Designer or the asset is being used by another designer - SVC4301")})
     @PermissionAllowed(AafPermission.PermNames.DELETE_VALUE)
     public Response deleteArtifact(
-            @Parameter(description = "The user ID of the DCAE Designer. This user must also have Designer role in SDC",
-                    required = true) @HeaderParam(value = Constants.USER_ID_HEADER) final String userId,
-            @Parameter(description = "X-ECOMP-RequestID header",
-                    required = false) @HeaderParam(value = Constants.X_ECOMP_REQUEST_ID_HEADER) String requestId,
-            @Parameter(description = "X-ECOMP-InstanceID header", required = true) @HeaderParam(
-                    value = Constants.X_ECOMP_INSTANCE_ID_HEADER) final String instanceIdHeader,
-            @Parameter(description = "Determines the format of the body of the response",
-                    required = false) @HeaderParam(value = Constants.ACCEPT_HEADER) String accept,
-            @Parameter(description = "The username and password",
-                    required = true) @HeaderParam(value = Constants.AUTHORIZATION_HEADER) String authorization,
-            @Parameter(schema = @Schema(allowableValues = {"resources,services"}),description = "The requested asset type",
-                    required = true) @PathParam("assetType") final String assetType,
-            @Parameter(description = "The uuid of the asset as published in the metadata",
-                    required = true) @PathParam("uuid") final String uuid,
-            @Parameter(
-                    description = "The uuid of the artifact as published in the asset detailed metadata or in the response of the upload / update operation",
-                    required = true) @PathParam("artifactUUID") final String artifactUUID) {
-
+        @Parameter(description = "The user ID of the DCAE Designer. This user must also have Designer role in SDC", required = true) @HeaderParam(value = Constants.USER_ID_HEADER) final String userId,
+        @Parameter(description = "X-ECOMP-RequestID header", required = false) @HeaderParam(value = Constants.X_ECOMP_REQUEST_ID_HEADER) String requestId,
+        @Parameter(description = "X-ECOMP-InstanceID header", required = true) @HeaderParam(value = Constants.X_ECOMP_INSTANCE_ID_HEADER) final String instanceIdHeader,
+        @Parameter(description = "Determines the format of the body of the response", required = false) @HeaderParam(value = Constants.ACCEPT_HEADER) String accept,
+        @Parameter(description = "The username and password", required = true) @HeaderParam(value = Constants.AUTHORIZATION_HEADER) String authorization,
+        @Parameter(schema = @Schema(allowableValues = {
+            "resources,services"}), description = "The requested asset type", required = true) @PathParam("assetType") final String assetType,
+        @Parameter(description = "The uuid of the asset as published in the metadata", required = true) @PathParam("uuid") final String uuid,
+        @Parameter(description = "The uuid of the artifact as published in the asset detailed metadata or in the response of the upload / update operation", required = true) @PathParam("artifactUUID") final String artifactUUID) {
         Wrapper<Response> responseWrapper = new Wrapper<>();
         ResponseFormat responseFormat = null;
         String requestURI = request.getRequestURI();
@@ -694,10 +568,8 @@ public class ArtifactExternalServlet extends AbstractValidationsServlet {
         log.debug(DOUBLE_CURLY_BRACKETS, startLog, url);
         ComponentTypeEnum componentType = ComponentTypeEnum.findByParamName(assetType);
         String componentTypeValue = componentType == null ? null : componentType.getValue();
-
         ResourceCommonInfo resourceCommonInfo = new ResourceCommonInfo(componentTypeValue);
         ArtifactDefinition artifactDefinition = null;
-
         if (componentType == null) {
             log.debug("deleteArtifact: assetType parameter {} is not valid", assetType);
             responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.INVALID_CONTENT);
@@ -713,11 +585,11 @@ public class ArtifactExternalServlet extends AbstractValidationsServlet {
             responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.MISSING_USER_ID);
             responseWrapper.setInnerElement(buildErrorResponse(responseFormat));
         }
-
         try {
             if (responseWrapper.isEmpty()) {
-                artifactDefinition = artifactsBusinessLogic.deleteArtifactOnComponentByUUID(request, componentType, uuid, artifactUUID,
-                        resourceCommonInfo, new ArtifactOperationInfo(true, false, ArtifactOperationEnum.DELETE));
+                artifactDefinition = artifactsBusinessLogic
+                    .deleteArtifactOnComponentByUUID(request, componentType, uuid, artifactUUID, resourceCommonInfo,
+                        new ArtifactOperationInfo(true, false, ArtifactOperationEnum.DELETE));
                 Object representation = RepresentationUtils.toRepresentation(artifactDefinition);
                 Map<String, String> headers = new HashMap<>();
                 headers.put(Constants.MD5_HEADER, GeneralUtility.calculateMD5Base64EncodedByString((String) representation));
@@ -730,13 +602,13 @@ public class ArtifactExternalServlet extends AbstractValidationsServlet {
             log.debug(message, e);
             responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR);
             responseWrapper.setInnerElement(buildErrorResponse(responseFormat));
-        }  catch (ComponentException e){
+        } catch (ComponentException e) {
             responseFormat = getComponentsUtils().getResponseFormat(e);
             throw e;
-        }
-        finally{
-            getComponentsUtils().auditExternalCrudApi(responseFormat, AuditingActionEnum.ARTIFACT_DELETE_BY_API, resourceCommonInfo,
-                    request, artifactDefinition, artifactUUID);
+        } finally {
+            getComponentsUtils()
+                .auditExternalCrudApi(responseFormat, AuditingActionEnum.ARTIFACT_DELETE_BY_API, resourceCommonInfo, request, artifactDefinition,
+                    artifactUUID);
         }
         return responseWrapper.getInnerElement();
     }
@@ -747,51 +619,33 @@ public class ArtifactExternalServlet extends AbstractValidationsServlet {
     @DELETE
     @Path("{assetType}/{uuid}/resourceInstances/{resourceInstanceName}/artifacts/{artifactUUID}")
     @Produces(MediaType.APPLICATION_JSON)
-    @Operation(description = "deletes an artifact of a resource insatnce", method = "DELETE",
-            summary = "deletes an artifact of a resource insatnce", responses = {
-            @ApiResponse(content = @Content(array = @ArraySchema(schema = @Schema(implementation = Response.class)))),
-            @ApiResponse(responseCode = "200", description = "Artifact deleted", content = @Content(
-                    array = @ArraySchema(schema = @Schema(implementation = ArtifactDefinition.class)))),
-            @ApiResponse(responseCode = "400", description = "Missing  'X-ECOMP-InstanceID'  HTTP header - POL5001"),
-            @ApiResponse(responseCode = "401",
-                    description = "ECOMP component  should authenticate itself  and  to  re-send  again  HTTP  request  with its Basic  Authentication credentials - POL5002"),
-            @ApiResponse(responseCode = "403", description = "ECOMP component is not authorized - POL5003"),
-            @ApiResponse(responseCode = "404", description = "Specified resource is not found - SVC4063"),
-            @ApiResponse(responseCode = "405",
-                    description = "Method  Not Allowed: Invalid HTTP method type used (PUT,DELETE,POST will be rejected) - POL4050"),
-            @ApiResponse(responseCode = "500",
-                    description = "The GET request failed either due to internal SDC problem or Cambria Service failure. ECOMP Component should continue the attempts to get the needed information - POL5000"),
-            @ApiResponse(responseCode = "400", description = "Invalid artifactType was defined as input - SVC4122"),
-            @ApiResponse(responseCode = "400",
-                    description = "Artifact type (mandatory field) is missing in request - SVC4124"),
-            @ApiResponse(responseCode = "400", description = "Invalid MD5 header - SVC4127"),
-            @ApiResponse(responseCode = "400", description = "Artifact name is missing in input - SVC4128"),
-            @ApiResponse(responseCode = "403",
-                    description = "Asset is being edited by different user. Only one user can checkout and edit an asset on given time. The asset will be available for checkout after the other user will checkin the asset - SVC4086"),
-            @ApiResponse(responseCode = "409",
-                    description = "Restricted Operation â€“ the user provided does not have role of Designer or the asset is being used by another designer - SVC4301")})
+    @Operation(description = "deletes an artifact of a resource insatnce", method = "DELETE", summary = "deletes an artifact of a resource insatnce", responses = {
+        @ApiResponse(content = @Content(array = @ArraySchema(schema = @Schema(implementation = Response.class)))),
+        @ApiResponse(responseCode = "200", description = "Artifact deleted", content = @Content(array = @ArraySchema(schema = @Schema(implementation = ArtifactDefinition.class)))),
+        @ApiResponse(responseCode = "400", description = "Missing  'X-ECOMP-InstanceID'  HTTP header - POL5001"),
+        @ApiResponse(responseCode = "401", description = "ECOMP component  should authenticate itself  and  to  re-send  again  HTTP  request  with its Basic  Authentication credentials - POL5002"),
+        @ApiResponse(responseCode = "403", description = "ECOMP component is not authorized - POL5003"),
+        @ApiResponse(responseCode = "404", description = "Specified resource is not found - SVC4063"),
+        @ApiResponse(responseCode = "405", description = "Method  Not Allowed: Invalid HTTP method type used (PUT,DELETE,POST will be rejected) - POL4050"),
+        @ApiResponse(responseCode = "500", description = "The GET request failed either due to internal SDC problem or Cambria Service failure. ECOMP Component should continue the attempts to get the needed information - POL5000"),
+        @ApiResponse(responseCode = "400", description = "Invalid artifactType was defined as input - SVC4122"),
+        @ApiResponse(responseCode = "400", description = "Artifact type (mandatory field) is missing in request - SVC4124"),
+        @ApiResponse(responseCode = "400", description = "Invalid MD5 header - SVC4127"),
+        @ApiResponse(responseCode = "400", description = "Artifact name is missing in input - SVC4128"),
+        @ApiResponse(responseCode = "403", description = "Asset is being edited by different user. Only one user can checkout and edit an asset on given time. The asset will be available for checkout after the other user will checkin the asset - SVC4086"),
+        @ApiResponse(responseCode = "409", description = "Restricted Operation â€“ the user provided does not have role of Designer or the asset is being used by another designer - SVC4301")})
     @PermissionAllowed(AafPermission.PermNames.DELETE_VALUE)
     public Response deleteArtifactOnResourceInstance(
-            @Parameter(description = "The user ID of the DCAE Designer. This user must also have Designer role in SDC",
-                    required = true) @HeaderParam(value = Constants.USER_ID_HEADER) final String userId,
-            @Parameter(description = "X-ECOMP-RequestID header",
-                    required = false) @HeaderParam(value = Constants.X_ECOMP_REQUEST_ID_HEADER) String requestId,
-            @Parameter(description = "X-ECOMP-InstanceID header", required = true) @HeaderParam(
-                    value = Constants.X_ECOMP_INSTANCE_ID_HEADER) final String instanceIdHeader,
-            @Parameter(description = "Determines the format of the body of the response",
-                    required = false) @HeaderParam(value = Constants.ACCEPT_HEADER) String accept,
-            @Parameter(description = "The username and password",
-                    required = true) @HeaderParam(value = Constants.AUTHORIZATION_HEADER) String authorization,
-            @Parameter(schema = @Schema(allowableValues = {"resources,services"}),description = "The requested asset type",
-                    required = true) @PathParam("assetType") final String assetType,
-            @Parameter(description = "The uuid of the asset as published in the metadata",
-                    required = true) @PathParam("uuid") final String uuid,
-            @Parameter(
-                    description = "The uuid of the artifact as published in the asset detailed metadata or in the response of the upload / update operation",
-                    required = true) @PathParam("artifactUUID") final String artifactUUID,
-            @Parameter(description = "The component instance name (as publishedin the response of the detailed query)",
-                    required = true) @PathParam("resourceInstanceName") final String resourceInstanceName) {
-
+        @Parameter(description = "The user ID of the DCAE Designer. This user must also have Designer role in SDC", required = true) @HeaderParam(value = Constants.USER_ID_HEADER) final String userId,
+        @Parameter(description = "X-ECOMP-RequestID header", required = false) @HeaderParam(value = Constants.X_ECOMP_REQUEST_ID_HEADER) String requestId,
+        @Parameter(description = "X-ECOMP-InstanceID header", required = true) @HeaderParam(value = Constants.X_ECOMP_INSTANCE_ID_HEADER) final String instanceIdHeader,
+        @Parameter(description = "Determines the format of the body of the response", required = false) @HeaderParam(value = Constants.ACCEPT_HEADER) String accept,
+        @Parameter(description = "The username and password", required = true) @HeaderParam(value = Constants.AUTHORIZATION_HEADER) String authorization,
+        @Parameter(schema = @Schema(allowableValues = {
+            "resources,services"}), description = "The requested asset type", required = true) @PathParam("assetType") final String assetType,
+        @Parameter(description = "The uuid of the asset as published in the metadata", required = true) @PathParam("uuid") final String uuid,
+        @Parameter(description = "The uuid of the artifact as published in the asset detailed metadata or in the response of the upload / update operation", required = true) @PathParam("artifactUUID") final String artifactUUID,
+        @Parameter(description = "The component instance name (as publishedin the response of the detailed query)", required = true) @PathParam("resourceInstanceName") final String resourceInstanceName) {
         Wrapper<Response> responseWrapper = new Wrapper<>();
         ResponseFormat responseFormat = null;
         String requestURI = request.getRequestURI();
@@ -800,7 +654,6 @@ public class ArtifactExternalServlet extends AbstractValidationsServlet {
         ComponentTypeEnum componentType = ComponentTypeEnum.findByParamName(assetType);
         String componentTypeValue = componentType == null ? null : componentType.getValue();
         ResourceCommonInfo resourceCommonInfo = new ResourceCommonInfo(resourceInstanceName, componentTypeValue);
-
         if (componentType == null) {
             log.debug("deleteArtifactOnResourceInsatnce: assetType parameter {} is not valid", assetType);
             responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.INVALID_CONTENT);
@@ -820,7 +673,7 @@ public class ArtifactExternalServlet extends AbstractValidationsServlet {
         try {
             if (responseWrapper.isEmpty()) {
                 artifactDefinition = artifactsBusinessLogic.deleteArtifactOnRiByUUID(request, componentType, uuid, resourceInstanceName, artifactUUID,
-                        new ArtifactOperationInfo(true, false, ArtifactOperationEnum.DELETE));
+                    new ArtifactOperationInfo(true, false, ArtifactOperationEnum.DELETE));
                 Object representation = RepresentationUtils.toRepresentation(artifactDefinition);
                 Map<String, String> headers = new HashMap<>();
                 headers.put(Constants.MD5_HEADER, GeneralUtility.calculateMD5Base64EncodedByString((String) representation));
@@ -833,13 +686,13 @@ public class ArtifactExternalServlet extends AbstractValidationsServlet {
             log.debug(message, e);
             responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR);
             responseWrapper.setInnerElement(buildErrorResponse(responseFormat));
-        }  catch (ComponentException e){
+        } catch (ComponentException e) {
             responseFormat = getComponentsUtils().getResponseFormat(e);
             throw e;
-        }
-        finally{
-            getComponentsUtils().auditExternalCrudApi(responseFormat, AuditingActionEnum.ARTIFACT_DELETE_BY_API, resourceCommonInfo,
-                    request, artifactDefinition, artifactUUID);
+        } finally {
+            getComponentsUtils()
+                .auditExternalCrudApi(responseFormat, AuditingActionEnum.ARTIFACT_DELETE_BY_API, resourceCommonInfo, request, artifactDefinition,
+                    artifactUUID);
         }
         return responseWrapper.getInnerElement();
     }
@@ -850,40 +703,26 @@ public class ArtifactExternalServlet extends AbstractValidationsServlet {
     @GET
     @Path("/{assetType}/{uuid}/artifacts/{artifactUUID}")
     @Produces(MediaType.APPLICATION_OCTET_STREAM)
-    @Operation(description = "Download component artifact", method = "GET", summary = "Returns downloaded artifact",
-            responses = {@ApiResponse(responseCode = "200", description = "Artifact downloaded",
-                    content = @Content(array = @ArraySchema(schema = @Schema(implementation = String.class)))),
-                    @ApiResponse(responseCode = "400",
-                            description = "Missing  'X-ECOMP-InstanceID'  HTTP header - POL5001"),
-                    @ApiResponse(responseCode = "401",
-                            description = "ECOMP component  should authenticate itself  and  to  re-send  again  HTTP  request  with its Basic  Authentication credentials - POL5002"),
-                    @ApiResponse(responseCode = "403", description = "ECOMP component is not authorized - POL5003"),
-                    @ApiResponse(responseCode = "404", description = "Specified resource is not found - SVC4063"),
-                    @ApiResponse(responseCode = "405",
-                            description = "Method  Not Allowed: Invalid HTTP method type used (PUT,DELETE,POST will be rejected) - POL4050"),
-                    @ApiResponse(responseCode = "500",
-                            description = "The GET request failed either due to internal SDC problem or Cambria Service failure. ECOMP Component should continue the attempts to get the needed information - POL5000"),
-                    @ApiResponse(responseCode = "404", description = "Artifact was not found - SVC4505")})
+    @Operation(description = "Download component artifact", method = "GET", summary = "Returns downloaded artifact", responses = {
+        @ApiResponse(responseCode = "200", description = "Artifact downloaded", content = @Content(array = @ArraySchema(schema = @Schema(implementation = String.class)))),
+        @ApiResponse(responseCode = "400", description = "Missing  'X-ECOMP-InstanceID'  HTTP header - POL5001"),
+        @ApiResponse(responseCode = "401", description = "ECOMP component  should authenticate itself  and  to  re-send  again  HTTP  request  with its Basic  Authentication credentials - POL5002"),
+        @ApiResponse(responseCode = "403", description = "ECOMP component is not authorized - POL5003"),
+        @ApiResponse(responseCode = "404", description = "Specified resource is not found - SVC4063"),
+        @ApiResponse(responseCode = "405", description = "Method  Not Allowed: Invalid HTTP method type used (PUT,DELETE,POST will be rejected) - POL4050"),
+        @ApiResponse(responseCode = "500", description = "The GET request failed either due to internal SDC problem or Cambria Service failure. ECOMP Component should continue the attempts to get the needed information - POL5000"),
+        @ApiResponse(responseCode = "404", description = "Artifact was not found - SVC4505")})
     @PermissionAllowed(AafPermission.PermNames.DELETE_VALUE)
     public Response downloadComponentArtifact(
-            @Parameter(description = "The user ID of the DCAE Designer. This user must also have Designer role in SDC",
-                    required = true) @HeaderParam(value = Constants.USER_ID_HEADER) final String userId,
-            @Parameter(description = "X-ECOMP-RequestID header",
-                    required = false) @HeaderParam(value = Constants.X_ECOMP_REQUEST_ID_HEADER) String requestId,
-            @Parameter(description = "X-ECOMP-InstanceID header", required = true) @HeaderParam(
-                    value = Constants.X_ECOMP_INSTANCE_ID_HEADER) final String instanceIdHeader,
-            @Parameter(description = "Determines the format of the body of the response",
-                    required = false) @HeaderParam(value = Constants.ACCEPT_HEADER) String accept,
-            @Parameter(description = "The username and password",
-                    required = true) @HeaderParam(value = Constants.AUTHORIZATION_HEADER) String authorization,
-            @Parameter(schema = @Schema(allowableValues = {"resources,services"}),description = "The requested asset type",
-                    required = true) @PathParam("assetType") final String assetType,
-            @Parameter(description = "The uuid of the asset as published in the metadata",
-                    required = true) @PathParam("uuid") final String uuid,
-            @Parameter(
-                    description = "The uuid of the artifact as published in the asset detailed metadata or in the response of the upload / update operation",
-                    required = true) @PathParam("artifactUUID") final String artifactUUID) {
-
+        @Parameter(description = "The user ID of the DCAE Designer. This user must also have Designer role in SDC", required = true) @HeaderParam(value = Constants.USER_ID_HEADER) final String userId,
+        @Parameter(description = "X-ECOMP-RequestID header", required = false) @HeaderParam(value = Constants.X_ECOMP_REQUEST_ID_HEADER) String requestId,
+        @Parameter(description = "X-ECOMP-InstanceID header", required = true) @HeaderParam(value = Constants.X_ECOMP_INSTANCE_ID_HEADER) final String instanceIdHeader,
+        @Parameter(description = "Determines the format of the body of the response", required = false) @HeaderParam(value = Constants.ACCEPT_HEADER) String accept,
+        @Parameter(description = "The username and password", required = true) @HeaderParam(value = Constants.AUTHORIZATION_HEADER) String authorization,
+        @Parameter(schema = @Schema(allowableValues = {
+            "resources,services"}), description = "The requested asset type", required = true) @PathParam("assetType") final String assetType,
+        @Parameter(description = "The uuid of the asset as published in the metadata", required = true) @PathParam("uuid") final String uuid,
+        @Parameter(description = "The uuid of the artifact as published in the asset detailed metadata or in the response of the upload / update operation", required = true) @PathParam("artifactUUID") final String artifactUUID) {
         Wrapper<Response> responseWrapper = new Wrapper<>();
         ResponseFormat responseFormat = null;
         String requestURI = request.getRequestURI();
@@ -911,13 +750,13 @@ public class ArtifactExternalServlet extends AbstractValidationsServlet {
                 responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.OK);
                 responseWrapper.setInnerElement(buildOkResponse(responseFormat, is, headers));
             }
-        }  catch (ComponentException e){
+        } catch (ComponentException e) {
             responseFormat = getComponentsUtils().getResponseFormat(e);
             throw e;
-        }
-        finally{
-            getComponentsUtils().auditExternalDownloadArtifact(responseFormat, resourceCommonInfo,
-                    new DistributionData(instanceIdHeader, requestURI), requestId, artifactUUID, userId);
+        } finally {
+            getComponentsUtils()
+                .auditExternalDownloadArtifact(responseFormat, resourceCommonInfo, new DistributionData(instanceIdHeader, requestURI), requestId,
+                    artifactUUID, userId);
         }
         return responseWrapper.getInnerElement();
     }
@@ -928,43 +767,27 @@ public class ArtifactExternalServlet extends AbstractValidationsServlet {
     @GET
     @Path("/{assetType}/{uuid}/resourceInstances/{resourceInstanceName}/artifacts/{artifactUUID}")
     @Produces(MediaType.APPLICATION_OCTET_STREAM)
-    @Operation(description = "Download resource instance artifact", method = "GET",
-            summary = "Returns downloaded artifact", responses = {
-            @ApiResponse(content = @Content(array = @ArraySchema(schema = @Schema(implementation = Response.class)))),
-            @ApiResponse(responseCode = "200", description = "Artifact downloaded",
-                    content = @Content(array = @ArraySchema(schema = @Schema(implementation = String.class)))),
-            @ApiResponse(responseCode = "400", description = "Missing  'X-ECOMP-InstanceID'  HTTP header - POL5001"),
-            @ApiResponse(responseCode = "401",
-                    description = "ECOMP component  should authenticate itself  and  to  re-send  again  HTTP  request  with its Basic  Authentication credentials - POL5002"),
-            @ApiResponse(responseCode = "403", description = "ECOMP component is not authorized - POL5003"),
-            @ApiResponse(responseCode = "404", description = "Specified resource is not found - SVC4063"),
-            @ApiResponse(responseCode = "405",
-                    description = "Method  Not Allowed: Invalid HTTP method type used (PUT,DELETE,POST will be rejected) - POL4050"),
-            @ApiResponse(responseCode = "500",
-                    description = "The GET request failed either due to internal SDC problem or Cambria Service failure. ECOMP Component should continue the attempts to get the needed information - POL5000"),
-            @ApiResponse(responseCode = "404", description = "Artifact was not found - SVC4505")})
+    @Operation(description = "Download resource instance artifact", method = "GET", summary = "Returns downloaded artifact", responses = {
+        @ApiResponse(content = @Content(array = @ArraySchema(schema = @Schema(implementation = Response.class)))),
+        @ApiResponse(responseCode = "200", description = "Artifact downloaded", content = @Content(array = @ArraySchema(schema = @Schema(implementation = String.class)))),
+        @ApiResponse(responseCode = "400", description = "Missing  'X-ECOMP-InstanceID'  HTTP header - POL5001"),
+        @ApiResponse(responseCode = "401", description = "ECOMP component  should authenticate itself  and  to  re-send  again  HTTP  request  with its Basic  Authentication credentials - POL5002"),
+        @ApiResponse(responseCode = "403", description = "ECOMP component is not authorized - POL5003"),
+        @ApiResponse(responseCode = "404", description = "Specified resource is not found - SVC4063"),
+        @ApiResponse(responseCode = "405", description = "Method  Not Allowed: Invalid HTTP method type used (PUT,DELETE,POST will be rejected) - POL4050"),
+        @ApiResponse(responseCode = "500", description = "The GET request failed either due to internal SDC problem or Cambria Service failure. ECOMP Component should continue the attempts to get the needed information - POL5000"),
+        @ApiResponse(responseCode = "404", description = "Artifact was not found - SVC4505")})
     @PermissionAllowed(AafPermission.PermNames.READ_VALUE)
     public Response downloadResourceInstanceArtifact(
-            @Parameter(description = "The user ID of the DCAE Designer. This user must also have Designer role in SDC",
-                    required = true) @HeaderParam(value = Constants.USER_ID_HEADER) final String userId,
-            @Parameter(description = "X-ECOMP-RequestID header",
-                    required = false) @HeaderParam(value = Constants.X_ECOMP_REQUEST_ID_HEADER) String requestId,
-            @Parameter(description = "X-ECOMP-InstanceID header", required = true) @HeaderParam(
-                    value = Constants.X_ECOMP_INSTANCE_ID_HEADER) final String instanceIdHeader,
-            @Parameter(description = "Determines the format of the body of the response",
-                    required = false) @HeaderParam(value = Constants.ACCEPT_HEADER) String accept,
-            @Parameter(description = "The username and password",
-                    required = true) @HeaderParam(value = Constants.AUTHORIZATION_HEADER) String authorization,
-            @Parameter(description = "The requested asset type",
-                    required = true) @PathParam("assetType") final String assetType,
-            @Parameter(description = "The uuid of the asset as published in the metadata",
-                    required = true) @PathParam("uuid") final String uuid,
-            @Parameter(
-                    description = "The uuid of the artifact as published in the asset detailed metadata or in the response of the upload / update operation",
-                    required = true) @PathParam("artifactUUID") final String artifactUUID,
-            @Parameter(description = "The component instance name (as publishedin the response of the detailed query)",
-                    required = true) @PathParam("resourceInstanceName") final String resourceInstanceName) {
-
+        @Parameter(description = "The user ID of the DCAE Designer. This user must also have Designer role in SDC", required = true) @HeaderParam(value = Constants.USER_ID_HEADER) final String userId,
+        @Parameter(description = "X-ECOMP-RequestID header", required = false) @HeaderParam(value = Constants.X_ECOMP_REQUEST_ID_HEADER) String requestId,
+        @Parameter(description = "X-ECOMP-InstanceID header", required = true) @HeaderParam(value = Constants.X_ECOMP_INSTANCE_ID_HEADER) final String instanceIdHeader,
+        @Parameter(description = "Determines the format of the body of the response", required = false) @HeaderParam(value = Constants.ACCEPT_HEADER) String accept,
+        @Parameter(description = "The username and password", required = true) @HeaderParam(value = Constants.AUTHORIZATION_HEADER) String authorization,
+        @Parameter(description = "The requested asset type", required = true) @PathParam("assetType") final String assetType,
+        @Parameter(description = "The uuid of the asset as published in the metadata", required = true) @PathParam("uuid") final String uuid,
+        @Parameter(description = "The uuid of the artifact as published in the asset detailed metadata or in the response of the upload / update operation", required = true) @PathParam("artifactUUID") final String artifactUUID,
+        @Parameter(description = "The component instance name (as publishedin the response of the detailed query)", required = true) @PathParam("resourceInstanceName") final String resourceInstanceName) {
         Wrapper<Response> responseWrapper = new Wrapper<>();
         ResponseFormat responseFormat = null;
         String requestURI = request.getRequestURI();
@@ -984,20 +807,20 @@ public class ArtifactExternalServlet extends AbstractValidationsServlet {
         }
         try {
             if (responseWrapper.isEmpty()) {
-                byte[] value = artifactsBusinessLogic.downloadResourceInstanceArtifactByUUIDs(componentType, uuid, resourceInstanceName, artifactUUID);
+                byte[] value = artifactsBusinessLogic
+                    .downloadResourceInstanceArtifactByUUIDs(componentType, uuid, resourceInstanceName, artifactUUID);
                 InputStream is = new ByteArrayInputStream(value);
                 Map<String, String> headers = new HashMap<>();
                 headers.put(Constants.MD5_HEADER, GeneralUtility.calculateMD5Base64EncodedByByteArray(value));
                 responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.OK);
                 responseWrapper.setInnerElement(buildOkResponse(responseFormat, is, headers));
             }
-        }  catch (ComponentException e){
+        } catch (ComponentException e) {
             responseFormat = getComponentsUtils().getResponseFormat(e);
             throw e;
-        }
-        finally{
+        } finally {
             getComponentsUtils().auditExternalDownloadArtifact(responseFormat, new ResourceCommonInfo(resourceInstanceName, componentTypeValue),
-                    new DistributionData(instanceIdHeader, requestURI), requestId, artifactUUID, userId);
+                new DistributionData(instanceIdHeader, requestURI), requestId, artifactUUID, userId);
         }
         return responseWrapper.getInnerElement();
     }
index 0154284..1c8f150 100644 (file)
@@ -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.
  * limitations under the License.
  * ============LICENSE_END=========================================================
  */
-
 package org.openecomp.sdc.be.externalapi.servlet;
 
+import static org.openecomp.sdc.be.datatypes.enums.ComponentTypeEnum.RESOURCE;
+
 import com.jcabi.aspects.Loggable;
 import fj.data.Either;
 import io.swagger.v3.oas.annotations.Operation;
@@ -32,6 +33,24 @@ import io.swagger.v3.oas.annotations.servers.Server;
 import io.swagger.v3.oas.annotations.servers.Servers;
 import io.swagger.v3.oas.annotations.tags.Tag;
 import io.swagger.v3.oas.annotations.tags.Tags;
+import java.io.ByteArrayInputStream;
+import java.io.IOException;
+import java.io.InputStream;
+import java.util.EnumMap;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+import javax.inject.Inject;
+import javax.servlet.http.HttpServletRequest;
+import javax.ws.rs.GET;
+import javax.ws.rs.HeaderParam;
+import javax.ws.rs.Path;
+import javax.ws.rs.PathParam;
+import javax.ws.rs.Produces;
+import javax.ws.rs.QueryParam;
+import javax.ws.rs.core.Context;
+import javax.ws.rs.core.MediaType;
+import javax.ws.rs.core.Response;
 import org.apache.commons.lang3.tuple.ImmutablePair;
 import org.openecomp.sdc.be.components.impl.ComponentBusinessLogic;
 import org.openecomp.sdc.be.components.impl.ComponentBusinessLogicProvider;
@@ -65,34 +84,11 @@ import org.openecomp.sdc.common.util.GeneralUtility;
 import org.openecomp.sdc.exception.ResponseFormat;
 import org.springframework.stereotype.Controller;
 
-import javax.inject.Inject;
-import javax.servlet.http.HttpServletRequest;
-import javax.ws.rs.GET;
-import javax.ws.rs.HeaderParam;
-import javax.ws.rs.Path;
-import javax.ws.rs.PathParam;
-import javax.ws.rs.Produces;
-import javax.ws.rs.QueryParam;
-import javax.ws.rs.core.Context;
-import javax.ws.rs.core.MediaType;
-import javax.ws.rs.core.Response;
-import java.io.ByteArrayInputStream;
-import java.io.IOException;
-import java.io.InputStream;
-import java.util.EnumMap;
-import java.util.HashMap;
-import java.util.List;
-import java.util.Map;
-
-import static org.openecomp.sdc.be.datatypes.enums.ComponentTypeEnum.RESOURCE;
-
 /**
  * This Servlet serves external users for retrieving component metadata.
- * 
- * @author tgitelman
  *
+ * @author tgitelman
  */
-
 @Loggable(prepend = true, value = Loggable.DEBUG, trim = false)
 @Path("/v1/catalog")
 @Tags({@Tag(name = "SDC External APIs")})
@@ -100,22 +96,20 @@ import static org.openecomp.sdc.be.datatypes.enums.ComponentTypeEnum.RESOURCE;
 @Controller
 public class AssetsDataServlet extends AbstractValidationsServlet {
 
-    @Context
-    private HttpServletRequest request;
-
     private static final Logger log = Logger.getLogger(AssetsDataServlet.class);
-
     private final ElementBusinessLogic elementBusinessLogic;
     private final AssetMetadataConverter assetMetadataConverter;
     private final ServiceBusinessLogic serviceBusinessLogic;
     private final ResourceBusinessLogic resourceBusinessLogic;
     private final ComponentBusinessLogicProvider componentBusinessLogicProvider;
+    @Context
+    private HttpServletRequest request;
 
     @Inject
-    public AssetsDataServlet(UserBusinessLogic userBusinessLogic, ComponentInstanceBusinessLogic componentInstanceBL,
-            ComponentsUtils componentsUtils, ServletUtils servletUtils, ResourceImportManager resourceImportManager,
-            ElementBusinessLogic elementBusinessLogic, AssetMetadataConverter assetMetadataConverter,
-            ComponentBusinessLogicProvider componentBusinessLogicProvider, ServiceBusinessLogic serviceBusinessLogic, ResourceBusinessLogic resourceBusinessLogic) {
+    public AssetsDataServlet(UserBusinessLogic userBusinessLogic, ComponentInstanceBusinessLogic componentInstanceBL, ComponentsUtils componentsUtils,
+                             ServletUtils servletUtils, ResourceImportManager resourceImportManager, ElementBusinessLogic elementBusinessLogic,
+                             AssetMetadataConverter assetMetadataConverter, ComponentBusinessLogicProvider componentBusinessLogicProvider,
+                             ServiceBusinessLogic serviceBusinessLogic, ResourceBusinessLogic resourceBusinessLogic) {
         super(userBusinessLogic, componentInstanceBL, componentsUtils, servletUtils, resourceImportManager);
         this.elementBusinessLogic = elementBusinessLogic;
         this.assetMetadataConverter = assetMetadataConverter;
@@ -128,50 +122,33 @@ public class AssetsDataServlet extends AbstractValidationsServlet {
     @Path("/{assetType}")
     @Produces(MediaType.APPLICATION_JSON)
     @Operation(description = "Fetch list of assets", method = "GET", summary = "Returns list of assets", responses = {
-            @ApiResponse(responseCode = "200",
-                    description = "ECOMP component is authenticated and list of Catalog Assets Metadata is returned",
-                    content = @Content(array = @ArraySchema(schema = @Schema(implementation = AssetMetadata.class)))),
-            @ApiResponse(responseCode = "400", description = "Missing  'X-ECOMP-InstanceID'  HTTP header - POL5001"),
-            @ApiResponse(responseCode = "401",
-                    description = "ECOMP component  should authenticate itself  and  to  re-send  again  HTTP  request  with its Basic Authentication credentials - POL5002"),
-            @ApiResponse(responseCode = "403", description = "ECOMP component is not authorized - POL5003"),
-            @ApiResponse(responseCode = "405",
-                    description = "Method  Not Allowed  :  Invalid HTTP method type used ( PUT,DELETE,POST will be rejected) - POL4050"),
-            @ApiResponse(responseCode = "500",
-                    description = "The GET request failed either due to internal SDC problem. ECOMP Component should continue the attempts to get the needed information - POL5000")})
+        @ApiResponse(responseCode = "200", description = "ECOMP component is authenticated and list of Catalog Assets Metadata is returned", content = @Content(array = @ArraySchema(schema = @Schema(implementation = AssetMetadata.class)))),
+        @ApiResponse(responseCode = "400", description = "Missing  'X-ECOMP-InstanceID'  HTTP header - POL5001"),
+        @ApiResponse(responseCode = "401", description = "ECOMP component  should authenticate itself  and  to  re-send  again  HTTP  request  with its Basic Authentication credentials - POL5002"),
+        @ApiResponse(responseCode = "403", description = "ECOMP component is not authorized - POL5003"),
+        @ApiResponse(responseCode = "405", description = "Method  Not Allowed  :  Invalid HTTP method type used ( PUT,DELETE,POST will be rejected) - POL4050"),
+        @ApiResponse(responseCode = "500", description = "The GET request failed either due to internal SDC problem. ECOMP Component should continue the attempts to get the needed information - POL5000")})
     @PermissionAllowed(AafPermission.PermNames.READ_VALUE)
     public Response getAssetListExternal(
-            @Parameter(description = "X-ECOMP-RequestID header",
-                    required = false) @HeaderParam(value = Constants.X_ECOMP_REQUEST_ID_HEADER) String requestId,
-            @Parameter(description = "X-ECOMP-InstanceID header", required = true) @HeaderParam(
-                    value = Constants.X_ECOMP_INSTANCE_ID_HEADER) final String instanceIdHeader,
-            @Parameter(description = "Determines the format of the body of the response",
-                    required = false) @HeaderParam(value = Constants.ACCEPT_HEADER) String accept,
-            @Parameter(description = "The username and password",
-                    required = true) @HeaderParam(value = Constants.AUTHORIZATION_HEADER) String authorization,
-            @Parameter(description = "The requested asset type",schema = @Schema(allowableValues = {"resources", "services"}),
-                    required = true) @PathParam("assetType") final String assetType,
-            @Parameter(description = "The filter key (resourceType only for resources)",
-                    required = false) @QueryParam("category") String category,
-            @Parameter(description = "The filter key (resourceType only for resources)",
-                    required = false) @QueryParam("subCategory") String subCategory,
-            @Parameter(description = "The filter key (resourceType only for resources)",
-                    required = false) @QueryParam("distributionStatus") String distributionStatus,
-            @Parameter(description = "The filter key (resourceType only for resources)",
-                    required = false) @QueryParam("resourceType") String resourceType) throws IOException {
-
+        @Parameter(description = "X-ECOMP-RequestID header", required = false) @HeaderParam(value = Constants.X_ECOMP_REQUEST_ID_HEADER) String requestId,
+        @Parameter(description = "X-ECOMP-InstanceID header", required = true) @HeaderParam(value = Constants.X_ECOMP_INSTANCE_ID_HEADER) final String instanceIdHeader,
+        @Parameter(description = "Determines the format of the body of the response", required = false) @HeaderParam(value = Constants.ACCEPT_HEADER) String accept,
+        @Parameter(description = "The username and password", required = true) @HeaderParam(value = Constants.AUTHORIZATION_HEADER) String authorization,
+        @Parameter(description = "The requested asset type", schema = @Schema(allowableValues = {"resources",
+            "services"}), required = true) @PathParam("assetType") final String assetType,
+        @Parameter(description = "The filter key (resourceType only for resources)", required = false) @QueryParam("category") String category,
+        @Parameter(description = "The filter key (resourceType only for resources)", required = false) @QueryParam("subCategory") String subCategory,
+        @Parameter(description = "The filter key (resourceType only for resources)", required = false) @QueryParam("distributionStatus") String distributionStatus,
+        @Parameter(description = "The filter key (resourceType only for resources)", required = false) @QueryParam("resourceType") String resourceType)
+        throws IOException {
         ResponseFormat responseFormat = null;
         String query = request.getQueryString();
-        String requestURI = request.getRequestURI().endsWith("/")?
-                removeDuplicateSlashSeparator(request.getRequestURI()): request.getRequestURI();
+        String requestURI = request.getRequestURI().endsWith("/") ? removeDuplicateSlashSeparator(request.getRequestURI()) : request.getRequestURI();
         String url = request.getMethod() + " " + requestURI;
         log.debug("Start handle request of {}", url);
-
         AuditingActionEnum auditingActionEnum = query == null ? AuditingActionEnum.GET_ASSET_LIST : AuditingActionEnum.GET_FILTERED_ASSET_LIST;
-
         String resourceUrl = query == null ? requestURI : requestURI + "?" + query;
         DistributionData distributionData = new DistributionData(instanceIdHeader, resourceUrl);
-
         // Mandatory
         if (instanceIdHeader == null || instanceIdHeader.isEmpty()) {
             log.debug("getAssetList: Missing X-ECOMP-InstanceID header");
@@ -179,10 +156,8 @@ public class AssetsDataServlet extends AbstractValidationsServlet {
             getComponentsUtils().auditExternalGetAssetList(responseFormat, auditingActionEnum, distributionData, requestId);
             return buildErrorResponse(responseFormat);
         }
-
         try {
             Map<FilterKeyEnum, String> filters = new EnumMap<>(FilterKeyEnum.class);
-
             if (category != null) {
                 filters.put(FilterKeyEnum.CATEGORY, category);
             }
@@ -202,9 +177,8 @@ public class AssetsDataServlet extends AbstractValidationsServlet {
                 }
                 filters.put(FilterKeyEnum.RESOURCE_TYPE, resourceTypeEnum.name());
             }
-
-            Either<List<? extends Component>, ResponseFormat> assetTypeData = elementBusinessLogic.getFilteredCatalogComponents(assetType, filters, query);
-
+            Either<List<? extends Component>, ResponseFormat> assetTypeData = elementBusinessLogic
+                .getFilteredCatalogComponents(assetType, filters, query);
             if (assetTypeData.isRight()) {
                 log.debug("getAssetList: Asset Fetching Failed");
                 responseFormat = assetTypeData.right().value();
@@ -212,7 +186,8 @@ public class AssetsDataServlet extends AbstractValidationsServlet {
                 return buildErrorResponse(responseFormat);
             } else {
                 log.debug("getAssetList: Asset Fetching Success");
-                Either<List<? extends AssetMetadata>, ResponseFormat> resMetadata = assetMetadataConverter.convertToAssetMetadata(assetTypeData.left().value(), requestURI, false);
+                Either<List<? extends AssetMetadata>, ResponseFormat> resMetadata = assetMetadataConverter
+                    .convertToAssetMetadata(assetTypeData.left().value(), requestURI, false);
                 if (resMetadata.isRight()) {
                     log.debug("getAssetList: Asset conversion Failed");
                     responseFormat = resMetadata.right().value();
@@ -222,7 +197,6 @@ public class AssetsDataServlet extends AbstractValidationsServlet {
                 Object result = RepresentationUtils.toRepresentation(resMetadata.left().value());
                 responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.OK);
                 getComponentsUtils().auditExternalGetAssetList(responseFormat, auditingActionEnum, distributionData, requestId);
-
                 return buildOkResponse(responseFormat, result);
             }
         } catch (Exception e) {
@@ -233,7 +207,6 @@ public class AssetsDataServlet extends AbstractValidationsServlet {
     }
 
     /**
-     *
      * @param requestId
      * @param instanceIdHeader
      * @param accept
@@ -245,41 +218,28 @@ public class AssetsDataServlet extends AbstractValidationsServlet {
     @GET
     @Path("/{assetType}/{uuid}/metadata")
     @Produces(MediaType.APPLICATION_JSON)
-    @Operation(description = "Detailed metadata of asset by uuid", method = "GET",
-            summary = "Returns detailed metadata of an asset by uuid", responses = {@ApiResponse(responseCode = "200",
-            description = "ECOMP component is authenticated and list of Catalog Assets Metadata is returned",
-            content = @Content(array = @ArraySchema(schema = @Schema(implementation = AssetMetadata.class)))),
-            @ApiResponse(responseCode = "400", description = "Missing  'X-ECOMP-InstanceID'  HTTP header - POL5001"),
-            @ApiResponse(responseCode = "401",
-                    description = "ECOMP component  should authenticate itself  and  to  re-send  again  HTTP  request  with its Basic Authentication credentials - POL5002"),
-            @ApiResponse(responseCode = "403", description = "ECOMP component is not authorized - POL5003"),
-            @ApiResponse(responseCode = "404",
-                    description = "Error: Requested '%1' (uuid) resource was not found - SVC4063"),
-            @ApiResponse(responseCode = "405",
-                    description = "Method  Not Allowed  :  Invalid HTTP method type used ( PUT,DELETE,POST will be rejected) - POL4050"),
-            @ApiResponse(responseCode = "500",
-                    description = "The GET request failed either due to internal SDC problem. ECOMP Component should continue the attempts to get the needed information - POL5000")})
+    @Operation(description = "Detailed metadata of asset by uuid", method = "GET", summary = "Returns detailed metadata of an asset by uuid", responses = {
+        @ApiResponse(responseCode = "200", description = "ECOMP component is authenticated and list of Catalog Assets Metadata is returned", content = @Content(array = @ArraySchema(schema = @Schema(implementation = AssetMetadata.class)))),
+        @ApiResponse(responseCode = "400", description = "Missing  'X-ECOMP-InstanceID'  HTTP header - POL5001"),
+        @ApiResponse(responseCode = "401", description = "ECOMP component  should authenticate itself  and  to  re-send  again  HTTP  request  with its Basic Authentication credentials - POL5002"),
+        @ApiResponse(responseCode = "403", description = "ECOMP component is not authorized - POL5003"),
+        @ApiResponse(responseCode = "404", description = "Error: Requested '%1' (uuid) resource was not found - SVC4063"),
+        @ApiResponse(responseCode = "405", description = "Method  Not Allowed  :  Invalid HTTP method type used ( PUT,DELETE,POST will be rejected) - POL4050"),
+        @ApiResponse(responseCode = "500", description = "The GET request failed either due to internal SDC problem. ECOMP Component should continue the attempts to get the needed information - POL5000")})
     @PermissionAllowed(AafPermission.PermNames.READ_VALUE)
     public Response getAssetSpecificMetadataByUuidExternal(
-            @Parameter(description = "X-ECOMP-RequestID header",
-                    required = false) @HeaderParam(value = Constants.X_ECOMP_REQUEST_ID_HEADER) String requestId,
-            @Parameter(description = "X-ECOMP-InstanceID header", required = true) @HeaderParam(
-                    value = Constants.X_ECOMP_INSTANCE_ID_HEADER) final String instanceIdHeader,
-            @Parameter(description = "Determines the format of the body of the response",
-                    required = false) @HeaderParam(value = Constants.ACCEPT_HEADER) String accept,
-            @Parameter(description = "The username and password",
-                    required = true) @HeaderParam(value = Constants.AUTHORIZATION_HEADER) String authorization,
-            @Parameter(description = "The requested asset type",schema = @Schema(allowableValues = {"resources", "services"}),
-                    required = true) @PathParam("assetType") final String assetType,
-            @Parameter(description = "The requested asset uuid",
-                    required = true) @PathParam("uuid") final String uuid) throws IOException {
-
+        @Parameter(description = "X-ECOMP-RequestID header", required = false) @HeaderParam(value = Constants.X_ECOMP_REQUEST_ID_HEADER) String requestId,
+        @Parameter(description = "X-ECOMP-InstanceID header", required = true) @HeaderParam(value = Constants.X_ECOMP_INSTANCE_ID_HEADER) final String instanceIdHeader,
+        @Parameter(description = "Determines the format of the body of the response", required = false) @HeaderParam(value = Constants.ACCEPT_HEADER) String accept,
+        @Parameter(description = "The username and password", required = true) @HeaderParam(value = Constants.AUTHORIZATION_HEADER) String authorization,
+        @Parameter(description = "The requested asset type", schema = @Schema(allowableValues = {"resources",
+            "services"}), required = true) @PathParam("assetType") final String assetType,
+        @Parameter(description = "The requested asset uuid", required = true) @PathParam("uuid") final String uuid) throws IOException {
         ResponseFormat responseFormat = null;
         AuditingActionEnum auditingActionEnum = AuditingActionEnum.GET_ASSET_METADATA;
         String requestURI = request.getRequestURI();
         String url = request.getMethod() + " " + requestURI;
         log.debug("Start handle request of {}", url);
-
         ComponentTypeEnum componentType = ComponentTypeEnum.findByParamName(assetType);
         ResourceCommonInfo resourceCommonInfo = new ResourceCommonInfo(componentType.getValue());
         DistributionData distributionData = new DistributionData(instanceIdHeader, requestURI);
@@ -287,39 +247,31 @@ public class AssetsDataServlet extends AbstractValidationsServlet {
         if (instanceIdHeader == null || instanceIdHeader.isEmpty()) {
             log.debug("getAssetList: Missing X-ECOMP-InstanceID header");
             responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.MISSING_X_ECOMP_INSTANCE_ID);
-            getComponentsUtils().auditExternalGetAsset(responseFormat, auditingActionEnum, distributionData,
-                    resourceCommonInfo, requestId, uuid);
+            getComponentsUtils().auditExternalGetAsset(responseFormat, auditingActionEnum, distributionData, resourceCommonInfo, requestId, uuid);
             return buildErrorResponse(responseFormat);
         }
-
         try {
-
-            Either<List<? extends Component>, ResponseFormat> assetTypeData = elementBusinessLogic.getCatalogComponentsByUuidAndAssetType(assetType, uuid);
-
+            Either<List<? extends Component>, ResponseFormat> assetTypeData = elementBusinessLogic
+                .getCatalogComponentsByUuidAndAssetType(assetType, uuid);
             if (assetTypeData.isRight()) {
                 log.debug("getAssetList: Asset Fetching Failed");
                 responseFormat = assetTypeData.right().value();
-                getComponentsUtils().auditExternalGetAsset(responseFormat, auditingActionEnum, distributionData,
-                        resourceCommonInfo, requestId, uuid);
-
+                getComponentsUtils().auditExternalGetAsset(responseFormat, auditingActionEnum, distributionData, resourceCommonInfo, requestId, uuid);
                 return buildErrorResponse(responseFormat);
             }
             resourceCommonInfo.setResourceName(assetTypeData.left().value().iterator().next().getName());
             log.debug("getAssetList: Asset Fetching Success");
-            Either<List<? extends AssetMetadata>, ResponseFormat> resMetadata = assetMetadataConverter.convertToAssetMetadata(assetTypeData.left().value(), requestURI, true);
+            Either<List<? extends AssetMetadata>, ResponseFormat> resMetadata = assetMetadataConverter
+                .convertToAssetMetadata(assetTypeData.left().value(), requestURI, true);
             if (resMetadata.isRight()) {
                 log.debug("getAssetList: Asset conversion Failed");
                 responseFormat = resMetadata.right().value();
-
-                getComponentsUtils().auditExternalGetAsset(responseFormat, auditingActionEnum, distributionData,
-                        resourceCommonInfo, requestId, uuid);
+                getComponentsUtils().auditExternalGetAsset(responseFormat, auditingActionEnum, distributionData, resourceCommonInfo, requestId, uuid);
                 return buildErrorResponse(responseFormat);
             }
             Object result = RepresentationUtils.toRepresentation(resMetadata.left().value().iterator().next());
             responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.OK);
-            getComponentsUtils().auditExternalGetAsset(responseFormat, auditingActionEnum, distributionData,
-                    resourceCommonInfo, requestId, uuid);
-
+            getComponentsUtils().auditExternalGetAsset(responseFormat, auditingActionEnum, distributionData, resourceCommonInfo, requestId, uuid);
             return buildOkResponse(responseFormat, result);
         } catch (Exception e) {
             BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Fetch filtered list of assets");
@@ -329,7 +281,7 @@ public class AssetsDataServlet extends AbstractValidationsServlet {
     }
 
     private ComponentBusinessLogic getComponentBLByType(ComponentTypeEnum componentTypeEnum) {
-        if(componentTypeEnum.equals(RESOURCE)) {
+        if (componentTypeEnum.equals(RESOURCE)) {
             return resourceBusinessLogic;
         } else {
             // Implementation is the same for any ComponentBusinessLogic
@@ -338,7 +290,6 @@ public class AssetsDataServlet extends AbstractValidationsServlet {
     }
 
     /**
-     *
      * @param requestId
      * @param instanceIdHeader
      * @param accept
@@ -347,57 +298,40 @@ public class AssetsDataServlet extends AbstractValidationsServlet {
      * @param uuid
      * @return
      */
-
     @GET
     @Path("/{assetType}/{uuid}/toscaModel")
     @Produces(MediaType.APPLICATION_OCTET_STREAM)
     @Operation(description = "Fetch assets CSAR", method = "GET", summary = "Returns asset csar", responses = {
-            @ApiResponse(content = @Content(array = @ArraySchema(schema = @Schema(implementation = String.class)))),
-            @ApiResponse(responseCode = "200",
-                    description = "ECOMP component is authenticated and list of Catalog Assets Metadata is returned",
-                    content = @Content(array = @ArraySchema(schema = @Schema(implementation = String.class)))),
-            @ApiResponse(responseCode = "400", description = "Missing  'X-ECOMP-InstanceID'  HTTP header - POL5001"),
-            @ApiResponse(responseCode = "401",
-                    description = "ECOMP component  should authenticate itself  and  to  re-send  again  HTTP  request  with its Basic Authentication credentials - POL5002"),
-            @ApiResponse(responseCode = "403", description = "ECOMP component is not authorized - POL5003"),
-            @ApiResponse(responseCode = "404",
-                    description = "Error: Requested '%1' (uuid) resource was not found - SVC4063"),
-            @ApiResponse(responseCode = "405",
-                    description = "Method  Not Allowed  :  Invalid HTTP method type used ( PUT,DELETE,POST will be rejected) - POL4050"),
-            @ApiResponse(responseCode = "500",
-                    description = "The GET request failed either due to internal SDC problem. ECOMP Component should continue the attempts to get the needed information - POL5000")})
+        @ApiResponse(content = @Content(array = @ArraySchema(schema = @Schema(implementation = String.class)))),
+        @ApiResponse(responseCode = "200", description = "ECOMP component is authenticated and list of Catalog Assets Metadata is returned", content = @Content(array = @ArraySchema(schema = @Schema(implementation = String.class)))),
+        @ApiResponse(responseCode = "400", description = "Missing  'X-ECOMP-InstanceID'  HTTP header - POL5001"),
+        @ApiResponse(responseCode = "401", description = "ECOMP component  should authenticate itself  and  to  re-send  again  HTTP  request  with its Basic Authentication credentials - POL5002"),
+        @ApiResponse(responseCode = "403", description = "ECOMP component is not authorized - POL5003"),
+        @ApiResponse(responseCode = "404", description = "Error: Requested '%1' (uuid) resource was not found - SVC4063"),
+        @ApiResponse(responseCode = "405", description = "Method  Not Allowed  :  Invalid HTTP method type used ( PUT,DELETE,POST will be rejected) - POL4050"),
+        @ApiResponse(responseCode = "500", description = "The GET request failed either due to internal SDC problem. ECOMP Component should continue the attempts to get the needed information - POL5000")})
     @PermissionAllowed(AafPermission.PermNames.READ_VALUE)
     public Response getToscaModelExternal(
-            @Parameter(description = "X-ECOMP-RequestID header",
-                    required = false) @HeaderParam(value = Constants.X_ECOMP_REQUEST_ID_HEADER) String requestId,
-            @Parameter(description = "X-ECOMP-InstanceID header", required = true) @HeaderParam(
-                    value = Constants.X_ECOMP_INSTANCE_ID_HEADER) final String instanceIdHeader,
-            @Parameter(description = "Determines the format of the body of the response",
-                    required = false) @HeaderParam(value = Constants.ACCEPT_HEADER) String accept,
-            @Parameter(description = "The username and password",
-                    required = true) @HeaderParam(value = Constants.AUTHORIZATION_HEADER) String authorization,
-            @Parameter(description = "The requested asset type",schema = @Schema(allowableValues = {"resources", "services"}),
-                    required = true) @PathParam("assetType") final String assetType,
-            @Parameter(description = "The requested asset uuid",
-                    required = true) @PathParam("uuid") final String uuid) {
-
+        @Parameter(description = "X-ECOMP-RequestID header", required = false) @HeaderParam(value = Constants.X_ECOMP_REQUEST_ID_HEADER) String requestId,
+        @Parameter(description = "X-ECOMP-InstanceID header", required = true) @HeaderParam(value = Constants.X_ECOMP_INSTANCE_ID_HEADER) final String instanceIdHeader,
+        @Parameter(description = "Determines the format of the body of the response", required = false) @HeaderParam(value = Constants.ACCEPT_HEADER) String accept,
+        @Parameter(description = "The username and password", required = true) @HeaderParam(value = Constants.AUTHORIZATION_HEADER) String authorization,
+        @Parameter(description = "The requested asset type", schema = @Schema(allowableValues = {"resources",
+            "services"}), required = true) @PathParam("assetType") final String assetType,
+        @Parameter(description = "The requested asset uuid", required = true) @PathParam("uuid") final String uuid) {
         String url = request.getRequestURI();
         log.debug("Start handle request of {} {}", request.getMethod(), url);
         ResponseFormat responseFormat = null;
         ComponentTypeEnum componentType = ComponentTypeEnum.findByParamName(assetType);
         AuditingActionEnum auditingActionEnum = AuditingActionEnum.GET_TOSCA_MODEL;
-
         ResourceCommonInfo resourceCommonInfo = new ResourceCommonInfo(componentType.getValue());
         DistributionData distributionData = new DistributionData(instanceIdHeader, url);
-
         if (instanceIdHeader == null || instanceIdHeader.isEmpty()) {
             log.debug("getToscaModel: Missing X-ECOMP-InstanceID header");
             responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.MISSING_X_ECOMP_INSTANCE_ID);
-            getComponentsUtils().auditExternalGetAsset(responseFormat, auditingActionEnum, distributionData,
-                    resourceCommonInfo, requestId, uuid);
+            getComponentsUtils().auditExternalGetAsset(responseFormat, auditingActionEnum, distributionData, resourceCommonInfo, requestId, uuid);
             return buildErrorResponse(responseFormat);
         }
-
         try {
             ComponentBusinessLogic componentBusinessLogic = getComponentBLByType(componentType);
             ImmutablePair<String, byte[]> csarArtifact = componentBusinessLogic.getToscaModelByComponentUuid(componentType, uuid, resourceCommonInfo);
@@ -408,25 +342,20 @@ public class AssetsDataServlet extends AbstractValidationsServlet {
             headers.put(Constants.CONTENT_DISPOSITION_HEADER, getContentDispositionValue(csarArtifact.getLeft()));
             headers.put(Constants.MD5_HEADER, contenetMD5);
             responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.OK);
-            getComponentsUtils().auditExternalGetAsset(responseFormat, auditingActionEnum, distributionData,
-                    resourceCommonInfo, requestId, uuid);
+            getComponentsUtils().auditExternalGetAsset(responseFormat, auditingActionEnum, distributionData, resourceCommonInfo, requestId, uuid);
             return buildOkResponse(responseFormat, is, headers);
-
         } catch (ComponentException e) {
             responseFormat = e.getResponseFormat();
-            getComponentsUtils().auditExternalGetAsset(responseFormat, auditingActionEnum, distributionData,
-                    resourceCommonInfo, requestId, uuid);
+            getComponentsUtils().auditExternalGetAsset(responseFormat, auditingActionEnum, distributionData, resourceCommonInfo, requestId, uuid);
             BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Get asset tosca model");
             log.debug("failed to get asset tosca model", e);
             Response response = buildErrorResponse(responseFormat);
-            getComponentsUtils().auditExternalGetAsset(responseFormat, auditingActionEnum, distributionData,
-                    resourceCommonInfo, requestId, uuid);
+            getComponentsUtils().auditExternalGetAsset(responseFormat, auditingActionEnum, distributionData, resourceCommonInfo, requestId, uuid);
             return response;
         }
     }
 
-
     private String removeDuplicateSlashSeparator(String requestUri) {
-        return requestUri.substring(0, requestUri.length()-1);
+        return requestUri.substring(0, requestUri.length() - 1);
     }
 }
index 97678d7..5f6d8ea 100644 (file)
@@ -17,7 +17,6 @@
  * limitations under the License.
  * ============LICENSE_END=========================================================
  */
-
 package org.openecomp.sdc.be.externalapi.servlet;
 
 import static com.google.common.base.Strings.isNullOrEmpty;
@@ -104,26 +103,21 @@ import org.springframework.stereotype.Controller;
 @Controller
 public class CrudExternalServlet extends AbstractValidationsServlet {
 
-    @Context
-    private HttpServletRequest request;
-
     private static final Logger log = Logger.getLogger(CrudExternalServlet.class);
     private final ElementBusinessLogic elementBusinessLogic;
     private final AssetMetadataConverter assetMetadataUtils;
     private final LifecycleBusinessLogic lifecycleBusinessLogic;
     private final ResourceBusinessLogic resourceBusinessLogic;
     private final ServiceBusinessLogic serviceBusinessLogic;
+    @Context
+    private HttpServletRequest request;
 
     @Inject
-    public CrudExternalServlet(UserBusinessLogic userBusinessLogic,
-        ComponentInstanceBusinessLogic componentInstanceBL,
-        ComponentsUtils componentsUtils, ServletUtils servletUtils,
-        ResourceImportManager resourceImportManager,
-        ElementBusinessLogic elementBusinessLogic,
-        AssetMetadataConverter assetMetadataUtils,
-        LifecycleBusinessLogic lifecycleBusinessLogic,
-        ResourceBusinessLogic resourceBusinessLogic,
-        ServiceBusinessLogic serviceBusinessLogic) {
+    public CrudExternalServlet(UserBusinessLogic userBusinessLogic, ComponentInstanceBusinessLogic componentInstanceBL,
+                               ComponentsUtils componentsUtils, ServletUtils servletUtils, ResourceImportManager resourceImportManager,
+                               ElementBusinessLogic elementBusinessLogic, AssetMetadataConverter assetMetadataUtils,
+                               LifecycleBusinessLogic lifecycleBusinessLogic, ResourceBusinessLogic resourceBusinessLogic,
+                               ServiceBusinessLogic serviceBusinessLogic) {
         super(userBusinessLogic, componentInstanceBL, componentsUtils, servletUtils, resourceImportManager);
         this.elementBusinessLogic = elementBusinessLogic;
         this.assetMetadataUtils = assetMetadataUtils;
@@ -146,74 +140,41 @@ public class CrudExternalServlet extends AbstractValidationsServlet {
     @Consumes(MediaType.APPLICATION_JSON)
     @Produces(MediaType.APPLICATION_JSON)
     @Operation(parameters = {
-            @Parameter(required = true, schema = @Schema(implementation = org.openecomp.sdc.be.model.Resource.class),
-                    description = "json describe the created resource")},
-            description = "creates an asset (resource or service)", method = "POST",
-            summary = "Creates an asset (resource or service)", responses = {
-            @ApiResponse(responseCode = "200", description = "ECOMP component is authenticated and Asset created",
-                    content = @Content(array = @ArraySchema(schema = @Schema(implementation = Resource.class)))),
-            @ApiResponse(responseCode = "400", description = "Missing  X-ECOMP-InstanceID  HTTP header - POL5001"),
-            @ApiResponse(responseCode = "401",
-                    description = "ECOMP component  should authenticate itself  and  to  re-send  again  HTTP  request  with its Basic Authentication credentials - POL5002"),
-            @ApiResponse(responseCode = "403", description = "ECOMP component is not authorized - POL5003"),
-            @ApiResponse(responseCode = "404",
-                    description = "Error: Requested '%1' (uuid) resource was not found - SVC4063"),
-            @ApiResponse(responseCode = "405",
-                    description = "Method  Not Allowed  :  Invalid HTTP method type used ( PUT,DELETE,POST will be rejected) - POL4050"),
-            @ApiResponse(responseCode = "500",
-                    description = "The GET request failed either due to internal SDC problem. ECOMP Component should continue the attempts to get the needed information - POL5000"),
-            @ApiResponse(responseCode = "400",
-                    description = "The name provided for the newly created resource is already in use for another resource in SDC - SVC4050"),
-            @ApiResponse(responseCode = "400",
-                    description = "Invalid field format. One of the provided fields does not comply with the field rules - SVC4126"),
-            @ApiResponse(responseCode = "400",
-                    description = "Missing request body. The post request did not contain the expected body - SVC4500"),
-            @ApiResponse(responseCode = "400",
-                    description = "The resource name is missing in the request body - SVC4062"),
-            @ApiResponse(responseCode = "400",
-                    description = "Create VFCMT request: VFCMT description has wrong format - SVC4064"),
-            @ApiResponse(responseCode = "400",
-                    description = "Create VFCMT request: VFCMT description has wrong format (exceeds limit) - SVC4065"),
-            @ApiResponse(responseCode = "400",
-                    description = "Create VFCMT request: VFCMT tags exceeds character limit - SVC4066"),
-            @ApiResponse(responseCode = "400",
-                    description = "Create VFCMT request: VFCMT vendor name exceeds character limit - SVC4067"),
-            @ApiResponse(responseCode = "400",
-                    description = "Create VFCMT request: VFCMT vendor release exceeds character limit - SVC4068"),
-            @ApiResponse(responseCode = "400",
-                    description = "Create VFCMT request: VFCMT ATT Contact has wrong format - SVC4069"),
-            @ApiResponse(responseCode = "400",
-                    description = "Create VFCMT request: VFCMT name has wrong format - SVC4070"),
-            @ApiResponse(responseCode = "400",
-                    description = "Create VFCMT request: VFCMT vendor name has wrong format - SVC4071"),
-            @ApiResponse(responseCode = "400",
-                    description = "Create VFCMT request: VFCMT vendor release has wrong format - SVC4072"),
-            @ApiResponse(responseCode = "400",
-                    description = "Create VFCMT request: VFCMT name exceeds character limit - SVC4073"),
-            @ApiResponse(responseCode = "400", description = "Invalid Content. Missing PROJECT_CODE number - SVC4129"),
-            @ApiResponse(responseCode = "409",
-                    description = "Error: %1 (Service) with name '%2' already exists. - SVC4050")})
+        @Parameter(required = true, schema = @Schema(implementation = org.openecomp.sdc.be.model.Resource.class), description = "json describe the created resource")}, description = "creates an asset (resource or service)", method = "POST", summary = "Creates an asset (resource or service)", responses = {
+        @ApiResponse(responseCode = "200", description = "ECOMP component is authenticated and Asset created", content = @Content(array = @ArraySchema(schema = @Schema(implementation = Resource.class)))),
+        @ApiResponse(responseCode = "400", description = "Missing  X-ECOMP-InstanceID  HTTP header - POL5001"),
+        @ApiResponse(responseCode = "401", description = "ECOMP component  should authenticate itself  and  to  re-send  again  HTTP  request  with its Basic Authentication credentials - POL5002"),
+        @ApiResponse(responseCode = "403", description = "ECOMP component is not authorized - POL5003"),
+        @ApiResponse(responseCode = "404", description = "Error: Requested '%1' (uuid) resource was not found - SVC4063"),
+        @ApiResponse(responseCode = "405", description = "Method  Not Allowed  :  Invalid HTTP method type used ( PUT,DELETE,POST will be rejected) - POL4050"),
+        @ApiResponse(responseCode = "500", description = "The GET request failed either due to internal SDC problem. ECOMP Component should continue the attempts to get the needed information - POL5000"),
+        @ApiResponse(responseCode = "400", description = "The name provided for the newly created resource is already in use for another resource in SDC - SVC4050"),
+        @ApiResponse(responseCode = "400", description = "Invalid field format. One of the provided fields does not comply with the field rules - SVC4126"),
+        @ApiResponse(responseCode = "400", description = "Missing request body. The post request did not contain the expected body - SVC4500"),
+        @ApiResponse(responseCode = "400", description = "The resource name is missing in the request body - SVC4062"),
+        @ApiResponse(responseCode = "400", description = "Create VFCMT request: VFCMT description has wrong format - SVC4064"),
+        @ApiResponse(responseCode = "400", description = "Create VFCMT request: VFCMT description has wrong format (exceeds limit) - SVC4065"),
+        @ApiResponse(responseCode = "400", description = "Create VFCMT request: VFCMT tags exceeds character limit - SVC4066"),
+        @ApiResponse(responseCode = "400", description = "Create VFCMT request: VFCMT vendor name exceeds character limit - SVC4067"),
+        @ApiResponse(responseCode = "400", description = "Create VFCMT request: VFCMT vendor release exceeds character limit - SVC4068"),
+        @ApiResponse(responseCode = "400", description = "Create VFCMT request: VFCMT ATT Contact has wrong format - SVC4069"),
+        @ApiResponse(responseCode = "400", description = "Create VFCMT request: VFCMT name has wrong format - SVC4070"),
+        @ApiResponse(responseCode = "400", description = "Create VFCMT request: VFCMT vendor name has wrong format - SVC4071"),
+        @ApiResponse(responseCode = "400", description = "Create VFCMT request: VFCMT vendor release has wrong format - SVC4072"),
+        @ApiResponse(responseCode = "400", description = "Create VFCMT request: VFCMT name exceeds character limit - SVC4073"),
+        @ApiResponse(responseCode = "400", description = "Invalid Content. Missing PROJECT_CODE number - SVC4129"),
+        @ApiResponse(responseCode = "409", description = "Error: %1 (Service) with name '%2' already exists. - SVC4050")})
     @PermissionAllowed(AafPermission.PermNames.WRITE_VALUE)
     public Response createComponentExternal(
-            @Parameter(description = "Determines the format of the body of the request",
-                    required = true) @HeaderParam(value = Constants.CONTENT_TYPE_HEADER) String contentType,
-            @Parameter(description = "The user id",
-                    required = true) @HeaderParam(value = Constants.USER_ID_HEADER) final String userId,
-            @Parameter(description = "X-ECOMP-RequestID header",
-                    required = false) @HeaderParam(value = Constants.X_ECOMP_REQUEST_ID_HEADER) String requestId,
-            @Parameter(description = "X-ECOMP-InstanceID header", required = true) @HeaderParam(
-                    value = Constants.X_ECOMP_INSTANCE_ID_HEADER) final String instanceIdHeader,
-            @Parameter(description = "Determines the format of the body of the response",
-                    required = false) @HeaderParam(value = Constants.ACCEPT_HEADER) String accept,
-            @Parameter(description = "The username and password",
-                    required = true) @HeaderParam(value = Constants.AUTHORIZATION_HEADER) String authorization,
-            @Parameter(description = "The requested asset type", required = true,
-                    schema = @Schema(
-                            allowableValues = {"resources, services"})) @PathParam("assetType") final String assetType,
-            @Parameter(hidden = true) String data) {
-
+        @Parameter(description = "Determines the format of the body of the request", required = true) @HeaderParam(value = Constants.CONTENT_TYPE_HEADER) String contentType,
+        @Parameter(description = "The user id", required = true) @HeaderParam(value = Constants.USER_ID_HEADER) final String userId,
+        @Parameter(description = "X-ECOMP-RequestID header", required = false) @HeaderParam(value = Constants.X_ECOMP_REQUEST_ID_HEADER) String requestId,
+        @Parameter(description = "X-ECOMP-InstanceID header", required = true) @HeaderParam(value = Constants.X_ECOMP_INSTANCE_ID_HEADER) final String instanceIdHeader,
+        @Parameter(description = "Determines the format of the body of the response", required = false) @HeaderParam(value = Constants.ACCEPT_HEADER) String accept,
+        @Parameter(description = "The username and password", required = true) @HeaderParam(value = Constants.AUTHORIZATION_HEADER) String authorization,
+        @Parameter(description = "The requested asset type", required = true, schema = @Schema(allowableValues = {
+            "resources, services"})) @PathParam("assetType") final String assetType, @Parameter(hidden = true) String data) {
         init();
-
         Wrapper<ResponseFormat> responseWrapper = new Wrapper<>();
         String requestURI = request.getRequestURI();
         String url = request.getMethod() + " " + requestURI;
@@ -222,7 +183,6 @@ public class CrudExternalServlet extends AbstractValidationsServlet {
         User modifier = null;
         ResourceCommonInfo resourceCommonInfo = new ResourceCommonInfo(ComponentTypeEnum.RESOURCE.getValue());
         Service service = null;
-
         try {
             // Validate X-ECOMP-InstanceID Header
             if (responseWrapper.isEmpty()) {
@@ -233,75 +193,62 @@ public class CrudExternalServlet extends AbstractValidationsServlet {
                 validateHttpCspUserIdHeader(userId, responseWrapper);
             }
             // Validate assetType
-
-            if( responseWrapper.isEmpty() && !(AssetTypeEnum.RESOURCES.getValue().equals(assetType) || AssetTypeEnum.SERVICES.getValue().equals(assetType))) {
+            if (responseWrapper.isEmpty() && !(AssetTypeEnum.RESOURCES.getValue().equals(assetType) || AssetTypeEnum.SERVICES.getValue()
+                .equals(assetType))) {
                 responseWrapper.setInnerElement(getComponentsUtils().getResponseFormat(ActionStatus.RESTRICTED_OPERATION));
             }
-
-                       if (responseWrapper.isEmpty() && AssetTypeEnum.SERVICES.getValue().equals(assetType)) {
-
+            if (responseWrapper.isEmpty() && AssetTypeEnum.SERVICES.getValue().equals(assetType)) {
                 modifier = new User();
                 modifier.setUserId(userId);
                 Either<Service, ResponseFormat> convertResponse = getComponentsUtils()
-                        .convertJsonToObjectUsingObjectMapper(data, modifier, Service.class,
-                                null, ComponentTypeEnum.SERVICE);
-                if( convertResponse.isRight() ){
+                    .convertJsonToObjectUsingObjectMapper(data, modifier, Service.class, null, ComponentTypeEnum.SERVICE);
+                if (convertResponse.isRight()) {
                     responseWrapper.setInnerElement(convertResponse.right().value());
-                }
-                else{
+                } else {
                     service = convertResponse.left().value();
                 }
-
-                if (service==null){
-                    responseWrapper.setInnerElement(getComponentsUtils().getResponseFormat(
-                            ActionStatus.SERVICE_NOT_FOUND, ComponentTypeEnum.SERVICE.getValue()));
+                if (service == null) {
+                    responseWrapper.setInnerElement(
+                        getComponentsUtils().getResponseFormat(ActionStatus.SERVICE_NOT_FOUND, ComponentTypeEnum.SERVICE.getValue()));
                 }
-
                 //validate name exist
-                if(responseWrapper.isEmpty() && service != null && isNullOrEmpty(service.getName())){
-                    responseWrapper.setInnerElement(getComponentsUtils().getResponseFormat(
-                    ActionStatus.MISSING_COMPONENT_NAME, ComponentTypeEnum.SERVICE.getValue()));
+                if (responseWrapper.isEmpty() && service != null && isNullOrEmpty(service.getName())) {
+                    responseWrapper.setInnerElement(
+                        getComponentsUtils().getResponseFormat(ActionStatus.MISSING_COMPONENT_NAME, ComponentTypeEnum.SERVICE.getValue()));
                 }
-
                 //validate category
-                if(responseWrapper.isEmpty() && service != null && service.getCategories() != null && !service.getCategories().isEmpty() && !ExternalCategoryTypeEnum.containsIgnoreCase(service.getCategories().get(0).getName())){
+                if (responseWrapper.isEmpty() && service != null && service.getCategories() != null && !service.getCategories().isEmpty()
+                    && !ExternalCategoryTypeEnum.containsIgnoreCase(service.getCategories().get(0).getName())) {
                     log.debug("Service category is not supported {}", service.getCategories().get(0).getName());
-                    responseWrapper.setInnerElement(getComponentsUtils().getResponseFormat(
-                            ActionStatus.COMPONENT_INVALID_CATEGORY, ComponentTypeEnum.SERVICE.getValue()));
+                    responseWrapper.setInnerElement(
+                        getComponentsUtils().getResponseFormat(ActionStatus.COMPONENT_INVALID_CATEGORY, ComponentTypeEnum.SERVICE.getValue()));
                 }
-
-                if(responseWrapper.isEmpty() && service != null){
+                if (responseWrapper.isEmpty() && service != null) {
                     service.setSystemName(ValidationUtils.convertToSystemName(service.getName()));
-                    log.debug("Service system name :"+service.getSystemName());
+                    log.debug("Service system name :" + service.getSystemName());
                 }
-
-                               if(responseWrapper.isEmpty()){
-                                   Either<Service, ResponseFormat> actionResponse = serviceBusinessLogic.createService(service, modifier);
+                if (responseWrapper.isEmpty()) {
+                    Either<Service, ResponseFormat> actionResponse = serviceBusinessLogic.createService(service, modifier);
                     if (actionResponse.isRight()) {
                         log.debug("Failed to create service");
-                                           responseWrapper.setInnerElement(actionResponse.right().value());
-                                           return buildErrorResponse(responseWrapper.getInnerElement());
+                        responseWrapper.setInnerElement(actionResponse.right().value());
+                        return buildErrorResponse(responseWrapper.getInnerElement());
                     }
-
                     // Create the service in the dataModel
                     service = actionResponse.left().value();
                     Object result = RepresentationUtils.toRepresentation(actionResponse.left().value());
                     responseWrapper.setInnerElement(getComponentsUtils().getResponseFormat(ActionStatus.CREATED));
                     return buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.CREATED), result);
-                               }
-                               else{
-                                   return buildErrorResponse(responseWrapper.getInnerElement());
+                } else {
+                    return buildErrorResponse(responseWrapper.getInnerElement());
                 }
-
-
-
-                       } else {
+            } else {
                 //Validate resource type
-               if(responseWrapper.isEmpty()){
+                if (responseWrapper.isEmpty()) {
                     JSONParser parser = new JSONParser();
                     JSONObject jsonObj = (JSONObject) parser.parse(data);
                     String resourceType = (String) jsonObj.get(FilterKeyEnum.RESOURCE_TYPE.getName());
-                    if( StringUtils.isEmpty(resourceType) || !ResourceTypeEnum.containsName(resourceType) ){
+                    if (StringUtils.isEmpty(resourceType) || !ResourceTypeEnum.containsName(resourceType)) {
                         resourceCommonInfo.setResourceName((String) jsonObj.get("name"));
                         responseWrapper.setInnerElement(getComponentsUtils().getResponseFormat(ActionStatus.INVALID_CONTENT));
                     }
@@ -311,64 +258,57 @@ public class CrudExternalServlet extends AbstractValidationsServlet {
                     modifier = new User();
                     modifier.setUserId(userId);
                     Either<Resource, ResponseFormat> eitherResource = getComponentsUtils()
-                            .convertJsonToObjectUsingObjectMapper(data, modifier, Resource.class,
-                                    null, ComponentTypeEnum.RESOURCE);
-                    if( eitherResource.isRight() ){
+                        .convertJsonToObjectUsingObjectMapper(data, modifier, Resource.class, null, ComponentTypeEnum.RESOURCE);
+                    if (eitherResource.isRight()) {
                         responseWrapper.setInnerElement(eitherResource.right().value());
-                    }
-                    else{
+                    } else {
                         resource = eitherResource.left().value();
                     }
-
                 }
                 //validate name exist
-                if(responseWrapper.isEmpty() && isNullOrEmpty(resource.getName())){
-                        responseWrapper.setInnerElement(getComponentsUtils().getResponseFormat(
-                                ActionStatus.MISSING_COMPONENT_NAME, ComponentTypeEnum.RESOURCE.getValue()));
+                if (responseWrapper.isEmpty() && isNullOrEmpty(resource.getName())) {
+                    responseWrapper.setInnerElement(
+                        getComponentsUtils().getResponseFormat(ActionStatus.MISSING_COMPONENT_NAME, ComponentTypeEnum.RESOURCE.getValue()));
                 }
-
-                if(responseWrapper.isEmpty()){
+                if (responseWrapper.isEmpty()) {
                     resource.setDerivedFrom(Arrays.asList("tosca.nodes.Root"));
                     resource.setSystemName(ValidationUtils.convertToSystemName(resource.getName()));
-                    resource.setToscaResourceName(CommonBeUtils.generateToscaResourceName(ResourceTypeEnum.VFCMT.name(),
-                            resource.getSystemName()));
+                    resource.setToscaResourceName(CommonBeUtils.generateToscaResourceName(ResourceTypeEnum.VFCMT.name(), resource.getSystemName()));
                     handleCategories(data, resource, responseWrapper);
                 }
                 // Create the resource in the dataModel
                 if (responseWrapper.isEmpty()) {
-                    resource = resourceBusinessLogic.createResource(resource, null,
-                            modifier, null, null);
+                    resource = resourceBusinessLogic.createResource(resource, null, modifier, null, null);
                     return buildCreatedResourceResponse(resource, responseWrapper);
                 } else {
                     return buildErrorResponse(responseWrapper.getInnerElement());
                 }
             }
-
-        } catch (IOException|ParseException e) {
+        } catch (IOException | ParseException e) {
             final String message = "failed to create vfc monitoring template resource";
             BeEcompErrorManager.getInstance().logBeRestApiGeneralError(message);
             log.debug(message, e);
             responseWrapper.setInnerElement(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR));
             return buildErrorResponse(responseWrapper.getInnerElement());
-        } catch (ComponentException e){
+        } catch (ComponentException e) {
             ResponseFormat responseFormat = getComponentsUtils().getResponseFormat(e);
             responseWrapper.setInnerElement(responseFormat);
             return buildErrorResponse(responseFormat);
-        }
-        finally {
-               if(AssetTypeEnum.RESOURCES.getValue().equals(assetType)) {
-                       getComponentsUtils().auditCreateResourceExternalApi(responseWrapper.getInnerElement(), resourceCommonInfo, request, resource);
-               } else if(AssetTypeEnum.SERVICES.getValue().equals(assetType)) {
-                       getComponentsUtils().auditCreateServiceExternalApi(responseWrapper.getInnerElement(), request, service);
-               }
+        } finally {
+            if (AssetTypeEnum.RESOURCES.getValue().equals(assetType)) {
+                getComponentsUtils().auditCreateResourceExternalApi(responseWrapper.getInnerElement(), resourceCommonInfo, request, resource);
+            } else if (AssetTypeEnum.SERVICES.getValue().equals(assetType)) {
+                getComponentsUtils().auditCreateServiceExternalApi(responseWrapper.getInnerElement(), request, service);
+            }
         }
     }
 
     /**
      * Changing the lifecycle of an asset
-     * @param jsonChangeInfo    The description - request body
-     * @param assetType The requested asset type.Valid values are: resources / services (for VFCMT â€“ use "resources")
-     * @param uuid The uuid of the desired resource to be changed
+     *
+     * @param jsonChangeInfo      The description - request body
+     * @param assetType           The requested asset type.Valid values are: resources / services (for VFCMT â€“ use "resources")
+     * @param uuid                The uuid of the desired resource to be changed
      * @param lifecycleTransition The lifecycle operation to be performed on the asset.Valid values are:Checkin / Checkout /  CERTIFICATION_REQUEST
      * @param userId
      * @return
@@ -378,67 +318,45 @@ public class CrudExternalServlet extends AbstractValidationsServlet {
     @Consumes(MediaType.APPLICATION_JSON)
     @Produces(MediaType.APPLICATION_JSON)
     @Operation(parameters = {
-            @Parameter(required = true, schema = @Schema(implementation = org.openecomp.sdc.be.model.Resource.class),
-                    description = "json describe the created resource")},
-            description = "Change Resource lifecycle State", method = "POST", responses = {
-            @ApiResponse(responseCode = "200", description = "Resource state changed",
-                    content = @Content(array = @ArraySchema(schema = @Schema(implementation = AssetMetadata.class)))),
-            @ApiResponse(responseCode = "400", description = "Missing X-ECOMP-InstanceID HTTP header - POL5001"),
-            @ApiResponse(responseCode = "401",
-                    description = "ECOMP component  should authenticate itself  and  to  re-send  again  HTTP  request  with its Basic Authentication credentials - POL5002"),
-            @ApiResponse(responseCode = "403", description = "ECOMP component is not authorized - POL5003"),
-            @ApiResponse(responseCode = "404",
-                    description = "Error: Requested '%1' (uuid) resource was not found - SVC4063"),
-            @ApiResponse(responseCode = "405",
-                    description = "Method  Not Allowed  :  Invalid HTTP method type used ( PUT,DELETE,POST will be rejected) - POL4050"),
-            @ApiResponse(responseCode = "500",
-                    description = "The GET request failed either due to internal SDC problem. ECOMP Component should continue the attempts to get the needed information - POL5000"),
-            @ApiResponse(responseCode = "403", description = "Asset is already checked-out by another user - SVC4085"),
-            @ApiResponse(responseCode = "403",
-                    description = "Asset is being edited by different user. Only one user can checkout and edit an asset on given time. The asset will be available for checkout after the other user will checkin the asset - SVC4080")})
+        @Parameter(required = true, schema = @Schema(implementation = org.openecomp.sdc.be.model.Resource.class), description = "json describe the created resource")}, description = "Change Resource lifecycle State", method = "POST", responses = {
+        @ApiResponse(responseCode = "200", description = "Resource state changed", content = @Content(array = @ArraySchema(schema = @Schema(implementation = AssetMetadata.class)))),
+        @ApiResponse(responseCode = "400", description = "Missing X-ECOMP-InstanceID HTTP header - POL5001"),
+        @ApiResponse(responseCode = "401", description = "ECOMP component  should authenticate itself  and  to  re-send  again  HTTP  request  with its Basic Authentication credentials - POL5002"),
+        @ApiResponse(responseCode = "403", description = "ECOMP component is not authorized - POL5003"),
+        @ApiResponse(responseCode = "404", description = "Error: Requested '%1' (uuid) resource was not found - SVC4063"),
+        @ApiResponse(responseCode = "405", description = "Method  Not Allowed  :  Invalid HTTP method type used ( PUT,DELETE,POST will be rejected) - POL4050"),
+        @ApiResponse(responseCode = "500", description = "The GET request failed either due to internal SDC problem. ECOMP Component should continue the attempts to get the needed information - POL5000"),
+        @ApiResponse(responseCode = "403", description = "Asset is already checked-out by another user - SVC4085"),
+        @ApiResponse(responseCode = "403", description = "Asset is being edited by different user. Only one user can checkout and edit an asset on given time. The asset will be available for checkout after the other user will checkin the asset - SVC4080")})
     @PermissionAllowed(AafPermission.PermNames.WRITE_VALUE)
     public Response changeResourceStateExternal(
-            @Parameter(description = "Determines the format of the body of the request",
-                    required = true) @HeaderParam(value = Constants.CONTENT_TYPE_HEADER) String contentType,
-            @Parameter(description = "The user id",
-                    required = true) @HeaderParam(value = Constants.USER_ID_HEADER) final String userId,
-            @Parameter(description = "X-ECOMP-RequestID header",
-                    required = false) @HeaderParam(value = Constants.X_ECOMP_REQUEST_ID_HEADER) String requestId,
-            @Parameter(description = "X-ECOMP-InstanceID header", required = true) @HeaderParam(
-                    value = Constants.X_ECOMP_INSTANCE_ID_HEADER) final String instanceIdHeader,
-            @Parameter(description = "Determines the format of the body of the response",
-                    required = false) @HeaderParam(value = Constants.ACCEPT_HEADER) String accept,
-            @Parameter(description = "The username and password",
-                    required = true) @HeaderParam(value = Constants.AUTHORIZATION_HEADER) String authorization,
-            @Parameter(schema = @Schema(allowableValues = {"checkout, checkin"}),
-                    required = true) @PathParam(value = "lifecycleOperation") final String lifecycleTransition,
-            @Parameter(description = "id of component to be changed") @PathParam(value = "uuid") final String uuid,
-            @Parameter(description = "validValues: resources / services ",
-                    schema = @Schema(allowableValues = {ComponentTypeEnum.RESOURCE_PARAM_NAME ,
-                             ComponentTypeEnum.SERVICE_PARAM_NAME})) @PathParam(
-                                    value = "assetType") final String assetType,
-            @Parameter(hidden = true) String jsonChangeInfo) {
-
+        @Parameter(description = "Determines the format of the body of the request", required = true) @HeaderParam(value = Constants.CONTENT_TYPE_HEADER) String contentType,
+        @Parameter(description = "The user id", required = true) @HeaderParam(value = Constants.USER_ID_HEADER) final String userId,
+        @Parameter(description = "X-ECOMP-RequestID header", required = false) @HeaderParam(value = Constants.X_ECOMP_REQUEST_ID_HEADER) String requestId,
+        @Parameter(description = "X-ECOMP-InstanceID header", required = true) @HeaderParam(value = Constants.X_ECOMP_INSTANCE_ID_HEADER) final String instanceIdHeader,
+        @Parameter(description = "Determines the format of the body of the response", required = false) @HeaderParam(value = Constants.ACCEPT_HEADER) String accept,
+        @Parameter(description = "The username and password", required = true) @HeaderParam(value = Constants.AUTHORIZATION_HEADER) String authorization,
+        @Parameter(schema = @Schema(allowableValues = {
+            "checkout, checkin"}), required = true) @PathParam(value = "lifecycleOperation") final String lifecycleTransition,
+        @Parameter(description = "id of component to be changed") @PathParam(value = "uuid") final String uuid,
+        @Parameter(description = "validValues: resources / services ", schema = @Schema(allowableValues = {ComponentTypeEnum.RESOURCE_PARAM_NAME,
+            ComponentTypeEnum.SERVICE_PARAM_NAME})) @PathParam(value = "assetType") final String assetType,
+        @Parameter(hidden = true) String jsonChangeInfo) {
         Response response = null;
-
         init();
-
         String requestURI = request.getRequestURI();
         String url = request.getMethod() + " " + requestURI;
         log.debug("Start handle request of {}", url);
-
         Wrapper<ResponseFormat> responseWrapper = runValidations(assetType);
         ComponentTypeEnum componentType = ComponentTypeEnum.findByParamName(assetType);
         Component component = null;
         Component responseObject = null;
         User modifier = null;
-
-        try{
+        try {
             // Validate X-ECOMP-InstanceID Header
             if (responseWrapper.isEmpty()) {
                 validateXECOMPInstanceIDHeader(instanceIdHeader, responseWrapper);
             }
-
             if (responseWrapper.isEmpty()) {
                 //get user
                 Either<User, ResponseFormat> eitherGetUser = getUser(request, userId);
@@ -448,7 +366,6 @@ public class CrudExternalServlet extends AbstractValidationsServlet {
                     return buildErrorResponse(responseFormat);
                 }
                 modifier = eitherGetUser.left().value();
-
                 //get the component id from the uuid
                 Either<Component, ResponseFormat> latestVersion = lifecycleBusinessLogic.getLatestComponentByUuid(componentType, uuid);
                 if (latestVersion.isRight()) {
@@ -458,7 +375,6 @@ public class CrudExternalServlet extends AbstractValidationsServlet {
                 }
                 component = latestVersion.left().value();
                 String componentId = component.getUniqueId();
-
                 //validate the transition is valid
                 Either<LifeCycleTransitionEnum, ResponseFormat> validateEnum = validateTransitionEnum(lifecycleTransition, modifier);
                 if (validateEnum.isRight()) {
@@ -467,39 +383,37 @@ public class CrudExternalServlet extends AbstractValidationsServlet {
                     return buildErrorResponse(responseFormat);
                 }
                 LifeCycleTransitionEnum transitionEnum = validateEnum.left().value();
-
                 //create changeInfo
                 LifecycleChangeInfoWithAction changeInfo = new LifecycleChangeInfoWithAction();
                 try {
                     if (jsonChangeInfo != null && !jsonChangeInfo.isEmpty()) {
                         ObjectMapper mapper = new ObjectMapper();
-                        changeInfo = new LifecycleChangeInfoWithAction(mapper.readValue(jsonChangeInfo, LifecycleChangeInfoBase.class).getUserRemarks());
+                        changeInfo = new LifecycleChangeInfoWithAction(
+                            mapper.readValue(jsonChangeInfo, LifecycleChangeInfoBase.class).getUserRemarks());
                     }
-                }
-                catch (IOException e) {
+                } catch (IOException e) {
                     BeEcompErrorManager.getInstance().logBeInvalidJsonInput("convertJsonToObject");
                     log.debug("failed to convert from json {}", jsonChangeInfo, e);
-                    ResponseFormat responseFormat = getComponentsUtils().getInvalidContentErrorAndAudit(modifier, componentId, AuditingActionEnum.CHECKOUT_RESOURCE);
+                    ResponseFormat responseFormat = getComponentsUtils()
+                        .getInvalidContentErrorAndAudit(modifier, componentId, AuditingActionEnum.CHECKOUT_RESOURCE);
                     responseWrapper.setInnerElement(responseFormat);
                     return buildErrorResponse(responseFormat);
                 }
-
                 //execute business logic
-                Either<? extends Component, ResponseFormat> actionResponse = lifecycleBusinessLogic.changeComponentState(componentType, componentId, modifier, transitionEnum, changeInfo, false, true);
+                Either<? extends Component, ResponseFormat> actionResponse = lifecycleBusinessLogic
+                    .changeComponentState(componentType, componentId, modifier, transitionEnum, changeInfo, false, true);
                 if (actionResponse.isRight()) {
                     log.info("failed to change resource state");
                     ResponseFormat responseFormat = actionResponse.right().value();
                     responseWrapper.setInnerElement(responseFormat);
                     return buildErrorResponse(responseFormat);
                 }
-
                 log.debug("change state successful !!!");
                 responseObject = actionResponse.left().value();
                 response = buildCreatedResourceResponse(responseObject, responseWrapper);
             } else {
                 response = buildErrorResponse(responseWrapper.getInnerElement());
             }
-
             return response;
         } catch (IOException e) {
             BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Change Lifecycle State");
@@ -507,33 +421,29 @@ public class CrudExternalServlet extends AbstractValidationsServlet {
             ResponseFormat responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR);
             responseWrapper.setInnerElement(responseFormat);
             return buildErrorResponse(responseFormat);
-        } catch (ComponentException e){
+        } catch (ComponentException e) {
             ResponseFormat responseFormat = getComponentsUtils().getResponseFormat(e);
             responseWrapper.setInnerElement(responseFormat);
             return buildErrorResponse(responseFormat);
-        }
-        finally{
-            getComponentsUtils().auditChangeLifecycleAction(responseWrapper.getInnerElement(), componentType, requestId,
-                    component, responseObject, new DistributionData(instanceIdHeader, requestURI), modifier);
+        } finally {
+            getComponentsUtils().auditChangeLifecycleAction(responseWrapper.getInnerElement(), componentType, requestId, component, responseObject,
+                new DistributionData(instanceIdHeader, requestURI), modifier);
         }
     }
 
-    private Response buildCreatedResourceResponse(Component resource,
-            Wrapper<ResponseFormat> responseWrapper) throws IOException {
+    private Response buildCreatedResourceResponse(Component resource, Wrapper<ResponseFormat> responseWrapper) throws IOException {
         ResponseFormat responseFormat;
         Response response;
         Either<? extends AssetMetadata, ResponseFormat> resMetadata = assetMetadataUtils
-                .convertToSingleAssetMetadata(resource, request.getRequestURL().toString(),
-                        true);
+            .convertToSingleAssetMetadata(resource, request.getRequestURL().toString(), true);
         if (resMetadata.isRight()) {
             log.debug("Asset conversion Failed");
             responseFormat = resMetadata.right().value();
             responseWrapper.setInnerElement(responseFormat);
             response = buildErrorResponse(responseFormat);
-        }else{
+        } else {
             final AssetMetadata assetData = resMetadata.left().value();
             assetData.setToscaModelURL(null);
-
             responseWrapper.setInnerElement(getComponentsUtils().getResponseFormat(ActionStatus.CREATED));
             Object representation = RepresentationUtils.toRepresentation(assetData);
             response = buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.CREATED), representation);
@@ -541,29 +451,24 @@ public class CrudExternalServlet extends AbstractValidationsServlet {
         return response;
     }
 
-    private void handleCategories(String data, Resource resource,
-            Wrapper<ResponseFormat> responseWrapper) {
+    private void handleCategories(String data, Resource resource, Wrapper<ResponseFormat> responseWrapper) {
         try {
             JSONParser parser = new JSONParser();
             JSONObject jsonObj = (JSONObject) parser.parse(data);
             String category = (String) jsonObj.get(CategoryTypeEnum.CATEGORY.getValue());
             String subcategory = (String) jsonObj.get(CategoryTypeEnum.SUBCATEGORY.getValue());
             if (isNullOrEmpty(category)) {
-                responseWrapper.setInnerElement(getComponentsUtils().getResponseFormat(
-                        ActionStatus.COMPONENT_MISSING_CATEGORY, ComponentTypeEnum.RESOURCE.getValue()));
-            }
-            else if (isNullOrEmpty(subcategory)) {
-                responseWrapper.setInnerElement(getComponentsUtils().getResponseFormat(
-                        ActionStatus.COMPONENT_MISSING_SUBCATEGORY));
+                responseWrapper.setInnerElement(
+                    getComponentsUtils().getResponseFormat(ActionStatus.COMPONENT_MISSING_CATEGORY, ComponentTypeEnum.RESOURCE.getValue()));
+            } else if (isNullOrEmpty(subcategory)) {
+                responseWrapper.setInnerElement(getComponentsUtils().getResponseFormat(ActionStatus.COMPONENT_MISSING_SUBCATEGORY));
             }
             if (responseWrapper.isEmpty()) {
                 // get All Categories
-                Either<List<CategoryDefinition>, ActionStatus> allResourceCategories = elementBusinessLogic
-                        .getAllResourceCategories();
+                Either<List<CategoryDefinition>, ActionStatus> allResourceCategories = elementBusinessLogic.getAllResourceCategories();
                 // Error fetching categories
                 if (allResourceCategories.isRight()) {
-                    responseWrapper.setInnerElement(
-                            getComponentsUtils().getResponseFormat(allResourceCategories.right().value()));
+                    responseWrapper.setInnerElement(getComponentsUtils().getResponseFormat(allResourceCategories.right().value()));
                 } else {
                     addCategories(resource, category, subcategory, allResourceCategories, responseWrapper);
                 }
@@ -572,65 +477,57 @@ public class CrudExternalServlet extends AbstractValidationsServlet {
             log.debug("Exception occured in addCategories: {}", e.getMessage(), e);
             responseWrapper.setInnerElement(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR));
         }
-
     }
 
     private void addCategories(Resource resource, String category, String subcategory,
-            Either<List<CategoryDefinition>, ActionStatus> allResourceCategories,
-            Wrapper<ResponseFormat> responseWrapper) {
+                               Either<List<CategoryDefinition>, ActionStatus> allResourceCategories, Wrapper<ResponseFormat> responseWrapper) {
         Optional<CategoryDefinition> optionalCategory =
-                // Stream of all the categories
-                allResourceCategories.left().value().stream()
-                        // filter in only relevant category
-                        .filter(e -> e.getName().equals(category))
-                        // get the result
-                        .findAny();
+            // Stream of all the categories
+            allResourceCategories.left().value().stream()
+                // filter in only relevant category
+                .filter(e -> e.getName().equals(category))
+                // get the result
+                .findAny();
         if (!optionalCategory.isPresent()) {
-            responseWrapper.setInnerElement(getComponentsUtils().getResponseFormat(
-                    ActionStatus.COMPONENT_INVALID_CATEGORY, ComponentTypeEnum.RESOURCE.getValue()));
+            responseWrapper.setInnerElement(
+                getComponentsUtils().getResponseFormat(ActionStatus.COMPONENT_INVALID_CATEGORY, ComponentTypeEnum.RESOURCE.getValue()));
         } else {
             CategoryDefinition categoryDefinition = optionalCategory.get();
-
             List<SubCategoryDefinition> subCaregories =
-                    // Stream of all sub-categories of the relevant
-                    // category
-                    categoryDefinition.getSubcategories().stream()
-                            // filter in only relevant sub-category
-                            .filter(e -> e.getName().equals(subcategory))
-                            // get the result
-                            .collect(Collectors.toList());
-
-            if( subCaregories.isEmpty() ){
-                responseWrapper.setInnerElement(getComponentsUtils().getResponseFormat(
-                        ActionStatus.COMPONENT_INVALID_SUBCATEGORY, ComponentTypeEnum.RESOURCE.getValue()));
-            }
-            else{
+                // Stream of all sub-categories of the relevant
+
+                // category
+                categoryDefinition.getSubcategories().stream()
+                    // filter in only relevant sub-category
+                    .filter(e -> e.getName().equals(subcategory))
+                    // get the result
+                    .collect(Collectors.toList());
+            if (subCaregories.isEmpty()) {
+                responseWrapper.setInnerElement(
+                    getComponentsUtils().getResponseFormat(ActionStatus.COMPONENT_INVALID_SUBCATEGORY, ComponentTypeEnum.RESOURCE.getValue()));
+            } else {
                 categoryDefinition.setSubcategories(subCaregories);
                 resource.setCategories(Arrays.asList(categoryDefinition));
             }
-
         }
     }
 
     private Wrapper<ResponseFormat> runValidations(final String assetType) {
         Wrapper<ResponseFormat> responseWrapper = new Wrapper<>();
-
         // Validate X-ECOMP-InstanceID Header
         if (responseWrapper.isEmpty()) {
             String instanceId = request.getHeader(Constants.X_ECOMP_INSTANCE_ID_HEADER);
-            validateXECOMPInstanceIDHeader(instanceId,responseWrapper);
+            validateXECOMPInstanceIDHeader(instanceId, responseWrapper);
         }
         // Validate USER_ID Header
         if (responseWrapper.isEmpty()) {
-            validateHttpCspUserIdHeader(request.getHeader(Constants.USER_ID_HEADER),responseWrapper);
+            validateHttpCspUserIdHeader(request.getHeader(Constants.USER_ID_HEADER), responseWrapper);
         }
         // Validate assetType
-        if (responseWrapper.isEmpty()
-                && !AssetTypeEnum.RESOURCES.getValue().equals(assetType)
-                && !AssetTypeEnum.SERVICES.getValue().equals(assetType)) {
-                responseWrapper.setInnerElement(getComponentsUtils().getResponseFormat(ActionStatus.RESTRICTED_OPERATION));
+        if (responseWrapper.isEmpty() && !AssetTypeEnum.RESOURCES.getValue().equals(assetType) && !AssetTypeEnum.SERVICES.getValue()
+            .equals(assetType)) {
+            responseWrapper.setInnerElement(getComponentsUtils().getResponseFormat(ActionStatus.RESTRICTED_OPERATION));
         }
-
         return responseWrapper;
     }
 
@@ -643,5 +540,4 @@ public class CrudExternalServlet extends AbstractValidationsServlet {
             return Either.right(error);
         }
     }
-
 }
index 121460c..f93e99e 100644 (file)
@@ -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.
@@ -17,7 +17,6 @@
  * limitations under the License.
  * ============LICENSE_END=========================================================
  */
-
 package org.openecomp.sdc.be.externalapi.servlet;
 
 import fj.data.Either;
@@ -25,19 +24,8 @@ import io.swagger.v3.oas.annotations.servers.Server;
 import io.swagger.v3.oas.annotations.servers.Servers;
 import io.swagger.v3.oas.annotations.tags.Tag;
 import io.swagger.v3.oas.annotations.tags.Tags;
-import org.openecomp.sdc.be.components.impl.ExternalRefsBusinessLogic;
-import org.openecomp.sdc.be.components.impl.aaf.AafPermission;
-import org.openecomp.sdc.be.components.impl.aaf.PermissionAllowed;
-import org.openecomp.sdc.be.dao.api.ActionStatus;
-import org.openecomp.sdc.be.datatypes.enums.ComponentTypeEnum;
-import org.openecomp.sdc.be.dto.ExternalRefDTO;
-import org.openecomp.sdc.be.impl.ComponentsUtils;
-import org.openecomp.sdc.be.servlets.BeGenericServlet;
-import org.openecomp.sdc.be.user.UserBusinessLogic;
-import org.openecomp.sdc.common.datastructure.Wrapper;
-import org.openecomp.sdc.common.log.wrappers.Logger;
-import org.springframework.stereotype.Controller;
-
+import java.util.List;
+import java.util.Map;
 import javax.inject.Inject;
 import javax.ws.rs.Consumes;
 import javax.ws.rs.DELETE;
@@ -51,8 +39,18 @@ import javax.ws.rs.Produces;
 import javax.ws.rs.WebApplicationException;
 import javax.ws.rs.core.MediaType;
 import javax.ws.rs.core.Response;
-import java.util.List;
-import java.util.Map;
+import org.openecomp.sdc.be.components.impl.ExternalRefsBusinessLogic;
+import org.openecomp.sdc.be.components.impl.aaf.AafPermission;
+import org.openecomp.sdc.be.components.impl.aaf.PermissionAllowed;
+import org.openecomp.sdc.be.dao.api.ActionStatus;
+import org.openecomp.sdc.be.datatypes.enums.ComponentTypeEnum;
+import org.openecomp.sdc.be.dto.ExternalRefDTO;
+import org.openecomp.sdc.be.impl.ComponentsUtils;
+import org.openecomp.sdc.be.servlets.BeGenericServlet;
+import org.openecomp.sdc.be.user.UserBusinessLogic;
+import org.openecomp.sdc.common.datastructure.Wrapper;
+import org.openecomp.sdc.common.log.wrappers.Logger;
+import org.springframework.stereotype.Controller;
 
 @Path("/v1/catalog")
 @Tags({@Tag(name = "SDC External APIs")})
@@ -64,9 +62,8 @@ public class ExternalRefsServlet extends BeGenericServlet {
     private final ExternalRefsBusinessLogic businessLogic;
 
     @Inject
-    public ExternalRefsServlet(UserBusinessLogic userBusinessLogic,
-        ComponentsUtils componentsUtils,
-        ExternalRefsBusinessLogic externalRefsBusinessLogic) {
+    public ExternalRefsServlet(UserBusinessLogic userBusinessLogic, ComponentsUtils componentsUtils,
+                               ExternalRefsBusinessLogic externalRefsBusinessLogic) {
         super(userBusinessLogic, componentsUtils);
         this.businessLogic = externalRefsBusinessLogic;
     }
@@ -75,22 +72,18 @@ public class ExternalRefsServlet extends BeGenericServlet {
     @Path("/{assetType}/{uuid}/version/{version}/resourceInstances/{componentInstanceName}/externalReferences/{objectType}")
     @Produces(MediaType.APPLICATION_JSON)
     @PermissionAllowed({AafPermission.PermNames.READ_VALUE})
-    public Response getComponentInstanceExternalRef(
-            @PathParam("assetType") String assetType,
-            @PathParam("uuid") String uuid,
-            @PathParam("version") String version,
-            @PathParam("componentInstanceName") String componentInstanceName,
-            @PathParam("objectType") String objectType, @HeaderParam("USER_ID") String userId, @HeaderParam("X-ECOMP-InstanceID") String xEcompInstanceId) {
-
+    public Response getComponentInstanceExternalRef(@PathParam("assetType") String assetType, @PathParam("uuid") String uuid,
+                                                    @PathParam("version") String version,
+                                                    @PathParam("componentInstanceName") String componentInstanceName,
+                                                    @PathParam("objectType") String objectType, @HeaderParam("USER_ID") String userId,
+                                                    @HeaderParam("X-ECOMP-InstanceID") String xEcompInstanceId) {
         log.debug("GET component instance external interfaces {} {} {} {}", assetType, uuid, componentInstanceName, objectType);
-
         Response r = validateRequest(xEcompInstanceId);
-        if (r != null){
+        if (r != null) {
             return r;
         }
-
         Either<List<String>, ActionStatus> refsResult = this.businessLogic.getExternalReferences(uuid, version, componentInstanceName, objectType);
-        if (refsResult.isLeft()){
+        if (refsResult.isLeft()) {
             return this.buildOkResponse(refsResult.left().value());
         } else {
             return this.buildExtRefErrorResponse(refsResult.right().value(), uuid, version, componentInstanceName, objectType, "");
@@ -101,21 +94,17 @@ public class ExternalRefsServlet extends BeGenericServlet {
     @Path("/{assetType}/{uuid}/version/{version}/externalReferences/{objectType}")
     @Produces(MediaType.APPLICATION_JSON)
     @PermissionAllowed({AafPermission.PermNames.READ_VALUE})
-    public Map<String, List<String>> getAssetExternalRefByObjectType(
-            @PathParam("assetType") String assetType,
-            @PathParam("uuid") String uuid,
-            @PathParam("version") String version,
-            @PathParam("objectType") String objectType, @HeaderParam("USER_ID") String userId, @HeaderParam("X-ECOMP-InstanceID") String xEcompInstanceId) {
-
+    public Map<String, List<String>> getAssetExternalRefByObjectType(@PathParam("assetType") String assetType, @PathParam("uuid") String uuid,
+                                                                     @PathParam("version") String version, @PathParam("objectType") String objectType,
+                                                                     @HeaderParam("USER_ID") String userId,
+                                                                     @HeaderParam("X-ECOMP-InstanceID") String xEcompInstanceId) {
         log.debug("GET asset external references {} {} {}", assetType, uuid, objectType);
-
         Response r = validateRequest(xEcompInstanceId);
-        if (r != null){
+        if (r != null) {
             throw new WebApplicationException(r);
         }
-
         Either<Map<String, List<String>>, ActionStatus> refsResult = this.businessLogic.getExternalReferences(uuid, version, objectType);
-        if (refsResult.isLeft()){
+        if (refsResult.isLeft()) {
             return refsResult.left().value();
         } else {
             throw new WebApplicationException(this.buildExtRefErrorResponse(refsResult.right().value(), uuid, version, "", objectType, ""));
@@ -127,53 +116,46 @@ public class ExternalRefsServlet extends BeGenericServlet {
     @Consumes(MediaType.APPLICATION_JSON)
     @Produces(MediaType.APPLICATION_JSON)
     @PermissionAllowed({AafPermission.PermNames.WRITE_VALUE})
-    public Response addComponentInstanceExternalRef(
-            @PathParam("assetType") String assetType,
-            @PathParam("uuid") String uuid,
-            @PathParam("componentInstanceName") String componentInstanceName,
-            @PathParam("objectType") String objectType, ExternalRefDTO ref, @HeaderParam("USER_ID") String userId, @HeaderParam("X-ECOMP-InstanceID") String xEcompInstanceId) {
-
+    public Response addComponentInstanceExternalRef(@PathParam("assetType") String assetType, @PathParam("uuid") String uuid,
+                                                    @PathParam("componentInstanceName") String componentInstanceName,
+                                                    @PathParam("objectType") String objectType, ExternalRefDTO ref,
+                                                    @HeaderParam("USER_ID") String userId,
+                                                    @HeaderParam("X-ECOMP-InstanceID") String xEcompInstanceId) {
         log.debug("POST component instance external interfaces {} {} {} {} {}", assetType, uuid, componentInstanceName, objectType, ref);
-
         Response r = validateRequest(xEcompInstanceId);
-        if (r != null){
+        if (r != null) {
             return r;
         }
-
         ComponentTypeEnum componentType = ComponentTypeEnum.findByParamName(assetType);
         String uid = this.businessLogic.fetchComponentUniqueIdByUuid(uuid, componentType);
-        Either<String, ActionStatus> addResult = this.businessLogic.addExternalReference(uid, componentType, userId, componentInstanceName, objectType, ref);
+        Either<String, ActionStatus> addResult = this.businessLogic
+            .addExternalReference(uid, componentType, userId, componentInstanceName, objectType, ref);
         if (addResult.isLeft()) {
-            return Response.status(Response.Status.CREATED)
-                    .entity(ref)
-                    .build();
+            return Response.status(Response.Status.CREATED).entity(ref).build();
         } else {
             return this.buildExtRefErrorResponse(addResult.right().value(), uuid, "", componentInstanceName, objectType, ref.getReferenceUUID());
         }
-
     }
 
     @DELETE
     @Path("/{assetType}/{uuid}/resourceInstances/{componentInstanceName}/externalReferences/{objectType}/{reference}")
     @Produces(MediaType.APPLICATION_JSON)
     @PermissionAllowed({AafPermission.PermNames.DELETE_VALUE})
-    public Response deleteComponentInstanceReference(
-            @PathParam("assetType") String assetType,
-            @PathParam("uuid") String uuid,
-            @PathParam("componentInstanceName") String componentInstanceName,
-            @PathParam("objectType") String objectType,
-            @PathParam("reference") String reference, @HeaderParam("USER_ID") String userId, @HeaderParam("X-ECOMP-InstanceID") String xEcompInstanceId) {
-
+    public Response deleteComponentInstanceReference(@PathParam("assetType") String assetType, @PathParam("uuid") String uuid,
+                                                     @PathParam("componentInstanceName") String componentInstanceName,
+                                                     @PathParam("objectType") String objectType, @PathParam("reference") String reference,
+                                                     @HeaderParam("USER_ID") String userId,
+                                                     @HeaderParam("X-ECOMP-InstanceID") String xEcompInstanceId) {
         log.debug("DELETE component instance external interfaces {} {} {} {}", assetType, uuid, componentInstanceName, objectType);
-
         Response r = validateRequest(xEcompInstanceId);
-        if (r != null){
+        if (r != null) {
             return r;
         }
         ComponentTypeEnum componentType = ComponentTypeEnum.findByParamName(assetType);
         String uid = this.businessLogic.fetchComponentUniqueIdByUuid(uuid, componentType);
-        Either<String, ActionStatus> deleteStatus = this.businessLogic.deleteExternalReference(uid, componentType, userId, componentInstanceName, objectType, reference);
-        if (deleteStatus.isLeft()){
+        Either<String, ActionStatus> deleteStatus = this.businessLogic
+            .deleteExternalReference(uid, componentType, userId, componentInstanceName, objectType, reference);
+        if (deleteStatus.isLeft()) {
             return this.buildOkResponse(new ExternalRefDTO(reference));
         } else {
             return this.buildExtRefErrorResponse(deleteStatus.right().value(), uuid, "", componentInstanceName, objectType, reference);
@@ -185,45 +167,39 @@ public class ExternalRefsServlet extends BeGenericServlet {
     @Produces(MediaType.APPLICATION_JSON)
     @Consumes(MediaType.APPLICATION_JSON)
     @PermissionAllowed({AafPermission.PermNames.WRITE_VALUE})
-    public Response updateComponentInstanceReference(
-            @PathParam("assetType") String assetType,
-            @PathParam("uuid") String uuid,
-            @PathParam("componentInstanceName") String componentInstanceName,
-            @PathParam("objectType") String objectType,
-            @PathParam("oldRefValue") String oldRefValue,
-            ExternalRefDTO newRefValueDTO, @HeaderParam("USER_ID") String userId, @HeaderParam("X-ECOMP-InstanceID") String xEcompInstanceId) {
-
+    public Response updateComponentInstanceReference(@PathParam("assetType") String assetType, @PathParam("uuid") String uuid,
+                                                     @PathParam("componentInstanceName") String componentInstanceName,
+                                                     @PathParam("objectType") String objectType, @PathParam("oldRefValue") String oldRefValue,
+                                                     ExternalRefDTO newRefValueDTO, @HeaderParam("USER_ID") String userId,
+                                                     @HeaderParam("X-ECOMP-InstanceID") String xEcompInstanceId) {
         log.debug("PUT component instance external interfaces {} {} {} {}", assetType, uuid, componentInstanceName, objectType);
-
         Response r = validateRequest(xEcompInstanceId);
-        if (r != null){
+        if (r != null) {
             return r;
         }
-
         String newRefValue = newRefValueDTO.getReferenceUUID();
         ComponentTypeEnum componentType = ComponentTypeEnum.findByParamName(assetType);
         String uid = this.businessLogic.fetchComponentUniqueIdByUuid(uuid, componentType);
-        Either<String, ActionStatus> updateResult = this.businessLogic.updateExternalReference(uid, componentType, userId, componentInstanceName, objectType, oldRefValue, newRefValue);
-        if (updateResult.isLeft()){
+        Either<String, ActionStatus> updateResult = this.businessLogic
+            .updateExternalReference(uid, componentType, userId, componentInstanceName, objectType, oldRefValue, newRefValue);
+        if (updateResult.isLeft()) {
             return this.buildOkResponse(new ExternalRefDTO(newRefValue));
         } else {
             return this.buildExtRefErrorResponse(updateResult.right().value(), uuid, "", componentInstanceName, objectType, oldRefValue);
         }
-
     }
 
     private Response validateRequest(String xEcompInstanceIdHeader) {
         Wrapper<Response> responseWrapper = new Wrapper<>();
-
         //Validate X-ECOMP_INSTANCE_ID_HEADER
-        if (xEcompInstanceIdHeader == null || xEcompInstanceIdHeader.isEmpty()){
+        if (xEcompInstanceIdHeader == null || xEcompInstanceIdHeader.isEmpty()) {
             return this.buildExtRefErrorResponse(ActionStatus.MISSING_X_ECOMP_INSTANCE_ID, "", "", "", "", "");
         }
-
         return responseWrapper.getInnerElement();
     }
 
-    private Response buildExtRefErrorResponse(ActionStatus status, String uuid, String version, String componentInstanceName, String objectType, String ref){
+    private Response buildExtRefErrorResponse(ActionStatus status, String uuid, String version, String componentInstanceName, String objectType,
+                                              String ref) {
         switch (status) {
             case RESOURCE_NOT_FOUND:
                 return buildErrorResponse(componentsUtils.getResponseFormat(status, uuid));
@@ -232,9 +208,7 @@ public class ExternalRefsServlet extends BeGenericServlet {
             case COMPONENT_INSTANCE_NOT_FOUND:
                 return buildErrorResponse(componentsUtils.getResponseFormat(status, componentInstanceName, uuid));
             case EXT_REF_ALREADY_EXIST:
-                return Response.status(Response.Status.OK)
-                        .entity(new ExternalRefDTO(ref))
-                        .build();
+                return Response.status(Response.Status.OK).entity(new ExternalRefDTO(ref)).build();
             case EXT_REF_NOT_FOUND:
                 return buildErrorResponse(componentsUtils.getResponseFormat(status, objectType + "/" + ref));
             case MISSING_X_ECOMP_INSTANCE_ID:
index f590ebd..d203415 100644 (file)
@@ -17,7 +17,6 @@
  * limitations under the License.
  * ============LICENSE_END=========================================================
  */
-
 package org.openecomp.sdc.be.externalapi.servlet;
 
 import com.fasterxml.jackson.databind.ObjectMapper;
@@ -74,19 +73,15 @@ import org.springframework.stereotype.Controller;
 @Controller
 public class ServiceActivationServlet extends AbstractValidationsServlet {
 
-    @Context
-    private HttpServletRequest request;
-
     private static final Logger log = Logger.getLogger(ServiceActivationServlet.class);
-
     private final ServiceBusinessLogic serviceBusinessLogic;
+    @Context
+    private HttpServletRequest request;
 
     @Inject
-    public ServiceActivationServlet(UserBusinessLogic userBusinessLogic,
-        ComponentInstanceBusinessLogic componentInstanceBL,
-        ComponentsUtils componentsUtils, ServletUtils servletUtils,
-        ResourceImportManager resourceImportManager,
-        ServiceBusinessLogic serviceBusinessLogic) {
+    public ServiceActivationServlet(UserBusinessLogic userBusinessLogic, ComponentInstanceBusinessLogic componentInstanceBL,
+                                    ComponentsUtils componentsUtils, ServletUtils servletUtils, ResourceImportManager resourceImportManager,
+                                    ServiceBusinessLogic serviceBusinessLogic) {
         super(userBusinessLogic, componentInstanceBL, componentsUtils, servletUtils, resourceImportManager);
         this.serviceBusinessLogic = serviceBusinessLogic;
     }
@@ -99,67 +94,43 @@ public class ServiceActivationServlet extends AbstractValidationsServlet {
     @Consumes(MediaType.APPLICATION_JSON)
     @Produces(MediaType.APPLICATION_JSON)
     @Operation(description = "activate a service", method = "POST", summary = "Activates a service", responses = {
-            @ApiResponse(responseCode = "202",
-                    description = "ECOMP component is authenticated and required service may be distributed"),
-            @ApiResponse(responseCode = "400", description = "Missing  X-ECOMP-InstanceID  HTTP header - POL5001"),
-            @ApiResponse(responseCode = "401",
-                    description = "ECOMP component  should authenticate itself  and  to  re-send  again  HTTP  request  with its Basic Authentication credentials - POL5002"),
-            @ApiResponse(responseCode = "403", description = "ECOMP component is not authorized - POL5003"),
-            @ApiResponse(responseCode = "404",
-                    description = "Error: Requested '%1' (uuid) resource was not found - SVC4063"),
-            @ApiResponse(responseCode = "405",
-                    description = "Method  Not Allowed  :  Invalid HTTP method type used ( PUT,DELETE,POST will be rejected) - POL4050"),
-            @ApiResponse(responseCode = "500",
-                    description = "The request failed either due to internal SDC problem. ECOMP Component should continue the attempts to get the needed information - POL5000"),
-            @ApiResponse(responseCode = "400",
-                    description = "Invalid field format. One of the provided fields does not comply with the field rules - SVC4126"),
-            @ApiResponse(responseCode = "400",
-                    description = "Missing request body. The post request did not contain the expected body - SVC4500"),
-            @ApiResponse(responseCode = "400",
-                    description = "The resource name is missing in the request body - SVC4062"),
-            @ApiResponse(responseCode = "409", description = "Service state is invalid for this action"),
-            @ApiResponse(responseCode = "502",
-                    description = "The server was acting as a gateway or proxy and received an invalid response from the upstream server")})
+        @ApiResponse(responseCode = "202", description = "ECOMP component is authenticated and required service may be distributed"),
+        @ApiResponse(responseCode = "400", description = "Missing  X-ECOMP-InstanceID  HTTP header - POL5001"),
+        @ApiResponse(responseCode = "401", description = "ECOMP component  should authenticate itself  and  to  re-send  again  HTTP  request  with its Basic Authentication credentials - POL5002"),
+        @ApiResponse(responseCode = "403", description = "ECOMP component is not authorized - POL5003"),
+        @ApiResponse(responseCode = "404", description = "Error: Requested '%1' (uuid) resource was not found - SVC4063"),
+        @ApiResponse(responseCode = "405", description = "Method  Not Allowed  :  Invalid HTTP method type used ( PUT,DELETE,POST will be rejected) - POL4050"),
+        @ApiResponse(responseCode = "500", description = "The request failed either due to internal SDC problem. ECOMP Component should continue the attempts to get the needed information - POL5000"),
+        @ApiResponse(responseCode = "400", description = "Invalid field format. One of the provided fields does not comply with the field rules - SVC4126"),
+        @ApiResponse(responseCode = "400", description = "Missing request body. The post request did not contain the expected body - SVC4500"),
+        @ApiResponse(responseCode = "400", description = "The resource name is missing in the request body - SVC4062"),
+        @ApiResponse(responseCode = "409", description = "Service state is invalid for this action"),
+        @ApiResponse(responseCode = "502", description = "The server was acting as a gateway or proxy and received an invalid response from the upstream server")})
     @PermissionAllowed({AafPermission.PermNames.WRITE_VALUE})
     public Response activateServiceExternal(
-            @Parameter(description = "Determines the format of the body of the request",
-                    required = true) @HeaderParam(value = Constants.CONTENT_TYPE_HEADER) String contentType,
-            @Parameter(description = "The user id",
-                    required = true) @HeaderParam(value = Constants.USER_ID_HEADER) final String userId,
-            @Parameter(description = "X-ECOMP-RequestID header",
-                    required = false) @HeaderParam(value = Constants.X_ECOMP_REQUEST_ID_HEADER) String requestId,
-            @Parameter(description = "X-ECOMP-InstanceID header", required = true) @HeaderParam(
-                    value = Constants.X_ECOMP_INSTANCE_ID_HEADER) final String instanceIdHeader,
-            @Parameter(description = "Determines the format of the body of the response",
-                    required = false) @HeaderParam(value = Constants.ACCEPT_HEADER) String accept,
-            @Parameter(description = "The username and password",
-                    required = true) @HeaderParam(value = Constants.AUTHORIZATION_HEADER) String authorization,
-            @Parameter(description = "The serviceUUid to activate",
-                    required = true) @PathParam("serviceUUID") final String serviceUUID,
-            @Parameter(description = "The operational environment on which to activate the service on",
-                    required = true) @PathParam("opEnvId") final String opEnvId,
-            String data) throws IOException {
-
+        @Parameter(description = "Determines the format of the body of the request", required = true) @HeaderParam(value = Constants.CONTENT_TYPE_HEADER) String contentType,
+        @Parameter(description = "The user id", required = true) @HeaderParam(value = Constants.USER_ID_HEADER) final String userId,
+        @Parameter(description = "X-ECOMP-RequestID header", required = false) @HeaderParam(value = Constants.X_ECOMP_REQUEST_ID_HEADER) String requestId,
+        @Parameter(description = "X-ECOMP-InstanceID header", required = true) @HeaderParam(value = Constants.X_ECOMP_INSTANCE_ID_HEADER) final String instanceIdHeader,
+        @Parameter(description = "Determines the format of the body of the response", required = false) @HeaderParam(value = Constants.ACCEPT_HEADER) String accept,
+        @Parameter(description = "The username and password", required = true) @HeaderParam(value = Constants.AUTHORIZATION_HEADER) String authorization,
+        @Parameter(description = "The serviceUUid to activate", required = true) @PathParam("serviceUUID") final String serviceUUID,
+        @Parameter(description = "The operational environment on which to activate the service on", required = true) @PathParam("opEnvId") final String opEnvId,
+        String data) throws IOException {
         init();
-
         ResponseFormat responseFormat = null;
         String requestURI = request.getRequestURI();
         String url = request.getMethod() + " " + requestURI;
         log.debug("Start handle request of {}", url);
-
         User modifier = new User();
-
         try {
-
             Wrapper<ResponseFormat> responseWrapper = validateRequestHeaders(instanceIdHeader, userId);
-
             if (responseWrapper.isEmpty()) {
                 modifier.setUserId(userId);
                 log.debug("modifier id is {}", userId);
-
                 ServiceDistributionReqInfo reqMetadata = convertJsonToActivationMetadata(data);
-                Either<String, ResponseFormat> distResponse = serviceBusinessLogic.activateServiceOnTenantEnvironment(serviceUUID, opEnvId, modifier, reqMetadata);
-
+                Either<String, ResponseFormat> distResponse = serviceBusinessLogic
+                    .activateServiceOnTenantEnvironment(serviceUUID, opEnvId, modifier, reqMetadata);
                 if (distResponse.isRight()) {
                     log.debug("failed to activate service distribution");
                     responseFormat = distResponse.right().value();
@@ -179,8 +150,8 @@ public class ServiceActivationServlet extends AbstractValidationsServlet {
             log.debug("activate distribution failed with exception", e);
             throw e;
         } finally {
-            getComponentsUtils().auditExternalActivateService(responseFormat,
-                    new DistributionData(instanceIdHeader, requestURI), requestId, serviceUUID, modifier);
+            getComponentsUtils()
+                .auditExternalActivateService(responseFormat, new DistributionData(instanceIdHeader, requestURI), requestId, serviceUUID, modifier);
         }
     }
 
@@ -208,13 +179,10 @@ public class ServiceActivationServlet extends AbstractValidationsServlet {
     @Override
     protected void validateHttpCspUserIdHeader(String header, Wrapper<ResponseFormat> responseWrapper) {
         ResponseFormat responseFormat;
-        if( StringUtils.isEmpty(header)){
+        if (StringUtils.isEmpty(header)) {
             log.debug("MissingUSER_ID");
             responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.AUTH_FAILED);
             responseWrapper.setInnerElement(responseFormat);
         }
     }
 }
-
-
-
index 6bb8356..834eb5f 100644 (file)
  */
 package org.openecomp.sdc.be.externalapi.servlet.representation;
 
+import java.util.List;
 import lombok.Getter;
 import lombok.Setter;
 import org.openecomp.sdc.be.model.RequirementCapabilityRelDef;
 
-import java.util.List;
-
 @Getter
 @Setter
 public class AbstractResourceInfo {
@@ -30,6 +29,7 @@ public class AbstractResourceInfo {
     //获得abstractResourceUniqueId
     private String abstractResourceUniqueId;
     //private String abstractResourceNormalizedName;
+
     //获得componentInstancesRelations
     private List<RequirementCapabilityRelDef> componentInstancesRelations;
 }
index 7b68ffe..5f2a811 100644 (file)
@@ -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.
@@ -17,7 +17,6 @@
  * limitations under the License.
  * ============LICENSE_END=========================================================
  */
-
 package org.openecomp.sdc.be.externalapi.servlet.representation;
 
 import lombok.Getter;
@@ -26,6 +25,7 @@ import lombok.Setter;
 @Getter
 @Setter
 public class ArtifactMetadata {
+
     private String artifactName;
     private String artifactType;
     private String artifactURL;
index b12411a..67533ca 100644 (file)
@@ -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.
  * limitations under the License.
  * ============LICENSE_END=========================================================
  */
-
 package org.openecomp.sdc.be.externalapi.servlet.representation;
 
 public abstract class AssetMetadata implements IAssetMetadata {
+
     private String uuid;
     private String invariantUUID;
     private String name;
index 078d282..f30b2d0 100644 (file)
@@ -21,9 +21,8 @@ import lombok.Setter;
 @Getter
 @Setter
 public class CopyServiceInfo {
-    private String newServiceUUid;
 
+    private String newServiceUUid;
     private String newServiceName;
-
     private String oldServiceUUid;
 }
index 319e16a..b3a7552 100644 (file)
@@ -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.
@@ -17,7 +17,6 @@
  * limitations under the License.
  * ============LICENSE_END=========================================================
  */
-
 package org.openecomp.sdc.be.externalapi.servlet.representation;
 
 public interface IAssetMetadata {
@@ -41,5 +40,4 @@ public interface IAssetMetadata {
     String getToscaModelURL();
 
     void setToscaModelURL(String toscaModelURL);
-
 }
index 90801af..536230a 100644 (file)
@@ -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.
@@ -17,7 +17,6 @@
  * limitations under the License.
  * ============LICENSE_END=========================================================
  */
-
 package org.openecomp.sdc.be.externalapi.servlet.representation;
 
 import java.util.List;
@@ -27,6 +26,7 @@ import lombok.Setter;
 @Getter
 @Setter
 public class ProductAssetMetadata extends AssetMetadata {
+
     private String lifecycleState;
     private String lastUpdaterUserId;
     private boolean active;
index 2813706..6af527e 100644 (file)
@@ -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.
@@ -17,7 +17,6 @@
  * limitations under the License.
  * ============LICENSE_END=========================================================
  */
-
 package org.openecomp.sdc.be.externalapi.servlet.representation;
 
 import lombok.AllArgsConstructor;
@@ -28,6 +27,7 @@ import lombok.Setter;
 @Setter
 @AllArgsConstructor
 public class ProductCategoryGroupMetadata {
+
     private String category;
     private String subCategory;
     private String group;
index db312e5..11c6b60 100644 (file)
@@ -18,24 +18,19 @@ package org.openecomp.sdc.be.externalapi.servlet.representation;
 import lombok.Getter;
 import lombok.Setter;
 import org.openecomp.sdc.be.model.ComponentInstance;
-import org.openecomp.sdc.be.model.RequirementCapabilityRelDef;
-
-import java.util.List;
 
 @Getter
 @Setter
 public class ReplaceVNFInfo {
+
     /*
         delete vnf param
      */
     private String serviceUniqueId;
-
     private String abstractResourceUniqueId;
-
     /*
         add vnf param
      */
     private ComponentInstance realVNFComponentInstance;
-
     //private List<RequirementCapabilityRelDef> componentInstancesRelations;
-}
+} 
index 0e50c4d..a810045 100644 (file)
@@ -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.
@@ -17,7 +17,6 @@
  * limitations under the License.
  * ============LICENSE_END=========================================================
  */
-
 package org.openecomp.sdc.be.externalapi.servlet.representation;
 
 import java.util.List;
index a75335a..80e2ec1 100644 (file)
@@ -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.
@@ -17,7 +17,6 @@
  * limitations under the License.
  * ============LICENSE_END=========================================================
  */
-
 package org.openecomp.sdc.be.externalapi.servlet.representation;
 
 import lombok.Getter;
@@ -26,6 +25,7 @@ import lombok.Setter;
 @Getter
 @Setter
 public class ResourceAssetMetadata extends AssetMetadata {
+
     private String category;
     private String subCategory;
     private String resourceType;
index da2a9ec..a219e33 100644 (file)
@@ -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.
@@ -17,7 +17,6 @@
  * limitations under the License.
  * ============LICENSE_END=========================================================
  */
-
 package org.openecomp.sdc.be.externalapi.servlet.representation;
 
 import java.util.List;
@@ -27,6 +26,7 @@ import lombok.Setter;
 @Getter
 @Setter
 public class ResourceInstanceMetadata {
+
     private String resourceInstanceName;
     private String resourceName;
     private String resourceInvariantUUID;
index cc4e398..1610ece 100644 (file)
@@ -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.
@@ -17,7 +17,6 @@
  * limitations under the License.
  * ============LICENSE_END=========================================================
  */
-
 package org.openecomp.sdc.be.externalapi.servlet.representation;
 
 import java.util.List;
@@ -27,6 +26,7 @@ import lombok.Setter;
 @Getter
 @Setter
 public class ServiceAssetDetailedMetadata extends ServiceAssetMetadata {
+
     private String lastUpdaterFullName;
     private List<ResourceInstanceMetadata> resources;
     private List<ArtifactMetadata> artifacts;
index 3308343..ee3978c 100644 (file)
@@ -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.
@@ -17,7 +17,6 @@
  * limitations under the License.
  * ============LICENSE_END=========================================================
  */
-
 package org.openecomp.sdc.be.externalapi.servlet.representation;
 
 import lombok.Getter;
@@ -26,6 +25,7 @@ import lombok.Setter;
 @Getter
 @Setter
 public class ServiceAssetMetadata extends AssetMetadata {
+
     private String category;
     private String lifecycleState;
     private String lastUpdaterUserId;
index 0450251..3abc621 100644 (file)
@@ -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.
@@ -17,7 +17,6 @@
  * limitations under the License.
  * ============LICENSE_END=========================================================
  */
-
 package org.openecomp.sdc.be.externalapi.servlet.representation;
 
 /**
@@ -29,6 +28,7 @@ public class ServiceDistributionReqInfo {
 
     public ServiceDistributionReqInfo() {
     }
+
     public ServiceDistributionReqInfo(String workloadContext) {
         this.workloadContext = workloadContext;
     }
index 1ba33ad..725fd3c 100644 (file)
@@ -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.
@@ -17,7 +17,6 @@
  * limitations under the License.
  * ============LICENSE_END=========================================================
  */
-
 package org.openecomp.sdc.be.externalapi.servlet.representation;
 
 import lombok.AllArgsConstructor;
@@ -33,5 +32,6 @@ import lombok.Setter;
 @NoArgsConstructor
 @AllArgsConstructor
 public class ServiceDistributionRespInfo {
+
     private String distributionId;
 }
index 7836fcc..8e2111c 100644 (file)
  * limitations under the License.
  * ============LICENSE_END=========================================================
  */
-
 package org.openecomp.sdc.be.facade.operations;
 
+import java.util.Arrays;
+import java.util.List;
 import org.openecomp.sdc.be.catalog.api.IComponentMessage;
 import org.openecomp.sdc.be.catalog.api.IStatus;
 import org.openecomp.sdc.be.catalog.enums.ChangeTypeEnum;
@@ -33,51 +34,42 @@ import org.openecomp.sdc.be.model.Component;
 import org.openecomp.sdc.be.model.Resource;
 import org.openecomp.sdc.common.log.wrappers.Logger;
 
-import java.util.Arrays;
-import java.util.List;
-
-
 @org.springframework.stereotype.Component
 public class CatalogOperation {
-    
-    private static final Logger log = Logger.getLogger(CatalogOperation.class); 
-    
+
+    private static final Logger log = Logger.getLogger(CatalogOperation.class);
     private static final List<ResourceTypeEnum> EXCLUDE_TYPES = Arrays.asList(ResourceTypeEnum.VFCMT, ResourceTypeEnum.Configuration);
-    
     private final DmaapProducer msProducer;
-    
-    public CatalogOperation(DmaapProducer msProducer){
+
+    public CatalogOperation(DmaapProducer msProducer) {
         this.msProducer = msProducer;
     }
-    
-    public ActionStatus updateCatalog(ChangeTypeEnum changeTypeEnum, Component component){
+
+    public ActionStatus updateCatalog(ChangeTypeEnum changeTypeEnum, Component component) {
         ActionStatus result = ActionStatus.OK;
-       try{
-            if(isNeedToUpdateCatalog(component)){
-                IComponentMessage message = new ComponentMessage(component, changeTypeEnum, CatalogUpdateTimestamp.buildDummyCatalogUpdateTimestamp());
+        try {
+            if (isNeedToUpdateCatalog(component)) {
+                IComponentMessage message = new ComponentMessage(component, changeTypeEnum,
+                    CatalogUpdateTimestamp.buildDummyCatalogUpdateTimestamp());
                 IStatus status = msProducer.pushMessage(message);
                 result = FacadeOperationUtils.convertStatusToActionStatus(status);
             }
-           
-       }catch(Exception e){
-           log.debug("updateCatalog - failed to updateCatalog and send notification {}", e.getMessage());
-           return ActionStatus.OK;
-       }
+        } catch (Exception e) {
+            log.debug("updateCatalog - failed to updateCatalog and send notification {}", e.getMessage());
+            return ActionStatus.OK;
+        }
         return result;
     }
-    
-    private boolean isNeedToUpdateCatalog(Component component) {
-          boolean isUpdateCatalog = true;
-             if(component.getComponentType() == ComponentTypeEnum.RESOURCE){
-                 return ((Resource)component).isAbstract() || EXCLUDE_TYPES.contains(((Resource)component).getResourceType())? false : true;
-               
-              }
-            return isUpdateCatalog;
-     }
 
+    private boolean isNeedToUpdateCatalog(Component component) {
+        boolean isUpdateCatalog = true;
+        if (component.getComponentType() == ComponentTypeEnum.RESOURCE) {
+            return ((Resource) component).isAbstract() || EXCLUDE_TYPES.contains(((Resource) component).getResourceType()) ? false : true;
+        }
+        return isUpdateCatalog;
+    }
 
     public DmaapProducer getMsProducer() {
         return msProducer;
     }
-    
 }
index 0cc4a1c..aab98ed 100644 (file)
@@ -17,7 +17,6 @@
  * limitations under the License.
  * ============LICENSE_END=========================================================
  */
-
 package org.openecomp.sdc.be.facade.operations;
 
 import org.openecomp.sdc.be.catalog.api.IStatus;
@@ -26,14 +25,15 @@ import org.openecomp.sdc.be.dao.api.ActionStatus;
 import org.openecomp.sdc.common.log.wrappers.Logger;
 
 public class FacadeOperationUtils {
-    private static final Logger log = Logger.getLogger(CatalogOperation.class); 
-    
+
+    private static final Logger log = Logger.getLogger(CatalogOperation.class);
+
     private FacadeOperationUtils() {
     }
 
     public static ActionStatus convertStatusToActionStatus(IStatus status) {
         ActionStatus result = ActionStatus.OK;
-        if (status.getResultStatus() != ResultStatusEnum.SUCCESS){
+        if (status.getResultStatus() != ResultStatusEnum.SUCCESS) {
             log.debug("updateCatalog - failed to  send notification {}", status);
         }
         return result;
index fb30826..4f444c6 100644 (file)
@@ -17,7 +17,6 @@
  * limitations under the License.
  * ============LICENSE_END=========================================================
  */
-
 package org.openecomp.sdc.be.facade.operations;
 
 import org.openecomp.sdc.be.catalog.api.IStatus;
@@ -31,29 +30,27 @@ import org.springframework.stereotype.Component;
 
 @Component
 public class UserOperation {
+
     private static final Logger log = Logger.getLogger(UserOperation.class);
-    private final DmaapProducer msProducer; 
-    
+    private final DmaapProducer msProducer;
+
     @Autowired
-    public UserOperation(DmaapProducer msProducer){
+    public UserOperation(DmaapProducer msProducer) {
         this.msProducer = msProducer;
     }
-    
-    public ActionStatus updateUserCache(UserOperationEnum operation, String userId, String role){
-       try {
-            UserMessage message = new UserMessage(operation, userId,role);
+
+    public ActionStatus updateUserCache(UserOperationEnum operation, String userId, String role) {
+        try {
+            UserMessage message = new UserMessage(operation, userId, role);
             IStatus status = msProducer.pushMessage(message);
             return FacadeOperationUtils.convertStatusToActionStatus(status);
-           
-       } catch(Exception e) {
-           log.debug("update user cache - failed to send notification to update user cache {}", e.getMessage());
-           return ActionStatus.OK;
-       }
+        } catch (Exception e) {
+            log.debug("update user cache - failed to send notification to update user cache {}", e.getMessage());
+            return ActionStatus.OK;
+        }
     }
-    
 
     public DmaapProducer getMsProducer() {
         return msProducer;
     }
-
 }
index e12ac92..0f44f41 100644 (file)
@@ -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.
  * limitations under the License.
  * ============LICENSE_END=========================================================
  */
-
 package org.openecomp.sdc.be.filters;
 
 import com.google.gson.Gson;
 import com.google.gson.GsonBuilder;
+import java.io.IOException;
 import java.nio.charset.StandardCharsets;
 import java.util.Arrays;
 import java.util.List;
+import java.util.StringTokenizer;
+import javax.annotation.Priority;
+import javax.servlet.ServletContext;
+import javax.servlet.http.HttpServletRequest;
+import javax.ws.rs.container.ContainerRequestContext;
+import javax.ws.rs.container.ContainerRequestFilter;
+import javax.ws.rs.core.Context;
+import javax.ws.rs.core.Response;
+import javax.ws.rs.core.Response.ResponseBuilder;
+import javax.ws.rs.core.Response.Status;
 import org.apache.commons.codec.binary.Base64;
 import org.glassfish.jersey.server.ContainerRequest;
 import org.openecomp.sdc.be.config.Configuration;
@@ -40,39 +50,22 @@ import org.openecomp.sdc.common.log.wrappers.LoggerSdcAudit;
 import org.openecomp.sdc.exception.ResponseFormat;
 import org.springframework.web.context.WebApplicationContext;
 
-import javax.annotation.Priority;
-import javax.servlet.ServletContext;
-import javax.servlet.http.HttpServletRequest;
-import javax.ws.rs.container.ContainerRequestContext;
-import javax.ws.rs.container.ContainerRequestFilter;
-import javax.ws.rs.core.Context;
-import javax.ws.rs.core.Response;
-import javax.ws.rs.core.Response.ResponseBuilder;
-import javax.ws.rs.core.Response.Status;
-import java.io.IOException;
-import java.util.StringTokenizer;
-
 @Priority(10)
 public class BasicAuthenticationFilter implements ContainerRequestFilter {
 
-
-       private static LoggerSdcAudit audit = new LoggerSdcAudit(BasicAuthenticationFilter.class);
     private static final Logger log = Logger.getLogger(BasicAuthenticationFilter.class);
     private static final String COMPONENT_UTILS_FAILED = "Authentication Filter Failed to get component utils.";
     private static final ConfigurationManager configurationManager = ConfigurationManager.getConfigurationManager();
     private static final Configuration.BasicAuthConfig basicAuthConf = configurationManager.getConfiguration().getBasicAuth();
-
+    private static LoggerSdcAudit audit = new LoggerSdcAudit(BasicAuthenticationFilter.class);
+    protected Gson gson = new GsonBuilder().setPrettyPrinting().create();
     @Context
     private HttpServletRequest sr;
-
-    protected Gson gson = new GsonBuilder().setPrettyPrinting().create();
-
     private String realm = "ASDC";
 
     @Override
     public void filter(ContainerRequestContext requestContext) throws IOException {
         audit.startLog(requestContext);
-
         if (!basicAuthConf.isEnabled()) {
             return;
         }
@@ -80,7 +73,6 @@ public class BasicAuthenticationFilter implements ContainerRequestFilter {
         if (excludedUrls.contains(((ContainerRequest) requestContext).getRequestUri().getPath())) {
             return;
         }
-
         String authHeader = requestContext.getHeaderString(Constants.AUTHORIZATION_HEADER);
         if (authHeader != null) {
             StringTokenizer st = new StringTokenizer(authHeader);
@@ -103,20 +95,18 @@ public class BasicAuthenticationFilter implements ContainerRequestFilter {
             log.error("Authentication Filter Failed no authorization header");
             authRequiredError(requestContext);
         }
-
     }
 
-       private void checkUserCredentials(ContainerRequestContext requestContext, String credentials) {
+    private void checkUserCredentials(ContainerRequestContext requestContext, String credentials) {
         int p = credentials.indexOf(':');
         if (p != -1) {
             String userName = credentials.substring(0, p).trim();
             String password = credentials.substring(p + 1).trim();
-
             if (!userName.equals(basicAuthConf.getUserName()) || !password.equals(basicAuthConf.getUserPass())) {
                 log.error("Authentication Failed. Invalid userName or password");
                 authInvalidPasswordError(requestContext, userName);
             }
-          authSuccessful(requestContext, userName);
+            authSuccessful(requestContext, userName);
         } else {
             log.error("Authentication Filter Failed Couldn't retrieve authentication, no basic authentication.");
             authInvalidHeaderError(requestContext);
@@ -128,9 +118,7 @@ public class BasicAuthenticationFilter implements ContainerRequestFilter {
         if (componentUtils == null) {
             abortWith(requestContext, COMPONENT_UTILS_FAILED, Response.status(Status.INTERNAL_SERVER_ERROR).build());
         } else {
-            componentUtils
-                .auditAuthEvent(requestContext.getUriInfo().getPath(), userName, AuthStatus.AUTH_SUCCESS.toString(),
-                    realm);
+            componentUtils.auditAuthEvent(requestContext.getUriInfo().getPath(), userName, AuthStatus.AUTH_SUCCESS.toString(), realm);
         }
     }
 
@@ -139,8 +127,7 @@ public class BasicAuthenticationFilter implements ContainerRequestFilter {
         if (componentUtils == null) {
             abortWith(requestContext, COMPONENT_UTILS_FAILED, Response.status(Status.INTERNAL_SERVER_ERROR).build());
         } else {
-            componentUtils.auditAuthEvent(requestContext.getUriInfo().getPath(), userName,
-                AuthStatus.AUTH_FAILED_INVALID_PASSWORD.toString(), realm);
+            componentUtils.auditAuthEvent(requestContext.getUriInfo().getPath(), userName, AuthStatus.AUTH_FAILED_INVALID_PASSWORD.toString(), realm);
             ResponseFormat responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.AUTH_FAILED);
             abortWith(requestContext, responseFormat.getFormattedMessage(), buildErrorResponse(responseFormat, false));
         }
@@ -149,53 +136,50 @@ public class BasicAuthenticationFilter implements ContainerRequestFilter {
     private void authInvalidHeaderError(ContainerRequestContext requestContext) {
         ComponentsUtils componentUtils = getComponentsUtils();
         if (componentUtils == null) {
-                       abortWith(requestContext, COMPONENT_UTILS_FAILED, Response.status(Status.INTERNAL_SERVER_ERROR).build());
+            abortWith(requestContext, COMPONENT_UTILS_FAILED, Response.status(Status.INTERNAL_SERVER_ERROR).build());
         }
-        getComponentsUtils().auditAuthEvent(requestContext.getUriInfo().getPath(), "", AuthStatus.AUTH_FAILED_INVALID_AUTHENTICATION_HEADER.toString(), realm);
+        getComponentsUtils()
+            .auditAuthEvent(requestContext.getUriInfo().getPath(), "", AuthStatus.AUTH_FAILED_INVALID_AUTHENTICATION_HEADER.toString(), realm);
         ResponseFormat responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.AUTH_FAILED_INVALIDE_HEADER);
-               abortWith(requestContext, responseFormat.getFormattedMessage(), buildErrorResponse(responseFormat, false));
+        abortWith(requestContext, responseFormat.getFormattedMessage(), buildErrorResponse(responseFormat, false));
     }
 
     private void authRequiredError(ContainerRequestContext requestContext) {
         ComponentsUtils componentUtils = getComponentsUtils();
         if (componentUtils == null) {
-                       abortWith(requestContext, COMPONENT_UTILS_FAILED, Response.status(Status.INTERNAL_SERVER_ERROR).build());
+            abortWith(requestContext, COMPONENT_UTILS_FAILED, Response.status(Status.INTERNAL_SERVER_ERROR).build());
         }
         getComponentsUtils().auditAuthEvent(requestContext.getUriInfo().getPath(), "", AuthStatus.AUTH_REQUIRED.toString(), realm);
         ResponseFormat responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.AUTH_REQUIRED);
-               abortWith(requestContext, responseFormat.getFormattedMessage(), buildErrorResponse(responseFormat, true));
+        abortWith(requestContext, responseFormat.getFormattedMessage(), buildErrorResponse(responseFormat, true));
     }
 
     private ComponentsUtils getComponentsUtils() {
         ServletContext context = sr.getSession().getServletContext();
-        WebAppContextWrapper webApplicationContextWrapper = (WebAppContextWrapper) context.getAttribute(Constants.WEB_APPLICATION_CONTEXT_WRAPPER_ATTR);
+        WebAppContextWrapper webApplicationContextWrapper = (WebAppContextWrapper) context
+            .getAttribute(Constants.WEB_APPLICATION_CONTEXT_WRAPPER_ATTR);
         WebApplicationContext webApplicationContext = webApplicationContextWrapper.getWebAppContext(context);
         return webApplicationContext.getBean(ComponentsUtils.class);
     }
 
-    public enum AuthStatus {
-        AUTH_REQUIRED, AUTH_FAILED_USER_NOT_FOUND, AUTH_FAILED_INVALID_PASSWORD, AUTH_FAILED_INVALID_AUTHENTICATION_HEADER, AUTH_SUCCESS
-    }
-
     protected Response buildErrorResponse(ResponseFormat requestErrorWrapper, boolean addWwwAuthenticationHeader) {
         ResponseBuilder responseBuilder = Response.status(requestErrorWrapper.getStatus());
         if (addWwwAuthenticationHeader) {
             responseBuilder = responseBuilder.header("WWW-Authenticate", "Basic realm=\"" + realm + "\"");
         }
-               return responseBuilder.entity(gson.toJson(requestErrorWrapper.getRequestError())).build();
+        return responseBuilder.entity(gson.toJson(requestErrorWrapper.getRequestError())).build();
     }
 
-       private void abortWith(ContainerRequestContext requestContext, String message, Response response) {
-
-               audit.logEntry(sr.getRemoteAddr(),
-                               requestContext,
+    private void abortWith(ContainerRequestContext requestContext, String message, Response response) {
+        audit.logEntry(sr.getRemoteAddr(), requestContext,
 //                             response.getStatusInfo(),
-                               LogLevel.ERROR,
-                               Severity.WARNING,
-                               message, null);
+            LogLevel.ERROR, Severity.WARNING, message, null);
+        log.error(message);
+        audit.clearMyData();
+        requestContext.abortWith(response);
+    }
 
-               log.error(message);
-               audit.clearMyData();
-               requestContext.abortWith(response);
-       }
+    public enum AuthStatus {
+        AUTH_REQUIRED, AUTH_FAILED_USER_NOT_FOUND, AUTH_FAILED_INVALID_PASSWORD, AUTH_FAILED_INVALID_AUTHENTICATION_HEADER, AUTH_SUCCESS
+    }
 }
index 49b9fbf..7edd162 100644 (file)
  * limitations under the License.
  * ============LICENSE_END=========================================================
  */
-
 package org.openecomp.sdc.be.filters;
 
+import java.io.IOException;
+import java.util.function.Supplier;
+import javax.annotation.Priority;
+import javax.servlet.FilterChain;
+import javax.servlet.FilterConfig;
+import javax.servlet.ServletContext;
+import javax.servlet.ServletException;
+import javax.servlet.ServletRequest;
+import javax.servlet.ServletResponse;
+import javax.servlet.http.HttpServletRequest;
 import org.onap.aaf.cadi.Access;
 import org.onap.aaf.cadi.PropAccess;
 import org.onap.aaf.cadi.config.Config;
@@ -34,24 +43,12 @@ import org.openecomp.sdc.common.log.wrappers.Logger;
 import org.openecomp.sdc.common.util.ThreadLocalsHolder;
 import org.springframework.web.context.WebApplicationContext;
 
-import javax.annotation.Priority;
-import javax.servlet.FilterChain;
-import javax.servlet.FilterConfig;
-import javax.servlet.ServletContext;
-import javax.servlet.ServletException;
-import javax.servlet.ServletRequest;
-import javax.servlet.ServletResponse;
-import javax.servlet.http.HttpServletRequest;
-import java.io.IOException;
-import java.util.function.Supplier;
-
 @Priority(2)
 public class BeCadiServletFilter extends CadiFilter {
 
     private static final Logger log = Logger.getLogger(BeCadiServletFilter.class);
-    private ConfigurationManager configurationManager = ConfigurationManager.getConfigurationManager();
     private static final String BE_CADI_SERVICE_FILTER = "BeCadiServletFilter: ";
-
+    private ConfigurationManager configurationManager = ConfigurationManager.getConfigurationManager();
 
     public BeCadiServletFilter() {
         super();
@@ -70,7 +67,6 @@ public class BeCadiServletFilter extends CadiFilter {
         log.debug(BE_CADI_SERVICE_FILTER);
     }
 
-
     /**
      * Use this to pass in a PreContructed CADI Filter, but with initializing... let Servlet do it
      *
@@ -80,7 +76,6 @@ public class BeCadiServletFilter extends CadiFilter {
      * @throws ServletException
      */
     public BeCadiServletFilter(boolean init, PropAccess access, Object... moreTafLurs) throws ServletException {
-
         super(init, access, moreTafLurs);
         log.debug(BE_CADI_SERVICE_FILTER);
     }
@@ -88,7 +83,7 @@ public class BeCadiServletFilter extends CadiFilter {
     private void checkIfNullProperty(String key, String value) {
         /* When value is null, so not defined in application.properties
            set nothing in System properties */
-        if (value != null) {
+        if (value != null) { 
             /* Ensure that any properties already defined in System.prop by JVM params
                 won't be overwritten by Spring application.properties values */
             System.setProperty(key, System.getProperty(key, value));
@@ -97,26 +92,21 @@ public class BeCadiServletFilter extends CadiFilter {
 
     @Override
     public void init(FilterConfig filterConfig) throws ServletException {
-
         // set some properties in System so that Cadi filter will find its config
+
         // The JVM values set will always overwrite the Spring ones.
         CadiFilterParams cadiFilterParams = configurationManager.getConfiguration().getCadiFilterParams();
         checkIfNullProperty(Config.HOSTNAME, cadiFilterParams.getHostname());
         log.debug("BeCadiServletFilter: HOSTNAME", cadiFilterParams.getHostname());
-
         checkIfNullProperty(Config.CADI_KEYFILE, cadiFilterParams.getCadi_keyfile());
         checkIfNullProperty(Config.CADI_LOGLEVEL, cadiFilterParams.getCadi_loglevel());
-
-
         checkIfNullProperty(Config.CADI_LATITUDE, cadiFilterParams.getAFT_LATITUDE());
         checkIfNullProperty(Config.CADI_LONGITUDE, cadiFilterParams.getAFT_LONGITUDE());
-
         checkIfNullProperty(Config.AAF_URL, cadiFilterParams.getAaf_url());
         //checkIfNullProperty(Config.AAF_LOCATE_URL, cadiFilterParams.getAafLocateUrl());
         checkIfNullProperty(Config.AAF_APPID, cadiFilterParams.getAaf_id());
         checkIfNullProperty(Config.AAF_APPPASS, cadiFilterParams.getAaf_password());
         checkIfNullProperty(Config.AAF_ENV, cadiFilterParams.getAFT_ENVIRONMENT());
-
         checkIfNullProperty(Config.CADI_X509_ISSUERS, cadiFilterParams.getCadiX509Issuers());
         checkIfNullProperty(Config.CADI_TRUSTSTORE, cadiFilterParams.getCadi_truststore());
         checkIfNullProperty(Config.CADI_TRUSTSTORE_PASSWORD, cadiFilterParams.getCadi_truststore_password());
@@ -129,10 +119,8 @@ public class BeCadiServletFilter extends CadiFilter {
         }
     }
 
-
     @Override
     public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
-
         if (ThreadLocalsHolder.isExternalRequest() && isNeedAuth()) {
             log.debug("doFilter: {}", request.getContentType());
             HttpServletRequest hreq = (HttpServletRequest) request;
@@ -150,31 +138,14 @@ public class BeCadiServletFilter extends CadiFilter {
         return configurationManager.getConfiguration().getAafAuthNeeded();
     }
 
-
     ThreadLocalUtils getThreadLocalUtils(ServletContext context) {
         return getClassFromWebAppContext(context, () -> ThreadLocalUtils.class);
     }
 
     <T> T getClassFromWebAppContext(ServletContext context, Supplier<Class<T>> businessLogicClassGen) {
-        WebAppContextWrapper webApplicationContextWrapper = (WebAppContextWrapper) context.getAttribute(Constants.WEB_APPLICATION_CONTEXT_WRAPPER_ATTR);
+        WebAppContextWrapper webApplicationContextWrapper = (WebAppContextWrapper) context
+            .getAttribute(Constants.WEB_APPLICATION_CONTEXT_WRAPPER_ATTR);
         WebApplicationContext webApplicationContext = webApplicationContextWrapper.getWebAppContext(context);
         return webApplicationContext.getBean(businessLogicClassGen.get());
     }
-
-
 }
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
index de8969a..e40dfe4 100644 (file)
  * limitations under the License.
  * ============LICENSE_END=========================================================
  */
-
 package org.openecomp.sdc.be.filters;
 
+import java.io.IOException;
+import javax.servlet.FilterChain;
+import javax.servlet.ServletException;
+import javax.servlet.ServletRequest;
+import javax.servlet.ServletResponse;
 import org.onap.sdc.security.PortalClient;
 import org.onap.sdc.security.filters.RestrictionAccessFilter;
 import org.openecomp.sdc.common.log.wrappers.Logger;
 import org.openecomp.sdc.common.util.ThreadLocalsHolder;
 import org.springframework.stereotype.Component;
 
-import javax.servlet.FilterChain;
-import javax.servlet.ServletException;
-import javax.servlet.ServletRequest;
-import javax.servlet.ServletResponse;
-import java.io.IOException;
-
 @Component("beRestrictionAccessFilter")
 public class BeRestrictionAccessFilter extends RestrictionAccessFilter {
 
     private static final Logger log = Logger.getLogger(RestrictionAccessFilter.class.getName());
 
-    public BeRestrictionAccessFilter(FilterConfiguration configuration, ThreadLocalUtils threadLocalUtils,
-                       PortalClient portalClient) {
+    public BeRestrictionAccessFilter(FilterConfiguration configuration, ThreadLocalUtils threadLocalUtils, PortalClient portalClient) {
         super(configuration, threadLocalUtils, portalClient);
     }
 
     @Override
-    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
+    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain)
+        throws IOException, ServletException {
         if (ThreadLocalsHolder.isInternalRequest()) {
             super.doFilter(servletRequest, servletResponse, filterChain);
         } else {
index c559751..ea1df86 100644 (file)
  * limitations under the License.
  * ============LICENSE_END=========================================================
  */
-
 package org.openecomp.sdc.be.filters;
 
 import com.google.gson.GsonBuilder;
+import java.io.IOException;
+import javax.annotation.Priority;
+import javax.servlet.ServletContext;
+import javax.servlet.http.HttpServletRequest;
+import javax.ws.rs.container.ContainerRequestContext;
+import javax.ws.rs.container.ContainerResponseContext;
+import javax.ws.rs.core.Context;
+import javax.ws.rs.core.Response;
+import javax.ws.rs.ext.Provider;
 import org.onap.logging.filter.base.AuditLogContainerFilter;
 import org.onap.logging.ref.slf4j.ONAPLogConstants;
 import org.openecomp.sdc.be.config.BeEcompErrorManager;
@@ -39,23 +47,13 @@ import org.openecomp.sdc.exception.ResponseFormat;
 import org.slf4j.MDC;
 import org.springframework.web.context.WebApplicationContext;
 
-import javax.annotation.Priority;
-import javax.servlet.ServletContext;
-import javax.servlet.http.HttpServletRequest;
-import javax.ws.rs.container.ContainerRequestContext;
-import javax.ws.rs.container.ContainerResponseContext;
-import javax.ws.rs.core.Context;
-import javax.ws.rs.core.Response;
-import javax.ws.rs.ext.Provider;
-import java.io.IOException;
-
 @Provider
 @Priority(1)
 public class BeServletFilter extends AuditLogContainerFilter {
 
+    private static final Logger log = Logger.getLogger(BeServletFilter.class);
     @Context
     private HttpServletRequest sr;
-    private static final Logger log = Logger.getLogger(BeServletFilter.class);
 
     @Override
     public void filter(ContainerRequestContext requestContext) {
@@ -63,7 +61,9 @@ public class BeServletFilter extends AuditLogContainerFilter {
             try {
                 super.filter(requestContext);
                 // In case of 405 response code, this function is not entered, then
+
                 // we'll process
+
                 // the MDC fields and UUID during the response
                 ThreadLocalsHolder.setMdcProcessed(true);
                 // Timing HTTP request
@@ -95,16 +95,14 @@ public class BeServletFilter extends AuditLogContainerFilter {
                     ResponseFormat responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.NOT_ALLOWED);
                     responseContext.setEntity(new GsonBuilder().setPrettyPrinting().create().toJson(responseFormat.getRequestError()));
                 }
-
                 if (ThreadLocalsHolder.isMdcProcessed()) {
                     // filter() was executed during request - this is the regular
+
                     // flow
                     responseContext.getHeaders().add(Constants.X_ECOMP_REQUEST_ID_HEADER, ThreadLocalsHolder.getUuid());
                 }
                 writeToJanusGraph(responseContext);
-
                 outHttpResponse(responseContext);
-
             } catch (Exception e) {
                 BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Error during request filter");
                 log.debug("Error during response filter: {} ", e);
@@ -121,9 +119,8 @@ public class BeServletFilter extends AuditLogContainerFilter {
         HealingJanusGraphDao janusGraphDao = getJanusGraphDao();
         if (janusGraphDao != null) {
             int status = responseContext.getStatus();
-            if (status == Response.Status.OK.getStatusCode() ||
-                    status == Response.Status.CREATED.getStatusCode() ||
-                    status == Response.Status.NO_CONTENT.getStatusCode()) {
+            if (status == Response.Status.OK.getStatusCode() || status == Response.Status.CREATED.getStatusCode()
+                || status == Response.Status.NO_CONTENT.getStatusCode()) {
                 janusGraphDao.commit();
                 log.debug("Doing commit from filter");
             } else {
@@ -137,26 +134,24 @@ public class BeServletFilter extends AuditLogContainerFilter {
         // UserId for logging
         String userId = requestContext.getHeaderString(Constants.USER_ID_HEADER);
         MDC.put("userId", userId);
-
         String serviceInstanceID = requestContext.getHeaderString(Constants.X_ECOMP_SERVICE_ID_HEADER);
         MDC.put(ILogConfiguration.MDC_SERVICE_INSTANCE_ID, serviceInstanceID);
-
         MDC.put("remoteAddr", sr.getRemoteAddr());
         MDC.put("localAddr", sr.getLocalAddr());
     }
 
     private ComponentsUtils getComponentsUtils() {
         ServletContext context = this.sr.getSession().getServletContext();
-
-        WebAppContextWrapper webApplicationContextWrapper = (WebAppContextWrapper) context.getAttribute(Constants.WEB_APPLICATION_CONTEXT_WRAPPER_ATTR);
+        WebAppContextWrapper webApplicationContextWrapper = (WebAppContextWrapper) context
+            .getAttribute(Constants.WEB_APPLICATION_CONTEXT_WRAPPER_ATTR);
         WebApplicationContext webApplicationContext = webApplicationContextWrapper.getWebAppContext(context);
         return webApplicationContext.getBean(ComponentsUtils.class);
     }
 
     private HealingJanusGraphDao getJanusGraphDao() {
         ServletContext context = this.sr.getSession().getServletContext();
-
-        WebAppContextWrapper webApplicationContextWrapper = (WebAppContextWrapper) context.getAttribute(Constants.WEB_APPLICATION_CONTEXT_WRAPPER_ATTR);
+        WebAppContextWrapper webApplicationContextWrapper = (WebAppContextWrapper) context
+            .getAttribute(Constants.WEB_APPLICATION_CONTEXT_WRAPPER_ATTR);
         WebApplicationContext webApplicationContext = webApplicationContextWrapper.getWebAppContext(context);
         return webApplicationContext.getBean(HealingJanusGraphDao.class);
     }
index 5ccbb26..fe881b3 100644 (file)
@@ -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.
  * limitations under the License.
  * ============LICENSE_END=========================================================
  */
-
 package org.openecomp.sdc.be.filters;
 
 import com.google.gson.Gson;
 import com.google.gson.GsonBuilder;
+import java.io.IOException;
+import java.util.ArrayList;
+import java.util.List;
+import javax.annotation.Priority;
+import javax.servlet.ServletContext;
+import javax.servlet.http.HttpServletRequest;
+import javax.ws.rs.container.ContainerRequestContext;
+import javax.ws.rs.container.ContainerRequestFilter;
+import javax.ws.rs.core.Context;
+import javax.ws.rs.core.Response;
+import javax.ws.rs.core.Response.ResponseBuilder;
+import javax.ws.rs.core.Response.Status;
 import org.onap.logging.ref.slf4j.ONAPLogConstants;
 import org.openecomp.sdc.be.components.health.HealthCheckBusinessLogic;
 import org.openecomp.sdc.be.dao.api.ActionStatus;
@@ -38,45 +49,27 @@ import org.openecomp.sdc.exception.ResponseFormat;
 import org.slf4j.MarkerFactory;
 import org.springframework.web.context.WebApplicationContext;
 
-import javax.annotation.Priority;
-import javax.servlet.ServletContext;
-import javax.servlet.http.HttpServletRequest;
-import javax.ws.rs.container.ContainerRequestContext;
-import javax.ws.rs.container.ContainerRequestFilter;
-import javax.ws.rs.core.Context;
-import javax.ws.rs.core.Response;
-import javax.ws.rs.core.Response.ResponseBuilder;
-import javax.ws.rs.core.Response.Status;
-import java.io.IOException;
-import java.util.ArrayList;
-import java.util.List;
-
 @Priority(11)
 public class ComponentsAvailabilityFilter implements ContainerRequestFilter {
 
-       private static LoggerSdcAudit audit = new LoggerSdcAudit(ComponentsAvailabilityFilter.class);
-
+    private static final Logger log = Logger.getLogger(ComponentsAvailabilityFilter.class);
+    private static LoggerSdcAudit audit = new LoggerSdcAudit(ComponentsAvailabilityFilter.class);
     @Context
     protected HttpServletRequest sr;
     protected Gson gson = new GsonBuilder().setPrettyPrinting().create();
-    private static final Logger log = Logger.getLogger(ComponentsAvailabilityFilter.class);
 
     @Override
     public void filter(ContainerRequestContext requestContext) throws IOException {
-
-               audit.startLog(requestContext);
-
+        audit.startLog(requestContext);
         String requestUrl = requestContext.getUriInfo().getPath();
         if (!"healthCheck".equals(requestUrl)) {
             List<HealthCheckInfo> beHealthCheckInfos = getBeHealthCheckInfos(this.sr.getSession().getServletContext());
             ActionStatus status = getAggregateBeStatus(beHealthCheckInfos);
-
             if (!status.equals(ActionStatus.OK)) {
                 log.error("Components Availability Filter Failed - ES/Cassandra is DOWN");
                 availabilityError(requestContext);
             }
         }
-
     }
 
     protected ActionStatus getAggregateBeStatus(List<HealthCheckInfo> beHealthCheckInfos) {
@@ -91,7 +84,6 @@ public class ComponentsAvailabilityFilter implements ContainerRequestFilter {
     }
 
     protected List<HealthCheckInfo> getBeHealthCheckInfos(ServletContext servletContext) {
-
         List<HealthCheckInfo> healthCheckInfos = new ArrayList<>();
         HealthCheckBusinessLogic healthCheckBusinessLogic = getHealthCheckBL(servletContext);
         healthCheckInfos.add(healthCheckBusinessLogic.getJanusGraphHealthCheck());
@@ -100,7 +92,8 @@ public class ComponentsAvailabilityFilter implements ContainerRequestFilter {
 
     protected ComponentsUtils getComponentsUtils() {
         ServletContext context = sr.getSession().getServletContext();
-        WebAppContextWrapper webApplicationContextWrapper = (WebAppContextWrapper) context.getAttribute(Constants.WEB_APPLICATION_CONTEXT_WRAPPER_ATTR);
+        WebAppContextWrapper webApplicationContextWrapper = (WebAppContextWrapper) context
+            .getAttribute(Constants.WEB_APPLICATION_CONTEXT_WRAPPER_ATTR);
         WebApplicationContext webApplicationContext = webApplicationContextWrapper.getWebAppContext(context);
         return webApplicationContext.getBean(ComponentsUtils.class);
     }
@@ -108,34 +101,27 @@ public class ComponentsAvailabilityFilter implements ContainerRequestFilter {
     protected void availabilityError(ContainerRequestContext requestContext) {
         ComponentsUtils componentUtils = getComponentsUtils();
         if (componentUtils == null) {
-                       String message = "Components Availability Filter Failed to get component utils.";
-                       abortWith(requestContext, message, Response.status(Status.INTERNAL_SERVER_ERROR).build());
+            String message = "Components Availability Filter Failed to get component utils.";
+            abortWith(requestContext, message, Response.status(Status.INTERNAL_SERVER_ERROR).build());
         }
         ResponseFormat responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR);
         ResponseBuilder responseBuilder = Response.status(responseFormat.getStatus());
         Response response = responseBuilder.entity(gson.toJson(responseFormat.getRequestError())).build();
-               abortWith(requestContext, responseFormat.getRequestError().toString(), response);
+        abortWith(requestContext, responseFormat.getRequestError().toString(), response);
     }
 
     private HealthCheckBusinessLogic getHealthCheckBL(ServletContext context) {
-        WebAppContextWrapper webApplicationContextWrapper = (WebAppContextWrapper) context.getAttribute(Constants.WEB_APPLICATION_CONTEXT_WRAPPER_ATTR);
+        WebAppContextWrapper webApplicationContextWrapper = (WebAppContextWrapper) context
+            .getAttribute(Constants.WEB_APPLICATION_CONTEXT_WRAPPER_ATTR);
         WebApplicationContext webApplicationContext = webApplicationContextWrapper.getWebAppContext(context);
         return webApplicationContext.getBean(HealthCheckBusinessLogic.class);
     }
 
-
-       private void abortWith(ContainerRequestContext requestContext, String message, Response response) {
-
-               audit.logExit(sr.getRemoteAddr(),
-                               requestContext,
-                               response.getStatusInfo(),
-                               LogLevel.ERROR,
-                               Severity.OK,
-                               message,
-                MarkerFactory.getMarker(ONAPLogConstants.Markers.EXIT.getName()));
-
-               log.error(message);
-               audit.clearMyData();
-               requestContext.abortWith(response);
-       }
+    private void abortWith(ContainerRequestContext requestContext, String message, Response response) {
+        audit.logExit(sr.getRemoteAddr(), requestContext, response.getStatusInfo(), LogLevel.ERROR, Severity.OK, message,
+            MarkerFactory.getMarker(ONAPLogConstants.Markers.EXIT.getName()));
+        log.error(message);
+        audit.clearMyData();
+        requestContext.abortWith(response);
+    }
 }
index 7bd9c46..70a6775 100644 (file)
  * limitations under the License.
  * ============LICENSE_END=========================================================
  */
-
 package org.openecomp.sdc.be.filters;
 
+import java.util.List;
 import org.onap.sdc.security.ISessionValidationFilterConfiguration;
 import org.openecomp.sdc.be.config.Configuration;
 
-import java.util.List;
-
 public class FilterConfiguration implements ISessionValidationFilterConfiguration {
 
     protected Configuration config;
index 9b9fd6d..c5f0881 100644 (file)
  * limitations under the License.
  * ============LICENSE_END=========================================================
  */
-
 package org.openecomp.sdc.be.filters;
 
-import org.apache.http.HttpStatus;
-import org.openecomp.sdc.be.components.impl.exceptions.ComponentException;
-import org.openecomp.sdc.be.config.Configuration;
-import org.openecomp.sdc.be.servlets.exception.ComponentExceptionMapper;
-import org.openecomp.sdc.common.api.FilterDecisionEnum;
-import org.openecomp.sdc.common.log.wrappers.Logger;
-import org.openecomp.sdc.common.util.ThreadLocalsHolder;
-import org.springframework.beans.factory.annotation.Autowired;
-import org.springframework.stereotype.Component;
-
+import java.io.IOException;
+import java.util.List;
+import java.util.stream.Stream;
 import javax.servlet.Filter;
 import javax.servlet.FilterChain;
 import javax.servlet.FilterConfig;
@@ -39,23 +31,27 @@ import javax.servlet.ServletResponse;
 import javax.servlet.http.HttpServletRequest;
 import javax.servlet.http.HttpServletResponse;
 import javax.ws.rs.WebApplicationException;
-import java.io.IOException;
-import java.util.List;
-import java.util.stream.Stream;
+import org.apache.http.HttpStatus;
+import org.openecomp.sdc.be.components.impl.exceptions.ComponentException;
+import org.openecomp.sdc.be.config.Configuration;
+import org.openecomp.sdc.be.servlets.exception.ComponentExceptionMapper;
+import org.openecomp.sdc.common.api.FilterDecisionEnum;
+import org.openecomp.sdc.common.log.wrappers.Logger;
+import org.openecomp.sdc.common.util.ThreadLocalsHolder;
+import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.stereotype.Component;
 
 @Component("gatewayFilter")
 public class GatewayFilter implements Filter {
 
+    private static final Logger log = Logger.getLogger(BeServletFilter.class);
     private Configuration.CookieConfig authCookieConf;
     private Configuration config;
-    private static final Logger log = Logger.getLogger(BeServletFilter.class);
-
     @Autowired
     private ThreadLocalUtils threadLocalUtils;
     @Autowired
     private ComponentExceptionMapper componentExceptionMapper;
 
-
     public GatewayFilter(org.openecomp.sdc.be.config.Configuration configuration) {
         this.authCookieConf = configuration.getAuthCookie();
     }
@@ -66,7 +62,6 @@ public class GatewayFilter implements Filter {
 
     @Override
     public void doFilter(ServletRequest req, ServletResponse res, FilterChain filterChain) throws IOException, ServletException {
-
         HttpServletRequest httpRequest = (HttpServletRequest) req;
         HttpServletResponse httpResponse = (HttpServletResponse) res;
         try {
@@ -77,12 +72,10 @@ public class GatewayFilter implements Filter {
             }
         } catch (ComponentException ce) {
             componentExceptionMapper.writeToResponse(ce, httpResponse);
-
         } catch (WebApplicationException we) {
             httpResponse.setStatus(we.getResponse().getStatus());
             setDefaultHttpParams(httpResponse);
             httpResponse.getWriter().write(we.getMessage());
-
         } catch (Exception ex) {
             httpResponse.setStatus(HttpStatus.SC_INTERNAL_SERVER_ERROR);
             setDefaultHttpParams(httpResponse);
@@ -106,10 +99,10 @@ public class GatewayFilter implements Filter {
     }
 
     private Boolean isConsumerBusinessLogic() {
-       return config.getConsumerBusinessLogic();
+        return config.getConsumerBusinessLogic();
     }
+
     @Override
     public void destroy() {
-
     }
 }
index 2ed10dc..7bceebe 100644 (file)
@@ -17,7 +17,6 @@
  * limitations under the License.
  * ============LICENSE_END=========================================================
  */
-
 package org.openecomp.sdc.be.filters;
 
 import org.onap.sdc.security.IPortalConfiguration;
@@ -32,11 +31,16 @@ public class PortalConfiguration implements IPortalConfiguration {
     private String uebKey;
 
     public PortalConfiguration() throws org.onap.portalsdk.core.onboarding.exception.CipherUtilException {
-        this.portalUser = org.onap.portalsdk.core.onboarding.util.PortalApiProperties.getProperty(org.onap.sdc.security.PortalClient.PortalPropertiesEnum.USER.value());
-        this.portalPassword = org.onap.portalsdk.core.onboarding.util.PortalApiProperties.getProperty(PortalClient.PortalPropertiesEnum.PASSWORD.value());
-        this.portalAppName = org.onap.portalsdk.core.onboarding.util.PortalApiProperties.getProperty(PortalClient.PortalPropertiesEnum.APP_NAME.value());
-        this.ecompPortalRestURL = org.onap.portalsdk.core.onboarding.util.PortalApiProperties.getProperty(org.onap.sdc.security.PortalClient.PortalPropertiesEnum.ECOMP_REST_URL.value());
-        this.uebKey = org.onap.portalsdk.core.onboarding.util.PortalApiProperties.getProperty(org.onap.sdc.security.PortalClient.PortalPropertiesEnum.UEB_APP_KEY.value());
+        this.portalUser = org.onap.portalsdk.core.onboarding.util.PortalApiProperties
+            .getProperty(org.onap.sdc.security.PortalClient.PortalPropertiesEnum.USER.value());
+        this.portalPassword = org.onap.portalsdk.core.onboarding.util.PortalApiProperties
+            .getProperty(PortalClient.PortalPropertiesEnum.PASSWORD.value());
+        this.portalAppName = org.onap.portalsdk.core.onboarding.util.PortalApiProperties
+            .getProperty(PortalClient.PortalPropertiesEnum.APP_NAME.value());
+        this.ecompPortalRestURL = org.onap.portalsdk.core.onboarding.util.PortalApiProperties
+            .getProperty(org.onap.sdc.security.PortalClient.PortalPropertiesEnum.ECOMP_REST_URL.value());
+        this.uebKey = org.onap.portalsdk.core.onboarding.util.PortalApiProperties
+            .getProperty(org.onap.sdc.security.PortalClient.PortalPropertiesEnum.UEB_APP_KEY.value());
     }
 
     @Override
@@ -133,4 +137,4 @@ public class PortalConfiguration implements IPortalConfiguration {
     public String getExtReqReadTimeout() {
         return null;
     }
-}
\ No newline at end of file
+}
index 4fc576b..faf33de 100644 (file)
  * limitations under the License.
  * ============LICENSE_END=========================================================
  */
-
 package org.openecomp.sdc.be.filters;
 
+import java.io.IOException;
+import java.util.Arrays;
+import java.util.List;
+import java.util.Set;
+import javax.servlet.Filter;
+import javax.servlet.FilterChain;
+import javax.servlet.FilterConfig;
+import javax.servlet.ServletException;
+import javax.servlet.ServletRequest;
+import javax.servlet.ServletResponse;
+import javax.servlet.http.HttpServletResponse;
 import org.apache.commons.collections.CollectionUtils;
 import org.openecomp.sdc.be.components.impl.exceptions.ByActionStatusComponentException;
 import org.openecomp.sdc.be.components.impl.exceptions.ComponentException;
@@ -33,18 +43,6 @@ import org.openecomp.sdc.common.util.ThreadLocalsHolder;
 import org.springframework.beans.factory.annotation.Autowired;
 import org.springframework.stereotype.Component;
 
-import javax.servlet.Filter;
-import javax.servlet.FilterChain;
-import javax.servlet.FilterConfig;
-import javax.servlet.ServletException;
-import javax.servlet.ServletRequest;
-import javax.servlet.ServletResponse;
-import javax.servlet.http.HttpServletResponse;
-import java.io.IOException;
-import java.util.Arrays;
-import java.util.List;
-import java.util.Set;
-
 @Component("reqValidationFilter")
 public class ReqValidationFilter implements Filter {
 
@@ -53,18 +51,17 @@ public class ReqValidationFilter implements Filter {
     public ComponentExceptionMapper componentExceptionMapper;
 
     @Override
-    public void init(FilterConfig filterConfig){
-
+    public void init(FilterConfig filterConfig) {
     }
 
     @Override
-    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
+    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain)
+        throws IOException, ServletException {
         HttpServletResponse httpResponse = (HttpServletResponse) servletResponse;
         try {
             log.debug("Validating User roles - filter");
             List<String> validRoles = Arrays.asList(UserRoleEnum.ADMIN.getName(), UserRoleEnum.DESIGNER.getName());
             UserContext userContext = ThreadLocalsHolder.getUserContext();
-
             if (userContext != null && CollectionUtils.isNotEmpty(userContext.getUserRoles())) {
                 Set<String> userRoles = userContext.getUserRoles();
                 if (!userRoles.stream().anyMatch(role -> validRoles.contains(role))) {
@@ -80,6 +77,5 @@ public class ReqValidationFilter implements Filter {
 
     @Override
     public void destroy() {
-
     }
 }
index 3df33c5..d895b69 100644 (file)
  * limitations under the License.
  * ============LICENSE_END=========================================================
  */
-
 package org.openecomp.sdc.be.filters;
 
+import java.util.Arrays;
+import java.util.HashSet;
+import java.util.Set;
+import javax.servlet.http.HttpServletRequest;
 import org.onap.sdc.security.AuthenticationCookie;
 import org.onap.sdc.security.IUsersThreadLocalHolder;
 import org.onap.sdc.security.PortalClient;
@@ -32,31 +35,23 @@ import org.openecomp.sdc.common.log.wrappers.Logger;
 import org.openecomp.sdc.common.util.ThreadLocalsHolder;
 import org.springframework.beans.factory.annotation.Autowired;
 
-import javax.servlet.http.HttpServletRequest;
-import java.util.Arrays;
-import java.util.HashSet;
-import java.util.Set;
-
 public class ThreadLocalUtils implements IUsersThreadLocalHolder {
 
+    private static final Logger log = Logger.getLogger(ThreadLocalUtils.class);
     @Autowired
     PortalClient portalClient;
-
     @Autowired
     UserBusinessLogic userBusinessLogic;
 
-    private static final Logger log = Logger.getLogger(ThreadLocalUtils.class);
-
     @Override
     public void setUserContext(AuthenticationCookie authenticationCookie) {
         UserContext userContext;
-        userContext = new UserContext(authenticationCookie.getUserID(), authenticationCookie.getRoles(), authenticationCookie.getFirstName(), authenticationCookie.getLastName());
+        userContext = new UserContext(authenticationCookie.getUserID(), authenticationCookie.getRoles(), authenticationCookie.getFirstName(),
+            authenticationCookie.getLastName());
         ThreadLocalsHolder.setUserContext(userContext);
     }
 
-
     protected void setUserContext(HttpServletRequest httpRequest) {
-
         String user_id = httpRequest.getHeader(Constants.USER_ID_HEADER);
         if (user_id != null) {
             String userRolesFromPortal = null;
@@ -70,7 +65,9 @@ public class ThreadLocalUtils implements IUsersThreadLocalHolder {
             }
             UserContext userContext = new UserContext(user_id, roles, null, null);
             ThreadLocalsHolder.setUserContext(userContext);
-        } else log.debug("user_id value in req header is null, userContext will not be initialized");
+        } else {
+            log.debug("user_id value in req header is null, userContext will not be initialized");
+        }
     }
 
     protected void setUserContextFromDB(HttpServletRequest httpRequest) {
@@ -78,7 +75,9 @@ public class ThreadLocalUtils implements IUsersThreadLocalHolder {
         //there are some internal request that have no user_id header e.g. healthcheck
         if (user_id != null) {
             updateUserContext(user_id);
-        } else log.debug("user_id value in req header is null, userContext will not be initialized");
+        } else {
+            log.debug("user_id value in req header is null, userContext will not be initialized");
+        }
     }
 
     private void updateUserContext(String user_id) {
@@ -87,5 +86,4 @@ public class ThreadLocalUtils implements IUsersThreadLocalHolder {
         UserContext userContext = new UserContext(user_id, roles, user.getFirstName(), user.getLastName());
         ThreadLocalsHolder.setUserContext(userContext);
     }
-
 }
index 98b3c84..8451cab 100644 (file)
@@ -19,7 +19,6 @@
  * Modifications copyright (c) 2019 Nokia
  * ================================================================================
  */
-
 package org.openecomp.sdc.be.impl;
 
 import com.fasterxml.jackson.databind.DeserializationFeature;
@@ -134,9 +133,9 @@ public class ComponentsUtils {
     private static final String CONVERT_JSON_TO_OBJECT = "convertJsonToObject";
     private static final Logger log = Logger.getLogger(ComponentsUtils.class);
     private static final String PARTNER_NAME = "UNKNOWN";
+    private static LoggerSdcAudit audit = new LoggerSdcAudit(DmaapConsumer.class);
     private final AuditingManager auditingManager;
     private final ResponseFormatManager responseFormatManager;
-    private static LoggerSdcAudit audit = new LoggerSdcAudit(DmaapConsumer.class);
 
     @Autowired
     public ComponentsUtils(AuditingManager auditingManager) {
@@ -144,6 +143,55 @@ public class ComponentsUtils {
         this.responseFormatManager = ResponseFormatManager.getInstance();
     }
 
+    public static <T> T parseJsonToObject(String data, Class<T> clazz) {
+        Type constraintType = new TypeToken<PropertyConstraint>() {
+        }.getType();
+        Gson gson = new GsonBuilder().registerTypeAdapter(constraintType, new PropertyConstraintDeserialiser()).create();
+        log.trace("convert json to object. json=\n{}", data);
+        return gson.fromJson(data, clazz);
+    }
+
+    private static Set<String> getNodesFiltersToBeDeleted(final Component component, final String componentInstanceName) {
+        return component.getComponentInstances().stream().filter(ci -> isNodeFilterUsingChangedCi(ci, componentInstanceName))
+            .map(ComponentInstance::getName).collect(Collectors.toSet());
+    }
+
+    public static Set<String> getNodesFiltersToBeDeleted(final Component component, final ComponentInstance componentInstance) {
+        return getNodesFiltersToBeDeleted(component, componentInstance.getName());
+    }
+
+    private static boolean isNodeFilterUsingChangedCi(final ComponentInstance componentInstance, final String componentInstanceName) {
+        if (CollectionUtils.isEmpty(componentInstance.getDirectives())) {
+            return false;
+        }
+        if (componentInstance.getNodeFilter() == null || componentInstance.getNodeFilter().getProperties() == null
+            || componentInstance.getNodeFilter().getProperties().getListToscaDataDefinition() == null) {
+            return false;
+        }
+        return componentInstance.getNodeFilter().getProperties().getListToscaDataDefinition().stream()
+            .anyMatch(property -> isPropertyConstraintChangedByCi(property, componentInstanceName));
+    }
+
+    private static boolean isPropertyConstraintChangedByCi(
+        final RequirementNodeFilterPropertyDataDefinition requirementNodeFilterPropertyDataDefinition, final String componentInstanceName) {
+        final List<String> constraints = requirementNodeFilterPropertyDataDefinition.getConstraints();
+        if (constraints == null) {
+            return false;
+        }
+        return constraints.stream().anyMatch(constraint -> isConstraintChangedByCi(constraint, componentInstanceName));
+    }
+
+    private static boolean isConstraintChangedByCi(final String constraint, final String componentInstanceName) {
+        final UIConstraint uiConstraint = new ConstraintConvertor().convert(constraint);
+        if (uiConstraint == null || uiConstraint.getSourceType() == null) {
+            return false;
+        }
+        if (!uiConstraint.getSourceType().equals(ConstraintConvertor.PROPERTY_CONSTRAINT)) {
+            return false;
+        }
+        return uiConstraint.getSourceName().equals(componentInstanceName);
+    }
+
     public AuditingManager getAuditingManager() {
         return auditingManager;
     }
@@ -167,26 +215,17 @@ public class ComponentsUtils {
         }
     }
 
-    public static <T> T parseJsonToObject(String data, Class<T> clazz) {
-        Type constraintType = new TypeToken<PropertyConstraint>() {}.getType();
-        Gson gson = new GsonBuilder().registerTypeAdapter(constraintType, new PropertyConstraintDeserialiser()).create();
-        log.trace("convert json to object. json=\n{}", data);
-        return gson.fromJson(data, clazz);
-    }
-
-    public <T> Either<T, ResponseFormat> convertJsonToObjectUsingObjectMapper(String data, User user, Class<T> clazz, AuditingActionEnum actionEnum, ComponentTypeEnum typeEnum) {
+    public <T> Either<T, ResponseFormat> convertJsonToObjectUsingObjectMapper(String data, User user, Class<T> clazz, AuditingActionEnum actionEnum,
+                                                                              ComponentTypeEnum typeEnum) {
         T component;
         ObjectMapper mapper = new ObjectMapper().configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
         mapper.configure(DeserializationFeature.ACCEPT_SINGLE_VALUE_AS_ARRAY, true);
         mapper.configure(DeserializationFeature.READ_UNKNOWN_ENUM_VALUES_AS_NULL, true);
-
         try {
             log.trace("convert json to object. json=\n{}", data);
-
             SimpleModule module = new SimpleModule("customDeserializationModule");
             module.addDeserializer(PropertyConstraint.class, new PropertyConstraintJacksonDeserializer());
             mapper.registerModule(module);
-
             component = mapper.readValue(data, clazz);
             if (component == null) {
                 BeEcompErrorManager.getInstance().logBeInvalidJsonInput(CONVERT_JSON_TO_OBJECT);
@@ -212,15 +251,17 @@ public class ComponentsUtils {
     }
 
     public <T> Either<List<T>, ResponseFormat> convertToResponseFormatOrNotFoundErrorToEmptyList(StorageOperationStatus storageOperationStatus) {
-        return storageOperationStatus.equals(StorageOperationStatus.NOT_FOUND) ? Either.left(Collections.emptyList()) :
-                Either.right(getResponseFormat(storageOperationStatus));
+        return storageOperationStatus.equals(StorageOperationStatus.NOT_FOUND) ? Either.left(Collections.emptyList())
+            : Either.right(getResponseFormat(storageOperationStatus));
     }
 
     /**
-     * Returns the response format of resource error with respective variables according to actionStatus. This is needed for cases where actionStatus is anonymously converted from storage operation, and the caller doesn't know what actionStatus he
-     * received. It's caller's Responsibility to fill the resource object passed to this function with needed fields.
+     * Returns the response format of resource error with respective variables according to actionStatus. This is needed for cases where actionStatus
+     * is anonymously converted from storage operation, and the caller doesn't know what actionStatus he received. It's caller's Responsibility to
+     * fill the resource object passed to this function with needed fields.
      * <p>
-     * Note that RESOURCE_IN_USE case passes hardcoded "resource" string to the error parameter. This means that if Resource object will also be used for Service, this code needs to be refactored and we should tell Resource from Service.
+     * Note that RESOURCE_IN_USE case passes hardcoded "resource" string to the error parameter. This means that if Resource object will also be used
+     * for Service, this code needs to be refactored and we should tell Resource from Service.
      *
      * @param actionStatus
      * @param resource
@@ -231,19 +272,21 @@ public class ComponentsUtils {
             return getResponseFormat(actionStatus);
         }
         ResponseFormat responseFormat;
-
         switch (actionStatus) {
             case COMPONENT_VERSION_ALREADY_EXIST:
-                responseFormat = getResponseFormat(ActionStatus.COMPONENT_VERSION_ALREADY_EXIST, ComponentTypeEnum.RESOURCE.getValue(), resource.getVersion());
+                responseFormat = getResponseFormat(ActionStatus.COMPONENT_VERSION_ALREADY_EXIST, ComponentTypeEnum.RESOURCE.getValue(),
+                    resource.getVersion());
                 break;
             case RESOURCE_NOT_FOUND:
                 responseFormat = getResponseFormat(ActionStatus.RESOURCE_NOT_FOUND, resource.getName());
                 break;
             case COMPONENT_NAME_ALREADY_EXIST:
-                responseFormat = getResponseFormat(ActionStatus.COMPONENT_NAME_ALREADY_EXIST, ComponentTypeEnum.RESOURCE.getValue(), resource.getName());
+                responseFormat = getResponseFormat(ActionStatus.COMPONENT_NAME_ALREADY_EXIST, ComponentTypeEnum.RESOURCE.getValue(),
+                    resource.getName());
                 break;
             case COMPONENT_IN_USE:
-                responseFormat = getResponseFormat(ActionStatus.COMPONENT_IN_USE, ComponentTypeEnum.RESOURCE.name().toLowerCase(), resource.getUniqueId());
+                responseFormat = getResponseFormat(ActionStatus.COMPONENT_IN_USE, ComponentTypeEnum.RESOURCE.name().toLowerCase(),
+                    resource.getUniqueId());
                 break;
             default:
                 responseFormat = getResponseFormat(actionStatus);
@@ -256,12 +299,10 @@ public class ComponentsUtils {
         if (resourceName == null) {
             return getResponseFormat(actionStatus);
         }
-
         ResponseFormat responseFormat;
         if (actionStatus == ActionStatus.RESOURCE_NOT_FOUND) {
             responseFormat = getResponseFormat(ActionStatus.RESOURCE_NOT_FOUND, resourceName);
-        }
-        else {
+        } else {
             responseFormat = getResponseFormat(actionStatus);
         }
         return responseFormat;
@@ -271,12 +312,10 @@ public class ComponentsUtils {
         if (capabilityType == null) {
             return getResponseFormat(actionStatus);
         }
-
         ResponseFormat responseFormat;
         if (actionStatus == ActionStatus.CAPABILITY_TYPE_ALREADY_EXIST) {
             responseFormat = getResponseFormat(ActionStatus.CAPABILITY_TYPE_ALREADY_EXIST, capabilityType.getType());
-        }
-        else {
+        } else {
             responseFormat = getResponseFormat(actionStatus);
         }
         return responseFormat;
@@ -286,28 +325,27 @@ public class ComponentsUtils {
         if (obj == null) {
             return getResponseFormat(actionStatus);
         }
-
         ResponseFormat responseFormat = null;
         if (actionStatus == ActionStatus.MISSING_CAPABILITY_TYPE) {
             if (obj instanceof List && org.apache.commons.collections.CollectionUtils.isNotEmpty((List) obj)) {
                 List list = (List) obj;
                 if (list.get(0) instanceof RequirementDefinition) {
                     responseFormat = getResponseFormat(ActionStatus.MISSING_CAPABILITY_TYPE, ((RequirementDefinition) list
-                            .get(0)).getName());    //Arbitray index, all we need is single object
+                        .get(0)).getName());    //Arbitray index, all we need is single object
                     return responseFormat;
                 }
             }
             log.debug("UNKNOWN TYPE : expecting obj as a non empty List<RequirmentsDefinitions>");
-        }
-        else {
+        } else {
             responseFormat = getResponseFormat(actionStatus);
         }
         return responseFormat;
     }
 
     /**
-     * Returns the response format of resource error with respective variables according to actionStatus. This is needed for cases where actionStatus is anynomously converted from storage operation, and the caller doesn't know what actionStatus he
-     * received. It's caller's responisibility to fill the passed resource object with needed fields.
+     * Returns the response format of resource error with respective variables according to actionStatus. This is needed for cases where actionStatus
+     * is anynomously converted from storage operation, and the caller doesn't know what actionStatus he received. It's caller's responisibility to
+     * fill the passed resource object with needed fields.
      *
      * @param actionStatus
      * @param user
@@ -349,7 +387,6 @@ public class ComponentsUtils {
 
     public ResponseFormat getResponseFormatByDE(ActionStatus actionStatus, String envName) {
         ResponseFormat responseFormat;
-
         switch (actionStatus) {
             case DISTRIBUTION_ENVIRONMENT_NOT_AVAILABLE:
                 responseFormat = getResponseFormat(ActionStatus.DISTRIBUTION_ENVIRONMENT_NOT_AVAILABLE, envName);
@@ -366,7 +403,6 @@ public class ComponentsUtils {
 
     public ResponseFormat getResponseFormatByArtifactId(ActionStatus actionStatus, String artifactId) {
         ResponseFormat responseFormat;
-
         switch (actionStatus) {
             case RESOURCE_NOT_FOUND:
             case ARTIFACT_NOT_FOUND:
@@ -393,8 +429,6 @@ public class ComponentsUtils {
         return responseFormat;
     }
 
-
-
     public ResponseFormat getInvalidContentErrorForConsumerAndAudit(User user, ConsumerDefinition consumer, AuditingActionEnum actionEnum) {
         ResponseFormat responseFormat = responseFormatManager.getResponseFormat(ActionStatus.INVALID_CONTENT);
         log.debug(AUDIT_BEFORE_SENDING_RESPONSE);
@@ -405,11 +439,12 @@ public class ComponentsUtils {
     private ResponseFormat getInvalidContentErrorAndAuditComponent(User user, AuditingActionEnum actionEnum, ComponentTypeEnum typeEnum) {
         ResponseFormat responseFormat = responseFormatManager.getResponseFormat(ActionStatus.INVALID_CONTENT);
         log.debug(AUDIT_BEFORE_SENDING_RESPONSE);
-        auditComponentAdmin(responseFormat, user, null,  actionEnum, typeEnum);
+        auditComponentAdmin(responseFormat, user, null, actionEnum, typeEnum);
         return responseFormat;
     }
 
-    public void auditResource(ResponseFormat responseFormat, User modifier, Resource resource, AuditingActionEnum actionEnum, ResourceVersionInfo prevResFields) {
+    public void auditResource(ResponseFormat responseFormat, User modifier, Resource resource, AuditingActionEnum actionEnum,
+                              ResourceVersionInfo prevResFields) {
         auditResource(responseFormat, modifier, resource, resource.getName(), actionEnum, prevResFields, null, null);
     }
 
@@ -429,20 +464,15 @@ public class ComponentsUtils {
                               ResourceVersionInfo prevResFields, String currentArtifactUuid, ArtifactDefinition artifactDefinition) {
         if (actionEnum != null) {
             int status = responseFormat.getStatus();
-
             String uuid = null;
             String resourceCurrVersion = null;
             String resourceCurrState = null;
             String invariantUUID = null;
             String resourceType = ComponentTypeEnum.RESOURCE.getValue();
             String toscaNodeType = null;
-
             log.trace(INSIDE_AUDITING_FOR_AUDIT_ACTION, actionEnum);
-
             String message = getMessageString(responseFormat);
-
             String artifactData = buildAuditingArtifactData(artifactDefinition);
-
             if (resource != null) {
                 resourceName = resource.getName();
                 resourceCurrVersion = resource.getVersion();
@@ -452,30 +482,15 @@ public class ComponentsUtils {
                 if (resource.getResourceType() != null) {
                     resourceType = resource.getResourceType().name();
                 }
-                invariantUUID =  resource.getInvariantUUID();
-                uuid =  resource.getUUID();
+                invariantUUID = resource.getInvariantUUID();
+                uuid = resource.getUUID();
                 toscaNodeType = resource.getToscaResourceName();
             }
-
-            AuditEventFactory factory = AuditResourceEventFactoryManager.createResourceEventFactory(
-                    actionEnum,
-                    CommonAuditData.newBuilder()
-                            .status(status)
-                            .description(message)
-                            .requestId(ThreadLocalsHolder.getUuid())
-                            .serviceInstanceId(uuid)
-                            .build(),
-                    new ResourceCommonInfo(resourceName, resourceType),
-                    prevResFields,
-                    ResourceVersionInfo.newBuilder()
-                            .artifactUuid(currentArtifactUuid)
-                            .state(resourceCurrState)
-                            .version(resourceCurrVersion)
-                            .build(),
-                    invariantUUID,
-                    modifier,
-                    artifactData, null, null, toscaNodeType);
-
+            AuditEventFactory factory = AuditResourceEventFactoryManager.createResourceEventFactory(actionEnum,
+                CommonAuditData.newBuilder().status(status).description(message).requestId(ThreadLocalsHolder.getUuid()).serviceInstanceId(uuid)
+                    .build(), new ResourceCommonInfo(resourceName, resourceType), prevResFields,
+                ResourceVersionInfo.newBuilder().artifactUuid(currentArtifactUuid).state(resourceCurrState).version(resourceCurrVersion).build(),
+                invariantUUID, modifier, artifactData, null, null, toscaNodeType);
             getAuditingManager().auditEvent(factory);
         }
     }
@@ -492,260 +507,163 @@ public class ComponentsUtils {
     public void auditDistributionDownload(ResponseFormat responseFormat, DistributionData distributionData) {
         log.trace("Inside auditing");
         int status = responseFormat.getStatus();
-
         String message = getMessageString(responseFormat);
-
         AuditDistributionDownloadEventFactory factory = new AuditDistributionDownloadEventFactory(
-                CommonAuditData.newBuilder()
-                        .status(status)
-                        .description(message)
-                        .requestId(ThreadLocalsHolder.getUuid())
-                        .build(),
-                distributionData);
+            CommonAuditData.newBuilder().status(status).description(message).requestId(ThreadLocalsHolder.getUuid()).build(), distributionData);
         getAuditingManager().auditEvent(factory);
     }
 
     public void auditExternalGetAsset(ResponseFormat responseFormat, AuditingActionEnum actionEnum, DistributionData distributionData,
                                       ResourceCommonInfo resourceCommonInfo, String requestId, String serviceInstanceId) {
         log.trace(INSIDE_AUDITING_FOR_AUDIT_ACTION, actionEnum);
-
         AuditEventFactory factory = new AuditAssetExternalApiEventFactory(actionEnum,
-                CommonAuditData.newBuilder()
-                        .status(responseFormat.getStatus())
-                        .description(getMessageString(responseFormat))
-                        .requestId(requestId)
-                        .serviceInstanceId(serviceInstanceId)
-                        .build(),
-                resourceCommonInfo, distributionData);
-
+            CommonAuditData.newBuilder().status(responseFormat.getStatus()).description(getMessageString(responseFormat)).requestId(requestId)
+                .serviceInstanceId(serviceInstanceId).build(), resourceCommonInfo, distributionData);
         getAuditingManager().auditEvent(factory);
     }
 
-    public void auditExternalGetAssetList(ResponseFormat responseFormat, AuditingActionEnum actionEnum, DistributionData distributionData, String requestId) {
+    public void auditExternalGetAssetList(ResponseFormat responseFormat, AuditingActionEnum actionEnum, DistributionData distributionData,
+                                          String requestId) {
         log.trace(INSIDE_AUDITING_FOR_AUDIT_ACTION, actionEnum);
-
         AuditEventFactory factory = new AuditAssetListExternalApiEventFactory(actionEnum,
-                CommonAuditData.newBuilder()
-                        .status(responseFormat.getStatus())
-                        .description(getMessageString(responseFormat))
-                        .requestId(requestId)
-                        .build(),
-                distributionData);
-
+            CommonAuditData.newBuilder().status(responseFormat.getStatus()).description(getMessageString(responseFormat)).requestId(requestId)
+                .build(), distributionData);
         getAuditingManager().auditEvent(factory);
     }
 
-    public void auditChangeLifecycleAction(ResponseFormat responseFormat, ComponentTypeEnum componentType, String requestId,
-                                           Component component, Component responseObject, DistributionData distributionData, User modifier) {
-
+    public void auditChangeLifecycleAction(ResponseFormat responseFormat, ComponentTypeEnum componentType, String requestId, Component component,
+                                           Component responseObject, DistributionData distributionData, User modifier) {
         String invariantUuid = "";
         String serviceInstanceId = "";
         ResourceVersionInfo currResourceVersionInfo = null;
         ResourceVersionInfo prevResourceVersionInfo = null;
         ResourceCommonInfo resourceCommonInfo = new ResourceCommonInfo(componentType.getValue());
-
         if (component != null) {
             prevResourceVersionInfo = buildResourceVersionInfoFromComponent(component);
             resourceCommonInfo.setResourceName(component.getName());
         }
-
-        if (responseObject != null){
+        if (responseObject != null) {
             currResourceVersionInfo = buildResourceVersionInfoFromComponent(responseObject);
             invariantUuid = responseObject.getInvariantUUID();
             serviceInstanceId = responseObject.getUUID();
-        }
-        else if (component != null){
+        } else if (component != null) {
             currResourceVersionInfo = buildResourceVersionInfoFromComponent(component);
             invariantUuid = component.getInvariantUUID();
             serviceInstanceId = component.getUUID();
         }
-
         if (prevResourceVersionInfo == null) {
-            prevResourceVersionInfo = ResourceVersionInfo.newBuilder()
-                    .build();
+            prevResourceVersionInfo = ResourceVersionInfo.newBuilder().build();
         }
         if (currResourceVersionInfo == null) {
-            currResourceVersionInfo = ResourceVersionInfo.newBuilder()
-                    .build();
+            currResourceVersionInfo = ResourceVersionInfo.newBuilder().build();
         }
         AuditEventFactory factory = new AuditChangeLifecycleExternalApiEventFactory(
-                CommonAuditData.newBuilder()
-                        .serviceInstanceId(serviceInstanceId)
-                        .requestId(requestId)
-                        .description(getMessageString(responseFormat))
-                        .status(responseFormat.getStatus())
-                        .build(),
-                resourceCommonInfo, distributionData,
-                prevResourceVersionInfo, currResourceVersionInfo,
-                invariantUuid, modifier);
-
+            CommonAuditData.newBuilder().serviceInstanceId(serviceInstanceId).requestId(requestId).description(getMessageString(responseFormat))
+                .status(responseFormat.getStatus()).build(), resourceCommonInfo, distributionData, prevResourceVersionInfo, currResourceVersionInfo,
+            invariantUuid, modifier);
         getAuditingManager().auditEvent(factory);
     }
 
     private ResourceVersionInfo buildResourceVersionInfoFromComponent(Component component) {
-        return ResourceVersionInfo.newBuilder()
-                .version(component.getVersion())
-                .state(component.getLifecycleState().name())
-                .build();
+        return ResourceVersionInfo.newBuilder().version(component.getVersion()).state(component.getLifecycleState().name()).build();
     }
 
-    public void auditExternalCrudApi(ResponseFormat responseFormat, AuditingActionEnum actionEnum, ResourceCommonInfo resourceCommonInfo, HttpServletRequest request,
-                                     ArtifactDefinition artifactDefinition, String artifactUuid) {
+    public void auditExternalCrudApi(ResponseFormat responseFormat, AuditingActionEnum actionEnum, ResourceCommonInfo resourceCommonInfo,
+                                     HttpServletRequest request, ArtifactDefinition artifactDefinition, String artifactUuid) {
         log.trace(INSIDE_AUDITING_FOR_AUDIT_ACTION, actionEnum);
-
         ResourceVersionInfo currResourceVersionInfo;
         User modifier = new User();
         modifier.setUserId(request.getHeader(Constants.USER_ID_HEADER));
         String artifactData = "";
         DistributionData distributionData = new DistributionData(request.getHeader(Constants.X_ECOMP_INSTANCE_ID_HEADER), request.getRequestURI());
         String requestId = request.getHeader(Constants.X_ECOMP_REQUEST_ID_HEADER);
-
-
         if (artifactDefinition == null) {
-            currResourceVersionInfo = ResourceVersionInfo.newBuilder()
-                    .artifactUuid(artifactUuid)
-                    .build();
-        }
-        else {
-            currResourceVersionInfo = ResourceVersionInfo.newBuilder()
-                    .artifactUuid(artifactDefinition.getArtifactUUID())
-                    .version(artifactDefinition.getArtifactVersion())
-                    .build();
+            currResourceVersionInfo = ResourceVersionInfo.newBuilder().artifactUuid(artifactUuid).build();
+        } else {
+            currResourceVersionInfo = ResourceVersionInfo.newBuilder().artifactUuid(artifactDefinition.getArtifactUUID())
+                .version(artifactDefinition.getArtifactVersion()).build();
             artifactData = buildAuditingArtifactData(artifactDefinition);
             modifier.setUserId(artifactDefinition.getUserIdLastUpdater());
         }
         AuditEventFactory factory = new AuditCrudExternalApiArtifactEventFactory(actionEnum,
-                CommonAuditData.newBuilder()
-                        .status(responseFormat.getStatus())
-                        .description(getMessageString(responseFormat))
-                        .requestId(requestId)
-                        .build(),
-                resourceCommonInfo, distributionData, ResourceVersionInfo.newBuilder().build(), currResourceVersionInfo,
-                null, modifier, artifactData);
-
+            CommonAuditData.newBuilder().status(responseFormat.getStatus()).description(getMessageString(responseFormat)).requestId(requestId)
+                .build(), resourceCommonInfo, distributionData, ResourceVersionInfo.newBuilder().build(), currResourceVersionInfo, null, modifier,
+            artifactData);
         getAuditingManager().auditEvent(factory);
     }
 
-    public boolean isExternalApiEvent(AuditingActionEnum auditingActionEnum){
+    public boolean isExternalApiEvent(AuditingActionEnum auditingActionEnum) {
         return auditingActionEnum != null && auditingActionEnum.getAuditingEsType().equals(AuditingTypesConstants.EXTERNAL_API_EVENT_TYPE);
     }
 
     public void auditCreateResourceExternalApi(ResponseFormat responseFormat, ResourceCommonInfo resourceCommonInfo, HttpServletRequest request,
                                                Resource resource) {
-
         String invariantUuid = null;
         String serviceInstanceId = null;
-
         User modifier = new User();
         modifier.setUserId(request.getHeader(Constants.USER_ID_HEADER));
         DistributionData distributionData = new DistributionData(request.getHeader(Constants.X_ECOMP_INSTANCE_ID_HEADER), request.getRequestURI());
         String requestId = request.getHeader(Constants.X_ECOMP_REQUEST_ID_HEADER);
-
         ResourceVersionInfo currResourceVersionInfo;
-
-        if( resource != null ){
-            currResourceVersionInfo = ResourceVersionInfo.newBuilder()
-                    .state(LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT.name())
-                    .version(ImportUtils.Constants.FIRST_NON_CERTIFIED_VERSION)
-                    .build();
+        if (resource != null) {
+            currResourceVersionInfo = ResourceVersionInfo.newBuilder().state(LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT.name())
+                .version(ImportUtils.Constants.FIRST_NON_CERTIFIED_VERSION).build();
             resourceCommonInfo.setResourceName(resource.getName());
             invariantUuid = resource.getInvariantUUID();
             serviceInstanceId = resource.getUUID();
+        } else {
+            currResourceVersionInfo = ResourceVersionInfo.newBuilder().build();
         }
-        else {
-            currResourceVersionInfo = ResourceVersionInfo.newBuilder()
-                    .build();
-        }
-
         AuditEventFactory factory = new AuditCreateResourceExternalApiEventFactory(
-                CommonAuditData.newBuilder()
-                        .status(responseFormat.getStatus())
-                        .description(getMessageString(responseFormat))
-                        .requestId(requestId)
-                        .serviceInstanceId(serviceInstanceId)
-                        .build(),
-                resourceCommonInfo, distributionData,
-                currResourceVersionInfo, invariantUuid, modifier);
-
+            CommonAuditData.newBuilder().status(responseFormat.getStatus()).description(getMessageString(responseFormat)).requestId(requestId)
+                .serviceInstanceId(serviceInstanceId).build(), resourceCommonInfo, distributionData, currResourceVersionInfo, invariantUuid,
+            modifier);
         getAuditingManager().auditEvent(factory);
     }
-    
+
     public void auditCreateServiceExternalApi(ResponseFormat responseFormat, HttpServletRequest request, Component service) {
-       
-       String invariantUuid = null;
+        String invariantUuid = null;
         String serviceInstanceId = null;
-       
-       User modifier = new User();
+        User modifier = new User();
         modifier.setUserId(request.getHeader(Constants.USER_ID_HEADER));
         DistributionData distributionData = new DistributionData(request.getHeader(Constants.X_ECOMP_INSTANCE_ID_HEADER), request.getRequestURI());
         String requestId = request.getHeader(Constants.X_ECOMP_REQUEST_ID_HEADER);
-        
-        if(null != service) {
-               invariantUuid = service.getInvariantUUID();
-               serviceInstanceId = service.getUUID();
-        }
-        
-       AuditEventFactory factory = new AuditCreateServiceExternalApiEventFactory(
-                CommonAuditData.newBuilder()
-                        .status(responseFormat.getStatus())
-                        .description(getMessageString(responseFormat))
-                        .requestId(requestId)
-                        .serviceInstanceId(serviceInstanceId)
-                        .build(),
-                        new ResourceCommonInfo(ComponentTypeEnum.SERVICE.name()), distributionData, invariantUuid, modifier);
-
+        if (null != service) {
+            invariantUuid = service.getInvariantUUID();
+            serviceInstanceId = service.getUUID();
+        }
+        AuditEventFactory factory = new AuditCreateServiceExternalApiEventFactory(
+            CommonAuditData.newBuilder().status(responseFormat.getStatus()).description(getMessageString(responseFormat)).requestId(requestId)
+                .serviceInstanceId(serviceInstanceId).build(), new ResourceCommonInfo(ComponentTypeEnum.SERVICE.name()), distributionData,
+            invariantUuid, modifier);
         getAuditingManager().auditEvent(factory);
-       
     }
 
-    public void auditExternalActivateService(ResponseFormat responseFormat, DistributionData distributionData, String requestId, String serviceInstanceUuid, User modifier) {
+    public void auditExternalActivateService(ResponseFormat responseFormat, DistributionData distributionData, String requestId,
+                                             String serviceInstanceUuid, User modifier) {
         AuditEventFactory factory = new AuditActivateServiceExternalApiEventFactory(
-                CommonAuditData.newBuilder()
-                        .serviceInstanceId(serviceInstanceUuid)
-                        .description(getMessageString(responseFormat))
-                        .status(responseFormat.getStatus())
-                        .requestId(requestId)
-                        .build(),
-                new ResourceCommonInfo(ComponentTypeEnum.SERVICE.name()), distributionData, "", modifier);
+            CommonAuditData.newBuilder().serviceInstanceId(serviceInstanceUuid).description(getMessageString(responseFormat))
+                .status(responseFormat.getStatus()).requestId(requestId).build(), new ResourceCommonInfo(ComponentTypeEnum.SERVICE.name()),
+            distributionData, "", modifier);
         getAuditingManager().auditEvent(factory);
     }
 
-    public void auditExternalDownloadArtifact(ResponseFormat responseFormat, ResourceCommonInfo resourceCommonInfo,
-                                              DistributionData distributionData, String requestId, String currArtifactUuid, String userId) {
+    public void auditExternalDownloadArtifact(ResponseFormat responseFormat, ResourceCommonInfo resourceCommonInfo, DistributionData distributionData,
+                                              String requestId, String currArtifactUuid, String userId) {
         User modifier = new User();
         modifier.setUserId(userId);
-
         AuditEventFactory factory = new AuditDownloadArtifactExternalApiEventFactory(
-                CommonAuditData.newBuilder()
-                        .description(getMessageString(responseFormat))
-                        .status(responseFormat.getStatus())
-                        .requestId(requestId)
-                        .build(),
-                resourceCommonInfo, distributionData,
-                ResourceVersionInfo.newBuilder()
-                        .artifactUuid(currArtifactUuid)
-                        .build(),
-                modifier);
+            CommonAuditData.newBuilder().description(getMessageString(responseFormat)).status(responseFormat.getStatus()).requestId(requestId)
+                .build(), resourceCommonInfo, distributionData, ResourceVersionInfo.newBuilder().artifactUuid(currArtifactUuid).build(), modifier);
         getAuditingManager().auditEvent(factory);
     }
 
     private String buildAuditingArtifactData(ArtifactDefinition artifactDefinition) {
         StringBuilder sb = new StringBuilder();
         if (artifactDefinition != null) {
-            sb.append(artifactDefinition.getArtifactGroupType().getType())
-                    .append(",")
-                    .append("'")
-                    .append(artifactDefinition.getArtifactLabel())
-                    .append("'")
-                    .append(",")
-                    .append(artifactDefinition.getArtifactType())
-                    .append(",")
-                    .append(artifactDefinition.getArtifactName())
-                    .append(",")
-                    .append(artifactDefinition.getTimeout())
-                    .append(",")
-                    .append(artifactDefinition.getEsId());
-
+            sb.append(artifactDefinition.getArtifactGroupType().getType()).append(",").append("'").append(artifactDefinition.getArtifactLabel())
+                .append("'").append(",").append(artifactDefinition.getArtifactType()).append(",").append(artifactDefinition.getArtifactName())
+                .append(",").append(artifactDefinition.getTimeout()).append(",").append(artifactDefinition.getEsId());
             sb.append(",");
             sb.append(artifactDefinition.getArtifactVersion() != null ? artifactDefinition.getArtifactVersion() : " ");
             sb.append(",");
@@ -754,27 +672,20 @@ public class ComponentsUtils {
         return sb.toString();
     }
 
-    public void auditCategory(ResponseFormat responseFormat, User modifier, String categoryName, String subCategoryName, String groupingName, AuditingActionEnum actionEnum, String componentType) {
+    public void auditCategory(ResponseFormat responseFormat, User modifier, String categoryName, String subCategoryName, String groupingName,
+                              AuditingActionEnum actionEnum, String componentType) {
         log.trace(INSIDE_AUDITING_FOR_AUDIT_ACTION, actionEnum);
-
         AuditEventFactory factory = new AuditCategoryEventFactory(actionEnum,
-                CommonAuditData.newBuilder()
-                        .description(getMessageString(responseFormat))
-                        .status(responseFormat.getStatus())
-                        .requestId(ThreadLocalsHolder.getUuid())
-                        .build(),
-                modifier, categoryName, subCategoryName, groupingName, componentType);
-
+            CommonAuditData.newBuilder().description(getMessageString(responseFormat)).status(responseFormat.getStatus())
+                .requestId(ThreadLocalsHolder.getUuid()).build(), modifier, categoryName, subCategoryName, groupingName, componentType);
         getAuditingManager().auditEvent(factory);
     }
 
     public ActionStatus convertFromStorageResponse(StorageOperationStatus storageResponse) {
-
         return convertFromStorageResponse(storageResponse, ComponentTypeEnum.RESOURCE);
     }
 
     public ActionStatus convertFromStorageResponse(StorageOperationStatus storageResponse, ComponentTypeEnum type) {
-
         ActionStatus responseEnum = ActionStatus.GENERAL_ERROR;
         if (storageResponse == null) {
             return responseEnum;
@@ -847,9 +758,9 @@ public class ComponentsUtils {
             case COMPONENT_IS_ARCHIVED:
                 responseEnum = ActionStatus.COMPONENT_IS_ARCHIVED;
                 break;
-        case DECLARED_INPUT_USED_BY_OPERATION:
-            responseEnum = ActionStatus.DECLARED_INPUT_USED_BY_OPERATION;
-            break;
+            case DECLARED_INPUT_USED_BY_OPERATION:
+                responseEnum = ActionStatus.DECLARED_INPUT_USED_BY_OPERATION;
+                break;
             default:
                 responseEnum = ActionStatus.GENERAL_ERROR;
                 break;
@@ -878,7 +789,6 @@ public class ComponentsUtils {
 
     public ActionStatus convertFromStorageResponseForCapabilityType(StorageOperationStatus storageResponse) {
         ActionStatus responseEnum;
-
         switch (storageResponse) {
             case OK:
                 responseEnum = ActionStatus.OK;
@@ -906,7 +816,6 @@ public class ComponentsUtils {
 
     public ActionStatus convertFromStorageResponseForLifecycleType(StorageOperationStatus storageResponse) {
         ActionStatus responseEnum;
-
         switch (storageResponse) {
             case OK:
                 responseEnum = ActionStatus.OK;
@@ -934,7 +843,6 @@ public class ComponentsUtils {
 
     public ActionStatus convertFromStorageResponseForResourceInstance(StorageOperationStatus storageResponse, boolean isRelation) {
         ActionStatus responseEnum;
-
         switch (storageResponse) {
             case OK:
                 responseEnum = ActionStatus.OK;
@@ -974,11 +882,9 @@ public class ComponentsUtils {
 
     public ResponseFormat getResponseFormatForResourceInstance(ActionStatus actionStatus, String serviceName, String resourceInstanceName) {
         ResponseFormat responseFormat;
-
         if (actionStatus == ActionStatus.RESOURCE_INSTANCE_NOT_FOUND) {
             responseFormat = getResponseFormat(actionStatus, resourceInstanceName);
-        }
-        else {
+        } else {
             responseFormat = getResponseFormat(actionStatus, serviceName);
         }
         return responseFormat;
@@ -988,8 +894,7 @@ public class ComponentsUtils {
         ResponseFormat responseFormat;
         if (actionStatus == ActionStatus.RESOURCE_INSTANCE_NOT_FOUND) {
             responseFormat = getResponseFormat(actionStatus, resourceInstanceName);
-        }
-        else {
+        } else {
             responseFormat = getResponseFormat(actionStatus);
         }
         return responseFormat;
@@ -997,7 +902,6 @@ public class ComponentsUtils {
 
     public ActionStatus convertFromStorageResponseForResourceInstanceProperty(StorageOperationStatus storageResponse) {
         ActionStatus responseEnum;
-
         switch (storageResponse) {
             case OK:
                 responseEnum = ActionStatus.OK;
@@ -1028,36 +932,46 @@ public class ComponentsUtils {
         return responseEnum;
     }
 
-    public void auditComponent(ResponseFormat responseFormat, User modifier, Component component, AuditingActionEnum actionEnum, ResourceCommonInfo resourceCommonInfo, ResourceVersionInfo prevComponent, String comment) {
+    public void auditComponent(ResponseFormat responseFormat, User modifier, Component component, AuditingActionEnum actionEnum,
+                               ResourceCommonInfo resourceCommonInfo, ResourceVersionInfo prevComponent, String comment) {
         auditComponent(responseFormat, modifier, component, actionEnum, resourceCommonInfo, prevComponent, null, comment, null, null);
     }
 
-    public void auditComponentAdmin(ResponseFormat responseFormat, User modifier, Component component, AuditingActionEnum actionEnum, ComponentTypeEnum typeEnum) {
-        auditComponent(responseFormat, modifier, component, actionEnum, new ResourceCommonInfo(typeEnum.getValue()), ResourceVersionInfo.newBuilder().build());
+    public void auditComponentAdmin(ResponseFormat responseFormat, User modifier, Component component, AuditingActionEnum actionEnum,
+                                    ComponentTypeEnum typeEnum) {
+        auditComponent(responseFormat, modifier, component, actionEnum, new ResourceCommonInfo(typeEnum.getValue()),
+            ResourceVersionInfo.newBuilder().build());
     }
 
-    public void auditComponentAdmin(ResponseFormat responseFormat, User modifier, Component component, AuditingActionEnum actionEnum, ComponentTypeEnum typeEnum, String comment) {
-        auditComponent(responseFormat, modifier, component, actionEnum, new ResourceCommonInfo(typeEnum.getValue()), ResourceVersionInfo.newBuilder().build(), null,
-                comment, null, null);
+    public void auditComponentAdmin(ResponseFormat responseFormat, User modifier, Component component, AuditingActionEnum actionEnum,
+                                    ComponentTypeEnum typeEnum, String comment) {
+        auditComponent(responseFormat, modifier, component, actionEnum, new ResourceCommonInfo(typeEnum.getValue()),
+            ResourceVersionInfo.newBuilder().build(), null, comment, null, null);
     }
 
-    public void auditComponentAdmin(ResponseFormat responseFormat, User modifier, Component component, AuditingActionEnum actionEnum, ComponentTypeEnum typeEnum, ResourceVersionInfo prevComponent) {
+    public void auditComponentAdmin(ResponseFormat responseFormat, User modifier, Component component, AuditingActionEnum actionEnum,
+                                    ComponentTypeEnum typeEnum, ResourceVersionInfo prevComponent) {
         auditComponent(responseFormat, modifier, component, actionEnum, new ResourceCommonInfo(typeEnum.getValue()), prevComponent);
     }
 
-    public void auditComponent(ResponseFormat responseFormat, User modifier, Component component, AuditingActionEnum actionEnum, ResourceCommonInfo resourceCommonInfo, ResourceVersionInfo prevComponent) {
+    public void auditComponent(ResponseFormat responseFormat, User modifier, Component component, AuditingActionEnum actionEnum,
+                               ResourceCommonInfo resourceCommonInfo, ResourceVersionInfo prevComponent) {
         auditComponent(responseFormat, modifier, component, actionEnum, resourceCommonInfo, prevComponent, null, null, null, null);
     }
 
-    public void auditComponent(ResponseFormat responseFormat, User modifier, AuditingActionEnum actionEnum, ResourceCommonInfo resourceCommonInfo, String comment) {
-        auditComponent(responseFormat, modifier, null, actionEnum, resourceCommonInfo, ResourceVersionInfo.newBuilder().build(), null, comment, null, null);
+    public void auditComponent(ResponseFormat responseFormat, User modifier, AuditingActionEnum actionEnum, ResourceCommonInfo resourceCommonInfo,
+                               String comment) {
+        auditComponent(responseFormat, modifier, null, actionEnum, resourceCommonInfo, ResourceVersionInfo.newBuilder().build(), null, comment, null,
+            null);
     }
 
-    public void auditComponent(ResponseFormat responseFormat, User modifier, Component component, AuditingActionEnum actionEnum, ResourceCommonInfo resourceCommonInfo, ResourceVersionInfo prevComponent, ResourceVersionInfo currComponent) {
+    public void auditComponent(ResponseFormat responseFormat, User modifier, Component component, AuditingActionEnum actionEnum,
+                               ResourceCommonInfo resourceCommonInfo, ResourceVersionInfo prevComponent, ResourceVersionInfo currComponent) {
         auditComponent(responseFormat, modifier, component, actionEnum, resourceCommonInfo, prevComponent, currComponent, null, null, null);
     }
 
-    public void auditComponent(ResponseFormat responseFormat, User modifier, Component component, AuditingActionEnum actionEnum, ResourceCommonInfo resourceCommonInfo, ResourceVersionInfo prevComponent, ResourceVersionInfo currComponent,
+    public void auditComponent(ResponseFormat responseFormat, User modifier, Component component, AuditingActionEnum actionEnum,
+                               ResourceCommonInfo resourceCommonInfo, ResourceVersionInfo prevComponent, ResourceVersionInfo currComponent,
                                String comment, ArtifactDefinition artifactDefinition, String did) {
         if (actionEnum != null) {
             String uuid = null;
@@ -1066,13 +980,10 @@ public class ComponentsUtils {
             String currArtifactUid = null;
             String currVersion = null;
             String dcurrStatus = null;
-
             log.trace(INSIDE_AUDITING_FOR_AUDIT_ACTION, actionEnum);
-
             String message = getMessageString(responseFormat);
             int status = responseFormat.getStatus();
             String artifactData = buildAuditingArtifactData(artifactDefinition);
-
             if (component != null) {
                 // fields that are filled during creation and might still be empty
                 if (component.getLifecycleState() != null) {
@@ -1095,192 +1006,117 @@ public class ComponentsUtils {
                     currVersion = currComponent.getVersion();
                 }
             }
-            AuditEventFactory factory = AuditResourceEventFactoryManager.createResourceEventFactory(
-                    actionEnum,
-                    CommonAuditData.newBuilder()
-                            .status(status)
-                            .description(message)
-                            .requestId(ThreadLocalsHolder.getUuid())
-                            .serviceInstanceId(uuid)
-                            .build(),
-                    resourceCommonInfo, prevComponent,
-                    ResourceVersionInfo.newBuilder()
-                            .artifactUuid(currArtifactUid)
-                            .state(currState)
-                            .version(currVersion)
-                            .distributionStatus(dcurrStatus)
-                            .build(),
-                    invariantUUID,
-                    modifier, artifactData, comment, did, null);
-
+            AuditEventFactory factory = AuditResourceEventFactoryManager.createResourceEventFactory(actionEnum,
+                CommonAuditData.newBuilder().status(status).description(message).requestId(ThreadLocalsHolder.getUuid()).serviceInstanceId(uuid)
+                    .build(), resourceCommonInfo, prevComponent,
+                ResourceVersionInfo.newBuilder().artifactUuid(currArtifactUid).state(currState).version(currVersion).distributionStatus(dcurrStatus)
+                    .build(), invariantUUID, modifier, artifactData, comment, did, null);
             getAuditingManager().auditEvent(factory);
         }
     }
 
-    public void auditDistributionEngine(AuditingActionEnum action, String environmentName, DistributionTopicData distributionTopicData, String status) {
+    public void auditDistributionEngine(AuditingActionEnum action, String environmentName, DistributionTopicData distributionTopicData,
+                                        String status) {
         auditDistributionEngine(action, environmentName, distributionTopicData, null, null, status);
     }
 
-
-    public void auditDistributionEngine(AuditingActionEnum action, String environmentName, DistributionTopicData distributionTopicData, String role, String apiKey, String status) {
-        AuditEventFactory factory = AuditDistributionEngineEventFactoryManager.createDistributionEngineEventFactory(action,
-                environmentName, distributionTopicData, role, apiKey, status);
+    public void auditDistributionEngine(AuditingActionEnum action, String environmentName, DistributionTopicData distributionTopicData, String role,
+                                        String apiKey, String status) {
+        AuditEventFactory factory = AuditDistributionEngineEventFactoryManager
+            .createDistributionEngineEventFactory(action, environmentName, distributionTopicData, role, apiKey, status);
         getAuditingManager().auditEvent(factory);
     }
 
-
-    public void auditEnvironmentEngine(AuditingActionEnum actionEnum, String environmentID,
-                                       String environmentType, String action, String environmentName, String tenantContext) {
-        AuditEventFactory factory = new AuditEcompOpEnvEventFactory(actionEnum, environmentID, environmentName,
-                environmentType, action, tenantContext);
+    public void auditEnvironmentEngine(AuditingActionEnum actionEnum, String environmentID, String environmentType, String action,
+                                       String environmentName, String tenantContext) {
+        AuditEventFactory factory = new AuditEcompOpEnvEventFactory(actionEnum, environmentID, environmentName, environmentType, action,
+            tenantContext);
         audit.startAuditFetchLog(PARTNER_NAME, DmaapConsumer.class.getName());
-        audit.logEntry(LogLevel.INFO, Severity.OK, null,
-                MarkerFactory.getMarker(ONAPLogConstants.Markers.ENTRY.getName()), environmentID);
+        audit.logEntry(LogLevel.INFO, Severity.OK, null, MarkerFactory.getMarker(ONAPLogConstants.Markers.ENTRY.getName()), environmentID);
         getAuditingManager().auditEvent(factory, audit);
     }
 
-    public void auditDistributionNotification(String serviceUUID, String resourceName, String resourceType, String currVersion, User modifier, String environmentName, String currState,
-                                              String topicName, String distributionId, String description, String status, String workloadContext, String tenant) {
-
+    public void auditDistributionNotification(String serviceUUID, String resourceName, String resourceType, String currVersion, User modifier,
+                                              String environmentName, String currState, String topicName, String distributionId, String description,
+                                              String status, String workloadContext, String tenant) {
         AuditEventFactory factory = new AuditDistributionNotificationEventFactory(
-                CommonAuditData.newBuilder()
-                        .serviceInstanceId(serviceUUID)
-                        .status(status)
-                        .description(description)
-                        .requestId(ThreadLocalsHolder.getUuid())
-                        .build(),
-                new ResourceCommonInfo(resourceName, resourceType),
-                ResourceVersionInfo.newBuilder()
-                        .state(currState)
-                        .version(currVersion)
-                        .build(),
-                distributionId, modifier, topicName,
-                new OperationalEnvAuditData(environmentName, workloadContext, tenant));
-
+            CommonAuditData.newBuilder().serviceInstanceId(serviceUUID).status(status).description(description)
+                .requestId(ThreadLocalsHolder.getUuid()).build(), new ResourceCommonInfo(resourceName, resourceType),
+            ResourceVersionInfo.newBuilder().state(currState).version(currVersion).build(), distributionId, modifier, topicName,
+            new OperationalEnvAuditData(environmentName, workloadContext, tenant));
         getAuditingManager().auditEvent(factory);
     }
 
     public void auditAuthEvent(String url, String user, String authStatus, String realm) {
-        AuditEventFactory factory = new AuditAuthRequestEventFactory(
-                CommonAuditData.newBuilder()
-                        .requestId(ThreadLocalsHolder.getUuid())
-                        .build(),
-                user, url, realm, authStatus);
+        AuditEventFactory factory = new AuditAuthRequestEventFactory(CommonAuditData.newBuilder().requestId(ThreadLocalsHolder.getUuid()).build(),
+            user, url, realm, authStatus);
         getAuditingManager().auditEvent(factory);
     }
 
-    public void auditDistributionStatusNotification(String distributionId, String consumerId, String topicName,
-                                                    String resourceUrl, String statusTime, String status,
-                                                    String errorReason, LoggerSdcAudit audit) {
-        AuditEventFactory factory =  new AuditDistributionStatusEventFactory(
-                CommonAuditData.newBuilder()
-                        .description(errorReason)
-                        .status(status)
-                        .requestId(distributionId)
-                        .build(),
-                new DistributionData(consumerId, resourceUrl),
-                distributionId, topicName, statusTime);
-
+    public void auditDistributionStatusNotification(String distributionId, String consumerId, String topicName, String resourceUrl, String statusTime,
+                                                    String status, String errorReason, LoggerSdcAudit audit) {
+        AuditEventFactory factory = new AuditDistributionStatusEventFactory(
+            CommonAuditData.newBuilder().description(errorReason).status(status).requestId(distributionId).build(),
+            new DistributionData(consumerId, resourceUrl), distributionId, topicName, statusTime);
         getAuditingManager().auditEvent(factory, audit);
     }
 
     public void auditGetUebCluster(String consumerId, String status, String description) {
         AuditEventFactory factory = new AuditGetUebClusterEventFactory(
-                CommonAuditData.newBuilder()
-                        .description(description)
-                        .status(status)
-                        .requestId(ThreadLocalsHolder.getUuid())
-                        .build(),
-                consumerId);
-
+            CommonAuditData.newBuilder().description(description).status(status).requestId(ThreadLocalsHolder.getUuid()).build(), consumerId);
         getAuditingManager().auditEvent(factory);
     }
 
     public void auditMissingInstanceIdAsDistributionEngineEvent(AuditingActionEnum actionEnum, String status) {
-        AuditEventFactory factory = AuditDistributionEngineEventFactoryManager.createDistributionEngineEventFactory(
-                actionEnum, "",
-                DistributionTopicData.newBuilder()
-                        .build(), null, null, status);
+        AuditEventFactory factory = AuditDistributionEngineEventFactoryManager
+            .createDistributionEngineEventFactory(actionEnum, "", DistributionTopicData.newBuilder().build(), null, null, status);
         getAuditingManager().auditEvent(factory);
     }
 
-
-    public void auditRegisterOrUnRegisterEvent(AuditingActionEnum action, String consumerId, String apiPublicKey, String envName, String status, String distributionStatus, String notifTopicName, String statusTopicName) {
+    public void auditRegisterOrUnRegisterEvent(AuditingActionEnum action, String consumerId, String apiPublicKey, String envName, String status,
+                                               String distributionStatus, String notifTopicName, String statusTopicName) {
         String appliedStatus = !StringUtils.isEmpty(status) ? status : distributionStatus;
-
         AuditEventFactory factory = new AuditRegUnregDistributionEngineEventFactory(action,
-                CommonAuditData.newBuilder()
-                        .requestId(ThreadLocalsHolder.getUuid())
-                        .status(appliedStatus)
-                        .build(),
-                DistributionTopicData.newBuilder()
-                        .statusTopic(statusTopicName)
-                        .notificationTopic(notifTopicName)
-                        .build(),
-                consumerId, apiPublicKey, envName);
-
+            CommonAuditData.newBuilder().requestId(ThreadLocalsHolder.getUuid()).status(appliedStatus).build(),
+            DistributionTopicData.newBuilder().statusTopic(statusTopicName).notificationTopic(notifTopicName).build(), consumerId, apiPublicKey,
+            envName);
         getAuditingManager().auditEvent(factory);
     }
 
-    public void auditServiceDistributionDeployed(String serviceName, String serviceVersion, String serviceUUID, String distributionId, String status, String desc, User modifier) {
-
+    public void auditServiceDistributionDeployed(String serviceName, String serviceVersion, String serviceUUID, String distributionId, String status,
+                                                 String desc, User modifier) {
         AuditEventFactory factory = new AuditDistributionDeployEventFactory(
-                CommonAuditData.newBuilder()
-                        .requestId(ThreadLocalsHolder.getUuid())
-                        .serviceInstanceId(serviceUUID)
-                        .status(status)
-                        .description(desc)
-                        .build(),
-                new ResourceCommonInfo(serviceName, "Service"),
-                distributionId,
-                modifier,
-                serviceVersion);
-
+            CommonAuditData.newBuilder().requestId(ThreadLocalsHolder.getUuid()).serviceInstanceId(serviceUUID).status(status).description(desc)
+                .build(), new ResourceCommonInfo(serviceName, "Service"), distributionId, modifier, serviceVersion);
         getAuditingManager().auditEvent(factory);
-
     }
 
-    public void auditConsumerCredentialsEvent(AuditingActionEnum actionEnum, ConsumerDefinition consumer, ResponseFormat responseFormat, User modifier) {
+    public void auditConsumerCredentialsEvent(AuditingActionEnum actionEnum, ConsumerDefinition consumer, ResponseFormat responseFormat,
+                                              User modifier) {
         AuditEventFactory factory = new AuditConsumerEventFactory(actionEnum,
-                CommonAuditData.newBuilder()
-                        .description(getMessageString(responseFormat))
-                        .status(responseFormat.getStatus())
-                        .requestId(ThreadLocalsHolder.getUuid())
-                        .build(),
-                modifier, consumer);
-
+            CommonAuditData.newBuilder().description(getMessageString(responseFormat)).status(responseFormat.getStatus())
+                .requestId(ThreadLocalsHolder.getUuid()).build(), modifier, consumer);
         getAuditingManager().auditEvent(factory);
     }
 
     public void auditGetUsersList(User user, String details, ResponseFormat responseFormat) {
-
         AuditEventFactory factory = new AuditGetUsersListEventFactory(
-                CommonAuditData.newBuilder()
-                        .description(getMessageString(responseFormat))
-                        .status(responseFormat.getStatus())
-                        .requestId(ThreadLocalsHolder.getUuid())
-                        .build(),
-                user, details);
+            CommonAuditData.newBuilder().description(getMessageString(responseFormat)).status(responseFormat.getStatus())
+                .requestId(ThreadLocalsHolder.getUuid()).build(), user, details);
         getAuditingManager().auditEvent(factory);
     }
 
-    public void auditAdminUserActionAndThrowException(AuditingActionEnum actionEnum, User modifier, User userBefore,
-                                                      User userAfter, ActionStatus status, String... params) {
+    public void auditAdminUserActionAndThrowException(AuditingActionEnum actionEnum, User modifier, User userBefore, User userAfter,
+                                                      ActionStatus status, String... params) {
         ResponseFormat responseFormat = getResponseFormat(status, params);
         auditAdminUserAction(actionEnum, modifier, userBefore, userAfter, responseFormat);
         throw new ByResponseFormatComponentException(responseFormat);
     }
 
     public void auditAdminUserAction(AuditingActionEnum actionEnum, User modifier, User userBefore, User userAfter, ResponseFormat responseFormat) {
-
         AuditEventFactory factory = new AuditUserAdminEventFactory(actionEnum,
-                CommonAuditData.newBuilder()
-                        .description(getMessageString(responseFormat))
-                        .status(responseFormat.getStatus())
-                        .requestId(ThreadLocalsHolder.getUuid())
-                        .build(),
-                modifier, userBefore, userAfter);
-
+            CommonAuditData.newBuilder().description(getMessageString(responseFormat)).status(responseFormat.getStatus())
+                .requestId(ThreadLocalsHolder.getUuid()).build(), modifier, userBefore, userAfter);
         getAuditingManager().auditEvent(factory);
     }
 
@@ -1289,26 +1125,16 @@ public class ComponentsUtils {
     }
 
     public void auditUserAccess(User user, ResponseFormat responseFormat) {
-
-        AuditEventFactory factory = new AuditUserAccessEventFactory(CommonAuditData.newBuilder()
-                .description(getMessageString(responseFormat))
-                .status(responseFormat.getStatus())
-                .requestId(ThreadLocalsHolder.getUuid())
-                .build(),
-                user);
-
+        AuditEventFactory factory = new AuditUserAccessEventFactory(
+            CommonAuditData.newBuilder().description(getMessageString(responseFormat)).status(responseFormat.getStatus())
+                .requestId(ThreadLocalsHolder.getUuid()).build(), user);
         getAuditingManager().auditEvent(factory);
     }
 
     public void auditGetCategoryHierarchy(User user, String details, ResponseFormat responseFormat) {
-
-        AuditEventFactory factory = new AuditGetCategoryHierarchyEventFactory(CommonAuditData.newBuilder()
-                .description(getMessageString(responseFormat))
-                .status(responseFormat.getStatus())
-                .requestId(ThreadLocalsHolder.getUuid())
-                .build(),
-                user, details);
-
+        AuditEventFactory factory = new AuditGetCategoryHierarchyEventFactory(
+            CommonAuditData.newBuilder().description(getMessageString(responseFormat)).status(responseFormat.getStatus())
+                .requestId(ThreadLocalsHolder.getUuid()).build(), user, details);
         getAuditingManager().auditEvent(factory);
     }
 
@@ -1317,22 +1143,24 @@ public class ComponentsUtils {
             return getResponseFormat(actionStatus);
         }
         ResponseFormat responseFormat;
-
         switch (actionStatus) {
             case COMPONENT_VERSION_ALREADY_EXIST:
                 responseFormat = getResponseFormat(ActionStatus.COMPONENT_VERSION_ALREADY_EXIST, type.getValue(), component.getVersion());
                 break;
             case RESOURCE_NOT_FOUND:
-                responseFormat = getResponseFormat(ActionStatus.RESOURCE_NOT_FOUND, component.getComponentMetadataDefinition().getMetadataDataDefinition().getName());
+                responseFormat = getResponseFormat(ActionStatus.RESOURCE_NOT_FOUND,
+                    component.getComponentMetadataDefinition().getMetadataDataDefinition().getName());
                 break;
             case COMPONENT_NAME_ALREADY_EXIST:
-                responseFormat = getResponseFormat(ActionStatus.COMPONENT_NAME_ALREADY_EXIST, type.getValue(), component.getComponentMetadataDefinition().getMetadataDataDefinition().getName());
+                responseFormat = getResponseFormat(ActionStatus.COMPONENT_NAME_ALREADY_EXIST, type.getValue(),
+                    component.getComponentMetadataDefinition().getMetadataDataDefinition().getName());
                 break;
             case COMPONENT_IN_USE:
                 responseFormat = getResponseFormat(ActionStatus.COMPONENT_IN_USE, type.name().toLowerCase(), component.getUniqueId());
                 break;
             case SERVICE_DEPLOYMENT_ARTIFACT_NOT_FOUND:
-                responseFormat = getResponseFormat(ActionStatus.SERVICE_DEPLOYMENT_ARTIFACT_NOT_FOUND, component.getComponentMetadataDefinition().getMetadataDataDefinition().getName());
+                responseFormat = getResponseFormat(ActionStatus.SERVICE_DEPLOYMENT_ARTIFACT_NOT_FOUND,
+                    component.getComponentMetadataDefinition().getMetadataDataDefinition().getName());
                 break;
             default:
                 responseFormat = getResponseFormat(actionStatus);
@@ -1347,7 +1175,6 @@ public class ComponentsUtils {
 
     public ActionStatus convertFromStorageResponseForAdditionalInformation(StorageOperationStatus storageResponse) {
         ActionStatus responseEnum;
-
         switch (storageResponse) {
             case OK:
                 responseEnum = ActionStatus.OK;
@@ -1373,7 +1200,7 @@ public class ComponentsUtils {
                 responseEnum = ActionStatus.OK;
                 break;
             case ELEMENT_NOT_FOUND:
-                if(elementType!= null && elementType == JsonPresentationFields.PROPERTY){
+                if (elementType != null && elementType == JsonPresentationFields.PROPERTY) {
                     responseEnum = ActionStatus.PROPERTY_NOT_FOUND;
                 }
                 break;
@@ -1394,20 +1221,20 @@ public class ComponentsUtils {
         return responseEnum;
     }
 
-    public ResponseFormat getResponseFormatAdditionalProperty(ActionStatus actionStatus, AdditionalInfoParameterInfo additionalInfoParameterInfo, NodeTypeEnum nodeType, AdditionalInformationEnum labelOrValue) {
-
+    public ResponseFormat getResponseFormatAdditionalProperty(ActionStatus actionStatus, AdditionalInfoParameterInfo additionalInfoParameterInfo,
+                                                              NodeTypeEnum nodeType, AdditionalInformationEnum labelOrValue) {
         if (additionalInfoParameterInfo == null) {
             additionalInfoParameterInfo = new AdditionalInfoParameterInfo();
         }
         if (labelOrValue == null) {
             labelOrValue = AdditionalInformationEnum.None;
         }
-
         switch (actionStatus) {
             case COMPONENT_NAME_ALREADY_EXIST:
                 return getResponseFormat(actionStatus, "Additional parameter", additionalInfoParameterInfo.getKey());
             case ADDITIONAL_INFORMATION_EXCEEDS_LIMIT:
-                return getResponseFormat(actionStatus, labelOrValue.name().toLowerCase(), ValidationUtils.ADDITIONAL_INFORMATION_KEY_MAX_LENGTH.toString());
+                return getResponseFormat(actionStatus, labelOrValue.name().toLowerCase(),
+                    ValidationUtils.ADDITIONAL_INFORMATION_KEY_MAX_LENGTH.toString());
             case ADDITIONAL_INFORMATION_MAX_NUMBER_REACHED:
                 return getResponseFormat(actionStatus, nodeType.name().toLowerCase());
             case ADDITIONAL_INFORMATION_EMPTY_STRING_NOT_ALLOWED:
@@ -1421,7 +1248,6 @@ public class ComponentsUtils {
             default:
                 return getResponseFormat(actionStatus);
         }
-
     }
 
     public ResponseFormat getResponseFormatAdditionalProperty(ActionStatus actionStatus) {
@@ -1430,7 +1256,6 @@ public class ComponentsUtils {
 
     public ActionStatus convertFromStorageResponseForConsumer(StorageOperationStatus storageResponse) {
         ActionStatus responseEnum;
-
         switch (storageResponse) {
             case OK:
                 responseEnum = ActionStatus.OK;
@@ -1461,7 +1286,6 @@ public class ComponentsUtils {
 
     public ActionStatus convertFromStorageResponseForGroupType(StorageOperationStatus storageResponse) {
         ActionStatus responseEnum;
-
         switch (storageResponse) {
             case OK:
                 responseEnum = ActionStatus.OK;
@@ -1489,7 +1313,6 @@ public class ComponentsUtils {
 
     public ActionStatus convertFromStorageResponseForDataType(StorageOperationStatus storageResponse) {
         ActionStatus responseEnum;
-
         switch (storageResponse) {
             case OK:
                 responseEnum = ActionStatus.OK;
@@ -1523,7 +1346,6 @@ public class ComponentsUtils {
             return getResponseFormat(actionStatus);
         }
         ResponseFormat responseFormat;
-
         switch (actionStatus) {
             case GROUP_MEMBER_EMPTY:
             case GROUP_TYPE_ALREADY_EXIST:
@@ -1534,23 +1356,19 @@ public class ComponentsUtils {
                 break;
         }
         return responseFormat;
-
     }
 
     public ResponseFormat getResponseFormatByPolicyType(ActionStatus actionStatus, PolicyTypeDefinition policyType) {
         if (policyType == null) {
             return getResponseFormat(actionStatus);
         }
-
         ResponseFormat responseFormat;
         if (actionStatus == ActionStatus.POLICY_TYPE_ALREADY_EXIST) {
             responseFormat = getResponseFormat(actionStatus, policyType.getType());
-        }
-        else {
+        } else {
             responseFormat = getResponseFormat(actionStatus);
         }
         return responseFormat;
-
     }
 
     public ResponseFormat getResponseFormatByDataType(ActionStatus actionStatus, DataTypeDefinition dataType, List<String> properties) {
@@ -1558,7 +1376,6 @@ public class ComponentsUtils {
             return getResponseFormat(actionStatus);
         }
         ResponseFormat responseFormat;
-
         switch (actionStatus) {
             case DATA_TYPE_ALREADY_EXIST:
                 responseFormat = getResponseFormat(actionStatus, dataType.getName());
@@ -1587,7 +1404,6 @@ public class ComponentsUtils {
             case DATA_TYPE_CANNOT_BE_UPDATED_BAD_REQUEST:
                 responseFormat = getResponseFormat(actionStatus, dataType.getName());
                 break;
-
             default:
                 responseFormat = getResponseFormat(actionStatus);
                 break;
@@ -1616,9 +1432,8 @@ public class ComponentsUtils {
     }
 
     public ResponseFormat getResponseFormat(ComponentException exception) {
-        return exception instanceof ByResponseFormatComponentException ?
-            getResponseFormat((ByResponseFormatComponentException) exception):
-            getResponseFormat((ByActionStatusComponentException) exception);
+        return exception instanceof ByResponseFormatComponentException ? getResponseFormat((ByResponseFormatComponentException) exception)
+            : getResponseFormat((ByActionStatusComponentException) exception);
     }
 
     public ResponseFormat getResponseFormat(ByResponseFormatComponentException exception) {
@@ -1629,10 +1444,8 @@ public class ComponentsUtils {
         return getResponseFormat(exception.getActionStatus(), exception.getParams());
     }
 
-    public ActionStatus convertFromStorageResponseForRelationshipType(
-            StorageOperationStatus storageResponse) {
+    public ActionStatus convertFromStorageResponseForRelationshipType(StorageOperationStatus storageResponse) {
         ActionStatus responseEnum;
-
         switch (storageResponse) {
             case OK:
                 responseEnum = ActionStatus.OK;
@@ -1663,93 +1476,35 @@ public class ComponentsUtils {
         return getResponseFormat(status, exception.getParams());
     }
 
-
     public List<UiLeftPaletteComponent> convertComponentToUiLeftPaletteComponentObject(List<Component> components) {
         List<UiLeftPaletteComponent> uiLeftPaletteComponents = new ArrayList<>();
-        components.forEach(c-> uiLeftPaletteComponents.add(new UiLeftPaletteComponent(c)));
+        components.forEach(c -> uiLeftPaletteComponents.add(new UiLeftPaletteComponent(c)));
         return uiLeftPaletteComponents;
     }
 
-    private static Set<String> getNodesFiltersToBeDeleted(final Component component,
-                                                         final String componentInstanceName) {
-        return component.getComponentInstances().stream()
-            .filter(ci -> isNodeFilterUsingChangedCi(ci, componentInstanceName))
-            .map(ComponentInstance::getName).collect(Collectors.toSet());
-    }
-    
-    public static Set<String> getNodesFiltersToBeDeleted(final Component component, 
-                                                         final ComponentInstance componentInstance) {
-        return getNodesFiltersToBeDeleted(component, componentInstance.getName());
-    }
-
-    private static boolean isNodeFilterUsingChangedCi(final ComponentInstance componentInstance, 
-                                                      final String componentInstanceName) {
-        if (CollectionUtils.isEmpty(componentInstance.getDirectives())) {
-            return false;
-        }
-        if (componentInstance.getNodeFilter() == null || componentInstance.getNodeFilter().getProperties() == null
-            || componentInstance.getNodeFilter().getProperties().getListToscaDataDefinition() == null) {
-            return false;
-        }
-        return componentInstance.getNodeFilter().getProperties().getListToscaDataDefinition().stream()
-            .anyMatch(property -> isPropertyConstraintChangedByCi(property, componentInstanceName));
-    }
-
-    private static boolean isPropertyConstraintChangedByCi(
-        final RequirementNodeFilterPropertyDataDefinition requirementNodeFilterPropertyDataDefinition, 
-        final String componentInstanceName) {
-        final List<String> constraints = requirementNodeFilterPropertyDataDefinition.getConstraints();
-        if (constraints == null) {
-            return false;
-        }
-        return constraints.stream().anyMatch(constraint -> isConstraintChangedByCi(constraint, componentInstanceName));
-    }
-
-    private static boolean isConstraintChangedByCi(final String constraint, 
-                                                   final String componentInstanceName) {
-        final UIConstraint uiConstraint = new ConstraintConvertor().convert(constraint);
-        if (uiConstraint == null || uiConstraint.getSourceType() == null) {
-            return false;
-        }
-        if (!uiConstraint.getSourceType().equals(ConstraintConvertor.PROPERTY_CONSTRAINT)) {
-            return false;
-        }
-        return uiConstraint.getSourceName().equals(componentInstanceName);
-    }
-
     public F<StorageOperationStatus, ResponseFormat> toResponseFormat() {
         return sos -> getResponseFormat(convertFromStorageResponse(sos));
     }
 
-
-    public Optional<UIConstraint> parseToConstraint(final String componentJson,
-                                                    final User user,
-                                                    final ComponentTypeEnum componentTypeEnum) {
-        final Either<UIConstraint, ResponseFormat> uiConstraintResponseFormatEither =
-            convertJsonToObjectUsingObjectMapper(componentJson, user, UIConstraint.class,
-                AuditingActionEnum.CREATE_RESOURCE, componentTypeEnum);
+    public Optional<UIConstraint> parseToConstraint(final String componentJson, final User user, final ComponentTypeEnum componentTypeEnum) {
+        final Either<UIConstraint, ResponseFormat> uiConstraintResponseFormatEither = convertJsonToObjectUsingObjectMapper(componentJson, user,
+            UIConstraint.class, AuditingActionEnum.CREATE_RESOURCE, componentTypeEnum);
         if (uiConstraintResponseFormatEither.isRight()) {
             return Optional.empty();
         }
         return Optional.of(uiConstraintResponseFormatEither.left().value());
     }
 
-    private Either<List, ResponseFormat> parseToConstraints(final String componentJson,
-                                                           final User user,
-                                                           final ComponentTypeEnum componentTypeEnum) {
-        return convertJsonToObjectUsingObjectMapper(componentJson, user, List.class, AuditingActionEnum.CREATE_RESOURCE,
-            componentTypeEnum);
+    private Either<List, ResponseFormat> parseToConstraints(final String componentJson, final User user, final ComponentTypeEnum componentTypeEnum) {
+        return convertJsonToObjectUsingObjectMapper(componentJson, user, List.class, AuditingActionEnum.CREATE_RESOURCE, componentTypeEnum);
     }
 
-    public List<UIConstraint> validateAndParseConstraint(final ComponentTypeEnum componentTypeEnum,
-                                                         final String constraintData,
+    public List<UIConstraint> validateAndParseConstraint(final ComponentTypeEnum componentTypeEnum, final String constraintData,
                                                          final User userModifier) {
-
         final String FAILED_TO_PARSE_CONSTRAINT_DATA = "Failed to Parse Constraint Data {}";
         final Either<List, ResponseFormat> convertResponse = parseToConstraints(constraintData, userModifier, componentTypeEnum);
         if (convertResponse.isRight()) {
-            log.error(EcompLoggerErrorCode.DATA_ERROR, FAILED_TO_PARSE_CONSTRAINT_DATA, constraintData,
-                convertResponse.right().value());
+            log.error(EcompLoggerErrorCode.DATA_ERROR, FAILED_TO_PARSE_CONSTRAINT_DATA, constraintData, convertResponse.right().value());
             return Collections.emptyList();
         }
         final List<Map<String, String>> uiConstraintsMaps = (List<Map<String, String>>) convertResponse.left().value();
@@ -1757,10 +1512,7 @@ public class ComponentsUtils {
             log.error(EcompLoggerErrorCode.DATA_ERROR, FAILED_TO_PARSE_CONSTRAINT_DATA, constraintData);
             return Collections.emptyList();
         }
-
-        return uiConstraintsMaps.stream().map(dataMap -> new com.fasterxml.jackson.databind.ObjectMapper()
-            .convertValue(dataMap, UIConstraint.class)).collect(Collectors.toList());
+        return uiConstraintsMaps.stream().map(dataMap -> new com.fasterxml.jackson.databind.ObjectMapper().convertValue(dataMap, UIConstraint.class))
+            .collect(Collectors.toList());
     }
-
-
 }
index 6ef64d4..f34dbd3 100644 (file)
@@ -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.
  * limitations under the License.
  * ============LICENSE_END=========================================================
  */
-
 package org.openecomp.sdc.be.impl;
 
-
 import com.google.common.collect.HashMultimap;
 import com.google.common.collect.SetMultimap;
+import java.util.Collection;
+import java.util.HashMap;
+import java.util.HashSet;
+import java.util.List;
+import java.util.Map;
+import java.util.Objects;
+import java.util.Set;
+import java.util.stream.Collectors;
 import org.apache.commons.collections.CollectionUtils;
 import org.javatuples.Pair;
 import org.openecomp.sdc.be.components.merge.instance.DataForMergeHolder;
@@ -37,21 +43,11 @@ import org.openecomp.sdc.be.model.Component;
 import org.openecomp.sdc.be.model.ComponentInstance;
 import org.openecomp.sdc.be.model.Service;
 
-import java.util.Collection;
-import java.util.HashMap;
-import java.util.HashSet;
-import java.util.List;
-import java.util.Map;
-import java.util.Objects;
-import java.util.Set;
-import java.util.stream.Collectors;
-
 public class ForwardingPathUtils {
 
     public static final String FORWARDING_PATH_NODE_NAME = "Forwarding Path";
     public static final String FORWARDER_CAPABILITY = "org.openecomp.capabilities.Forwarder";
 
-
     public ServiceRelations convertServiceToServiceRelations(Service service) {
         ServiceRelations serviceRelations = new ServiceRelations();
         List<ComponentInstance> componentInstances = service.getComponentInstances();
@@ -68,14 +64,15 @@ public class ForwardingPathUtils {
     }
 
     private void initNodeToCP(ComponentInstance ci, SetMultimap<NameIdPair, NameIdPair> nodeToCP) {
-        if (ci.getCapabilities() == null){
+        if (ci.getCapabilities() == null) {
             return;
         }
         Set<CapabilityDefinition> capabilities = ci.getCapabilities().values().stream().flatMap(Collection::stream).collect(Collectors.toSet());
         if (!CollectionUtils.isNotEmpty(capabilities)) {
             return;
         }
-        Set<CapabilityDefinition> forwarderCapabilities = capabilities.stream().filter(capabilityDefinition -> capabilityDefinition.getType().equals(FORWARDER_CAPABILITY)).collect(Collectors.toSet());
+        Set<CapabilityDefinition> forwarderCapabilities = capabilities.stream()
+            .filter(capabilityDefinition -> capabilityDefinition.getType().equals(FORWARDER_CAPABILITY)).collect(Collectors.toSet());
         if (!CollectionUtils.isNotEmpty(forwarderCapabilities)) {
             return;
         }
@@ -83,11 +80,9 @@ public class ForwardingPathUtils {
         forwarderCapabilities.forEach(fc -> {
             NameIdPair capability = new NameIdPair(fc.getName(), fc.getName(), fc.getOwnerId());
             nodeToCP.put(node, capability);
-         });
-
+        });
     }
 
-
     private void handleRelDef(Set<NameIdPairWrapper> relations, SetMultimap<NameIdPair, NameIdPair> nodeToCP) {
         nodeToCP.keySet().forEach(fromNode -> {
             NameIdPairWrapper nameIdPairWrapper = new NameIdPairWrapper();
@@ -98,12 +93,10 @@ public class ForwardingPathUtils {
                 fromCps.forEach(fromCP -> handleFromCp(nodeToCP, nameIdPairWrapper));
             }
         });
-
     }
 
     private void handleFromCp(SetMultimap<NameIdPair, NameIdPair> nodeToCP, NameIdPairWrapper wrapper) {
         Map<NameIdPair, Set<NameIdPair>> options = toMap(nodeToCP);
-
         Set<NameIdPair> cpOptions = options.get(wrapper.getNameIdPair());
         List<NameIdPairWrapper> wrappers = cpOptions.stream().map(this::createWrapper).collect(Collectors.toList());
         wrappers.forEach(cpOptionWrapper -> {
@@ -118,71 +111,58 @@ public class ForwardingPathUtils {
         return nameIdPairWrapper;
     }
 
-
     private Map<NameIdPair, Set<NameIdPair>> toMap(SetMultimap<NameIdPair, NameIdPair> nodeToCP) {
         Map<NameIdPair, Set<NameIdPair>> retVal = new HashMap<>();
         nodeToCP.asMap().forEach((nameIdPair, nameIdPairs) -> retVal.put(nameIdPair, new HashSet<>(nameIdPairs)));
         return retVal;
     }
 
-
-    public Set<String> findForwardingPathNamesToDeleteOnComponentInstanceDeletion(Service containerService,
-        String componentInstanceId) {
+    public Set<String> findForwardingPathNamesToDeleteOnComponentInstanceDeletion(Service containerService, String componentInstanceId) {
         return findForwardingPathToDeleteOnCIDeletion(containerService, componentInstanceId).values().stream()
             .map(ForwardingPathDataDefinition::getName).collect(Collectors.toSet());
     }
 
-    private Map<String, ForwardingPathDataDefinition> findForwardingPathToDeleteOnCIDeletion(Service containerService,
-        String componentInstanceId) {
-        return containerService.getForwardingPaths().entrySet().stream()
-            .filter(entry -> elementContainsCI(entry, componentInstanceId))
+    private Map<String, ForwardingPathDataDefinition> findForwardingPathToDeleteOnCIDeletion(Service containerService, String componentInstanceId) {
+        return containerService.getForwardingPaths().entrySet().stream().filter(entry -> elementContainsCI(entry, componentInstanceId))
             .collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue));
     }
 
-    private boolean elementContainsCI(Map.Entry<String, ForwardingPathDataDefinition> fpEntry,
-        String componentInstanceId) {
-        return fpEntry.getValue().getPathElements()
-            .getListToscaDataDefinition().stream()
+    private boolean elementContainsCI(Map.Entry<String, ForwardingPathDataDefinition> fpEntry, String componentInstanceId) {
+        return fpEntry.getValue().getPathElements().getListToscaDataDefinition().stream()
             .anyMatch(element -> elementContainsCI(element, componentInstanceId));
     }
 
-    private boolean elementContainsCI(ForwardingPathElementDataDefinition elementDataDefinitions,
-        String componentInstanceId) {
-        return elementDataDefinitions.getFromNode().equals(componentInstanceId)
-            || elementDataDefinitions.getToNode().equals(componentInstanceId);
+    private boolean elementContainsCI(ForwardingPathElementDataDefinition elementDataDefinitions, String componentInstanceId) {
+        return elementDataDefinitions.getFromNode().equals(componentInstanceId) || elementDataDefinitions.getToNode().equals(componentInstanceId);
     }
 
     public Pair<Map<String, ForwardingPathDataDefinition>, Map<String, ForwardingPathDataDefinition>> updateForwardingPathOnVersionChange(
-        Service containerService, DataForMergeHolder dataHolder,
-        Component updatedContainerComponent, String newInstanceId) {
+        Service containerService, DataForMergeHolder dataHolder, Component updatedContainerComponent, String newInstanceId) {
         Map<String, ForwardingPathDataDefinition> updated = containerService.getForwardingPaths().entrySet().stream()
             .filter(entry -> elementContainsCIAndForwarder(entry.getValue(), dataHolder.getOrigComponentInstId(), updatedContainerComponent))
-            .collect(Collectors.toMap(Map.Entry::getKey,
-                entry ->  updateCI(entry.getValue(), dataHolder.getOrigComponentInstId(),newInstanceId)));
-        Map<String, ForwardingPathDataDefinition> deleted = containerService.getForwardingPaths().entrySet().stream()
-            .filter(entry -> elementContainsCIAndDoesNotContainForwarder(entry.getValue(),  dataHolder.getOrigComponentInstId(), updatedContainerComponent))
-            .collect(Collectors.toMap(Map.Entry::getKey,Map.Entry::getValue));
+            .collect(Collectors.toMap(Map.Entry::getKey, entry -> updateCI(entry.getValue(), dataHolder.getOrigComponentInstId(), newInstanceId)));
+        Map<String, ForwardingPathDataDefinition> deleted = containerService.getForwardingPaths().entrySet().stream().filter(
+            entry -> elementContainsCIAndDoesNotContainForwarder(entry.getValue(), dataHolder.getOrigComponentInstId(), updatedContainerComponent))
+            .collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue));
         return new Pair<>(updated, deleted);
     }
 
-    public Set<String> getForwardingPathsToBeDeletedOnVersionChange(
-        Service containerService, DataForMergeHolder dataHolder, Component updatedContainerComponent) {
-        return containerService.getForwardingPaths().entrySet().stream()
-          .filter(entry -> elementContainsCIAndDoesNotContainForwarder(entry.getValue(),
-              dataHolder.getOrigComponentInstId(), updatedContainerComponent))
-           .map(entry -> entry.getValue().getUniqueId()).collect( Collectors.toSet());
+    public Set<String> getForwardingPathsToBeDeletedOnVersionChange(Service containerService, DataForMergeHolder dataHolder,
+                                                                    Component updatedContainerComponent) {
+        return containerService.getForwardingPaths().entrySet().stream().filter(
+            entry -> elementContainsCIAndDoesNotContainForwarder(entry.getValue(), dataHolder.getOrigComponentInstId(), updatedContainerComponent))
+            .map(entry -> entry.getValue().getUniqueId()).collect(Collectors.toSet());
     }
 
     private ForwardingPathDataDefinition updateCI(ForwardingPathDataDefinition inFP, String oldCI, String newCI) {
         ForwardingPathDataDefinition retVal = new ForwardingPathDataDefinition(inFP);
-        List<ForwardingPathElementDataDefinition> fpList = retVal.getPathElements().getListToscaDataDefinition()
-            .stream().map(element -> updateElement(element, oldCI, newCI)).collect(Collectors.toList());
+        List<ForwardingPathElementDataDefinition> fpList = retVal.getPathElements().getListToscaDataDefinition().stream()
+            .map(element -> updateElement(element, oldCI, newCI)).collect(Collectors.toList());
         retVal.setPathElements(new ListDataDefinition<>(fpList));
         return retVal;
     }
 
-    private ForwardingPathElementDataDefinition updateElement(ForwardingPathElementDataDefinition element, String oldCI,
-        String newCI) {
+    private ForwardingPathElementDataDefinition updateElement(ForwardingPathElementDataDefinition element, String oldCI, String newCI) {
         ForwardingPathElementDataDefinition retVal = new ForwardingPathElementDataDefinition(element);
         if (retVal.getFromNode().equals(oldCI)) {
             retVal.setFromNode(newCI);
@@ -190,87 +170,66 @@ public class ForwardingPathUtils {
         if (retVal.getToNode().equals(oldCI)) {
             retVal.setToNode(newCI);
         }
-        if (Objects.equals(retVal.getToCPOriginId(),oldCI )) {
+        if (Objects.equals(retVal.getToCPOriginId(), oldCI)) {
             retVal.setToCPOriginId(newCI);
         }
-        if (Objects.equals(retVal.getFromCPOriginId(),oldCI)) {
+        if (Objects.equals(retVal.getFromCPOriginId(), oldCI)) {
             retVal.setFromCPOriginId(newCI);
         }
         return retVal;
     }
 
-    private boolean elementContainsCIAndForwarder(ForwardingPathDataDefinition forwardingPathDataDefinition,
-        String oldCIId, Component newCI) {
-        return forwardingPathDataDefinition.getPathElements()
-            .getListToscaDataDefinition().stream()
+    private boolean elementContainsCIAndForwarder(ForwardingPathDataDefinition forwardingPathDataDefinition, String oldCIId, Component newCI) {
+        return forwardingPathDataDefinition.getPathElements().getListToscaDataDefinition().stream()
             .anyMatch(element -> elementContainsCIAndForwarder(element, oldCIId, newCI));
     }
 
-    private boolean elementContainsCIAndForwarder(ForwardingPathElementDataDefinition elementDataDefinitions,
-        String oldCIId, Component newCI) {
-        return (elementDataDefinitions.getFromNode().equals(oldCIId) && ciContainsForwarder(newCI,
-            elementDataDefinitions.getFromCP()))
-            || (elementDataDefinitions.getToNode().equals(oldCIId) && ciContainsForwarder(newCI,
-            elementDataDefinitions.getToCP()));
+    private boolean elementContainsCIAndForwarder(ForwardingPathElementDataDefinition elementDataDefinitions, String oldCIId, Component newCI) {
+        return (elementDataDefinitions.getFromNode().equals(oldCIId) && ciContainsForwarder(newCI, elementDataDefinitions.getFromCP())) || (
+            elementDataDefinitions.getToNode().equals(oldCIId) && ciContainsForwarder(newCI, elementDataDefinitions.getToCP()));
     }
 
     private boolean ciContainsForwarder(Component newCI, String capabilityID) {
-        if (newCI.getCapabilities() == null){
+        if (newCI.getCapabilities() == null) {
             return false;
         }
-        return newCI.getCapabilities().values()
-            .stream()
-            .flatMap(List::stream)
-            .anyMatch(c -> c.getName().equals(capabilityID));
+        return newCI.getCapabilities().values().stream().flatMap(List::stream).anyMatch(c -> c.getName().equals(capabilityID));
     }
 
-    private boolean elementContainsCIAndDoesNotContainForwarder(
-        ForwardingPathDataDefinition forwardingPathDataDefinition,
-        String oldCIId, Component newCI) {
-        return forwardingPathDataDefinition.getPathElements()
-            .getListToscaDataDefinition().stream()
+    private boolean elementContainsCIAndDoesNotContainForwarder(ForwardingPathDataDefinition forwardingPathDataDefinition, String oldCIId,
+                                                                Component newCI) {
+        return forwardingPathDataDefinition.getPathElements().getListToscaDataDefinition().stream()
             .anyMatch(element -> elementContainsCIAndDoesNotContainForwarder(element, oldCIId, newCI));
     }
 
-    private boolean elementContainsCIAndDoesNotContainForwarder(
-        ForwardingPathElementDataDefinition elementDataDefinitions,
-        String oldCIId, Component newCI) {
-        return (elementDataDefinitions.getFromNode().equals(oldCIId) && !ciContainsForwarder(newCI,
-            elementDataDefinitions.getFromCP()))
-            || (elementDataDefinitions.getToNode().equals(oldCIId) && !ciContainsForwarder(newCI,
-            elementDataDefinitions.getToCP()));
+    private boolean elementContainsCIAndDoesNotContainForwarder(ForwardingPathElementDataDefinition elementDataDefinitions, String oldCIId,
+                                                                Component newCI) {
+        return (elementDataDefinitions.getFromNode().equals(oldCIId) && !ciContainsForwarder(newCI, elementDataDefinitions.getFromCP())) || (
+            elementDataDefinitions.getToNode().equals(oldCIId) && !ciContainsForwarder(newCI, elementDataDefinitions.getToCP()));
     }
 
-
     public Set<ForwardingPathDataDefinition> updateComponentInstanceName(Collection<ForwardingPathDataDefinition> forwardingPathDataDefinitions,
-        String oldName, String newName){
-        return  forwardingPathDataDefinitions.stream().filter(fp -> shouldRenameCI(fp,oldName)).
-            map(forwardingPathDataDefinition -> renamePathCI(forwardingPathDataDefinition,oldName,newName))
-            .collect(Collectors.toSet());
-
+                                                                         String oldName, String newName) {
+        return forwardingPathDataDefinitions.stream().filter(fp -> shouldRenameCI(fp, oldName))
+            .map(forwardingPathDataDefinition -> renamePathCI(forwardingPathDataDefinition, oldName, newName)).collect(Collectors.toSet());
     }
 
-    public boolean shouldRenameCI(ForwardingPathDataDefinition forwardingPathDataDefinitions,
-        String oldName){
+    public boolean shouldRenameCI(ForwardingPathDataDefinition forwardingPathDataDefinitions, String oldName) {
         return forwardingPathDataDefinitions.getPathElements().getListToscaDataDefinition().stream()
             .anyMatch(pe -> pe.getToNode().equals(oldName) || pe.getFromNode().equals(oldName));
     }
 
-    public ForwardingPathDataDefinition renamePathCI(ForwardingPathDataDefinition forwardingPathDataDefinitions,
-        String oldName, String newName){
-        forwardingPathDataDefinitions.getPathElements().getListToscaDataDefinition().stream()
-            .forEach(pe -> renamePathCI(pe,oldName, newName));
+    public ForwardingPathDataDefinition renamePathCI(ForwardingPathDataDefinition forwardingPathDataDefinitions, String oldName, String newName) {
+        forwardingPathDataDefinitions.getPathElements().getListToscaDataDefinition().stream().forEach(pe -> renamePathCI(pe, oldName, newName));
         return forwardingPathDataDefinitions;
     }
 
-    public void renamePathCI(ForwardingPathElementDataDefinition pathElementDataDefinition,
-        String oldName, String newName){
-        if (pathElementDataDefinition.getFromNode().equals(oldName)){
+    public void renamePathCI(ForwardingPathElementDataDefinition pathElementDataDefinition, String oldName, String newName) {
+        if (pathElementDataDefinition.getFromNode().equals(oldName)) {
             pathElementDataDefinition.setFromNode(newName);
         }
-        if(pathElementDataDefinition.getToNode().equals(oldName)){
+        if (pathElementDataDefinition.getToNode().equals(oldName)) {
             pathElementDataDefinition.setToNode(newName);
         }
-
     }
 }
index e6d7df6..866affc 100644 (file)
@@ -13,7 +13,6 @@
  * See the License for the specific language governing permissions and
  * limitations under the License.
  */
-
 package org.openecomp.sdc.be.impl;
 
 import java.util.List;
@@ -33,56 +32,45 @@ import org.openecomp.sdc.be.ui.model.UIConstraint;
 
 public class ServiceFilterUtils {
 
-
     private ServiceFilterUtils() {
     }
 
-
-     public static boolean isNodeFilterAffectedByPropertyRemoval(Service service, String ciName, String propertyName) {
+    public static boolean isNodeFilterAffectedByPropertyRemoval(Service service, String ciName, String propertyName) {
         return service.getComponentInstances().stream().filter(ci -> ci.getNodeFilter() != null)
-                      .anyMatch(ci -> propertyIsUsedInCI(ci, ciName, propertyName));
+            .anyMatch(ci -> propertyIsUsedInCI(ci, ciName, propertyName));
     }
 
-
     private static boolean propertyIsUsedInCI(ComponentInstance ci, String ciName, String propertyName) {
         if (CollectionUtils.isEmpty(ci.getDirectives())) {
             return false;
         }
         if (ci.getNodeFilter() == null || ci.getNodeFilter().getProperties() == null
-                    || ci.getNodeFilter().getProperties().getListToscaDataDefinition() == null) {
+            || ci.getNodeFilter().getProperties().getListToscaDataDefinition() == null) {
             return false;
         }
-        return ci.getNodeFilter().getProperties().getListToscaDataDefinition().stream()
-                 .flatMap(prop -> prop.getConstraints().stream()).map(String::new)
-                 .filter(constraint -> new ConstraintConvertor().convert(constraint).getSourceType()
-                                                                .equals(ConstraintConvertor.PROPERTY_CONSTRAINT))
-                 .anyMatch(constraintStr -> {
-                     UIConstraint uiConstraint = new ConstraintConvertor().convert(constraintStr);
-                     return uiConstraint.getSourceName().equals(ciName) && uiConstraint.getValue().equals(propertyName);
-                 });
-
+        return ci.getNodeFilter().getProperties().getListToscaDataDefinition().stream().flatMap(prop -> prop.getConstraints().stream())
+            .map(String::new)
+            .filter(constraint -> new ConstraintConvertor().convert(constraint).getSourceType().equals(ConstraintConvertor.PROPERTY_CONSTRAINT))
+            .anyMatch(constraintStr -> {
+                UIConstraint uiConstraint = new ConstraintConvertor().convert(constraintStr);
+                return uiConstraint.getSourceName().equals(ciName) && uiConstraint.getValue().equals(propertyName);
+            });
     }
 
-    public static Map<String, CINodeFilterDataDefinition> getRenamedNodesFilter(Service service, String oldName,
-            String newName) {
+    public static Map<String, CINodeFilterDataDefinition> getRenamedNodesFilter(Service service, String oldName, String newName) {
         return service.getComponentInstances().stream().filter(ci -> isNodeFilterUsingChangedCi(ci, oldName))
-                      .map(ci -> renameOldCiNames(ci, oldName, newName))
-                      .collect(Collectors.toMap(Pair::getValue0, Pair::getValue1));
+            .map(ci -> renameOldCiNames(ci, oldName, newName)).collect(Collectors.toMap(Pair::getValue0, Pair::getValue1));
     }
 
-    private static Pair<String, CINodeFilterDataDefinition> renameOldCiNames(ComponentInstance ci, String oldName,
-            String newName) {
+    private static Pair<String, CINodeFilterDataDefinition> renameOldCiNames(ComponentInstance ci, String oldName, String newName) {
         ci.getNodeFilter().getProperties().getListToscaDataDefinition().stream()
-          .filter(property -> isPropertyConstraintChangedByCi(property, oldName))
-          .forEach(property -> renamePropertyCiNames(property, oldName, newName));
-
+            .filter(property -> isPropertyConstraintChangedByCi(property, oldName))
+            .forEach(property -> renamePropertyCiNames(property, oldName, newName));
         return new Pair<>(ci.getUniqueId(), ci.getNodeFilter());
     }
 
-    private static void renamePropertyCiNames(RequirementNodeFilterPropertyDataDefinition property, String oldName,
-            String newName) {
-        final List<String> constraints = property.getConstraints().stream().map(getConstraintString(oldName, newName))
-                                                 .collect(Collectors.toList());
+    private static void renamePropertyCiNames(RequirementNodeFilterPropertyDataDefinition property, String oldName, String newName) {
+        final List<String> constraints = property.getConstraints().stream().map(getConstraintString(oldName, newName)).collect(Collectors.toList());
         property.setConstraints(constraints);
     }
 
@@ -97,34 +85,29 @@ public class ServiceFilterUtils {
         };
     }
 
-
     public static Set<String> getNodesFiltersToBeDeleted(Service service, String ciName) {
-        return service.getComponentInstances().stream().filter(ci -> isNodeFilterUsingChangedCi(ci, ciName))
-                      .map(ComponentInstance::getName).collect(Collectors.toSet());
+        return service.getComponentInstances().stream().filter(ci -> isNodeFilterUsingChangedCi(ci, ciName)).map(ComponentInstance::getName)
+            .collect(Collectors.toSet());
     }
 
-
-
     public static Set<String> getNodesFiltersToBeDeleted(Service service, ComponentInstance inCi) {
         return getNodesFiltersToBeDeleted(service, inCi.getName());
     }
 
-
-
     private static boolean isNodeFilterUsingChangedCi(ComponentInstance ci, String name) {
         if (CollectionUtils.isEmpty(ci.getDirectives())) {
             return false;
         }
         if (ci.getNodeFilter() == null || ci.getNodeFilter().getProperties() == null
-                    || ci.getNodeFilter().getProperties().getListToscaDataDefinition() == null) {
+            || ci.getNodeFilter().getProperties().getListToscaDataDefinition() == null) {
             return false;
         }
         return ci.getNodeFilter().getProperties().getListToscaDataDefinition().stream()
-                 .anyMatch(property -> isPropertyConstraintChangedByCi(property, name));
+            .anyMatch(property -> isPropertyConstraintChangedByCi(property, name));
     }
 
-    private static boolean isPropertyConstraintChangedByCi(
-            RequirementNodeFilterPropertyDataDefinition requirementNodeFilterPropertyDataDefinition, String name) {
+    private static boolean isPropertyConstraintChangedByCi(RequirementNodeFilterPropertyDataDefinition requirementNodeFilterPropertyDataDefinition,
+                                                           String name) {
         List<String> constraints = requirementNodeFilterPropertyDataDefinition.getConstraints();
         if (constraints == null) {
             return false;
@@ -144,8 +127,8 @@ public class ServiceFilterUtils {
     }
 
     public static Set<String> getNodesFiltersToBeDeleted(Service service, InputDefinition changedInput) {
-        return service.getComponentInstances().stream().filter(ci -> isNodeFilterUsingChangedInput(ci, changedInput))
-                      .map(ComponentInstance::getName).collect(Collectors.toSet());
+        return service.getComponentInstances().stream().filter(ci -> isNodeFilterUsingChangedInput(ci, changedInput)).map(ComponentInstance::getName)
+            .collect(Collectors.toSet());
     }
 
     private static boolean isNodeFilterUsingChangedInput(ComponentInstance ci, InputDefinition changedInput) {
@@ -153,12 +136,11 @@ public class ServiceFilterUtils {
             return false;
         }
         return ci.getNodeFilter().getProperties().getListToscaDataDefinition().stream()
-                 .anyMatch(property -> isPropertyConstraintChangedByInput(property, changedInput));
+            .anyMatch(property -> isPropertyConstraintChangedByInput(property, changedInput));
     }
 
-    private static boolean isPropertyConstraintChangedByInput(
-            RequirementNodeFilterPropertyDataDefinition requirementNodeFilterPropertyDataDefinition,
-            InputDefinition changedInput) {
+    private static boolean isPropertyConstraintChangedByInput(RequirementNodeFilterPropertyDataDefinition requirementNodeFilterPropertyDataDefinition,
+                                                              InputDefinition changedInput) {
         List<String> constraints = requirementNodeFilterPropertyDataDefinition.getConstraints();
         return constraints.stream().anyMatch(constraint -> isConstraintChangedByInput(constraint, changedInput));
     }
@@ -170,5 +152,4 @@ public class ServiceFilterUtils {
         }
         return uiConstraint.getValue().equals(changedInput.getName());
     }
-
 }
index 70bfd60..6941504 100644 (file)
@@ -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.
  * limitations under the License.
  * ============LICENSE_END=========================================================
  */
-
 package org.openecomp.sdc.be.impl;
 
 import com.google.gson.Gson;
+import javax.annotation.Resource;
 import lombok.Getter;
 import org.openecomp.sdc.be.user.UserBusinessLogic;
 import org.springframework.stereotype.Component;
 
-import javax.annotation.Resource;
-
 @Component("servletUtils")
 @Getter
 public class ServletUtils {
+
     @Resource
     private ComponentsUtils componentsUtils;
-
     private Gson gson = new Gson();
-
     @Resource
     private UserBusinessLogic userAdmin;
 }
index 0275928..3690d71 100644 (file)
@@ -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.
  * limitations under the License.
  * ============LICENSE_END=========================================================
  */
-
 package org.openecomp.sdc.be.impl;
 
+import javax.servlet.ServletContext;
 import org.springframework.web.context.WebApplicationContext;
 import org.springframework.web.context.support.WebApplicationContextUtils;
 
-import javax.servlet.ServletContext;
-
 public class WebAppContextWrapper {
 
     public WebApplicationContext getWebAppContext(ServletContext context) {
-
         return WebApplicationContextUtils.getWebApplicationContext(context);
     }
-
 }
index d800f35..7d4070a 100644 (file)
@@ -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,7 +19,6 @@
  * Modifications copyright (c) 2019 Nokia
  * ================================================================================
  */
-
 package org.openecomp.sdc.be.info;
 
 import lombok.Getter;
@@ -31,7 +30,9 @@ import org.openecomp.sdc.be.model.ArtifactDefinition;
 public class ArtifactDefinitionInfo {
 
     private String uniqueId;
-    /** Specifies the display name of the artifact. */
+    /**
+     * Specifies the display name of the artifact.
+     */
     private String artifactName;
     private String artifactDisplayName;
     private String artifactVersion;
@@ -45,3 +46,4 @@ public class ArtifactDefinitionInfo {
         artifactUUID = artifactDefinition.getArtifactUUID();
     }
 }
+
index ab088ec..2fedcc3 100644 (file)
@@ -17,7 +17,6 @@
  * limitations under the License.
  * ============LICENSE_END=========================================================
  */
-
 package org.openecomp.sdc.be.info;
 
 import com.google.gson.Gson;
@@ -50,10 +49,10 @@ import org.openecomp.sdc.exception.ResponseFormat;
 @Setter
 @NoArgsConstructor
 public class ArtifactTemplateInfo {
+
+    public static final String CSAR_ARTIFACT = "artifacts";
     private static final Logger log = Logger.getLogger(ArtifactTemplateInfo.class);
     private static final Gson gson = new Gson();
-    public static final String CSAR_ARTIFACT = "artifacts";
-
     private static final String ARTIFACT_TEMPLATE_TYPE = "type";
     private static final String FILE_NAME = "fileName";
     private static final String ARTIFACT_TEMPLATE_ENV = "env";
@@ -64,14 +63,12 @@ public class ArtifactTemplateInfo {
     private static final String CSAR_VOLUME = "volume";
     private static final String CSAR_NESTED = "nested";
     private static final String DESC = "description";
-
     private String type;
     private String fileName;
     private String env;
     private boolean base;
     private String groupName;
     private String description;
-
     private List<ArtifactTemplateInfo> relatedArtifactsInfo;
 
     public ArtifactTemplateInfo(String type, String fileName, String env, List<ArtifactTemplateInfo> relatedArtifactsInfo) {
@@ -81,14 +78,14 @@ public class ArtifactTemplateInfo {
         this.relatedArtifactsInfo = relatedArtifactsInfo;
     }
 
-    public static Either<ArtifactTemplateInfo, ResponseFormat> createArtifactTemplateInfoFromJson(ComponentsUtils componentsUtils, String type, Map<String, Object> o, List<ArtifactTemplateInfo> createdArtifactTemplateInfoList,
-            ArtifactTemplateInfo parentArtifact) {
+    public static Either<ArtifactTemplateInfo, ResponseFormat> createArtifactTemplateInfoFromJson(ComponentsUtils componentsUtils, String type,
+                                                                                                  Map<String, Object> o,
+                                                                                                  List<ArtifactTemplateInfo> createdArtifactTemplateInfoList,
+                                                                                                  ArtifactTemplateInfo parentArtifact) {
         String content = gson.toJson(o);
         JsonObject jsonElement = new JsonObject();
         ArtifactTemplateInfo resourceInfo = new ArtifactTemplateInfo();
-
         jsonElement = gson.fromJson(content, jsonElement.getClass());
-
         Map<String, Object> artifactTemplateMap = ComponentsUtils.parseJsonToObject(jsonElement.toString(), HashMap.class);
         if (artifactTemplateMap.containsKey(ARTIFACT_TEMPLATE_TYPE)) {
             resourceInfo.setType((String) artifactTemplateMap.get(ARTIFACT_TEMPLATE_TYPE));
@@ -104,8 +101,7 @@ public class ArtifactTemplateInfo {
             String envStr = "";
             if (envObj instanceof String) {
                 envStr = (String) envObj;
-            }
-            else if (envObj instanceof Map) {
+            } else if (envObj instanceof Map) {
                 Map envMap = (Map) envObj;
                 if (envMap.containsKey(FILE_NAME)) {
                     envStr = (String) envMap.get(FILE_NAME);
@@ -118,57 +114,45 @@ public class ArtifactTemplateInfo {
         } else {
             resourceInfo.setDescription((String) artifactTemplateMap.get(FILE_NAME));
         }
-
         boolean artifactTypeExist = false;
         String correctType;
         if (type.equalsIgnoreCase(CSAR_NESTED)) {
             correctType = ArtifactTypeEnum.HEAT_NESTED.getType();
-        }
-        else if (type.equalsIgnoreCase(CSAR_VOLUME)) {
+        } else if (type.equalsIgnoreCase(CSAR_VOLUME)) {
             correctType = ArtifactTypeEnum.HEAT_VOL.getType();
-        }
-        else if (type.equalsIgnoreCase(CSAR_NETWORK)) {
+        } else if (type.equalsIgnoreCase(CSAR_NETWORK)) {
             correctType = ArtifactTypeEnum.HEAT_NET.getType();
-        }
-        else if (type.equalsIgnoreCase(CSAR_ARTIFACT)){
-            if( parentArtifact != null) {
+        } else if (type.equalsIgnoreCase(CSAR_ARTIFACT)) {
+            if (parentArtifact != null) {
                 correctType = ArtifactTypeEnum.HEAT_ARTIFACT.getType();
-            }
-            else {
+            } else {
                 correctType = resourceInfo.type;
             }
-        }
-        else if (type.equalsIgnoreCase(CSAR_HEAT)) {
+        } else if (type.equalsIgnoreCase(CSAR_HEAT)) {
             correctType = ArtifactTypeEnum.HEAT.getType();
-        }
-        else if (type.equalsIgnoreCase(CSAR_HELM)) {
+        } else if (type.equalsIgnoreCase(CSAR_HELM)) {
             correctType = ArtifactTypeEnum.HELM.getType();
-        }
-        else {
+        } else {
             correctType = ArtifactTypeEnum.OTHER.getType();
         }
         Either<List<ArtifactType>, ActionStatus> allArtifactTypes = getDeploymentArtifactTypes(NodeTypeEnum.Resource);
-
         if (allArtifactTypes.isRight()) {
-            BeEcompErrorManager.getInstance().logBeInvalidConfigurationError("Artifact Upload / Update", "artifactTypes", allArtifactTypes.right().value().name());
+            BeEcompErrorManager.getInstance()
+                .logBeInvalidConfigurationError("Artifact Upload / Update", "artifactTypes", allArtifactTypes.right().value().name());
             return Either.right(componentsUtils.getResponseFormat(ActionStatus.FAILED_RETRIVE_ARTIFACTS_TYPES));
         }
-
         for (ArtifactType artType : allArtifactTypes.left().value()) {
-
             if (artType.getName().contains(correctType)) {
                 resourceInfo.type = artType.getName();
                 artifactTypeExist = true;
                 break;
             }
         }
-
         if (!artifactTypeExist) {
             BeEcompErrorManager.getInstance().logBeInvalidTypeError("Artifact", "-Not supported artifact type ", correctType);
-            log.debug("Not supported artifact type = {}" , correctType);
+            log.debug("Not supported artifact type = {}", correctType);
             return Either.right(componentsUtils.getResponseFormat(ActionStatus.ARTIFACT_TYPE_NOT_SUPPORTED, correctType));
         }
-
         Either<Boolean, ResponseFormat> eitherNeedToCreate = validateEnv(componentsUtils, createdArtifactTemplateInfoList, resourceInfo);
         if (eitherNeedToCreate.isRight()) {
             return Either.right(eitherNeedToCreate.right().value());
@@ -186,7 +170,8 @@ public class ArtifactTemplateInfo {
             if (o.get(key) instanceof List) {
                 List<Map<String, Object>> artifList = (List<Map<String, Object>>) o.get(key);
                 for (Map<String, Object> relatedArtifactsMap : artifList) {
-                    Either<ArtifactTemplateInfo, ResponseFormat> relatedArtifact = ArtifactTemplateInfo.createArtifactTemplateInfoFromJson(componentsUtils, key, relatedArtifactsMap, createdArtifactTemplateInfoList, resourceInfo);
+                    Either<ArtifactTemplateInfo, ResponseFormat> relatedArtifact = ArtifactTemplateInfo
+                        .createArtifactTemplateInfoFromJson(componentsUtils, key, relatedArtifactsMap, createdArtifactTemplateInfoList, resourceInfo);
                     if (relatedArtifact.isRight()) {
                         return relatedArtifact;
                     }
@@ -200,32 +185,40 @@ public class ArtifactTemplateInfo {
         return Either.left(resourceInfo);
     }
 
-    private static Either<Boolean, ResponseFormat> validateIsAlreadyExist(ComponentsUtils componentsUtils, ArtifactTemplateInfo resourceInfo, List<ArtifactTemplateInfo> createdArtifactTemplateInfoList, ArtifactTemplateInfo parentArtifact) {
-
+    private static Either<Boolean, ResponseFormat> validateIsAlreadyExist(ComponentsUtils componentsUtils, ArtifactTemplateInfo resourceInfo,
+                                                                          List<ArtifactTemplateInfo> createdArtifactTemplateInfoList,
+                                                                          ArtifactTemplateInfo parentArtifact) {
         if (parentArtifact == null) {
-            if (createdArtifactTemplateInfoList == null || createdArtifactTemplateInfoList.isEmpty())
+            if (createdArtifactTemplateInfoList == null || createdArtifactTemplateInfoList.isEmpty()) {
                 return Either.left(true);
+            }
             for (ArtifactTemplateInfo createdArtifact : createdArtifactTemplateInfoList) {
-                if (createdArtifact.getType().equalsIgnoreCase(resourceInfo.getType()) && createdArtifact.getFileName().equalsIgnoreCase(resourceInfo.getFileName())) {
-                    return Either.right(componentsUtils.getResponseFormat(ActionStatus.ARTIFACT_ALRADY_EXIST_IN_MASTER_IN_CSAR, resourceInfo.getFileName(), createdArtifact.type));
+                if (createdArtifact.getType().equalsIgnoreCase(resourceInfo.getType()) && createdArtifact.getFileName()
+                    .equalsIgnoreCase(resourceInfo.getFileName())) {
+                    return Either.right(componentsUtils
+                        .getResponseFormat(ActionStatus.ARTIFACT_ALRADY_EXIST_IN_MASTER_IN_CSAR, resourceInfo.getFileName(), createdArtifact.type));
                 }
             }
             return Either.left(true);
         } else {
             List<ArtifactTemplateInfo> relatedArtifacts = parentArtifact.getRelatedArtifactsInfo();
-            if (relatedArtifacts == null || relatedArtifacts.isEmpty())
+            if (relatedArtifacts == null || relatedArtifacts.isEmpty()) {
                 return Either.left(true);
+            }
             for (ArtifactTemplateInfo relatedArtifact : relatedArtifacts) {
-                if (relatedArtifact.getType().equalsIgnoreCase(resourceInfo.getType()) && relatedArtifact.getFileName().equalsIgnoreCase(resourceInfo.getFileName())) {
-                    return Either.right(componentsUtils.getResponseFormat(ActionStatus.ARTIFACT_ALRADY_EXIST_IN_MASTER_IN_CSAR, resourceInfo.getFileName(), parentArtifact.getFileName()));
+                if (relatedArtifact.getType().equalsIgnoreCase(resourceInfo.getType()) && relatedArtifact.getFileName()
+                    .equalsIgnoreCase(resourceInfo.getFileName())) {
+                    return Either.right(componentsUtils
+                        .getResponseFormat(ActionStatus.ARTIFACT_ALRADY_EXIST_IN_MASTER_IN_CSAR, resourceInfo.getFileName(),
+                            parentArtifact.getFileName()));
                 }
             }
             return Either.left(true);
         }
     }
 
-    private static Either<Boolean, ResponseFormat> validateParentType(ComponentsUtils componentsUtils, ArtifactTemplateInfo resourceInfo, ArtifactTemplateInfo parentArtifact) {
-
+    private static Either<Boolean, ResponseFormat> validateParentType(ComponentsUtils componentsUtils, ArtifactTemplateInfo resourceInfo,
+                                                                      ArtifactTemplateInfo parentArtifact) {
         if (parentArtifact == null) {
             return Either.left(true);
         }
@@ -233,78 +226,99 @@ public class ArtifactTemplateInfo {
             return Either.left(true);
         }
         if (resourceInfo.getType().equalsIgnoreCase(ArtifactTypeEnum.HEAT.getType())) {
-            return Either.right(componentsUtils.getResponseFormat(ActionStatus.ARTIFACT_NOT_VALID_IN_MASTER, resourceInfo.getFileName(), resourceInfo.getType(), parentArtifact.getFileName(), parentArtifact.getType()));
+            return Either.right(componentsUtils
+                .getResponseFormat(ActionStatus.ARTIFACT_NOT_VALID_IN_MASTER, resourceInfo.getFileName(), resourceInfo.getType(),
+                    parentArtifact.getFileName(), parentArtifact.getType()));
         }
-        if ((resourceInfo.getType().equalsIgnoreCase(ArtifactTypeEnum.HEAT_NET.getType()) || resourceInfo.getType().equalsIgnoreCase(ArtifactTypeEnum.HEAT_VOL.getType()))
-                && !parentArtifact.getType().equalsIgnoreCase(ArtifactTypeEnum.HEAT.getType())) {
-            return Either.right(componentsUtils.getResponseFormat(ActionStatus.ARTIFACT_NOT_VALID_IN_MASTER, resourceInfo.getFileName(), resourceInfo.getType(), parentArtifact.getFileName(), parentArtifact.getType()));
+        if ((resourceInfo.getType().equalsIgnoreCase(ArtifactTypeEnum.HEAT_NET.getType()) || resourceInfo.getType()
+            .equalsIgnoreCase(ArtifactTypeEnum.HEAT_VOL.getType())) && !parentArtifact.getType().equalsIgnoreCase(ArtifactTypeEnum.HEAT.getType())) {
+            return Either.right(componentsUtils
+                .getResponseFormat(ActionStatus.ARTIFACT_NOT_VALID_IN_MASTER, resourceInfo.getFileName(), resourceInfo.getType(),
+                    parentArtifact.getFileName(), parentArtifact.getType()));
         }
         if (parentArtifact.getType().equalsIgnoreCase(ArtifactTypeEnum.HEAT_NESTED.getType())) {
-            if (resourceInfo.getType().equalsIgnoreCase(ArtifactTypeEnum.HEAT_ARTIFACT.getType()) || resourceInfo.getType().equalsIgnoreCase(ArtifactTypeEnum.HEAT_NESTED.getType())) {
+            if (resourceInfo.getType().equalsIgnoreCase(ArtifactTypeEnum.HEAT_ARTIFACT.getType()) || resourceInfo.getType()
+                .equalsIgnoreCase(ArtifactTypeEnum.HEAT_NESTED.getType())) {
                 return Either.left(true);
             }
-            return Either.right(componentsUtils.getResponseFormat(ActionStatus.ARTIFACT_NOT_VALID_IN_MASTER, resourceInfo.getFileName(), resourceInfo.getType(), parentArtifact.getFileName(), parentArtifact.getType()));
+            return Either.right(componentsUtils
+                .getResponseFormat(ActionStatus.ARTIFACT_NOT_VALID_IN_MASTER, resourceInfo.getFileName(), resourceInfo.getType(),
+                    parentArtifact.getFileName(), parentArtifact.getType()));
         }
-        if (parentArtifact.getType().equalsIgnoreCase(ArtifactTypeEnum.HEAT.getType()) && resourceInfo.getType().equalsIgnoreCase(ArtifactTypeEnum.HEAT.getType())) {
-            return Either.right(componentsUtils.getResponseFormat(ActionStatus.ARTIFACT_NOT_VALID_IN_MASTER, resourceInfo.getFileName(), resourceInfo.getType(), parentArtifact.getFileName(), parentArtifact.getType()));
+        if (parentArtifact.getType().equalsIgnoreCase(ArtifactTypeEnum.HEAT.getType()) && resourceInfo.getType()
+            .equalsIgnoreCase(ArtifactTypeEnum.HEAT.getType())) {
+            return Either.right(componentsUtils
+                .getResponseFormat(ActionStatus.ARTIFACT_NOT_VALID_IN_MASTER, resourceInfo.getFileName(), resourceInfo.getType(),
+                    parentArtifact.getFileName(), parentArtifact.getType()));
         }
-
         if (parentArtifact.getType().equalsIgnoreCase(ArtifactTypeEnum.HEAT.getType())) {
             return Either.left(true);
         }
         return Either.left(true);
     }
 
-    private static Either<Boolean, ResponseFormat> validateEnv(ComponentsUtils componentsUtils, List<ArtifactTemplateInfo> createdArtifactTemplateInfoList, ArtifactTemplateInfo resourceInfo) {
-
-        if (createdArtifactTemplateInfoList == null || createdArtifactTemplateInfoList.isEmpty())
+    private static Either<Boolean, ResponseFormat> validateEnv(ComponentsUtils componentsUtils,
+                                                               List<ArtifactTemplateInfo> createdArtifactTemplateInfoList,
+                                                               ArtifactTemplateInfo resourceInfo) {
+        if (createdArtifactTemplateInfoList == null || createdArtifactTemplateInfoList.isEmpty()) {
             return Either.left(true);
-        if (resourceInfo.getType().equalsIgnoreCase(ArtifactTypeEnum.HEAT_NESTED.getType()) || resourceInfo.getType().equalsIgnoreCase(ArtifactTypeEnum.HEAT_ARTIFACT.getType()))
+        }
+        if (resourceInfo.getType().equalsIgnoreCase(ArtifactTypeEnum.HEAT_NESTED.getType()) || resourceInfo.getType()
+            .equalsIgnoreCase(ArtifactTypeEnum.HEAT_ARTIFACT.getType())) {
             return Either.left(true);
+        }
         for (ArtifactTemplateInfo createdArtifactTemplateInfo : createdArtifactTemplateInfoList) {
             // check if artifact with this name already parsed. If parsed check
+
             // env name. it must be the same.
             if (resourceInfo.getFileName().equalsIgnoreCase(createdArtifactTemplateInfo.getFileName())) {
-                if ((resourceInfo.getEnv() == null || resourceInfo.getEnv().isEmpty()) && (createdArtifactTemplateInfo.getEnv() != null && !createdArtifactTemplateInfo.getEnv().isEmpty())) {
-                    log.debug("Artifact  file with name {} type{}  already parsed but with env {}", resourceInfo.getFileName(), resourceInfo.getType(), createdArtifactTemplateInfo.getEnv());
-                    return Either.right(componentsUtils.getResponseFormat(ActionStatus.ARTIFACT_NOT_VALID_ENV, resourceInfo.getFileName(), resourceInfo.getType(), resourceInfo.getEnv(), createdArtifactTemplateInfo.getEnv()));
+                if ((resourceInfo.getEnv() == null || resourceInfo.getEnv().isEmpty()) && (createdArtifactTemplateInfo.getEnv() != null
+                    && !createdArtifactTemplateInfo.getEnv().isEmpty())) {
+                    log.debug("Artifact  file with name {} type{}  already parsed but with env {}", resourceInfo.getFileName(),
+                        resourceInfo.getType(), createdArtifactTemplateInfo.getEnv());
+                    return Either.right(componentsUtils
+                        .getResponseFormat(ActionStatus.ARTIFACT_NOT_VALID_ENV, resourceInfo.getFileName(), resourceInfo.getType(),
+                            resourceInfo.getEnv(), createdArtifactTemplateInfo.getEnv()));
                 }
-                if (resourceInfo.getEnv() != null && !resourceInfo.getEnv().isEmpty() && createdArtifactTemplateInfo.getEnv() != null && !createdArtifactTemplateInfo.getEnv().isEmpty()
-                        && !createdArtifactTemplateInfo.getEnv().equalsIgnoreCase(resourceInfo.getEnv())) {
-                    log.debug("Artifact  file with name {} type{} env {} already parsed but with env {}", resourceInfo.getFileName(), resourceInfo.getType(), resourceInfo.getEnv(), createdArtifactTemplateInfo.getEnv());
-                    return Either.right(componentsUtils.getResponseFormat(ActionStatus.ARTIFACT_NOT_VALID_ENV, resourceInfo.getFileName(), resourceInfo.getType(), resourceInfo.getEnv(), createdArtifactTemplateInfo.getEnv()));
+                if (resourceInfo.getEnv() != null && !resourceInfo.getEnv().isEmpty() && createdArtifactTemplateInfo.getEnv() != null
+                    && !createdArtifactTemplateInfo.getEnv().isEmpty() && !createdArtifactTemplateInfo.getEnv()
+                    .equalsIgnoreCase(resourceInfo.getEnv())) {
+                    log.debug("Artifact  file with name {} type{} env {} already parsed but with env {}", resourceInfo.getFileName(),
+                        resourceInfo.getType(), resourceInfo.getEnv(), createdArtifactTemplateInfo.getEnv());
+                    return Either.right(componentsUtils
+                        .getResponseFormat(ActionStatus.ARTIFACT_NOT_VALID_ENV, resourceInfo.getFileName(), resourceInfo.getType(),
+                            resourceInfo.getEnv(), createdArtifactTemplateInfo.getEnv()));
                 }
-                if ((resourceInfo.getEnv() != null && !resourceInfo.getEnv().isEmpty()) && (createdArtifactTemplateInfo.getEnv() == null || createdArtifactTemplateInfo.getEnv().isEmpty())) {
-                    log.debug("Artifact  file with name {} type{} env {} already parsed but with env {}", resourceInfo.getFileName(), resourceInfo.getType(), resourceInfo.getEnv(), createdArtifactTemplateInfo.getEnv());
-                    return Either.right(componentsUtils.getResponseFormat(ActionStatus.ARTIFACT_NOT_VALID_ENV, resourceInfo.getFileName(), resourceInfo.getType(), resourceInfo.getEnv(), createdArtifactTemplateInfo.getEnv()));
+                if ((resourceInfo.getEnv() != null && !resourceInfo.getEnv().isEmpty()) && (createdArtifactTemplateInfo.getEnv() == null
+                    || createdArtifactTemplateInfo.getEnv().isEmpty())) {
+                    log.debug("Artifact  file with name {} type{} env {} already parsed but with env {}", resourceInfo.getFileName(),
+                        resourceInfo.getType(), resourceInfo.getEnv(), createdArtifactTemplateInfo.getEnv());
+                    return Either.right(componentsUtils
+                        .getResponseFormat(ActionStatus.ARTIFACT_NOT_VALID_ENV, resourceInfo.getFileName(), resourceInfo.getType(),
+                            resourceInfo.getEnv(), createdArtifactTemplateInfo.getEnv()));
                 }
             }
             List<ArtifactTemplateInfo> relatedArtifacts = createdArtifactTemplateInfo.getRelatedArtifactsInfo();
             Either<Boolean, ResponseFormat> status = validateEnv(componentsUtils, relatedArtifacts, resourceInfo);
-            if (status.isRight())
+            if (status.isRight()) {
                 return status;
+            }
         }
         return Either.left(true);
     }
 
     private static Either<List<ArtifactType>, ActionStatus> getDeploymentArtifactTypes(final NodeTypeEnum parentType) {
-
         final List<ArtifactConfiguration> deploymentArtifacts;
-        final List<ArtifactConfiguration> artifactConfigurationList =
-            ConfigurationManager.getConfigurationManager().getConfiguration().getArtifacts();
-
+        final List<ArtifactConfiguration> artifactConfigurationList = ConfigurationManager.getConfigurationManager().getConfiguration()
+            .getArtifacts();
         if (parentType == NodeTypeEnum.Service) {
-            deploymentArtifacts = artifactConfigurationList.stream()
-                .filter(artifactConfiguration ->
-                    artifactConfiguration.hasSupport(ArtifactGroupTypeEnum.DEPLOYMENT)
-                        && artifactConfiguration.hasSupport(ComponentType.SERVICE))
-                .collect(Collectors.toList());
+            deploymentArtifacts = artifactConfigurationList.stream().filter(
+                artifactConfiguration -> artifactConfiguration.hasSupport(ArtifactGroupTypeEnum.DEPLOYMENT) && artifactConfiguration
+                    .hasSupport(ComponentType.SERVICE)).collect(Collectors.toList());
         } else {
-            deploymentArtifacts = artifactConfigurationList.stream()
-                .filter(artifactConfiguration ->
-                    artifactConfiguration.hasSupport(ArtifactGroupTypeEnum.DEPLOYMENT)
-                        && artifactConfiguration.hasSupport(ComponentType.RESOURCE))
-                .collect(Collectors.toList());
+            deploymentArtifacts = artifactConfigurationList.stream().filter(
+                artifactConfiguration -> artifactConfiguration.hasSupport(ArtifactGroupTypeEnum.DEPLOYMENT) && artifactConfiguration
+                    .hasSupport(ComponentType.RESOURCE)).collect(Collectors.toList());
         }
         final List<ArtifactType> artifactTypes = new ArrayList<>();
         if (CollectionUtils.isNotEmpty(deploymentArtifacts)) {
@@ -315,7 +329,6 @@ public class ArtifactTemplateInfo {
             });
             return Either.left(artifactTypes);
         }
-
         return Either.right(ActionStatus.GENERAL_ERROR);
     }
 
index 7ef74a1..0a09156 100644 (file)
@@ -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.
  * limitations under the License.
  * ============LICENSE_END=========================================================
  */
-
 package org.openecomp.sdc.be.info;
 
+import java.util.List;
 import lombok.Getter;
 import lombok.Setter;
 import org.openecomp.sdc.be.model.ArtifactType;
 
-import java.util.List;
-
 @Getter
 @Setter
 public class ArtifactTypesInfo {
+
     private Integer heatDefaultTimeout = 60;
     private List<ArtifactType> artifactTypes;
 }
index 02e1238..7997ba4 100644 (file)
@@ -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,7 +19,6 @@
  * Modifications copyright (c) 2019 Nokia
  * ================================================================================
  */
-
 package org.openecomp.sdc.be.info;
 
 import lombok.AllArgsConstructor;
@@ -32,6 +31,7 @@ import org.openecomp.sdc.be.model.RequirementCapabilityRelDef;
 @Setter
 @AllArgsConstructor
 public class CreateAndAssotiateInfo {
+
     private ComponentInstance node;
     private RequirementCapabilityRelDef associate;
 }
index 0850be8..524cd31 100644 (file)
  * Modifications copyright (c) 2019 Nokia
  * ================================================================================
  */
-
 package org.openecomp.sdc.be.info;
 
+import java.util.Arrays;
+import java.util.Optional;
 import lombok.AllArgsConstructor;
 import lombok.Getter;
 import org.openecomp.sdc.common.log.wrappers.Logger;
 
-import java.util.Arrays;
-import java.util.Optional;
-
 @Getter
 @AllArgsConstructor
 public enum DistributionStatus {
     DEPLOYED("Deployed", "DEPLOYED");
-
+    private static final Logger log = Logger.getLogger(DistributionStatus.class);
     private String name;
     private String auditingStatus;
 
-    private static final Logger log = Logger.getLogger(DistributionStatus.class);
-
     public static DistributionStatus getStatusByAuditingStatusName(String auditingStatus) {
-        Optional<DistributionStatus> distributionStatus = Arrays.stream(values())
-            .filter(value -> value.getAuditingStatus().equals(auditingStatus)).findAny();
-        if (!distributionStatus.isPresent()){
+        Optional<DistributionStatus> distributionStatus = Arrays.stream(values()).filter(value -> value.getAuditingStatus().equals(auditingStatus))
+            .findAny();
+        if (!distributionStatus.isPresent()) {
             log.debug("No DistributionStatus is mapped to name {}", auditingStatus);
         }
         // it should be replaced by some exception handling. Keeping it only for the purpose of backward compatibility
index 9fc7476..e730ae2 100644 (file)
@@ -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,7 +19,6 @@
  * Modifications copyright (c) 2019 Nokia
  * ================================================================================
  */
-
 package org.openecomp.sdc.be.info;
 
 import lombok.Getter;
index d57437f..acd0c47 100644 (file)
@@ -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.
@@ -17,7 +17,6 @@
  * limitations under the License.
  * ============LICENSE_END=========================================================
  */
-
 package org.openecomp.sdc.be.info;
 
 import java.util.List;
@@ -27,5 +26,6 @@ import lombok.Setter;
 @Getter
 @Setter
 public class DistributionStatusListResponse {
+
     private List<DistributionStatusInfo> distributionStatusList;
 }
index f7bb1ea..a203def 100644 (file)
@@ -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,7 +19,6 @@
  * Modifications copyright (c) 2019 Nokia
  * ================================================================================
  */
-
 package org.openecomp.sdc.be.info;
 
 import lombok.AllArgsConstructor;
@@ -32,6 +31,7 @@ import lombok.Setter;
 @NoArgsConstructor
 @AllArgsConstructor
 public class DistributionStatusOfServiceInfo {
+
     private String distributionID;
     private String timestamp;
     private String userId;
index 23a71c6..b5e9758 100644 (file)
@@ -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.
@@ -17,7 +17,6 @@
  * limitations under the License.
  * ============LICENSE_END=========================================================
  */
-
 package org.openecomp.sdc.be.info;
 
 import java.util.List;
@@ -27,5 +26,6 @@ import lombok.Setter;
 @Getter
 @Setter
 public class DistributionStatusOfServiceListResponce {
+
     private List<DistributionStatusOfServiceInfo> distributionStatusOfServiceList;
 }
index 7aa0070..fb85273 100644 (file)
@@ -17,7 +17,6 @@
  * limitations under the License.
  * ============LICENSE_END=========================================================
  */
-
 package org.openecomp.sdc.be.info;
 
 import java.util.Set;
@@ -31,6 +30,7 @@ import lombok.Setter;
 @AllArgsConstructor
 @NoArgsConstructor
 public class GenericArtifactQueryInfo {
+
     private Set<String> fields;
     private String parentId;
     private String artifactUniqueId;
index 54920ea..79b8860 100644 (file)
  */
 package org.openecomp.sdc.be.info;
 
+import java.util.ArrayList;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
 import lombok.AccessLevel;
 import lombok.Getter;
 import lombok.Setter;
@@ -28,46 +32,38 @@ import org.openecomp.sdc.be.model.GroupDefinition;
 import org.openecomp.sdc.be.model.GroupInstance;
 import org.openecomp.sdc.be.model.GroupProperty;
 
-import java.util.ArrayList;
-import java.util.HashMap;
-import java.util.List;
-import java.util.Map;
 @Getter
 @Setter
 public class GroupDefinitionInfo {
-    private String name;
 
+    private String name;
     private String description;
-
     // the id is unique per group instance on graph.
     private String uniqueId;
-
     // the id is unique per group instance on graph.
     private String groupInstanceUniqueId;
-
     // the group UUID should be changed when one of the artifacts/component
+
     // instances has been changed.
     private String groupUUID;
-
     // version should be changed when there is a change to the group's metadata
+
     // or to the groups members
+
     // (not necessarily when the VF version is changed). This field cannot be
+
     // updated by user
     private String version;
-
     private String invariantUUID;
     private String customizationUUID;
-
     private Boolean isBase = null;
-
     // artifacts - list of artifact uid. All artifacts in the group must already
+
     // be uploaded to the VF
     @Getter(AccessLevel.NONE)
     @Setter(AccessLevel.NONE)
     private List<ArtifactDefinitionInfo> artifacts;
-
     private Map<String, String> members;
-
     @Getter(AccessLevel.NONE)
     @Setter(AccessLevel.NONE)
     private List<? extends GroupProperty> properties;
@@ -98,19 +94,19 @@ public class GroupDefinitionInfo {
     }
 
     public List<ArtifactDefinitionInfo> getArtifacts() {
-        return (artifacts==null) ? null : new ArrayList<>(artifacts);
+        return (artifacts == null) ? null : new ArrayList<>(artifacts);
     }
 
-    public List<GroupProperty> getProperties() {
-        return (properties==null) ? null : new ArrayList<>(properties);
+    public void setArtifacts(List<ArtifactDefinitionInfo> artifacts) {
+        this.artifacts = (artifacts == null) ? null : new ArrayList<>(artifacts);
     }
 
-    public void setArtifacts(List<ArtifactDefinitionInfo> artifacts) {
-        this.artifacts = (artifacts==null) ? null : new ArrayList<>(artifacts);
+    public List<GroupProperty> getProperties() {
+        return (properties == null) ? null : new ArrayList<>(properties);
     }
 
     public void setProperties(List<? extends GroupProperty> properties) {
-        this.properties = (properties==null) ? null : new ArrayList<>(properties);
+        this.properties = (properties == null) ? null : new ArrayList<>(properties);
     }
 
     @Override
index ddee613..0559ee7 100644 (file)
@@ -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.
@@ -17,7 +17,6 @@
  * limitations under the License.
  * ============LICENSE_END=========================================================
  */
-
 package org.openecomp.sdc.be.info;
 
 import lombok.Getter;
@@ -26,6 +25,7 @@ import lombok.Setter;
 @Getter
 @Setter
 public class GroupTemplateInfo {
+
     private String groupName;
     private boolean base;
     private ArtifactTemplateInfo artifactTemplateInfo;
index 4ae38f9..d97da41 100644 (file)
@@ -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.
  * limitations under the License.
  * ============LICENSE_END=========================================================
  */
-
 package org.openecomp.sdc.be.info;
 
-import lombok.AccessLevel;
-import lombok.Getter;
-import lombok.Setter;
-import org.apache.commons.lang3.tuple.ImmutablePair;
-import org.openecomp.sdc.be.model.ArtifactDefinition;
-
 import java.util.ArrayList;
 import java.util.HashSet;
 import java.util.List;
 import java.util.Optional;
 import java.util.Set;
+import lombok.AccessLevel;
+import lombok.Getter;
+import lombok.Setter;
+import org.apache.commons.lang3.tuple.ImmutablePair;
+import org.openecomp.sdc.be.model.ArtifactDefinition;
 
 public class MergedArtifactInfo {
 
-    @Getter @Setter(AccessLevel.NONE)
+    @Getter
+    @Setter(AccessLevel.NONE)
     private List<ArtifactDefinition> createdArtifact;
-    @Getter @Setter
+    @Getter
+    @Setter
     private ArtifactTemplateInfo jsonArtifactTemplate;
     private Set<String> parsedArtifactsNames;
 
@@ -63,21 +63,20 @@ public class MergedArtifactInfo {
         List<ArtifactDefinition> resList = new ArrayList<>();
         for (ArtifactDefinition artifactDefinition : createdArtifact) {
             boolean isDissotiate = true;
-            if(parsedArtifactsNames.contains(artifactDefinition.getArtifactName())){
+            if (parsedArtifactsNames.contains(artifactDefinition.getArtifactName())) {
                 isDissotiate = false;
-            }else{
-                if (artifactDefinition.getGeneratedFromId() != null && !artifactDefinition.getGeneratedFromId().isEmpty()){
-                    Optional<ArtifactDefinition> op = createdArtifact.stream().filter(p -> p.getUniqueId().equals(artifactDefinition.getGeneratedFromId())).findAny();
-                    if(op.isPresent()){
+            } else {
+                if (artifactDefinition.getGeneratedFromId() != null && !artifactDefinition.getGeneratedFromId().isEmpty()) {
+                    Optional<ArtifactDefinition> op = createdArtifact.stream()
+                        .filter(p -> p.getUniqueId().equals(artifactDefinition.getGeneratedFromId())).findAny();
+                    if (op.isPresent()) {
                         ArtifactDefinition generatedFromArt = op.get();
-                        if(parsedArtifactsNames.contains(generatedFromArt.getArtifactName())){
+                        if (parsedArtifactsNames.contains(generatedFromArt.getArtifactName())) {
                             isDissotiate = false;
                         }
-                    }
-                    else{
+                    } else {
                         isDissotiate = true;
                     }
-
                 }
             }
             if (isDissotiate) {
@@ -87,14 +86,12 @@ public class MergedArtifactInfo {
                         isDeleted = true;
                         break;
                     }
-
                 }
-                if (!isDeleted)
+                if (!isDeleted) {
                     resList.add(artifactDefinition);
+                }
             }
-
         }
-
         return resList;
     }
 
@@ -112,16 +109,14 @@ public class MergedArtifactInfo {
         return resList;
     }
 
-    private void getUpdateArtifactsInGroup(List<ImmutablePair<ArtifactDefinition, ArtifactTemplateInfo>> resList, List<ArtifactTemplateInfo> jsonArtifacts) {
-
+    private void getUpdateArtifactsInGroup(List<ImmutablePair<ArtifactDefinition, ArtifactTemplateInfo>> resList,
+                                           List<ArtifactTemplateInfo> jsonArtifacts) {
         for (ArtifactTemplateInfo artifactTemplateInfo : jsonArtifacts) {
-
             for (ArtifactDefinition artifactDefinition : createdArtifact) {
                 if (artifactDefinition.getArtifactName().equalsIgnoreCase(artifactTemplateInfo.getFileName())) {
                     resList.add(new ImmutablePair<>(artifactDefinition, artifactTemplateInfo));
                 }
             }
-
             List<ArtifactTemplateInfo> relatedArtifacts = artifactTemplateInfo.getRelatedArtifactsInfo();
             if (relatedArtifacts != null && !relatedArtifacts.isEmpty()) {
                 getUpdateArtifactsInGroup(resList, relatedArtifacts);
@@ -130,7 +125,6 @@ public class MergedArtifactInfo {
     }
 
     private void getNewArtifactsInGroup(List<ArtifactTemplateInfo> resList, List<ArtifactTemplateInfo> jsonArtifacts) {
-
         for (ArtifactTemplateInfo artifactTemplateInfo : jsonArtifacts) {
             boolean isNewArtifact = true;
             for (ArtifactDefinition artifactDefinition : createdArtifact) {
@@ -138,8 +132,9 @@ public class MergedArtifactInfo {
                     isNewArtifact = false;
                 }
             }
-            if (isNewArtifact)
+            if (isNewArtifact) {
                 resList.add(artifactTemplateInfo);
+            }
             List<ArtifactTemplateInfo> relatedArtifacts = artifactTemplateInfo.getRelatedArtifactsInfo();
             if (relatedArtifacts != null && !relatedArtifacts.isEmpty()) {
                 getNewArtifactsInGroup(resList, relatedArtifacts);
@@ -148,7 +143,6 @@ public class MergedArtifactInfo {
     }
 
     private void createArtifactsGroupSet(List<ArtifactTemplateInfo> parsedGroupTemplateList, Set<String> parsedArtifactsName) {
-
         for (ArtifactTemplateInfo parsedGroupTemplate : parsedGroupTemplateList) {
             parsedArtifactsName.add(parsedGroupTemplate.getFileName());
             List<ArtifactTemplateInfo> relatedArtifacts = parsedGroupTemplate.getRelatedArtifactsInfo();
index a4d7db2..53d722d 100644 (file)
  */
 package org.openecomp.sdc.be.info;
 
+import java.util.EnumMap;
+import java.util.List;
+import java.util.Map;
 import lombok.AllArgsConstructor;
 import lombok.Getter;
 import lombok.Setter;
 import org.openecomp.sdc.be.components.impl.ArtifactsBusinessLogic.ArtifactOperationEnum;
 import org.openecomp.sdc.be.model.ArtifactDefinition;
 
-import java.util.EnumMap;
-import java.util.List;
-import java.util.Map;
-
 @Getter
 @Setter
 @AllArgsConstructor
 public class NodeTypeInfoToUpdateArtifacts {
+
     private String nodeName;
     private Map<String, EnumMap<ArtifactOperationEnum, List<ArtifactDefinition>>> nodeTypesArtifactsToHandle;
 }
index daeea5e..a795b16 100644 (file)
@@ -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.
  * limitations under the License.
  * ============LICENSE_END=========================================================
  */
-
 package org.openecomp.sdc.be.info;
 
 import com.fasterxml.jackson.annotation.JsonIgnore;
 import com.fasterxml.jackson.annotation.JsonProperty;
 import com.fasterxml.jackson.core.JsonProcessingException;
 import com.fasterxml.jackson.databind.ObjectMapper;
+import java.io.IOException;
 import lombok.Getter;
 import lombok.Setter;
 import org.apache.commons.lang3.StringUtils;
 import org.openecomp.sdc.common.log.wrappers.Logger;
 
-import java.io.IOException;
-
 @Getter
 @Setter
 public final class OperationalEnvInfo {
-    @JsonIgnore
-    private static ObjectMapper objectMapper = new ObjectMapper();
-    
+
     @JsonIgnore
     private static final Logger logger = Logger.getLogger(OperationalEnvInfo.class);
-    
+    @JsonIgnore
+    private static ObjectMapper objectMapper = new ObjectMapper();
     @JsonProperty("operational-environment-id")
     private String operationalEnvId;
-
     @JsonProperty("operational-environment-name")
     private String operationalEnvName;
-
     @JsonProperty("operational-environment-type")
     private String operationalEnvType;
-
     @JsonProperty("operational-environment-status")
     private String operationalEnvStatus;
-
     @JsonProperty("tenant-context")
     private String tenantContext;
-
     @JsonProperty("workload-context")
     private String workloadContext;
-
     @JsonProperty("resource-version")
     private String resourceVersion;
-
     @JsonProperty("relationship-list")
     private RelationshipList relationships;
 
+    public static OperationalEnvInfo createFromJson(String json) throws IOException {
+        return objectMapper.readValue(json, OperationalEnvInfo.class);
+    }
+
     @Override
     public String toString() {
         try {
             return objectMapper.writeValueAsString(this);
-        }
-        catch (JsonProcessingException e) {
+        } catch (JsonProcessingException e) {
             logger.debug("Convert object to string failed with exception. ", e);
             return StringUtils.EMPTY;
         }
     }
-    
-    public static OperationalEnvInfo createFromJson(String json) throws IOException {
-        return objectMapper.readValue(json, OperationalEnvInfo.class);
-    }
 }
index abea083..eac4e67 100644 (file)
@@ -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.
@@ -17,7 +17,6 @@
  * limitations under the License.
  * ============LICENSE_END=========================================================
  */
-
 package org.openecomp.sdc.be.info;
 
 import com.fasterxml.jackson.annotation.JsonProperty;
@@ -30,7 +29,6 @@ public final class RelatedToProperty {
 
     @JsonProperty("property-key")
     private String propertyKey;
-
     @JsonProperty("property-value")
     private String propertyValue;
 }
index 3c5f1e2..a93ab15 100644 (file)
@@ -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.
  * limitations under the License.
  * ============LICENSE_END=========================================================
  */
-
 package org.openecomp.sdc.be.info;
 
 import com.fasterxml.jackson.annotation.JsonProperty;
-
 import java.util.ArrayList;
 import java.util.List;
 import lombok.AccessLevel;
@@ -31,33 +29,29 @@ import lombok.Setter;
 @Getter
 @Setter
 public final class Relationship {
-    
+
     @JsonProperty("related-to")
     private String relatedTo;
-
-    @JsonProperty(value="relationship-label")
+    @JsonProperty(value = "relationship-label")
     private String relationshipLabel;
-
-    @JsonProperty(value="related-link", required=false)
+    @JsonProperty(value = "related-link", required = false)
     private String relatedLink;
-
     @JsonProperty("relationship-data")
     @Getter(AccessLevel.NONE)
     private List<RelationshipData> relationshipData;
-
     @JsonProperty("related-to-property")
     @Getter(AccessLevel.NONE)
     private List<RelatedToProperty> relatedToProperty;
 
     public List<RelationshipData> getRelationshipData() {
-        if(relationshipData == null) {
+        if (relationshipData == null) {
             relationshipData = new ArrayList<>();
         }
         return relationshipData;
     }
 
     public List<RelatedToProperty> getRelatedToProperty() {
-        if(relatedToProperty == null) {
+        if (relatedToProperty == null) {
             relatedToProperty = new ArrayList<>();
         }
         return relatedToProperty;
index fd8d660..cfbb5ac 100644 (file)
@@ -29,7 +29,6 @@ public final class RelationshipData {
 
     @JsonProperty("relationship-key")
     private String relationshipKey;
-
     @JsonProperty("relationship-value")
     private String relationshipValue;
 }
index f143e01..5191a44 100644 (file)
@@ -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.
@@ -17,7 +17,6 @@
  * limitations under the License.
  * ============LICENSE_END=========================================================
  */
-
 package org.openecomp.sdc.be.info;
 
 import java.util.ArrayList;
@@ -26,10 +25,11 @@ import lombok.Setter;
 
 @Setter
 public class RelationshipList {
+
     private List<Relationship> relationship;
 
     public List<Relationship> getRelationship() {
-        if(relationship == null) {
+        if (relationship == null) {
             relationship = new ArrayList<>();
         }
         return relationship;
index 3ad6728..c8f4b15 100644 (file)
@@ -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.
@@ -17,7 +17,6 @@
  * limitations under the License.
  * ============LICENSE_END=========================================================
  */
-
 package org.openecomp.sdc.be.info;
 
 import java.util.List;
@@ -29,6 +28,7 @@ import lombok.Setter;
 @Setter
 @AllArgsConstructor
 public class ServiceInfo {
+
     private String name;
     private List<ServiceVersionInfo> versions;
 }
index bf01436..ab54b47 100644 (file)
@@ -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.
@@ -17,7 +17,6 @@
  * limitations under the License.
  * ============LICENSE_END=========================================================
  */
-
 package org.openecomp.sdc.be.info;
 
 import lombok.Getter;
@@ -28,8 +27,12 @@ import lombok.Setter;
 @Setter
 @NoArgsConstructor
 public class ServiceVersionInfo {
+
     private String version;
     private String url;
+    private String artifactUuid;
+    private String state;
+    private String distributionStatus;
 
     public ServiceVersionInfo(String serviceName, String serviceVersion, String context) {
         super();
@@ -39,12 +42,6 @@ public class ServiceVersionInfo {
         url = sb.toString();
     }
 
-
-    private String artifactUuid;
-    private String state;
-    private String distributionStatus;
-
-
     public static Builder newBuilder() {
         return new Builder();
     }
@@ -52,13 +49,17 @@ public class ServiceVersionInfo {
     public String getArtifactUuid() {
         return artifactUuid;
     }
+
     public String getState() {
         return state;
     }
-    public String getDistributionStatus() { return distributionStatus; }
 
+    public String getDistributionStatus() {
+        return distributionStatus;
+    }
 
     public static class Builder {
+
         private final ServiceVersionInfo instance;
 
         private Builder() {
index 1a438e5..3d46458 100644 (file)
@@ -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.
@@ -17,7 +17,6 @@
  * limitations under the License.
  * ============LICENSE_END=========================================================
  */
-
 package org.openecomp.sdc.be.info;
 
 import java.util.List;
@@ -27,5 +26,6 @@ import lombok.Setter;
 @Getter
 @Setter
 public class ServicesWrapper {
+
     private List<ServiceInfo> services;
 }
index 1c09444..5cf827d 100644 (file)
@@ -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.
@@ -17,7 +17,6 @@
  * limitations under the License.
  * ============LICENSE_END=========================================================
  */
-
 package org.openecomp.sdc.be.info;
 
 import lombok.Getter;
@@ -26,6 +25,7 @@ import lombok.Setter;
 @Getter
 @Setter
 public class ServletJsonResponse {
+
     private String source;
     private String description;
 }
index 8df81c1..1af072e 100644 (file)
@@ -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.
@@ -17,7 +17,6 @@
  * limitations under the License.
  * ============LICENSE_END=========================================================
  */
-
 package org.openecomp.sdc.be.info;
 
 import java.util.List;
@@ -35,6 +34,7 @@ public class ToscaNodeTypeInfo {
 
     @Override
     public String toString() {
-        return "ToscaNodeTypeInfo [nodeName=" + nodeName + ", templateVersion=" + templateVersion + ", interfaces=" + interfaces + ", iconPath=" + iconPath + "]";
+        return "ToscaNodeTypeInfo [nodeName=" + nodeName + ", templateVersion=" + templateVersion + ", interfaces=" + interfaces + ", iconPath="
+            + iconPath + "]";
     }
 }
index 19ed017..b276ec6 100644 (file)
@@ -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.
@@ -17,7 +17,6 @@
  * limitations under the License.
  * ============LICENSE_END=========================================================
  */
-
 package org.openecomp.sdc.be.info;
 
 import java.util.List;
@@ -27,5 +26,6 @@ import lombok.Setter;
 @Getter
 @Setter
 public class ToscaNodeTypeInterface {
+
     private List<String> scripts;
 }
index 7d9de79..76be33c 100644 (file)
@@ -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.
  * limitations under the License.
  * ============LICENSE_END=========================================================
  */
-
 package org.openecomp.sdc.be.listen;
 
+import java.io.IOException;
+import java.io.InputStream;
+import java.util.jar.Attributes;
+import java.util.jar.Manifest;
+import javax.servlet.ServletContext;
+import javax.servlet.ServletContextEvent;
+import javax.servlet.ServletContextListener;
 import org.openecomp.sdc.be.config.ConfigurationManager;
 import org.openecomp.sdc.be.impl.WebAppContextWrapper;
 import org.openecomp.sdc.be.monitoring.BeMonitoringService;
@@ -28,45 +34,28 @@ import org.openecomp.sdc.common.impl.ExternalConfiguration;
 import org.openecomp.sdc.common.listener.AppContextListener;
 import org.openecomp.sdc.common.log.wrappers.Logger;
 
-import javax.servlet.ServletContext;
-import javax.servlet.ServletContextEvent;
-import javax.servlet.ServletContextListener;
-import java.io.IOException;
-import java.io.InputStream;
-import java.util.jar.Attributes;
-import java.util.jar.Manifest;
-
 public class BEAppContextListener extends AppContextListener implements ServletContextListener {
 
     private static final String MANIFEST_FILE_NAME = "/META-INF/MANIFEST.MF";
     private static final Logger log = Logger.getLogger(BEAppContextListener.class);
 
     public void contextInitialized(ServletContextEvent context) {
-
         super.contextInitialized(context);
-
         ConfigurationManager configurationManager = new ConfigurationManager(ExternalConfiguration.getConfigurationSource());
         log.debug("loading configuration from configDir: {} appName: {}", ExternalConfiguration.getConfigDir(), ExternalConfiguration.getAppName());
-
         context.getServletContext().setAttribute(Constants.CONFIGURATION_MANAGER_ATTR, configurationManager);
-
         WebAppContextWrapper webAppContextWrapper = new WebAppContextWrapper();
         context.getServletContext().setAttribute(Constants.WEB_APPLICATION_CONTEXT_WRAPPER_ATTR, webAppContextWrapper);
-
         context.getServletContext().setAttribute(Constants.ASDC_RELEASE_VERSION_ATTR, getVersionFromManifest(context));
-
         // Monitoring service
         BeMonitoringService bms = new BeMonitoringService(context.getServletContext());
         bms.start(configurationManager.getConfiguration().getSystemMonitoring().getProbeIntervalInSeconds(15));
-
         log.debug("After executing {}", this.getClass());
-
     }
 
     private String getVersionFromManifest(ServletContextEvent context) {
         ServletContext servletContext = context.getServletContext();
         InputStream inputStream = servletContext.getResourceAsStream(MANIFEST_FILE_NAME);
-
         String version = null;
         try {
             Manifest mf = new Manifest(inputStream);
@@ -77,11 +66,9 @@ public class BEAppContextListener extends AppContextListener implements ServletC
             } else {
                 log.info("ASDC version from MANIFEST is {}", version);
             }
-
         } catch (IOException e) {
             log.warn("failed to read ASDC version from MANIFEST", e);
         }
         return version;
     }
-
 }
index 547ae17..0d2616e 100644 (file)
  * limitations under the License.
  * ============LICENSE_END=========================================================
  */
-
 package org.openecomp.sdc.be.mixin;
 
 import com.fasterxml.jackson.annotation.JsonProperty;
+import java.util.List;
 import org.openecomp.sdc.be.datatypes.elements.PropertyRule;
 import org.openecomp.sdc.be.model.ComponentInstanceInput;
 import org.openecomp.sdc.be.view.MixinTarget;
 
-import java.util.List;
-
 @MixinTarget(target = ComponentInstanceInput.class)
-public abstract class ComponentInstanceInputMixin extends InputDefinitionMixin{
+public abstract class ComponentInstanceInputMixin extends InputDefinitionMixin {
+
     @JsonProperty
     abstract String getComponentInstanceId();
+
     @JsonProperty
     abstract String getComponentInstanceName();
+
     @JsonProperty
     abstract List<String> getPath();
+
     @JsonProperty
     abstract List<PropertyRule> getRules();
+
     @JsonProperty
     abstract String getValueUniqueUid();
 }
index f9c41fb..c5d97d6 100644 (file)
  * limitations under the License.
  * ============LICENSE_END=========================================================
  */
-
 package org.openecomp.sdc.be.mixin;
 
 import com.fasterxml.jackson.annotation.JsonProperty;
+import java.util.List;
 import org.openecomp.sdc.be.datatypes.elements.PropertyRule;
 import org.openecomp.sdc.be.model.ComponentInstanceProperty;
 import org.openecomp.sdc.be.view.MixinTarget;
 
-import java.util.List;
-
 @MixinTarget(target = ComponentInstanceProperty.class)
 public abstract class ComponentInstancePropertyMixin extends PropertyDefinitionMixin {
 
     @JsonProperty
     abstract String getComponentInstanceId();
+
     @JsonProperty
     abstract String getComponentInstanceName();
+
     @JsonProperty
     abstract List<String> getPath();
+
     @JsonProperty
     abstract List<PropertyRule> getRules();
+
     @JsonProperty
     abstract String getValueUniqueUid();
 }
index c46b064..6ab0af6 100644 (file)
@@ -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.
  * limitations under the License.
  * ============LICENSE_END=========================================================
  */
-
 package org.openecomp.sdc.be.mixin;
 
 import com.fasterxml.jackson.annotation.JsonProperty;
+import java.util.Map;
 import org.openecomp.sdc.be.datatypes.elements.GroupDataDefinition;
 import org.openecomp.sdc.be.view.Mixin;
 import org.openecomp.sdc.be.view.MixinTarget;
 
-import java.util.Map;
-
 @MixinTarget(target = GroupDataDefinition.class)
-public abstract  class GroupCompositionMixin  extends Mixin {
+public abstract class GroupCompositionMixin extends Mixin {
+
     @JsonProperty
     abstract String getName();
+
     @JsonProperty("members")
     abstract Map<String, String> resolveMembersList();
+
     @JsonProperty
     abstract String getUniqueId();
+
     @JsonProperty
     abstract String getType();
-
-
 }
index b8ca0e3..db705cb 100644 (file)
@@ -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.
@@ -17,7 +17,6 @@
  * limitations under the License.
  * ============LICENSE_END=========================================================
  */
-
 package org.openecomp.sdc.be.mixin;
 
 import com.fasterxml.jackson.annotation.JsonProperty;
@@ -30,15 +29,16 @@ public abstract class GroupTypeMixin extends Mixin {
 
     @JsonProperty
     abstract String getType();
+
     @JsonProperty
     abstract String getVersion();
+
     @JsonProperty
     abstract String getUniqueId();
+
     @JsonProperty
     abstract String getName();
+
     @JsonProperty
     abstract String getIcon();
-
 }
-
-
index dba7ff5..0634a57 100644 (file)
  * limitations under the License.
  * ============LICENSE_END=========================================================
  */
-
 package org.openecomp.sdc.be.mixin;
 
 import com.fasterxml.jackson.annotation.JsonProperty;
+import java.util.List;
 import org.openecomp.sdc.be.model.ComponentInstanceInput;
 import org.openecomp.sdc.be.model.ComponentInstanceProperty;
 import org.openecomp.sdc.be.model.InputDefinition;
 import org.openecomp.sdc.be.view.MixinTarget;
 
-import java.util.List;
-
 @MixinTarget(target = InputDefinition.class)
 public abstract class InputDefinitionMixin extends PropertyDefinitionMixin {
 
     @JsonProperty
     abstract List<ComponentInstanceInput> getInputs();
+
     @JsonProperty
     abstract List<ComponentInstanceProperty> getProperties();
 }
index 6a5d245..a334df9 100644 (file)
@@ -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.
  * limitations under the License.
  * ============LICENSE_END=========================================================
  */
-
 package org.openecomp.sdc.be.mixin;
 
 import com.fasterxml.jackson.annotation.JsonProperty;
+import java.util.List;
+import java.util.Map;
 import org.openecomp.sdc.be.datatypes.elements.PolicyDataDefinition;
 import org.openecomp.sdc.be.datatypes.elements.PolicyTargetType;
 import org.openecomp.sdc.be.view.Mixin;
 import org.openecomp.sdc.be.view.MixinTarget;
 
-import java.util.List;
-import java.util.Map;
-
 @MixinTarget(target = PolicyDataDefinition.class)
-public abstract  class PolicyCompositionMixin extends Mixin {
+public abstract class PolicyCompositionMixin extends Mixin {
+
     @JsonProperty
     abstract String getName();
+
     @JsonProperty
     abstract Map<PolicyTargetType, List<String>> getTargets();
+
     @JsonProperty
     abstract String getUniqueId();
+
     @JsonProperty("type")
     abstract String getPolicyTypeName();
+
     @JsonProperty
     abstract String getInputPath();
+
     @JsonProperty
     abstract String getValue();
+
     @JsonProperty
     abstract String getInstanceUniqueId();
-
-
 }
index 1a371fd..bce79d2 100644 (file)
@@ -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.
@@ -17,7 +17,6 @@
  * limitations under the License.
  * ============LICENSE_END=========================================================
  */
-
 package org.openecomp.sdc.be.mixin;
 
 import com.fasterxml.jackson.annotation.JsonProperty;
@@ -30,15 +29,16 @@ public abstract class PolicyTypeMixin extends Mixin {
 
     @JsonProperty
     abstract String getName();
+
     @JsonProperty
     abstract String getType();
+
     @JsonProperty
     abstract String getVersion();
+
     @JsonProperty
     abstract String getUniqueId();
+
     @JsonProperty
     abstract String getIcon();
-
 }
-
-
index 17dcf96..5d567f7 100644 (file)
  * limitations under the License.
  * ============LICENSE_END=========================================================
  */
-
 package org.openecomp.sdc.be.mixin;
 
 import com.fasterxml.jackson.annotation.JsonProperty;
+import java.util.List;
 import org.openecomp.sdc.be.datatypes.elements.Annotation;
 import org.openecomp.sdc.be.datatypes.elements.GetInputValueDataDefinition;
 import org.openecomp.sdc.be.datatypes.elements.SchemaDefinition;
@@ -29,49 +29,66 @@ import org.openecomp.sdc.be.model.PropertyDefinition;
 import org.openecomp.sdc.be.view.Mixin;
 import org.openecomp.sdc.be.view.MixinTarget;
 
-import java.util.List;
-
 @MixinTarget(target = PropertyDefinition.class)
 public abstract class PropertyDefinitionMixin extends Mixin {
 
     @JsonProperty
     abstract List<Annotation> getAnnotations();
+
     @JsonProperty
     abstract String getDefaultValue();
+
     @JsonProperty
     abstract String getDescription();
+
     @JsonProperty
     abstract List<GetInputValueDataDefinition> getGetInputValues();
+
     @JsonProperty
     abstract String getInputId();
+
     @JsonProperty
     abstract String getInputPath();
+
     @JsonProperty
     abstract String getInstanceUniqueId();
+
     @JsonProperty
     abstract String getLabel();
+
     @JsonProperty
     abstract String getName();
+
     @JsonProperty
     abstract String getParentUniqueId();
+
     @JsonProperty
     abstract String getPropertyId();
+
     @JsonProperty
     abstract SchemaDefinition getSchema();
+
     @JsonProperty
     abstract SchemaDefinition getSchemaProperty();
+
     @JsonProperty
     abstract String getSchemaType();
+
     @JsonProperty
     abstract String getStatus();
+
     @JsonProperty
     abstract String getType();
+
     @JsonProperty
     abstract String getUniqueId();
+
     @JsonProperty
     abstract String getValue();
+
     @JsonProperty
     abstract boolean isGetInputProperty();
+
     @JsonProperty
     abstract List<PropertyConstraint> getConstraints();
 }
index 856d53f..03a2f59 100644 (file)
@@ -5,35 +5,33 @@
  * 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.
- * 
+ *
  * SPDX-License-Identifier: Apache-2.0
  * ============LICENSE_END=========================================================
  */
 package org.openecomp.sdc.be.plugins;
 
 import java.util.Map;
-
 import org.openecomp.sdc.be.model.Component;
 
 /**
  * Implementations of this interface shall generate entries to be included in a csar.
  */
 public interface CsarEntryGenerator {
-       
-       /**
-        * Generate entries to be included in a csar.
-        * 
-        * @param component the component the csar is based on
-        * @return Map of name to contents for entries to be included in the csar
-        */
-       Map<String, byte[]> generateCsarEntries(final Component component);
 
+    /**
+     * Generate entries to be included in a csar.
+     *
+     * @param component the component the csar is based on
+     * @return Map of name to contents for entries to be included in the csar
+     */
+    Map<String, byte[]> generateCsarEntries(final Component component);
 }
index 4981a33..f54bf49 100644 (file)
@@ -16,7 +16,6 @@
  *  SPDX-License-Identifier: Apache-2.0
  *  ============LICENSE_END=========================================================
  */
-
 package org.openecomp.sdc.be.plugins;
 
 import org.openecomp.sdc.be.model.Service;
@@ -39,5 +38,4 @@ public interface ServiceCreationPlugin {
      * @return a order
      */
     int getOrder();
-
 }
index cb0cc23..beaa08c 100644 (file)
@@ -19,7 +19,6 @@
  * Modifications copyright (c) 2019 Nokia
  * ================================================================================
  */
-
 package org.openecomp.sdc.be.servlets;
 
 import com.fasterxml.jackson.databind.ObjectMapper;
@@ -43,7 +42,6 @@ import javax.servlet.ServletContext;
 import javax.servlet.http.HttpServletRequest;
 import javax.ws.rs.core.Response;
 import org.apache.commons.codec.binary.Base64;
-import org.apache.commons.collections4.MapUtils;
 import org.apache.commons.io.IOUtils;
 import org.apache.commons.lang3.StringUtils;
 import org.apache.commons.lang3.tuple.ImmutablePair;
@@ -94,31 +92,38 @@ public abstract class AbstractValidationsServlet extends BeGenericServlet {
 
     private static final Logger log = Logger.getLogger(AbstractValidationsServlet.class);
     private static final String TOSCA_SIMPLE_YAML_PREFIX = "tosca_simple_yaml_";
-    private static final List<String> TOSCA_DEFINITION_VERSIONS = Arrays.asList(
-        TOSCA_SIMPLE_YAML_PREFIX + "1_0_0",
-        TOSCA_SIMPLE_YAML_PREFIX + "1_1_0",
-        "tosca_simple_profile_for_nfv_1_0_0",
-        TOSCA_SIMPLE_YAML_PREFIX + "1_0",
-        TOSCA_SIMPLE_YAML_PREFIX + "1_1",
-        TOSCA_SIMPLE_YAML_PREFIX + "1_2",
-        TOSCA_SIMPLE_YAML_PREFIX + "1_3");
+    private static final List<String> TOSCA_DEFINITION_VERSIONS = Arrays
+        .asList(TOSCA_SIMPLE_YAML_PREFIX + "1_0_0", TOSCA_SIMPLE_YAML_PREFIX + "1_1_0", "tosca_simple_profile_for_nfv_1_0_0",
+            TOSCA_SIMPLE_YAML_PREFIX + "1_0", TOSCA_SIMPLE_YAML_PREFIX + "1_1", TOSCA_SIMPLE_YAML_PREFIX + "1_2", TOSCA_SIMPLE_YAML_PREFIX + "1_3");
     private static final List<String> TOSCA_YML_CSAR_VALID_SUFFIX = Arrays.asList(".yml", ".yaml", ".csar", ".meta");
-
+    protected final ComponentInstanceBusinessLogic componentInstanceBusinessLogic;
     protected ServletUtils servletUtils;
     protected ResourceImportManager resourceImportManager;
-    protected final ComponentInstanceBusinessLogic componentInstanceBusinessLogic;
-
     protected ServiceImportManager serviceImportManager;
 
-    public AbstractValidationsServlet(UserBusinessLogic userBusinessLogic,
-        ComponentInstanceBusinessLogic componentInstanceBL, ComponentsUtils componentsUtils,
-        ServletUtils servletUtils, ResourceImportManager resourceImportManager) {
+    public AbstractValidationsServlet(UserBusinessLogic userBusinessLogic, ComponentInstanceBusinessLogic componentInstanceBL,
+                                      ComponentsUtils componentsUtils, ServletUtils servletUtils, ResourceImportManager resourceImportManager) {
         super(userBusinessLogic, componentsUtils);
         this.servletUtils = servletUtils;
         this.resourceImportManager = resourceImportManager;
         this.componentInstanceBusinessLogic = componentInstanceBL;
     }
 
+    public static void extractZipContents(Wrapper<String> yamlStringWrapper, File file) throws ZipException {
+        final Map<String, byte[]> unzippedFolder = ZipUtils.readZip(file, false);
+        String ymlName = unzippedFolder.keySet().iterator().next();
+        fillToscaTemplateFromZip(yamlStringWrapper, ymlName, file);
+    }
+
+    private static void fillToscaTemplateFromZip(final Wrapper<String> yamlStringWrapper, final String payloadName, final File file)
+        throws ZipException {
+        final Map<String, byte[]> unzippedFolder = ZipUtils.readZip(file, false);
+        final byte[] yamlFileInBytes = unzippedFolder.get(payloadName);
+        final String yamlAsString = new String(yamlFileInBytes, StandardCharsets.UTF_8);
+        log.debug("received yaml: {}", yamlAsString);
+        yamlStringWrapper.setInnerElement(yamlAsString);
+    }
+
     protected void init() {
     }
 
@@ -126,7 +131,7 @@ public abstract class AbstractValidationsServlet extends BeGenericServlet {
         if (serviceImportManager == null) {
             ServletContext context = servletRequest.getSession().getServletContext();
             WebAppContextWrapper webApplicationContextWrapper = (WebAppContextWrapper) context
-                    .getAttribute(Constants.WEB_APPLICATION_CONTEXT_WRAPPER_ATTR);
+                .getAttribute(Constants.WEB_APPLICATION_CONTEXT_WRAPPER_ATTR);
             WebApplicationContext webApplicationContext = webApplicationContextWrapper.getWebAppContext(context);
             serviceImportManager = webApplicationContext.getBean(ServiceImportManager.class);
         }
@@ -148,9 +153,7 @@ public abstract class AbstractValidationsServlet extends BeGenericServlet {
             log.info("user userId is null");
             Response response = returnMissingInformation(new User());
             responseWrapper.setInnerElement(response);
-        }
-
-        else {
+        } else {
             UserBusinessLogic userAdmin = getServletUtils().getUserAdmin();
             try {
                 User user = userAdmin.getUser(userUserId);
@@ -180,7 +183,6 @@ public abstract class AbstractValidationsServlet extends BeGenericServlet {
                 break;
             }
         }
-
     }
 
     protected void validateUserRole(Wrapper<Response> errorResponseWrapper, User user) {
@@ -190,18 +192,15 @@ public abstract class AbstractValidationsServlet extends BeGenericServlet {
             ResponseFormat responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.RESTRICTED_OPERATION);
             log.debug("audit before sending response");
             getComponentsUtils().auditResource(responseFormat, user, "", AuditingActionEnum.IMPORT_RESOURCE);
-
             Response response = buildErrorResponse(responseFormat);
             errorResponseWrapper.setInnerElement(response);
         }
-
     }
 
     protected void validateZip(final Wrapper<Response> responseWrapper, final File zipFile, final String payloadName) {
         if (StringUtils.isEmpty(payloadName)) {
             log.info("Invalid JSON was received. Payload name is empty");
-            final Response errorResponse =
-                buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.INVALID_CONTENT));
+            final Response errorResponse = buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.INVALID_CONTENT));
             responseWrapper.setInnerElement(errorResponse);
             return;
         }
@@ -210,19 +209,15 @@ public abstract class AbstractValidationsServlet extends BeGenericServlet {
             unzippedFolder = ZipUtils.readZip(zipFile, false);
         } catch (final ZipException e) {
             log.error("Could not read ZIP file '{}' for validation", zipFile.getName(), e);
-            final Response errorResponse =
-                buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.INVALID_CONTENT));
+            final Response errorResponse = buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.INVALID_CONTENT));
             responseWrapper.setInnerElement(errorResponse);
             return;
         }
         if (!unzippedFolder.containsKey(payloadName)) {
             log.info("Could no find payload '{}' in ZIP file '{}'", payloadName, zipFile.getName());
-            final Response errorResponse =
-                buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.INVALID_CONTENT));
+            final Response errorResponse = buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.INVALID_CONTENT));
             responseWrapper.setInnerElement(errorResponse);
         }
-
-
     }
 
     protected void validateCsar(final Wrapper<Response> responseWrapper, final File csarFile, final String payloadName) {
@@ -237,8 +232,7 @@ public abstract class AbstractValidationsServlet extends BeGenericServlet {
             unzippedFolder = ZipUtils.readZip(csarFile, false);
         } catch (final ZipException e) {
             log.error("Could not read CSAR file '{}' for validation", csarFile.getName(), e);
-            final Response errorResponse =
-                buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.INVALID_CONTENT));
+            final Response errorResponse = buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.INVALID_CONTENT));
             responseWrapper.setInnerElement(errorResponse);
             return;
         }
@@ -247,52 +241,29 @@ public abstract class AbstractValidationsServlet extends BeGenericServlet {
             Response errorResponse = buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.INVALID_CONTENT));
             responseWrapper.setInnerElement(errorResponse);
         }
-
     }
 
     protected void fillZipContents(Wrapper<String> yamlStringWrapper, File file) throws ZipException {
         extractZipContents(yamlStringWrapper, file);
     }
 
-    public static void extractZipContents(Wrapper<String> yamlStringWrapper, File file) throws ZipException {
-        final Map<String, byte[]> unzippedFolder = ZipUtils.readZip(file, false);
-        String ymlName = unzippedFolder.keySet().iterator().next();
-        fillToscaTemplateFromZip(yamlStringWrapper, ymlName, file);
-    }
-
-    private static void fillToscaTemplateFromZip(final Wrapper<String> yamlStringWrapper, final String payloadName,
-                                                 final File file) throws ZipException {
-        final Map<String, byte[]> unzippedFolder = ZipUtils.readZip(file, false);
-        final byte[] yamlFileInBytes = unzippedFolder.get(payloadName);
-        final String yamlAsString = new String(yamlFileInBytes, StandardCharsets.UTF_8);
-        log.debug("received yaml: {}", yamlAsString);
-        yamlStringWrapper.setInnerElement(yamlAsString);
-    }
-
-    protected void fillPayloadDataFromFile(Wrapper<Response> responseWrapper, UploadResourceInfo uploadResourceInfoWrapper, File file)  {
-        try(InputStream fileInputStream = new FileInputStream(file)){
-
-            byte [] data = new byte[(int)file.length()];
-            if( fileInputStream.read(data) == -1){
+    protected void fillPayloadDataFromFile(Wrapper<Response> responseWrapper, UploadResourceInfo uploadResourceInfoWrapper, File file) {
+        try (InputStream fileInputStream = new FileInputStream(file)) {
+            byte[] data = new byte[(int) file.length()];
+            if (fileInputStream.read(data) == -1) {
                 log.info("Invalid json was received.");
                 ResponseFormat responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.INVALID_CONTENT);
-
                 Response errorResp = buildErrorResponse(responseFormat);
                 responseWrapper.setInnerElement(errorResp);
             }
-            String payloadData =  Base64.encodeBase64String(data);
+            String payloadData = Base64.encodeBase64String(data);
             uploadResourceInfoWrapper.setPayloadData(payloadData);
-
-
-
         } catch (IOException e) {
             log.info("Invalid json was received or Error while closing input Stream.");
             log.debug("Invalid json was received or Error while closing input Stream. {}", e.getMessage(), e);
             ResponseFormat responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.INVALID_CONTENT);
-
             Response errorResp = buildErrorResponse(responseFormat);
             responseWrapper.setInnerElement(errorResp);
-
         }
     }
 
@@ -304,17 +275,16 @@ public abstract class AbstractValidationsServlet extends BeGenericServlet {
                 ResponseFormat responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.RESTRICTED_OPERATION);
                 log.debug("audit before sending response");
                 getComponentsUtils().auditResource(responseFormat, user, "", AuditingActionEnum.IMPORT_RESOURCE);
-
                 Response response = buildErrorResponse(responseFormat);
                 errorResponseWrapper.setInnerElement(response);
             }
         } else {
             validateUserRole(errorResponseWrapper, user);
         }
-
     }
 
-    protected void validateAndFillResourceJson(Wrapper<Response> responseWrapper, Wrapper<UploadResourceInfo> uploadResourceInfoWrapper, User user, ResourceAuthorityTypeEnum resourceAuthorityEnum, String resourceInfo) {
+    protected void validateAndFillResourceJson(Wrapper<Response> responseWrapper, Wrapper<UploadResourceInfo> uploadResourceInfoWrapper, User user,
+                                               ResourceAuthorityTypeEnum resourceAuthorityEnum, String resourceInfo) {
         boolean isValid;
         try {
             log.debug("The received json is {}", resourceInfo);
@@ -330,11 +300,9 @@ public abstract class AbstractValidationsServlet extends BeGenericServlet {
                 }
                 uploadResourceInfoWrapper.setInnerElement(resourceInfoObject);
             }
-
         } catch (JsonSyntaxException e) {
             log.debug("Invalid json was received. {}", e.getMessage(), e);
             isValid = false;
-
         }
         if (!isValid) {
             log.info("Invalid json was received.");
@@ -371,8 +339,8 @@ public abstract class AbstractValidationsServlet extends BeGenericServlet {
         log.debug("checking payload is valid tosca");
         boolean isValid;
         Map<String, Object> mappedToscaTemplate = (Map<String, Object>) new Yaml().load(toscaPayload);
-        Either<String, ResultStatusEnum> findFirstToscaStringElement = ImportUtils.findFirstToscaStringElement(mappedToscaTemplate, TypeUtils.ToscaTagNamesEnum.TOSCA_VERSION);
-
+        Either<String, ResultStatusEnum> findFirstToscaStringElement = ImportUtils
+            .findFirstToscaStringElement(mappedToscaTemplate, TypeUtils.ToscaTagNamesEnum.TOSCA_VERSION);
         if (findFirstToscaStringElement.isRight()) {
             isValid = false;
         } else {
@@ -383,17 +351,16 @@ public abstract class AbstractValidationsServlet extends BeGenericServlet {
                 isValid = TOSCA_DEFINITION_VERSIONS.contains(defenitionVersionFound);
             }
         }
-
         if (!isValid) {
             ResponseFormat responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.INVALID_TOSCA_TEMPLATE);
             Response errorResponse = buildErrorResponse(responseFormat);
             getComponentsUtils().auditResource(responseFormat, user, uploadResourceInfo.getName(), AuditingActionEnum.IMPORT_RESOURCE);
             responseWrapper.setInnerElement(errorResponse);
         }
-
     }
 
-    protected void validatePayloadIsYml(Wrapper<Response> responseWrapper, User user, UploadResourceInfo uploadResourceInfo, String toscaTamplatePayload) {
+    protected void validatePayloadIsYml(Wrapper<Response> responseWrapper, User user, UploadResourceInfo uploadResourceInfo,
+                                        String toscaTamplatePayload) {
         log.debug("checking tosca template is valid yml");
         YamlToObjectConverter yamlConvertor = new YamlToObjectConverter();
         boolean isYamlValid = yamlConvertor.isValidYaml(toscaTamplatePayload.getBytes());
@@ -412,7 +379,6 @@ public abstract class AbstractValidationsServlet extends BeGenericServlet {
      * @return Resource Type name
      */
     private String getResourceType(final String nodeTypeFullName) {
-
         final Optional<String> nodeTypeNamePrefix = getNodeTypeNamePrefix(nodeTypeFullName);
         if (nodeTypeNamePrefix.isPresent()) {
             final String nameWithouNamespacePrefix = nodeTypeFullName.substring(nodeTypeNamePrefix.get().length());
@@ -429,12 +395,13 @@ public abstract class AbstractValidationsServlet extends BeGenericServlet {
 
     /**
      * Extracts the Node Type Name prefix from the given Node Type Name.
+     *
      * @param nodeName - Node Type Name
      * @return Node Type Name prefix
      */
     private Optional<String> getNodeTypeNamePrefix(final String nodeName) {
-        final List<String> definedNodeTypeNamespaceList = ConfigurationManager.getConfigurationManager()
-            .getConfiguration().getDefinedResourceNamespace();
+        final List<String> definedNodeTypeNamespaceList = ConfigurationManager.getConfigurationManager().getConfiguration()
+            .getDefinedResourceNamespace();
         for (final String validNamespace : definedNodeTypeNamespaceList) {
             if (nodeName.startsWith(validNamespace)) {
                 return Optional.of(validNamespace);
@@ -443,13 +410,13 @@ public abstract class AbstractValidationsServlet extends BeGenericServlet {
         return Optional.empty();
     }
 
-    protected void validatePayloadNameSpace(final Wrapper<Response> responseWrapper,
-                                            final UploadResourceInfo resourceInfo,
-                                            final User user, final String toscaPayload) {
+    protected void validatePayloadNameSpace(final Wrapper<Response> responseWrapper, final UploadResourceInfo resourceInfo, final User user,
+                                            final String toscaPayload) {
         boolean isValid;
         String namespace = "";
         final Map<String, Object> mappedToscaTemplate = (Map<String, Object>) new Yaml().load(toscaPayload);
-        final Either<Map<String, Object>, ResultStatusEnum> toscaElement = ImportUtils.findFirstToscaMapElement(mappedToscaTemplate, TypeUtils.ToscaTagNamesEnum.NODE_TYPES);
+        final Either<Map<String, Object>, ResultStatusEnum> toscaElement = ImportUtils
+            .findFirstToscaMapElement(mappedToscaTemplate, TypeUtils.ToscaTagNamesEnum.NODE_TYPES);
         if (toscaElement.isRight() || toscaElement.left().value().size() != 1) {
             isValid = false;
         } else {
@@ -466,38 +433,38 @@ public abstract class AbstractValidationsServlet extends BeGenericServlet {
         }
     }
 
-    private void validatePayloadIsSingleResource(Wrapper<Response> responseWrapper, UploadResourceInfo uploadResourceInfo, User user, String toscaPayload) {
+    private void validatePayloadIsSingleResource(Wrapper<Response> responseWrapper, UploadResourceInfo uploadResourceInfo, User user,
+                                                 String toscaPayload) {
         log.debug("checking payload contains single resource");
         boolean isValid;
         Map<String, Object> mappedToscaTemplate = (Map<String, Object>) new Yaml().load(toscaPayload);
-        Either<Map<String, Object>, ResultStatusEnum> toscaElement = ImportUtils.findFirstToscaMapElement(mappedToscaTemplate, TypeUtils.ToscaTagNamesEnum.NODE_TYPES);
+        Either<Map<String, Object>, ResultStatusEnum> toscaElement = ImportUtils
+            .findFirstToscaMapElement(mappedToscaTemplate, TypeUtils.ToscaTagNamesEnum.NODE_TYPES);
         if (toscaElement.isRight()) {
             isValid = false;
         } else {
             isValid = toscaElement.left().value().size() == 1;
         }
-
         if (!isValid) {
             ResponseFormat responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.NOT_SINGLE_RESOURCE);
             Response errorResponse = buildErrorResponse(responseFormat);
             getComponentsUtils().auditResource(responseFormat, user, uploadResourceInfo.getName(), AuditingActionEnum.IMPORT_RESOURCE);
             responseWrapper.setInnerElement(errorResponse);
         }
-
     }
 
-    private void validatePayloadIsNotService(Wrapper<Response> responseWrapper, User user, UploadResourceInfo uploadResourceInfo, String toscaPayload) {
+    private void validatePayloadIsNotService(Wrapper<Response> responseWrapper, User user, UploadResourceInfo uploadResourceInfo,
+                                             String toscaPayload) {
         log.debug("checking payload is not a tosca service");
         Map<String, Object> mappedToscaTemplate = (Map<String, Object>) new Yaml().load(toscaPayload);
-        Either<Object, ResultStatusEnum> toscaElement = ImportUtils.findToscaElement(mappedToscaTemplate, TypeUtils.ToscaTagNamesEnum.TOPOLOGY_TEMPLATE, ToscaElementTypeEnum.ALL);
-
+        Either<Object, ResultStatusEnum> toscaElement = ImportUtils
+            .findToscaElement(mappedToscaTemplate, TypeUtils.ToscaTagNamesEnum.TOPOLOGY_TEMPLATE, ToscaElementTypeEnum.ALL);
         if (toscaElement.isLeft()) {
             ResponseFormat responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.NOT_RESOURCE_TOSCA_TEMPLATE);
             Response errorResponse = buildErrorResponse(responseFormat);
             getComponentsUtils().auditResource(responseFormat, user, uploadResourceInfo.getName(), AuditingActionEnum.IMPORT_RESOURCE);
             responseWrapper.setInnerElement(errorResponse);
         }
-
     }
 
     private void validateToscaTemplatePayloadName(Wrapper<Response> responseWrapper, UploadResourceInfo uploadResourceInfo, User user) {
@@ -521,7 +488,8 @@ public abstract class AbstractValidationsServlet extends BeGenericServlet {
         return isValidSuffix;
     }
 
-    private void validateMD5(Wrapper<Response> responseWrapper, User user, UploadResourceInfo resourceInfo, HttpServletRequest request, String resourceInfoJsonString) {
+    private void validateMD5(Wrapper<Response> responseWrapper, User user, UploadResourceInfo resourceInfo, HttpServletRequest request,
+                             String resourceInfoJsonString) {
         boolean isValid;
         String recievedMD5 = request.getHeader(Constants.MD5_HEADER);
         if (recievedMD5 == null) {
@@ -552,12 +520,12 @@ public abstract class AbstractValidationsServlet extends BeGenericServlet {
         throw new ByActionStatusComponentException(ActionStatus.UNSUPPORTED_ERROR, componentType);
     }
 
-
     ComponentTypeEnum convertToComponentType(String componentType) {
         return validateComponentType(componentType);
     }
 
-    private void fillToscaTemplateFromJson(Wrapper<Response> responseWrapper, Wrapper<String> yamlStringWrapper, User user, UploadResourceInfo resourceInfo) {
+    private void fillToscaTemplateFromJson(Wrapper<Response> responseWrapper, Wrapper<String> yamlStringWrapper, User user,
+                                           UploadResourceInfo resourceInfo) {
         if (resourceInfo.getPayloadData() == null || resourceInfo.getPayloadData().isEmpty()) {
             ResponseFormat responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.INVALID_RESOURCE_PAYLOAD);
             Response errorResponse = buildErrorResponse(responseFormat);
@@ -568,94 +536,77 @@ public abstract class AbstractValidationsServlet extends BeGenericServlet {
             String decodedPayload = new String(Base64.decodeBase64(toscaPayload));
             yamlStringWrapper.setInnerElement(decodedPayload);
         }
-
     }
 
-    void fillPayload(Wrapper<Response> responseWrapper, Wrapper<UploadResourceInfo> uploadResourceInfoWrapper, Wrapper<String> yamlStringWrapper, User user, String resourceInfoJsonString, ResourceAuthorityTypeEnum resourceAuthorityEnum,
-            File file) throws ZipException {
-
+    void fillPayload(Wrapper<Response> responseWrapper, Wrapper<UploadResourceInfo> uploadResourceInfoWrapper, Wrapper<String> yamlStringWrapper,
+                     User user, String resourceInfoJsonString, ResourceAuthorityTypeEnum resourceAuthorityEnum, File file) throws ZipException {
         if (responseWrapper.isEmpty()) {
             if (resourceAuthorityEnum.isBackEndImport()) {
                 // PrePayload Validations
                 if (responseWrapper.isEmpty()) {
                     validateDataNotNull(responseWrapper, file, resourceInfoJsonString);
                 }
-                if(!resourceAuthorityEnum.equals(ResourceAuthorityTypeEnum.CSAR_TYPE_BE)){
+                if (!resourceAuthorityEnum.equals(ResourceAuthorityTypeEnum.CSAR_TYPE_BE)) {
                     if (responseWrapper.isEmpty()) {
                         validateZip(responseWrapper, file, uploadResourceInfoWrapper.getInnerElement().getPayloadName());
                     }
-
                     // Fill PayLoad From File
                     if (responseWrapper.isEmpty()) {
                         fillToscaTemplateFromZip(yamlStringWrapper, uploadResourceInfoWrapper.getInnerElement().getPayloadName(), file);
                     }
-                }else{
-
+                } else {
                     if (responseWrapper.isEmpty()) {
                         validateCsar(responseWrapper, file, uploadResourceInfoWrapper.getInnerElement().getPayloadName());
                     }
-
                     // Fill PayLoad From File
                     if (responseWrapper.isEmpty()) {
                         fillPayloadDataFromFile(responseWrapper, uploadResourceInfoWrapper.getInnerElement(), file);
                     }
-
                 }
-
             } else {
                 // Fill PayLoad From JSON
                 if (responseWrapper.isEmpty()) {
                     fillToscaTemplateFromJson(responseWrapper, yamlStringWrapper, user, uploadResourceInfoWrapper.getInnerElement());
                 }
             }
-
         }
-
     }
 
     protected void specificResourceAuthorityValidations(final Wrapper<Response> responseWrapper,
                                                         final Wrapper<UploadResourceInfo> uploadResourceInfoWrapper,
-                                                        final Wrapper<String> yamlStringWrapper, final User user,
-                                                        final HttpServletRequest request, final String resourceInfoJsonString,
-                                                        final ResourceAuthorityTypeEnum resourceAuthorityEnum) {
-
+                                                        final Wrapper<String> yamlStringWrapper, final User user, final HttpServletRequest request,
+                                                        final String resourceInfoJsonString, final ResourceAuthorityTypeEnum resourceAuthorityEnum) {
         if (responseWrapper.isEmpty()) {
             // UI Only Validation
             if (!resourceAuthorityEnum.isBackEndImport()) {
                 importUIValidations(responseWrapper, uploadResourceInfoWrapper.getInnerElement(), user, request, resourceInfoJsonString);
             }
-
             // User Defined Type Resources
-            if (resourceAuthorityEnum.isUserTypeResource()
-                    && !CsarValidationUtils.isCsarPayloadName(uploadResourceInfoWrapper.getInnerElement().getPayloadName())
-                    && responseWrapper.isEmpty()) {
-                            validatePayloadNameSpace(responseWrapper, uploadResourceInfoWrapper.getInnerElement(), user, yamlStringWrapper.getInnerElement());
+            if (resourceAuthorityEnum.isUserTypeResource() && !CsarValidationUtils
+                .isCsarPayloadName(uploadResourceInfoWrapper.getInnerElement().getPayloadName()) && responseWrapper.isEmpty()) {
+                validatePayloadNameSpace(responseWrapper, uploadResourceInfoWrapper.getInnerElement(), user, yamlStringWrapper.getInnerElement());
             }
         }
     }
 
-    void commonGeneralValidations(Wrapper<Response> responseWrapper, Wrapper<User> userWrapper, Wrapper<UploadResourceInfo> uploadResourceInfoWrapper, ResourceAuthorityTypeEnum resourceAuthorityEnum, String userId,
-                                  String resourceInfoJsonString) {
-
+    void commonGeneralValidations(Wrapper<Response> responseWrapper, Wrapper<User> userWrapper, Wrapper<UploadResourceInfo> uploadResourceInfoWrapper,
+                                  ResourceAuthorityTypeEnum resourceAuthorityEnum, String userId, String resourceInfoJsonString) {
         if (responseWrapper.isEmpty()) {
             validateUserExist(responseWrapper, userWrapper, userId);
         }
-
         if (responseWrapper.isEmpty()) {
             validateUserRole(responseWrapper, userWrapper.getInnerElement(), resourceAuthorityEnum);
         }
-
         if (responseWrapper.isEmpty()) {
-            validateAndFillResourceJson(responseWrapper, uploadResourceInfoWrapper, userWrapper.getInnerElement(), resourceAuthorityEnum, resourceInfoJsonString);
+            validateAndFillResourceJson(responseWrapper, uploadResourceInfoWrapper, userWrapper.getInnerElement(), resourceAuthorityEnum,
+                resourceInfoJsonString);
         }
-
         if (responseWrapper.isEmpty()) {
             validateToscaTemplatePayloadName(responseWrapper, uploadResourceInfoWrapper.getInnerElement(), userWrapper.getInnerElement());
         }
         if (responseWrapper.isEmpty()) {
             validateResourceType(responseWrapper, uploadResourceInfoWrapper.getInnerElement(), userWrapper.getInnerElement());
         }
-
     }
 
     private void validateResourceType(Wrapper<Response> responseWrapper, UploadResourceInfo uploadResourceInfo, User user) {
@@ -668,7 +619,8 @@ public abstract class AbstractValidationsServlet extends BeGenericServlet {
         }
     }
 
-    private void importUIValidations(Wrapper<Response> responseWrapper, UploadResourceInfo resourceInfo, User user, HttpServletRequest request, String resourceInfoJsonString) {
+    private void importUIValidations(Wrapper<Response> responseWrapper, UploadResourceInfo resourceInfo, User user, HttpServletRequest request,
+                                     String resourceInfoJsonString) {
         if (responseWrapper.isEmpty()) {
             validateMD5(responseWrapper, user, resourceInfo, request, resourceInfoJsonString);
         }
@@ -677,8 +629,8 @@ public abstract class AbstractValidationsServlet extends BeGenericServlet {
         }
     }
 
-    void commonPayloadValidations(Wrapper<Response> responseWrapper, Wrapper<String> yamlStringWrapper, User user, UploadResourceInfo uploadResourceInfo) {
-
+    void commonPayloadValidations(Wrapper<Response> responseWrapper, Wrapper<String> yamlStringWrapper, User user,
+                                  UploadResourceInfo uploadResourceInfo) {
         if (responseWrapper.isEmpty()) {
             validatePayloadIsYml(responseWrapper, user, uploadResourceInfo, yamlStringWrapper.getInnerElement());
         }
@@ -693,8 +645,8 @@ public abstract class AbstractValidationsServlet extends BeGenericServlet {
         }
     }
 
-
-    void handleImport(Wrapper<Response> responseWrapper, User user, UploadResourceInfo resourceInfoObject, String yamlAsString, ResourceAuthorityTypeEnum authority, boolean createNewVersion, String resourceUniqueId) {
+    void handleImport(Wrapper<Response> responseWrapper, User user, UploadResourceInfo resourceInfoObject, String yamlAsString,
+                      ResourceAuthorityTypeEnum authority, boolean createNewVersion, String resourceUniqueId) {
         ImmutablePair<Resource, ActionStatus> createOrUpdateResponse = null;
         Response response = null;
         Object representation = null;
@@ -707,12 +659,12 @@ public abstract class AbstractValidationsServlet extends BeGenericServlet {
             createOrUpdateResponse = resourceImportManager.importNormativeResource(yamlAsString, resourceInfoObject, user, createNewVersion, true);
         } else {
             log.debug("import user resource (not normative type)");
-            createOrUpdateResponse = resourceImportManager.importUserDefinedResource(yamlAsString, resourceInfoObject, user,  false);
+            createOrUpdateResponse = resourceImportManager.importUserDefinedResource(yamlAsString, resourceInfoObject, user, false);
         }
-        if (createOrUpdateResponse!= null){
+        if (createOrUpdateResponse != null) {
             importedResourceStatus = createOrUpdateResponse;
         }
-        if(importedResourceStatus != null){
+        if (importedResourceStatus != null) {
             try {
                 representation = RepresentationUtils.toRepresentation(importedResourceStatus.left);
             } catch (IOException e) {
@@ -723,22 +675,22 @@ public abstract class AbstractValidationsServlet extends BeGenericServlet {
         responseWrapper.setInnerElement(response);
     }
 
-    private ImmutablePair<Resource, ActionStatus> importResourceFromUICsar(UploadResourceInfo resourceInfoObject, User user, String resourceUniqueId) {
-
+    private ImmutablePair<Resource, ActionStatus> importResourceFromUICsar(UploadResourceInfo resourceInfoObject, User user,
+                                                                           String resourceUniqueId) {
         Resource newResource;
         ActionStatus actionStatus;
         Resource resource = new Resource();
         String payloadName = resourceInfoObject.getPayloadName();
         fillResourceFromResourceInfoObject(resource, resourceInfoObject);
-
         Map<String, byte[]> csarUIPayload = getCsarFromPayload(resourceInfoObject);
         getAndValidateCsarYaml(csarUIPayload, resource, user, payloadName);
-
         if (resourceUniqueId == null || resourceUniqueId.isEmpty()) {
-            newResource = resourceImportManager.getResourceBusinessLogic().createResource(resource, AuditingActionEnum.CREATE_RESOURCE, user, csarUIPayload, payloadName);
+            newResource = resourceImportManager.getResourceBusinessLogic()
+                .createResource(resource, AuditingActionEnum.CREATE_RESOURCE, user, csarUIPayload, payloadName);
             actionStatus = ActionStatus.CREATED;
         } else {
-            newResource = resourceImportManager.getResourceBusinessLogic().validateAndUpdateResourceFromCsar(resource, user, csarUIPayload, payloadName, resourceUniqueId);
+            newResource = resourceImportManager.getResourceBusinessLogic()
+                .validateAndUpdateResourceFromCsar(resource, user, csarUIPayload, payloadName, resourceUniqueId);
             actionStatus = ActionStatus.OK;
         }
         return new ImmutablePair<>(newResource, actionStatus);
@@ -753,39 +705,34 @@ public abstract class AbstractValidationsServlet extends BeGenericServlet {
     }
 
     private void getAndValidateComponentCsarYaml(Map<String, byte[]> csarUIPayload, Component component, User user, String csarUUID) {
-
-        Either<ImmutablePair<String, String>, ResponseFormat> getToscaYamlRes = CsarValidationUtils.getToscaYaml(csarUIPayload, csarUUID, getComponentsUtils());
-
+        Either<ImmutablePair<String, String>, ResponseFormat> getToscaYamlRes = CsarValidationUtils
+            .getToscaYaml(csarUIPayload, csarUUID, getComponentsUtils());
         if (getToscaYamlRes.isRight()) {
             ResponseFormat responseFormat = getToscaYamlRes.right().value();
             log.debug("Error when try to get csar toscayamlFile with csar ID {}, error: {}", csarUUID, responseFormat);
             if (component instanceof Resource) {
-                BeEcompErrorManager.getInstance()
-                    .logBeDaoSystemError("Creating resource from CSAR: fetching CSAR with id " + csarUUID + " failed");
-                getComponentsUtils().auditResource(responseFormat, user, (Resource)component, AuditingActionEnum.CREATE_RESOURCE);
-            }else {
-                BeEcompErrorManager.getInstance()
-                    .logBeDaoSystemError("Creating service from CSAR: fetching CSAR with id " + csarUUID + " failed");
+                BeEcompErrorManager.getInstance().logBeDaoSystemError("Creating resource from CSAR: fetching CSAR with id " + csarUUID + " failed");
+                getComponentsUtils().auditResource(responseFormat, user, (Resource) component, AuditingActionEnum.CREATE_RESOURCE);
+            } else {
+                BeEcompErrorManager.getInstance().logBeDaoSystemError("Creating service from CSAR: fetching CSAR with id " + csarUUID + " failed");
             }
             throwComponentException(responseFormat);
         }
         String toscaYaml = getToscaYamlRes.left().value().getValue();
-
         log.debug("checking tosca template is valid yml");
         YamlToObjectConverter yamlConvertor = new YamlToObjectConverter();
         boolean isValid = yamlConvertor.isValidYaml(toscaYaml.getBytes());
         if (!isValid) {
             ResponseFormat responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.INVALID_YAML_FILE);
             if (component instanceof Resource) {
-                getComponentsUtils().auditResource(responseFormat, user, (Resource)component, AuditingActionEnum.IMPORT_RESOURCE);
+                getComponentsUtils().auditResource(responseFormat, user, (Resource) component, AuditingActionEnum.IMPORT_RESOURCE);
             }
             throwComponentException(responseFormat);
         }
-
         log.debug("checking payload is valid tosca");
         Map<String, Object> mappedToscaTemplate = (Map<String, Object>) new Yaml().load(toscaYaml);
-        Either<String, ResultStatusEnum> findFirstToscaStringElement = ImportUtils.findFirstToscaStringElement(mappedToscaTemplate, TypeUtils.ToscaTagNamesEnum.TOSCA_VERSION);
-
+        Either<String, ResultStatusEnum> findFirstToscaStringElement = ImportUtils
+            .findFirstToscaStringElement(mappedToscaTemplate, TypeUtils.ToscaTagNamesEnum.TOSCA_VERSION);
         if (findFirstToscaStringElement.isRight()) {
             isValid = false;
         } else {
@@ -796,12 +743,11 @@ public abstract class AbstractValidationsServlet extends BeGenericServlet {
                 isValid = TOSCA_DEFINITION_VERSIONS.contains(defenitionVersionFound);
             }
         }
-
         if (!isValid) {
             ResponseFormat responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.INVALID_TOSCA_TEMPLATE);
             if (component instanceof Resource) {
                 log.debug("enter getAndValidateComponentCsarYaml,component instanceof Resource");
-                getComponentsUtils().auditResource(responseFormat, user, (Resource)component, AuditingActionEnum.IMPORT_RESOURCE);
+                getComponentsUtils().auditResource(responseFormat, user, (Resource) component, AuditingActionEnum.IMPORT_RESOURCE);
             }
             throwComponentException(responseFormat);
         }
@@ -810,7 +756,6 @@ public abstract class AbstractValidationsServlet extends BeGenericServlet {
     private void fillResourceFromResourceInfoObject(Resource resource, UploadResourceInfo resourceInfoObject) {
         resourceImportManager.populateResourceMetadata(resourceInfoObject, resource);
         fillArtifacts(resource, resourceInfoObject);
-
     }
 
     private void fillArtifacts(Resource resource, UploadResourceInfo resourceInfoObject) {
@@ -824,7 +769,7 @@ public abstract class AbstractValidationsServlet extends BeGenericServlet {
         }
     }
 
-    private void buildArtifactsHM(List<UploadArtifactInfo> artifactList, Map<String, ArtifactDefinition> artifactsHM){
+    private void buildArtifactsHM(List<UploadArtifactInfo> artifactList, Map<String, ArtifactDefinition> artifactsHM) {
         for (UploadArtifactInfo artifact : artifactList) {
             ArtifactDefinition artifactDef = new ArtifactDefinition();
             artifactDef.setArtifactName(artifact.getArtifactName());
@@ -839,22 +784,19 @@ public abstract class AbstractValidationsServlet extends BeGenericServlet {
     private Map<String, byte[]> getCsarFromPayload(UploadResourceInfo innerElement) {
         String csarUUID = innerElement.getPayloadName();
         String payloadData = innerElement.getPayloadData();
-
         return getComponentCsarFromPayload(csarUUID, payloadData);
     }
 
-    private Map<String, byte[]> getComponentCsarFromPayload(String csarUUID, String payloadData){
+    private Map<String, byte[]> getComponentCsarFromPayload(String csarUUID, String payloadData) {
         if (payloadData == null) {
             log.info("Failed to decode received csar {}", csarUUID);
             throw new ByActionStatusComponentException(ActionStatus.CSAR_NOT_FOUND, csarUUID);
         }
-
         byte[] decodedPayload = Base64.decodeBase64(payloadData.getBytes(StandardCharsets.UTF_8));
         if (decodedPayload == null) {
             log.info("Failed to decode received csar {}", csarUUID);
             throw new ByActionStatusComponentException(ActionStatus.CSAR_NOT_FOUND, csarUUID);
         }
-
         Map<String, byte[]> csar = null;
         try {
             csar = ZipUtils.readZip(decodedPayload, false);
@@ -873,7 +815,6 @@ public abstract class AbstractValidationsServlet extends BeGenericServlet {
         } else {
             dataWrapper.setInnerElement(new String(bytes, StandardCharsets.UTF_8));
         }
-
     }
 
     <T> void validateClassParse(String data, Wrapper<T> parsedClassWrapper, Supplier<Class<T>> classGen, Wrapper<ResponseFormat> errorWrapper) {
@@ -890,7 +831,8 @@ public abstract class AbstractValidationsServlet extends BeGenericServlet {
         }
     }
 
-    void validateComponentInstanceBusinessLogic(HttpServletRequest request, String containerComponentType, Wrapper<ComponentInstanceBusinessLogic> blWrapper, Wrapper<ResponseFormat> errorWrapper) {
+    void validateComponentInstanceBusinessLogic(HttpServletRequest request, String containerComponentType,
+                                                Wrapper<ComponentInstanceBusinessLogic> blWrapper, Wrapper<ResponseFormat> errorWrapper) {
         ServletContext context = request.getSession().getServletContext();
         ComponentInstanceBusinessLogic componentInstanceLogic = getComponentInstanceBL(context);
         if (componentInstanceLogic == null) {
@@ -915,7 +857,7 @@ public abstract class AbstractValidationsServlet extends BeGenericServlet {
 
     protected void validateXECOMPInstanceIDHeader(String instanceIdHeader, Wrapper<ResponseFormat> responseWrapper) {
         ResponseFormat responseFormat;
-        if(StringUtils.isEmpty(instanceIdHeader) ){
+        if (StringUtils.isEmpty(instanceIdHeader)) {
             log.debug("Missing X-ECOMP-InstanceID header");
             responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.MISSING_X_ECOMP_INSTANCE_ID);
             responseWrapper.setInnerElement(responseFormat);
@@ -924,7 +866,7 @@ public abstract class AbstractValidationsServlet extends BeGenericServlet {
 
     protected void validateHttpCspUserIdHeader(String header, Wrapper<ResponseFormat> responseWrapper) {
         ResponseFormat responseFormat;
-        if( StringUtils.isEmpty(header)){
+        if (StringUtils.isEmpty(header)) {
             log.debug("MissingUSER_ID");
             responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.MISSING_USER_ID);
             responseWrapper.setInnerElement(responseFormat);
@@ -932,7 +874,6 @@ public abstract class AbstractValidationsServlet extends BeGenericServlet {
     }
 
     <T> Either<T, ResponseFormat> parseToObject(String json, Supplier<Class<T>> classSupplier) {
-
         try {
             T object = RepresentationUtils.fromRepresentation(json, classSupplier.get());
             return Either.left(object);
@@ -953,46 +894,37 @@ public abstract class AbstractValidationsServlet extends BeGenericServlet {
             return Either.right(responseFormat);
         }
     }
+
     protected void validateNotEmptyBody(String data) {
         if (StringUtils.isEmpty(data)) {
             throw new ByActionStatusComponentException(ActionStatus.MISSING_BODY);
         }
     }
 
-    protected void commonServiceGeneralValidations(
-        Wrapper<Response> responseWrapper, Wrapper<User> userWrapper,
-        Wrapper<UploadServiceInfo> uploadServiceInfoWrapper, ServiceAuthorityTypeEnum serviceAuthorityEnum,
-        String userUserId,
-        String serviceInfoJsonString) {
-
+    protected void commonServiceGeneralValidations(Wrapper<Response> responseWrapper, Wrapper<User> userWrapper,
+                                                   Wrapper<UploadServiceInfo> uploadServiceInfoWrapper, ServiceAuthorityTypeEnum serviceAuthorityEnum,
+                                                   String userUserId, String serviceInfoJsonString) {
         if (responseWrapper.isEmpty()) {
             validateUserExist(responseWrapper, userWrapper, userUserId);
         }
-
         if (responseWrapper.isEmpty()) {
             validateUserRole(responseWrapper, userWrapper.getInnerElement(), serviceAuthorityEnum);
         }
-
         if (responseWrapper.isEmpty()) {
-            validateAndFillServiceJson(responseWrapper, uploadServiceInfoWrapper, userWrapper.getInnerElement(),
-                serviceAuthorityEnum, serviceInfoJsonString);
+            validateAndFillServiceJson(responseWrapper, uploadServiceInfoWrapper, userWrapper.getInnerElement(), serviceAuthorityEnum,
+                serviceInfoJsonString);
         }
-
         if (responseWrapper.isEmpty()) {
-            validateToscaTemplatePayloadName(responseWrapper, uploadServiceInfoWrapper.getInnerElement(),
-                userWrapper.getInnerElement());
+            validateToscaTemplatePayloadName(responseWrapper, uploadServiceInfoWrapper.getInnerElement(), userWrapper.getInnerElement());
         }
-
     }
 
-    protected void validateUserRole(Wrapper<Response> errorResponseWrapper, User user,
-        ServiceAuthorityTypeEnum serviceAuthority) {
+    protected void validateUserRole(Wrapper<Response> errorResponseWrapper, User user, ServiceAuthorityTypeEnum serviceAuthority) {
         log.debug("validate user role");
         if (serviceAuthority == ServiceAuthorityTypeEnum.NORMATIVE_TYPE_BE) {
             if (!user.getRole().equals(Role.ADMIN.name())) {
                 log.info("user is not in appropriate role to perform action");
-                ResponseFormat responseFormat =
-                    getComponentsUtils().getResponseFormat(ActionStatus.RESTRICTED_OPERATION);
+                ResponseFormat responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.RESTRICTED_OPERATION);
                 log.debug("audit before sending response");
                 Response response = buildErrorResponse(responseFormat);
                 errorResponseWrapper.setInnerElement(response);
@@ -1000,12 +932,10 @@ public abstract class AbstractValidationsServlet extends BeGenericServlet {
         } else {
             validateUserRole(errorResponseWrapper, user);
         }
-
     }
 
-    protected void validateAndFillServiceJson(Wrapper<Response> responseWrapper,
-        Wrapper<UploadServiceInfo> uploadServiceInfoWrapper, User user,
-        ServiceAuthorityTypeEnum serviceAuthorityEnum, String serviceInfo) {
+    protected void validateAndFillServiceJson(Wrapper<Response> responseWrapper, Wrapper<UploadServiceInfo> uploadServiceInfoWrapper, User user,
+                                              ServiceAuthorityTypeEnum serviceAuthorityEnum, String serviceInfo) {
         boolean isValid;
         try {
             log.debug("The received json is {}", serviceInfo);
@@ -1014,25 +944,19 @@ public abstract class AbstractValidationsServlet extends BeGenericServlet {
                 isValid = false;
             } else {
                 if (!serviceAuthorityEnum.isBackEndImport()) {
-                    isValid =
-                        serviceInfoObject.getPayloadName() != null && !serviceInfoObject.getPayloadName().isEmpty();
+                    isValid = serviceInfoObject.getPayloadName() != null && !serviceInfoObject.getPayloadName().isEmpty();
                     //only service name is checked
                 } else {
                     isValid = true;
                 }
                 uploadServiceInfoWrapper.setInnerElement(serviceInfoObject);
-                log.debug("get isValid:{},serviceInfoObject get name:{},get tags:{},getContactId:{}," +
-                                " getPayloadName:{}",isValid,
-                        uploadServiceInfoWrapper.getInnerElement().getName(),
-                        uploadServiceInfoWrapper.getInnerElement().getTags(),
-                        uploadServiceInfoWrapper.getInnerElement().getContactId(),
-                        uploadServiceInfoWrapper.getInnerElement().getPayloadName());
+                log.debug("get isValid:{},serviceInfoObject get name:{},get tags:{},getContactId:{}," + " getPayloadName:{}", isValid,
+                    uploadServiceInfoWrapper.getInnerElement().getName(), uploadServiceInfoWrapper.getInnerElement().getTags(),
+                    uploadServiceInfoWrapper.getInnerElement().getContactId(), uploadServiceInfoWrapper.getInnerElement().getPayloadName());
             }
-
         } catch (JsonSyntaxException e) {
             log.debug("enter validateAndFillServiceJson,Invalid json was received. {}", e.getMessage(), e);
             isValid = false;
-
         }
         if (!isValid) {
             log.info("Invalid json was received.");
@@ -1042,72 +966,60 @@ public abstract class AbstractValidationsServlet extends BeGenericServlet {
         }
     }
 
-    protected void validateToscaTemplatePayloadName(Wrapper<Response> responseWrapper,
-        UploadServiceInfo uploadServiceInfo, User user) {
+    protected void validateToscaTemplatePayloadName(Wrapper<Response> responseWrapper, UploadServiceInfo uploadServiceInfo, User user) {
         String toscaTemplatePayloadName = uploadServiceInfo.getPayloadName();
         boolean isValidSuffix = isToscaTemplatePayloadNameValid(responseWrapper, toscaTemplatePayloadName);
         if (!isValidSuffix) {
-            ResponseFormat responseFormat =
-                getComponentsUtils().getResponseFormat(ActionStatus.INVALID_TOSCA_FILE_EXTENSION);
+            ResponseFormat responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.INVALID_TOSCA_FILE_EXTENSION);
             Response errorResponse = buildErrorResponse(responseFormat);
             responseWrapper.setInnerElement(errorResponse);
         }
-
     }
 
-
-    protected void specificServiceAuthorityValidations(Wrapper<Response> responseWrapper,
-        Wrapper<UploadServiceInfo> uploadServiceInfoWrapper, Wrapper<String> yamlStringWrapper, User user,
-        HttpServletRequest request, String serviceInfoJsonString, ServiceAuthorityTypeEnum serviceAuthorityEnum)
+    protected void specificServiceAuthorityValidations(Wrapper<Response> responseWrapper, Wrapper<UploadServiceInfo> uploadServiceInfoWrapper,
+                                                       Wrapper<String> yamlStringWrapper, User user, HttpServletRequest request,
+                                                       String serviceInfoJsonString, ServiceAuthorityTypeEnum serviceAuthorityEnum)
         throws FileNotFoundException {
-
         if (responseWrapper.isEmpty()) {
             // UI Only Validation
             if (!serviceAuthorityEnum.isBackEndImport()) {
-                importUIValidations(responseWrapper, uploadServiceInfoWrapper.getInnerElement(), user, request,
-                    serviceInfoJsonString);
+                importUIValidations(responseWrapper, uploadServiceInfoWrapper.getInnerElement(), user, request, serviceInfoJsonString);
             }
-
             // User Defined Type Services
-            if (serviceAuthorityEnum.isUserTypeService() && !CsarValidationUtils.isCsarPayloadName(
-                uploadServiceInfoWrapper.getInnerElement().getPayloadName())) {
+            if (serviceAuthorityEnum.isUserTypeService() && !CsarValidationUtils
+                .isCsarPayloadName(uploadServiceInfoWrapper.getInnerElement().getPayloadName())) {
                 if (responseWrapper.isEmpty()) {
-                    validatePayloadNameSpace(responseWrapper, uploadServiceInfoWrapper.getInnerElement(), user,
-                        yamlStringWrapper.getInnerElement());
+                    validatePayloadNameSpace(responseWrapper, uploadServiceInfoWrapper.getInnerElement(), user, yamlStringWrapper.getInnerElement());
                 }
-
             }
         }
     }
 
-    protected void importUIValidations(Wrapper<Response> responseWrapper, UploadServiceInfo serviceInfo, User user,
-        HttpServletRequest request, String serviceInfoJsonString) {
+    protected void importUIValidations(Wrapper<Response> responseWrapper, UploadServiceInfo serviceInfo, User user, HttpServletRequest request,
+                                       String serviceInfoJsonString) {
         if (responseWrapper.isEmpty()) {
             validateMD5(responseWrapper, user, serviceInfo, request, serviceInfoJsonString);
         }
-        if (responseWrapper.isEmpty() && request != null && request.getMethod() != null && request.getMethod()
-            .equals("POST")) {
+        if (responseWrapper.isEmpty() && request != null && request.getMethod() != null && request.getMethod().equals("POST")) {
             validateServiceDoesNotExist(responseWrapper, user, serviceInfo.getName());
         }
     }
 
-    protected void validatePayloadNameSpace(Wrapper<Response> responseWrapper, UploadServiceInfo serviceInfo, User user,
-        String toscaPayload) {
+    protected void validatePayloadNameSpace(Wrapper<Response> responseWrapper, UploadServiceInfo serviceInfo, User user, String toscaPayload) {
         boolean isValid;
         String nameSpace = "";
         Map<String, Object> mappedToscaTemplate = (Map<String, Object>) new Yaml().load(toscaPayload);
-        Either<Map<String, Object>, ResultStatusEnum> toscaElement =
-            ImportUtils.findFirstToscaMapElement(mappedToscaTemplate, TypeUtils.ToscaTagNamesEnum.NODE_TYPES);
+        Either<Map<String, Object>, ResultStatusEnum> toscaElement = ImportUtils
+            .findFirstToscaMapElement(mappedToscaTemplate, TypeUtils.ToscaTagNamesEnum.NODE_TYPES);
         if (toscaElement.isRight() || toscaElement.left().value().size() != 1) {
             isValid = false;
         } else {
             nameSpace = toscaElement.left().value().keySet().iterator().next();
             isValid = nameSpace.startsWith(Constants.USER_DEFINED_SERVICE_NAMESPACE_PREFIX);
-            log.debug("enter validatePayloadNameSpace,get nameSpace:{},get Valid is:{}",nameSpace,isValid);
+            log.debug("enter validatePayloadNameSpace,get nameSpace:{},get Valid is:{}", nameSpace, isValid);
         }
         if (!isValid) {
-            ResponseFormat responseFormat =
-                getComponentsUtils().getResponseFormat(ActionStatus.INVALID_SERVICE_NAMESPACE);
+            ResponseFormat responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.INVALID_SERVICE_NAMESPACE);
             Response errorResponse = buildErrorResponse(responseFormat);
             responseWrapper.setInnerElement(errorResponse);
         } else {
@@ -1120,11 +1032,10 @@ public abstract class AbstractValidationsServlet extends BeGenericServlet {
                 serviceInfo.setServiceType(ResourceTypeEnum.SERVICE.name());
             }
         }
-
     }
 
-    protected void validateMD5(Wrapper<Response> responseWrapper, User user, UploadServiceInfo serviceInfo,
-        HttpServletRequest request, String serviceInfoJsonString) {
+    protected void validateMD5(Wrapper<Response> responseWrapper, User user, UploadServiceInfo serviceInfo, HttpServletRequest request,
+                               String serviceInfoJsonString) {
         boolean isValid;
         String recievedMD5 = request.getHeader(Constants.MD5_HEADER);
         if (recievedMD5 == null) {
@@ -1134,14 +1045,12 @@ public abstract class AbstractValidationsServlet extends BeGenericServlet {
             isValid = calculateMD5.equals(recievedMD5);
         }
         if (!isValid) {
-            ResponseFormat responseFormat =
-                getComponentsUtils().getResponseFormat(ActionStatus.INVALID_SERVICE_CHECKSUM);
+            ResponseFormat responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.INVALID_SERVICE_CHECKSUM);
             Response errorResponse = buildErrorResponse(responseFormat);
             responseWrapper.setInnerElement(errorResponse);
         }
     }
 
-
     protected void validateServiceDoesNotExist(Wrapper<Response> responseWrapper, User user, String serviceName) {
         if (serviceImportManager.isServiceExist(serviceName)) {
             ResponseFormat responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.SERVICE_ALREADY_EXISTS);
@@ -1150,10 +1059,8 @@ public abstract class AbstractValidationsServlet extends BeGenericServlet {
         }
     }
 
-    protected void handleImportService(Wrapper<Response> responseWrapper, User user,
-        UploadServiceInfo serviceInfoObject, String yamlAsString, ServiceAuthorityTypeEnum authority,
-        boolean createNewVersion, String serviceUniqueId) throws ZipException {
-
+    protected void handleImportService(Wrapper<Response> responseWrapper, User user, UploadServiceInfo serviceInfoObject, String yamlAsString,
+                                       ServiceAuthorityTypeEnum authority, boolean createNewVersion, String serviceUniqueId) throws ZipException {
         Response response = null;
         Object representation = null;
         ImmutablePair<Service, ActionStatus> importedServiceStatus = null;
@@ -1161,57 +1068,45 @@ public abstract class AbstractValidationsServlet extends BeGenericServlet {
             log.debug("import service from csar");
             importedServiceStatus = importServiceFromUICsar(serviceInfoObject, user, serviceUniqueId);
         }
-
         if (importedServiceStatus != null) {
             try {
                 representation = RepresentationUtils.toRepresentation(importedServiceStatus.left);
             } catch (IOException e) {
                 log.debug("Error while building service representation : {}", e.getMessage(), e);
             }
-            response = buildOkResponse(getComponentsUtils().getResponseFormat(importedServiceStatus.right),
-                representation);
+            response = buildOkResponse(getComponentsUtils().getResponseFormat(importedServiceStatus.right), representation);
         }
         responseWrapper.setInnerElement(response);
     }
 
-    private ImmutablePair<Service, ActionStatus> importServiceFromUICsar(UploadServiceInfo serviceInfoObject, User user,
-        String serviceUniqueId) throws ZipException {
-
+    private ImmutablePair<Service, ActionStatus> importServiceFromUICsar(UploadServiceInfo serviceInfoObject, User user, String serviceUniqueId)
+        throws ZipException {
         Service newService;
         ImmutablePair<Service, ActionStatus> result = null;
         ActionStatus actionStatus;
         Service service = new Service();
         String payloadName = serviceInfoObject.getPayloadName();
         fillServiceFromServiceInfoObject(service, serviceInfoObject);
-
         Map<String, byte[]> csarUIPayloadRes = getCsarFromPayload(serviceInfoObject);
-
         getAndValidateCsarYaml(csarUIPayloadRes, service, user, payloadName);
-
         newService = serviceImportManager.getServiceImportBusinessLogic()
-            .createService(service, AuditingActionEnum.CREATE_SERVICE, user, csarUIPayloadRes,
-                payloadName);
+            .createService(service, AuditingActionEnum.CREATE_SERVICE, user, csarUIPayloadRes, payloadName);
         actionStatus = ActionStatus.CREATED;
-
         return new ImmutablePair<>(newService, actionStatus);
     }
 
-
     private void fillServiceFromServiceInfoObject(Service service, UploadServiceInfo serviceInfoObject) {
         serviceImportManager.populateServiceMetadata(serviceInfoObject, service);
         fillArtifacts(service, serviceInfoObject);
-
     }
 
-    private Map<String, byte[]> getCsarFromPayload(UploadServiceInfo innerElement)
-        throws ZipException {
+    private Map<String, byte[]> getCsarFromPayload(UploadServiceInfo innerElement) throws ZipException {
         String csarUUID = innerElement.getPayloadName();
         String payloadData = innerElement.getPayloadData();
         return getComponentCsarFromPayload(csarUUID, payloadData);
     }
 
-    private void getAndValidateCsarYaml(Map<String, byte[]> csarUIPayload, Service service, User user,
-        String csarUUID) {
+    private void getAndValidateCsarYaml(Map<String, byte[]> csarUIPayload, Service service, User user, String csarUUID) {
         getAndValidateComponentCsarYaml(csarUIPayload, service, user, csarUUID);
     }
 
@@ -1225,8 +1120,10 @@ public abstract class AbstractValidationsServlet extends BeGenericServlet {
             }
         }
     }
+
     /**
      * import service payload to postman
+     *
      * @param responseWrapper
      * @param uploadServiceInfoWrapper
      * @param yamlStringWrapper
@@ -1236,8 +1133,9 @@ public abstract class AbstractValidationsServlet extends BeGenericServlet {
      * @param file
      * @throws ZipException
      */
-    protected void fillServicePayload(Wrapper<Response> responseWrapper, Wrapper<UploadServiceInfo> uploadServiceInfoWrapper, Wrapper<String> yamlStringWrapper, User user, String serviceInfoJsonString, ServiceAuthorityTypeEnum serviceAuthorityEnum,
-                                      File file) throws ZipException {
+    protected void fillServicePayload(Wrapper<Response> responseWrapper, Wrapper<UploadServiceInfo> uploadServiceInfoWrapper,
+                                      Wrapper<String> yamlStringWrapper, User user, String serviceInfoJsonString,
+                                      ServiceAuthorityTypeEnum serviceAuthorityEnum, File file) throws ZipException {
         log.debug("enter fillServicePayload");
         if (responseWrapper.isEmpty()) {
             log.debug("enter fillServicePayload,get responseWrapper is empty");
@@ -1246,20 +1144,18 @@ public abstract class AbstractValidationsServlet extends BeGenericServlet {
                 if (responseWrapper.isEmpty()) {
                     validateDataNotNull(responseWrapper, file, serviceInfoJsonString);
                 }
-                if (responseWrapper.isEmpty()){
+                if (responseWrapper.isEmpty()) {
                     log.debug("enter fillServicePayload,responseWrapper is empty");
                 }
-                if(!serviceAuthorityEnum.equals(ServiceAuthorityTypeEnum.CSAR_TYPE_BE)){
+                if (!serviceAuthorityEnum.equals(ServiceAuthorityTypeEnum.CSAR_TYPE_BE)) {
                     if (responseWrapper.isEmpty()) {
                         validateZip(responseWrapper, file, uploadServiceInfoWrapper.getInnerElement().getPayloadName());
                     }
-
                     // Fill PayLoad From File
                     if (responseWrapper.isEmpty()) {
                         fillToscaTemplateFromZip(yamlStringWrapper, uploadServiceInfoWrapper.getInnerElement().getPayloadName(), file);
                     }
-                }else{
-
+                } else {
                     log.debug("enter fillServicePayload,ServiceAuthorityTypeEnum is CSAR_TYPE_BE");
                     if (responseWrapper.isEmpty()) {
                         validateCsar(responseWrapper, file, uploadServiceInfoWrapper.getInnerElement().getPayloadName());
@@ -1271,50 +1167,41 @@ public abstract class AbstractValidationsServlet extends BeGenericServlet {
                     if (responseWrapper.isEmpty()) {
                         fillServicePayloadDataFromFile(responseWrapper, uploadServiceInfoWrapper.getInnerElement(), file);
                     }
-
                 }
-
             } else {
                 // Fill PayLoad From JSON
                 if (responseWrapper.isEmpty()) {
                     fillServiceToscaTemplateFromJson(responseWrapper, yamlStringWrapper, user, uploadServiceInfoWrapper.getInnerElement());
                 }
             }
-
         }
-
     }
 
-    protected void fillServicePayloadDataFromFile(Wrapper<Response> responseWrapper, UploadServiceInfo uploadServiceInfoWrapper, File file)  {
-        try(InputStream fileInputStream = new FileInputStream(file)){
-
+    protected void fillServicePayloadDataFromFile(Wrapper<Response> responseWrapper, UploadServiceInfo uploadServiceInfoWrapper, File file) {
+        try (InputStream fileInputStream = new FileInputStream(file)) {
             log.debug("enter fillServicePayloadDataFromFile");
-            byte [] data = new byte[(int)file.length()];
-            if( fileInputStream.read(data) == -1){
+            byte[] data = new byte[(int) file.length()];
+            if (fileInputStream.read(data) == -1) {
                 log.info("Invalid json was received.");
                 ResponseFormat responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.INVALID_CONTENT);
-
                 Response errorResp = buildErrorResponse(responseFormat);
                 responseWrapper.setInnerElement(errorResp);
             }
-            String payloadData =  Base64.encodeBase64String(data);
+            String payloadData = Base64.encodeBase64String(data);
             uploadServiceInfoWrapper.setPayloadData(payloadData);
-            log.debug("enter fillServicePayloadDataFromFile,get payloadData:{}",
-                    uploadServiceInfoWrapper.getPayloadData());
-
-            log.debug("enter fillServicePayloadDataFromFile,get uploadService:{}",uploadServiceInfoWrapper);
-
+            log.debug("enter fillServicePayloadDataFromFile,get payloadData:{}", uploadServiceInfoWrapper.getPayloadData());
+            log.debug("enter fillServicePayloadDataFromFile,get uploadService:{}", uploadServiceInfoWrapper);
         } catch (IOException e) {
             log.info("Invalid json was received or Error while closing input Stream.");
             log.debug("Invalid json was received or Error while closing input Stream. {}", e.getMessage(), e);
             ResponseFormat responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.INVALID_CONTENT);
-
             Response errorResp = buildErrorResponse(responseFormat);
             responseWrapper.setInnerElement(errorResp);
         }
     }
 
-    private void fillServiceToscaTemplateFromJson(Wrapper<Response> responseWrapper, Wrapper<String> yamlStringWrapper, User user, UploadServiceInfo serviceInfo) {
+    private void fillServiceToscaTemplateFromJson(Wrapper<Response> responseWrapper, Wrapper<String> yamlStringWrapper, User user,
+                                                  UploadServiceInfo serviceInfo) {
         if (serviceInfo.getPayloadData() == null || serviceInfo.getPayloadData().isEmpty()) {
             ResponseFormat responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.INVALID_RESOURCE_PAYLOAD);
             Response errorResponse = buildErrorResponse(responseFormat);
@@ -1326,5 +1213,4 @@ public abstract class AbstractValidationsServlet extends BeGenericServlet {
             yamlStringWrapper.setInnerElement(decodedPayload);
         }
     }
-
 }
index 574d200..d9e5aed 100644 (file)
@@ -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.
@@ -17,7 +17,6 @@
  * limitations under the License.
  * ============LICENSE_END=========================================================
  */
-
 package org.openecomp.sdc.be.servlets;
 
 import com.jcabi.aspects.Loggable;
@@ -32,21 +31,6 @@ import io.swagger.v3.oas.annotations.servers.Server;
 import io.swagger.v3.oas.annotations.servers.Servers;
 import io.swagger.v3.oas.annotations.tags.Tag;
 import io.swagger.v3.oas.annotations.tags.Tags;
-import org.openecomp.sdc.be.components.impl.AdditionalInformationBusinessLogic;
-import org.openecomp.sdc.be.components.impl.aaf.AafPermission;
-import org.openecomp.sdc.be.components.impl.aaf.PermissionAllowed;
-import org.openecomp.sdc.be.config.BeEcompErrorManager;
-import org.openecomp.sdc.be.dao.api.ActionStatus;
-import org.openecomp.sdc.be.datatypes.elements.AdditionalInfoParameterInfo;
-import org.openecomp.sdc.be.datatypes.enums.NodeTypeEnum;
-import org.openecomp.sdc.be.impl.ComponentsUtils;
-import org.openecomp.sdc.be.model.AdditionalInformationDefinition;
-import org.openecomp.sdc.be.user.UserBusinessLogic;
-import org.openecomp.sdc.common.api.Constants;
-import org.openecomp.sdc.common.log.wrappers.Logger;
-import org.openecomp.sdc.exception.ResponseFormat;
-import org.springframework.stereotype.Controller;
-
 import javax.inject.Inject;
 import javax.servlet.ServletContext;
 import javax.servlet.http.HttpServletRequest;
@@ -62,7 +46,20 @@ import javax.ws.rs.Produces;
 import javax.ws.rs.core.Context;
 import javax.ws.rs.core.MediaType;
 import javax.ws.rs.core.Response;
-
+import org.openecomp.sdc.be.components.impl.AdditionalInformationBusinessLogic;
+import org.openecomp.sdc.be.components.impl.aaf.AafPermission;
+import org.openecomp.sdc.be.components.impl.aaf.PermissionAllowed;
+import org.openecomp.sdc.be.config.BeEcompErrorManager;
+import org.openecomp.sdc.be.dao.api.ActionStatus;
+import org.openecomp.sdc.be.datatypes.elements.AdditionalInfoParameterInfo;
+import org.openecomp.sdc.be.datatypes.enums.NodeTypeEnum;
+import org.openecomp.sdc.be.impl.ComponentsUtils;
+import org.openecomp.sdc.be.model.AdditionalInformationDefinition;
+import org.openecomp.sdc.be.user.UserBusinessLogic;
+import org.openecomp.sdc.common.api.Constants;
+import org.openecomp.sdc.common.log.wrappers.Logger;
+import org.openecomp.sdc.exception.ResponseFormat;
+import org.springframework.stereotype.Controller;
 
 @Loggable(prepend = true, value = Loggable.DEBUG, trim = false)
 @Path("/v1/catalog")
@@ -75,19 +72,16 @@ public class AdditionalInformationServlet extends BeGenericServlet {
     private static final String START_HANDLE_REQUEST_OF = "Start handle request of {}";
     private static final String MODIFIER_ID_IS = "modifier id is {}";
     private static final String FAILED_TO_UPDATE_ADDITIONAL_INFO_PROPERTY = "Failed to update additional information property. Reason - {}";
-
     private final AdditionalInformationBusinessLogic businessLogic;
 
     @Inject
-    public AdditionalInformationServlet(UserBusinessLogic userBusinessLogic,
-        ComponentsUtils componentsUtils,
-        AdditionalInformationBusinessLogic businessLogic) {
+    public AdditionalInformationServlet(UserBusinessLogic userBusinessLogic, ComponentsUtils componentsUtils,
+                                        AdditionalInformationBusinessLogic businessLogic) {
         super(userBusinessLogic, componentsUtils);
         this.businessLogic = businessLogic;
     }
 
     /**
-     *
      * @param resourceId
      * @param data
      * @param request
@@ -98,28 +92,21 @@ public class AdditionalInformationServlet extends BeGenericServlet {
     @Path("/resources/{resourceId}/additionalinfo")
     @Consumes(MediaType.APPLICATION_JSON)
     @Produces(MediaType.APPLICATION_JSON)
-    @Operation(description = "Create Additional Information Label and Value", method = "POST",
-            summary = "Returns created Additional Inforamtion property",  responses = {
-            @ApiResponse(content = @Content(array = @ArraySchema(schema = @Schema(implementation = Response.class)))),
-            @ApiResponse(responseCode = "201", description = "Additional information created"),
-            @ApiResponse(responseCode = "403", description = "Restricted operation"),
-            @ApiResponse(responseCode = "400", description = "Invalid content / Missing content"),
-            @ApiResponse(responseCode = "409", description = "Additional information key already exist")})
+    @Operation(description = "Create Additional Information Label and Value", method = "POST", summary = "Returns created Additional Inforamtion property", responses = {
+        @ApiResponse(content = @Content(array = @ArraySchema(schema = @Schema(implementation = Response.class)))),
+        @ApiResponse(responseCode = "201", description = "Additional information created"),
+        @ApiResponse(responseCode = "403", description = "Restricted operation"),
+        @ApiResponse(responseCode = "400", description = "Invalid content / Missing content"),
+        @ApiResponse(responseCode = "409", description = "Additional information key already exist")})
     @PermissionAllowed(AafPermission.PermNames.INTERNAL_ALL_VALUE)
     public Response createResourceAdditionalInformationLabel(
-            @Parameter(description = "resource id to update with new property",
-                    required = true) @PathParam("resourceId") final String resourceId,
-            @Parameter(description = "Additional information key value to be created", required = true) String data,
-            @Context final HttpServletRequest request,
-            @HeaderParam(value = Constants.USER_ID_HEADER) String userUserId) {
-
-        return createAdditionalInformationLabelForComponent(NodeTypeEnum.Resource, resourceId, request, userUserId,
-                data);
-
+        @Parameter(description = "resource id to update with new property", required = true) @PathParam("resourceId") final String resourceId,
+        @Parameter(description = "Additional information key value to be created", required = true) String data,
+        @Context final HttpServletRequest request, @HeaderParam(value = Constants.USER_ID_HEADER) String userUserId) {
+        return createAdditionalInformationLabelForComponent(NodeTypeEnum.Resource, resourceId, request, userUserId, data);
     }
 
     /**
-     *
      * @param serviceId
      * @param data
      * @param request
@@ -130,27 +117,21 @@ public class AdditionalInformationServlet extends BeGenericServlet {
     @Path("/services/{serviceId}/additionalinfo")
     @Consumes(MediaType.APPLICATION_JSON)
     @Produces(MediaType.APPLICATION_JSON)
-    @Operation(description = "Create Additional Information Label and Value", method = "POST",
-            summary = "Returns created Additional Inforamtion property",  responses = {
-            @ApiResponse(content = @Content(array = @ArraySchema(schema = @Schema(implementation = Response.class)))),
-            @ApiResponse(responseCode = "201", description = "Additional information created"),
-            @ApiResponse(responseCode = "403", description = "Restricted operation"),
-            @ApiResponse(responseCode = "400", description = "Invalid content / Missing content"),
-            @ApiResponse(responseCode = "409", description = "Additional information key already exist")})
+    @Operation(description = "Create Additional Information Label and Value", method = "POST", summary = "Returns created Additional Inforamtion property", responses = {
+        @ApiResponse(content = @Content(array = @ArraySchema(schema = @Schema(implementation = Response.class)))),
+        @ApiResponse(responseCode = "201", description = "Additional information created"),
+        @ApiResponse(responseCode = "403", description = "Restricted operation"),
+        @ApiResponse(responseCode = "400", description = "Invalid content / Missing content"),
+        @ApiResponse(responseCode = "409", description = "Additional information key already exist")})
     @PermissionAllowed(AafPermission.PermNames.INTERNAL_ALL_VALUE)
     public Response createServiceAdditionalInformationLabel(
-            @Parameter(description = "service id to update with new property",
-                    required = true) @PathParam("serviceId") final String serviceId,
-            @Parameter(description = "Additional information key value to be created", required = true) String data,
-            @Context final HttpServletRequest request,
-            @HeaderParam(value = Constants.USER_ID_HEADER) String userUserId) {
-
+        @Parameter(description = "service id to update with new property", required = true) @PathParam("serviceId") final String serviceId,
+        @Parameter(description = "Additional information key value to be created", required = true) String data,
+        @Context final HttpServletRequest request, @HeaderParam(value = Constants.USER_ID_HEADER) String userUserId) {
         return createAdditionalInformationLabelForComponent(NodeTypeEnum.Service, serviceId, request, userUserId, data);
-
     }
 
     /**
-     *
      * @param resourceId
      * @param labelId
      * @param data
@@ -162,28 +143,22 @@ public class AdditionalInformationServlet extends BeGenericServlet {
     @Path("/resources/{resourceId}/additionalinfo/{labelId}")
     @Consumes(MediaType.APPLICATION_JSON)
     @Produces(MediaType.APPLICATION_JSON)
-    @Operation(description = "Update Additional Information Label and Value", method = "PUT",
-            summary = "Returns updated Additional Inforamtion property",  responses = {
-            @ApiResponse(content = @Content(array = @ArraySchema(schema = @Schema(implementation = Response.class)))),
-            @ApiResponse(responseCode = "200", description = "Additional information updated"),
-            @ApiResponse(responseCode = "403", description = "Restricted operation"),
-            @ApiResponse(responseCode = "400", description = "Invalid content / Missing content"),
-            @ApiResponse(responseCode = "409", description = "Additional information key already exist")})
+    @Operation(description = "Update Additional Information Label and Value", method = "PUT", summary = "Returns updated Additional Inforamtion property", responses = {
+        @ApiResponse(content = @Content(array = @ArraySchema(schema = @Schema(implementation = Response.class)))),
+        @ApiResponse(responseCode = "200", description = "Additional information updated"),
+        @ApiResponse(responseCode = "403", description = "Restricted operation"),
+        @ApiResponse(responseCode = "400", description = "Invalid content / Missing content"),
+        @ApiResponse(responseCode = "409", description = "Additional information key already exist")})
     @PermissionAllowed(AafPermission.PermNames.INTERNAL_ALL_VALUE)
     public Response updateResourceAdditionalInformationLabel(
-            @Parameter(description = "resource id to update with new property",
-                    required = true) @PathParam("resourceId") final String resourceId,
-            @Parameter(description = "label id", required = true) @PathParam("labelId") final String labelId,
-            @Parameter(description = "Additional information key value to be created", required = true) String data,
-            @Context final HttpServletRequest request, @HeaderParam(value = Constants.USER_ID_HEADER) String userId) {
-
-        return updateAdditionalInformationLabelForComponent(NodeTypeEnum.Resource, resourceId, labelId, request, userId,
-                data);
-
+        @Parameter(description = "resource id to update with new property", required = true) @PathParam("resourceId") final String resourceId,
+        @Parameter(description = "label id", required = true) @PathParam("labelId") final String labelId,
+        @Parameter(description = "Additional information key value to be created", required = true) String data,
+        @Context final HttpServletRequest request, @HeaderParam(value = Constants.USER_ID_HEADER) String userId) {
+        return updateAdditionalInformationLabelForComponent(NodeTypeEnum.Resource, resourceId, labelId, request, userId, data);
     }
 
     /**
-     *
      * @param serviceId
      * @param labelId
      * @param data
@@ -195,28 +170,22 @@ public class AdditionalInformationServlet extends BeGenericServlet {
     @Path("/services/{serviceId}/additionalinfo/{labelId}")
     @Consumes(MediaType.APPLICATION_JSON)
     @Produces(MediaType.APPLICATION_JSON)
-    @Operation(description = "Update Additional Information Label and Value", method = "PUT",
-            summary = "Returns updated Additional Inforamtion property",  responses = {
-            @ApiResponse(content = @Content(array = @ArraySchema(schema = @Schema(implementation = Response.class)))),
-            @ApiResponse(responseCode = "200", description = "Additional information updated"),
-            @ApiResponse(responseCode = "403", description = "Restricted operation"),
-            @ApiResponse(responseCode = "400", description = "Invalid content / Missing content"),
-            @ApiResponse(responseCode = "409", description = "Additional information key already exist")})
+    @Operation(description = "Update Additional Information Label and Value", method = "PUT", summary = "Returns updated Additional Inforamtion property", responses = {
+        @ApiResponse(content = @Content(array = @ArraySchema(schema = @Schema(implementation = Response.class)))),
+        @ApiResponse(responseCode = "200", description = "Additional information updated"),
+        @ApiResponse(responseCode = "403", description = "Restricted operation"),
+        @ApiResponse(responseCode = "400", description = "Invalid content / Missing content"),
+        @ApiResponse(responseCode = "409", description = "Additional information key already exist")})
     @PermissionAllowed(AafPermission.PermNames.INTERNAL_ALL_VALUE)
     public Response updateServiceAdditionalInformationLabel(
-            @Parameter(description = "service id to update with new property",
-                    required = true) @PathParam("serviceId") final String serviceId,
-            @Parameter(description = "label id", required = true) @PathParam("labelId") final String labelId,
-            @Parameter(description = "Additional information key value to be created", required = true) String data,
-            @Context final HttpServletRequest request, @HeaderParam(value = Constants.USER_ID_HEADER) String userId) {
-
-        return updateAdditionalInformationLabelForComponent(NodeTypeEnum.Service, serviceId, labelId, request, userId,
-                data);
-
+        @Parameter(description = "service id to update with new property", required = true) @PathParam("serviceId") final String serviceId,
+        @Parameter(description = "label id", required = true) @PathParam("labelId") final String labelId,
+        @Parameter(description = "Additional information key value to be created", required = true) String data,
+        @Context final HttpServletRequest request, @HeaderParam(value = Constants.USER_ID_HEADER) String userId) {
+        return updateAdditionalInformationLabelForComponent(NodeTypeEnum.Service, serviceId, labelId, request, userId, data);
     }
 
     /**
-     *
      * @param resourceId
      * @param labelId
      * @param request
@@ -227,27 +196,21 @@ public class AdditionalInformationServlet extends BeGenericServlet {
     @Path("/resources/{resourceId}/additionalinfo/{labelId}")
     @Consumes(MediaType.APPLICATION_JSON)
     @Produces(MediaType.APPLICATION_JSON)
-    @Operation(description = "Create Additional Information Label and Value", method = "DELETE",
-            summary = "Returns deleted Additional Inforamtion property",  responses = {
-            @ApiResponse(content = @Content(array = @ArraySchema(schema = @Schema(implementation = Response.class)))),
-            @ApiResponse(responseCode = "200", description = "Additional information deleted"),
-            @ApiResponse(responseCode = "403", description = "Restricted operation"),
-            @ApiResponse(responseCode = "400", description = "Invalid content / Missing content"),
-            @ApiResponse(responseCode = "409", description = "Additional information key already exist")})
+    @Operation(description = "Create Additional Information Label and Value", method = "DELETE", summary = "Returns deleted Additional Inforamtion property", responses = {
+        @ApiResponse(content = @Content(array = @ArraySchema(schema = @Schema(implementation = Response.class)))),
+        @ApiResponse(responseCode = "200", description = "Additional information deleted"),
+        @ApiResponse(responseCode = "403", description = "Restricted operation"),
+        @ApiResponse(responseCode = "400", description = "Invalid content / Missing content"),
+        @ApiResponse(responseCode = "409", description = "Additional information key already exist")})
     @PermissionAllowed(AafPermission.PermNames.INTERNAL_ALL_VALUE)
     public Response updateResourceAdditionalInformationLabel(
-            @Parameter(description = "resource id to update with new property",
-                    required = true) @PathParam("resourceId") final String resourceId,
-            @Parameter(description = "label id", required = true) @PathParam("labelId") final String labelId,
-            @Context final HttpServletRequest request, @HeaderParam(value = Constants.USER_ID_HEADER) String userId) {
-
-        return deleteAdditionalInformationLabelForComponent(NodeTypeEnum.Resource, resourceId, labelId, request,
-                userId);
-
+        @Parameter(description = "resource id to update with new property", required = true) @PathParam("resourceId") final String resourceId,
+        @Parameter(description = "label id", required = true) @PathParam("labelId") final String labelId, @Context final HttpServletRequest request,
+        @HeaderParam(value = Constants.USER_ID_HEADER) String userId) {
+        return deleteAdditionalInformationLabelForComponent(NodeTypeEnum.Resource, resourceId, labelId, request, userId);
     }
 
     /**
-     *
      * @param serviceId
      * @param labelId
      * @param request
@@ -258,26 +221,21 @@ public class AdditionalInformationServlet extends BeGenericServlet {
     @Path("/services/{serviceId}/additionalinfo/{labelId}")
     @Consumes(MediaType.APPLICATION_JSON)
     @Produces(MediaType.APPLICATION_JSON)
-    @Operation(description = "Create Additional Information Label and Value", method = "DELETE",
-            summary = "Returns deleted Additional Inforamtion property",  responses = {
-            @ApiResponse(content = @Content(array = @ArraySchema(schema = @Schema(implementation = Response.class)))),
-            @ApiResponse(responseCode = "200", description = "Additional information deleted"),
-            @ApiResponse(responseCode = "403", description = "Restricted operation"),
-            @ApiResponse(responseCode = "400", description = "Invalid content / Missing content"),
-            @ApiResponse(responseCode = "409", description = "Additional information key already exist")})
+    @Operation(description = "Create Additional Information Label and Value", method = "DELETE", summary = "Returns deleted Additional Inforamtion property", responses = {
+        @ApiResponse(content = @Content(array = @ArraySchema(schema = @Schema(implementation = Response.class)))),
+        @ApiResponse(responseCode = "200", description = "Additional information deleted"),
+        @ApiResponse(responseCode = "403", description = "Restricted operation"),
+        @ApiResponse(responseCode = "400", description = "Invalid content / Missing content"),
+        @ApiResponse(responseCode = "409", description = "Additional information key already exist")})
     @PermissionAllowed(AafPermission.PermNames.INTERNAL_ALL_VALUE)
     public Response deleteServiceAdditionalInformationLabel(
-            @Parameter(description = "service id to update with new property",
-                    required = true) @PathParam("serviceId") final String serviceId,
-            @Parameter(description = "label id", required = true) @PathParam("labelId") final String labelId,
-            @Context final HttpServletRequest request, @HeaderParam(value = Constants.USER_ID_HEADER) String userId) {
-
+        @Parameter(description = "service id to update with new property", required = true) @PathParam("serviceId") final String serviceId,
+        @Parameter(description = "label id", required = true) @PathParam("labelId") final String labelId, @Context final HttpServletRequest request,
+        @HeaderParam(value = Constants.USER_ID_HEADER) String userId) {
         return deleteAdditionalInformationLabelForComponent(NodeTypeEnum.Service, serviceId, labelId, request, userId);
-
     }
 
     /**
-     *
      * @param resourceId
      * @param labelId
      * @param request
@@ -288,26 +246,21 @@ public class AdditionalInformationServlet extends BeGenericServlet {
     @Path("/resources/{resourceId}/additionalinfo/{labelId}")
     @Consumes(MediaType.APPLICATION_JSON)
     @Produces(MediaType.APPLICATION_JSON)
-    @Operation(description = "Get Additional Information by id", method = "GET",
-            summary = "Returns Additional Inforamtion property",  responses = {
-            @ApiResponse(content = @Content(array = @ArraySchema(schema = @Schema(implementation = Response.class)))),
-            @ApiResponse(responseCode = "200", description = "fetched additional information"),
-            @ApiResponse(responseCode = "403", description = "Restricted operation"),
-            @ApiResponse(responseCode = "400", description = "Invalid content / Missing content"),
-            @ApiResponse(responseCode = "409", description = "Additional information key already exist")})
+    @Operation(description = "Get Additional Information by id", method = "GET", summary = "Returns Additional Inforamtion property", responses = {
+        @ApiResponse(content = @Content(array = @ArraySchema(schema = @Schema(implementation = Response.class)))),
+        @ApiResponse(responseCode = "200", description = "fetched additional information"),
+        @ApiResponse(responseCode = "403", description = "Restricted operation"),
+        @ApiResponse(responseCode = "400", description = "Invalid content / Missing content"),
+        @ApiResponse(responseCode = "409", description = "Additional information key already exist")})
     @PermissionAllowed(AafPermission.PermNames.INTERNAL_ALL_VALUE)
     public Response getResourceAdditionalInformationLabel(
-            @Parameter(description = "resource id to update with new property",
-                    required = true) @PathParam("resourceId") final String resourceId,
-            @Parameter(description = "label id", required = true) @PathParam("labelId") final String labelId,
-            @Context final HttpServletRequest request, @HeaderParam(value = Constants.USER_ID_HEADER) String userId) {
-
+        @Parameter(description = "resource id to update with new property", required = true) @PathParam("resourceId") final String resourceId,
+        @Parameter(description = "label id", required = true) @PathParam("labelId") final String labelId, @Context final HttpServletRequest request,
+        @HeaderParam(value = Constants.USER_ID_HEADER) String userId) {
         return getAdditionalInformationLabelForComponent(NodeTypeEnum.Resource, resourceId, labelId, request, userId);
-
     }
 
     /**
-     *
      * @param serviceId
      * @param labelId
      * @param request
@@ -318,26 +271,21 @@ public class AdditionalInformationServlet extends BeGenericServlet {
     @Path("/services/{serviceId}/additionalinfo/{labelId}")
     @Consumes(MediaType.APPLICATION_JSON)
     @Produces(MediaType.APPLICATION_JSON)
-    @Operation(description = "Get Additional Information by id", method = "GET",
-            summary = "Returns Additional Inforamtion property",  responses = {
-            @ApiResponse(content = @Content(array = @ArraySchema(schema = @Schema(implementation = Response.class)))),
-            @ApiResponse(responseCode = "200", description = "fetched additional information"),
-            @ApiResponse(responseCode = "403", description = "Restricted operation"),
-            @ApiResponse(responseCode = "400", description = "Invalid content / Missing content"),
-            @ApiResponse(responseCode = "409", description = "Additional information key already exist")})
+    @Operation(description = "Get Additional Information by id", method = "GET", summary = "Returns Additional Inforamtion property", responses = {
+        @ApiResponse(content = @Content(array = @ArraySchema(schema = @Schema(implementation = Response.class)))),
+        @ApiResponse(responseCode = "200", description = "fetched additional information"),
+        @ApiResponse(responseCode = "403", description = "Restricted operation"),
+        @ApiResponse(responseCode = "400", description = "Invalid content / Missing content"),
+        @ApiResponse(responseCode = "409", description = "Additional information key already exist")})
     @PermissionAllowed(AafPermission.PermNames.INTERNAL_ALL_VALUE)
     public Response getServiceAdditionalInformationLabel(
-            @Parameter(description = "service id to update with new property",
-                    required = true) @PathParam("serviceId") final String serviceId,
-            @Parameter(description = "label id", required = true) @PathParam("labelId") final String labelId,
-            @Context final HttpServletRequest request, @HeaderParam(value = Constants.USER_ID_HEADER) String userId) {
-
+        @Parameter(description = "service id to update with new property", required = true) @PathParam("serviceId") final String serviceId,
+        @Parameter(description = "label id", required = true) @PathParam("labelId") final String labelId, @Context final HttpServletRequest request,
+        @HeaderParam(value = Constants.USER_ID_HEADER) String userId) {
         return getAdditionalInformationLabelForComponent(NodeTypeEnum.Service, serviceId, labelId, request, userId);
-
     }
 
     /**
-     *
      * @param resourceId
      * @param request
      * @param userId
@@ -347,25 +295,20 @@ public class AdditionalInformationServlet extends BeGenericServlet {
     @Path("/resources/{resourceId}/additionalinfo")
     @Consumes(MediaType.APPLICATION_JSON)
     @Produces(MediaType.APPLICATION_JSON)
-    @Operation(description = "Get all Additional Information under resource", method = "GET",
-            summary = "Returns Additional Inforamtion property",  responses = {
-            @ApiResponse(content = @Content(array = @ArraySchema(schema = @Schema(implementation = Response.class)))),
-            @ApiResponse(responseCode = "200", description = "list of additional information"),
-            @ApiResponse(responseCode = "403", description = "Restricted operation"),
-            @ApiResponse(responseCode = "400", description = "Invalid content / Missing content"),
-            @ApiResponse(responseCode = "409", description = "Additional information key already exist")})
+    @Operation(description = "Get all Additional Information under resource", method = "GET", summary = "Returns Additional Inforamtion property", responses = {
+        @ApiResponse(content = @Content(array = @ArraySchema(schema = @Schema(implementation = Response.class)))),
+        @ApiResponse(responseCode = "200", description = "list of additional information"),
+        @ApiResponse(responseCode = "403", description = "Restricted operation"),
+        @ApiResponse(responseCode = "400", description = "Invalid content / Missing content"),
+        @ApiResponse(responseCode = "409", description = "Additional information key already exist")})
     @PermissionAllowed(AafPermission.PermNames.INTERNAL_ALL_VALUE)
     public Response getAllResourceAdditionalInformationLabel(
-            @Parameter(description = "resource id to update with new property",
-                    required = true) @PathParam("resourceId") final String resourceId,
-            @Context final HttpServletRequest request, @HeaderParam(value = Constants.USER_ID_HEADER) String userId) {
-
+        @Parameter(description = "resource id to update with new property", required = true) @PathParam("resourceId") final String resourceId,
+        @Context final HttpServletRequest request, @HeaderParam(value = Constants.USER_ID_HEADER) String userId) {
         return getAllAdditionalInformationLabelForComponent(NodeTypeEnum.Resource, resourceId, request, userId);
-
     }
 
     /**
-     *
      * @param serviceId
      * @param request
      * @param userId
@@ -375,25 +318,20 @@ public class AdditionalInformationServlet extends BeGenericServlet {
     @Path("/services/{serviceId}/additionalinfo")
     @Consumes(MediaType.APPLICATION_JSON)
     @Produces(MediaType.APPLICATION_JSON)
-    @Operation(description = "Get all Additional Information under service", method = "GET",
-            summary = "Returns Additional Inforamtion property",  responses = {
-            @ApiResponse(content = @Content(array = @ArraySchema(schema = @Schema(implementation = Response.class)))),
-            @ApiResponse(responseCode = "200", description = "list of additional information"),
-            @ApiResponse(responseCode = "403", description = "Restricted operation"),
-            @ApiResponse(responseCode = "400", description = "Invalid content / Missing content"),
-            @ApiResponse(responseCode = "409", description = "Additional information key already exist")})
+    @Operation(description = "Get all Additional Information under service", method = "GET", summary = "Returns Additional Inforamtion property", responses = {
+        @ApiResponse(content = @Content(array = @ArraySchema(schema = @Schema(implementation = Response.class)))),
+        @ApiResponse(responseCode = "200", description = "list of additional information"),
+        @ApiResponse(responseCode = "403", description = "Restricted operation"),
+        @ApiResponse(responseCode = "400", description = "Invalid content / Missing content"),
+        @ApiResponse(responseCode = "409", description = "Additional information key already exist")})
     @PermissionAllowed(AafPermission.PermNames.INTERNAL_ALL_VALUE)
     public Response getAllServiceAdditionalInformationLabel(
-            @Parameter(description = "service id to update with new property",
-                    required = true) @PathParam("serviceId") final String serviceId,
-            @Context final HttpServletRequest request, @HeaderParam(value = Constants.USER_ID_HEADER) String userId) {
-
+        @Parameter(description = "service id to update with new property", required = true) @PathParam("serviceId") final String serviceId,
+        @Context final HttpServletRequest request, @HeaderParam(value = Constants.USER_ID_HEADER) String userId) {
         return getAllAdditionalInformationLabelForComponent(NodeTypeEnum.Service, serviceId, request, userId);
-
     }
 
     /**
-     *
      * Create additional information property under given resource/service
      *
      * @param nodeType
@@ -403,42 +341,34 @@ public class AdditionalInformationServlet extends BeGenericServlet {
      * @param data
      * @return
      */
-    protected Response createAdditionalInformationLabelForComponent(NodeTypeEnum nodeType, String uniqueId, HttpServletRequest request, String userId, String data) {
-
+    protected Response createAdditionalInformationLabelForComponent(NodeTypeEnum nodeType, String uniqueId, HttpServletRequest request, String userId,
+                                                                    String data) {
         ServletContext context = request.getSession().getServletContext();
-
         String url = request.getMethod() + " " + request.getRequestURI();
         log.debug(START_HANDLE_REQUEST_OF, url);
         log.debug(MODIFIER_ID_IS, userId);
         log.debug("data is {}", data);
-
         try {
             // convert json to AdditionalInfoParameterInfo
             AdditionalInfoParameterInfo additionalInfoParameterInfo = gson.fromJson(data, AdditionalInfoParameterInfo.class);
-
             // create the new property
-
-            Either<AdditionalInfoParameterInfo, ResponseFormat> either = businessLogic.createAdditionalInformation(nodeType, uniqueId, additionalInfoParameterInfo, userId);
-
+            Either<AdditionalInfoParameterInfo, ResponseFormat> either = businessLogic
+                .createAdditionalInformation(nodeType, uniqueId, additionalInfoParameterInfo, userId);
             if (either.isRight()) {
                 ResponseFormat responseFormat = either.right().value();
                 log.info("Failed to create additional information {}. Reason - {}", additionalInfoParameterInfo, responseFormat);
                 return buildErrorResponse(responseFormat);
             }
-
             AdditionalInfoParameterInfo createdAI = either.left().value();
-
-            log.debug("Additional information {}={} created successfully with id {}", createdAI.getKey(), createdAI.getValue(), createdAI.getUniqueId());
-
+            log.debug("Additional information {}={} created successfully with id {}", createdAI.getKey(), createdAI.getValue(),
+                createdAI.getUniqueId());
             ResponseFormat responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.CREATED);
             return buildOkResponse(responseFormat, createdAI);
-
         } catch (Exception e) {
             log.debug("Create additional information failed with exception", e);
             ResponseFormat responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR);
             return buildErrorResponse(responseFormat);
         }
-
     }
 
     /**
@@ -452,49 +382,39 @@ public class AdditionalInformationServlet extends BeGenericServlet {
      * @param data
      * @return
      */
-    protected Response updateAdditionalInformationLabelForComponent(NodeTypeEnum nodeType, String uniqueId, String labelId, HttpServletRequest request, String userId, String data) {
-
+    protected Response updateAdditionalInformationLabelForComponent(NodeTypeEnum nodeType, String uniqueId, String labelId,
+                                                                    HttpServletRequest request, String userId, String data) {
         ServletContext context = request.getSession().getServletContext();
-
         String url = request.getMethod() + " " + request.getRequestURI();
         log.debug(START_HANDLE_REQUEST_OF, url);
         log.debug(MODIFIER_ID_IS, userId);
         log.debug("data is {}", data);
-
         try {
             // convert json to AdditionalInfoParameterInfo
             AdditionalInfoParameterInfo additionalInfoParameterInfo = gson.fromJson(data, AdditionalInfoParameterInfo.class);
-
             // create the new property
-            
             additionalInfoParameterInfo.setUniqueId(labelId);
-
-            Either<AdditionalInfoParameterInfo, ResponseFormat> either = businessLogic.updateAdditionalInformation(nodeType, uniqueId, additionalInfoParameterInfo, userId);
-
+            Either<AdditionalInfoParameterInfo, ResponseFormat> either = businessLogic
+                .updateAdditionalInformation(nodeType, uniqueId, additionalInfoParameterInfo, userId);
             if (either.isRight()) {
                 ResponseFormat responseFormat = either.right().value();
                 log.info(FAILED_TO_UPDATE_ADDITIONAL_INFO_PROPERTY, responseFormat);
                 return buildErrorResponse(responseFormat);
             }
-
             AdditionalInfoParameterInfo createdAI = either.left().value();
-
-            log.debug("Additional information {}={} updated successfully with id {}", createdAI.getKey(), createdAI.getValue(), createdAI.getUniqueId());
-
+            log.debug("Additional information {}={} updated successfully with id {}", createdAI.getKey(), createdAI.getValue(),
+                createdAI.getUniqueId());
             ResponseFormat responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.OK);
             return buildOkResponse(responseFormat, createdAI);
-
         } catch (Exception e) {
             BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Update Additional Information");
             log.debug("Update additional information failed with exception", e);
             ResponseFormat responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR);
             return buildErrorResponse(responseFormat);
         }
-
     }
 
     /**
-     *
      * Delete an additional information property by id under given resource/service
      *
      * @param nodeType
@@ -504,41 +424,33 @@ public class AdditionalInformationServlet extends BeGenericServlet {
      * @param userId
      * @return
      */
-    protected Response deleteAdditionalInformationLabelForComponent(NodeTypeEnum nodeType, String uniqueId, String labelId, HttpServletRequest request, String userId) {
-
+    protected Response deleteAdditionalInformationLabelForComponent(NodeTypeEnum nodeType, String uniqueId, String labelId,
+                                                                    HttpServletRequest request, String userId) {
         ServletContext context = request.getSession().getServletContext();
-
         String url = request.getMethod() + " " + request.getRequestURI();
         log.debug(START_HANDLE_REQUEST_OF, url);
         log.debug(MODIFIER_ID_IS, userId);
-
         try {
-
             AdditionalInfoParameterInfo additionalInfoParameterInfo = new AdditionalInfoParameterInfo();
             additionalInfoParameterInfo.setUniqueId(labelId);
-
-            Either<AdditionalInfoParameterInfo, ResponseFormat> either = businessLogic.deleteAdditionalInformation(nodeType, uniqueId, additionalInfoParameterInfo, userId);
-
+            Either<AdditionalInfoParameterInfo, ResponseFormat> either = businessLogic
+                .deleteAdditionalInformation(nodeType, uniqueId, additionalInfoParameterInfo, userId);
             if (either.isRight()) {
                 ResponseFormat responseFormat = either.right().value();
                 log.info(FAILED_TO_UPDATE_ADDITIONAL_INFO_PROPERTY, responseFormat);
                 return buildErrorResponse(responseFormat);
             }
-
             AdditionalInfoParameterInfo createdAI = either.left().value();
-
-            log.debug("Additional information {}={} deleted successfully with id {}", createdAI.getKey(), createdAI.getValue(), createdAI.getUniqueId());
-
+            log.debug("Additional information {}={} deleted successfully with id {}", createdAI.getKey(), createdAI.getValue(),
+                createdAI.getUniqueId());
             ResponseFormat responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.OK);
             return buildOkResponse(responseFormat, createdAI);
-
         } catch (Exception e) {
             BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Delete Additional Information");
             log.debug("Delete additional information failed with exception", e);
             ResponseFormat responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR);
             return buildErrorResponse(responseFormat);
         }
-
     }
 
     /**
@@ -551,45 +463,34 @@ public class AdditionalInformationServlet extends BeGenericServlet {
      * @param userId
      * @return
      */
-    protected Response getAdditionalInformationLabelForComponent(NodeTypeEnum nodeType, String uniqueId, String labelId, HttpServletRequest request, String userId) {
-
+    protected Response getAdditionalInformationLabelForComponent(NodeTypeEnum nodeType, String uniqueId, String labelId, HttpServletRequest request,
+                                                                 String userId) {
         ServletContext context = request.getSession().getServletContext();
-
         String url = request.getMethod() + " " + request.getRequestURI();
         log.debug(START_HANDLE_REQUEST_OF, url);
         log.debug(MODIFIER_ID_IS, userId);
-
         try {
-
             // create the new property
-            
-
             AdditionalInfoParameterInfo additionalInfoParameterInfo = new AdditionalInfoParameterInfo();
             additionalInfoParameterInfo.setUniqueId(labelId);
-
-            Either<AdditionalInfoParameterInfo, ResponseFormat> either = businessLogic.getAdditionalInformation(nodeType, uniqueId, additionalInfoParameterInfo, userId);
-
+            Either<AdditionalInfoParameterInfo, ResponseFormat> either = businessLogic
+                .getAdditionalInformation(nodeType, uniqueId, additionalInfoParameterInfo, userId);
             if (either.isRight()) {
                 ResponseFormat responseFormat = either.right().value();
                 log.info(FAILED_TO_UPDATE_ADDITIONAL_INFO_PROPERTY, responseFormat);
                 return buildErrorResponse(responseFormat);
             }
-
             AdditionalInfoParameterInfo createdAI = either.left().value();
-
-            log.debug("Additional information {}={} fetched successfully with id {}", createdAI.getKey(), createdAI.getValue(), createdAI.getUniqueId());
-
+            log.debug("Additional information {}={} fetched successfully with id {}", createdAI.getKey(), createdAI.getValue(),
+                createdAI.getUniqueId());
             ResponseFormat responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.OK);
             return buildOkResponse(responseFormat, createdAI);
-
         } catch (Exception e) {
             BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Get Additional Information");
-
             log.debug("get additional information failed with exception", e);
             ResponseFormat responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR);
             return buildErrorResponse(responseFormat);
         }
-
     }
 
     /**
@@ -601,39 +502,28 @@ public class AdditionalInformationServlet extends BeGenericServlet {
      * @param userId
      * @return
      */
-    protected Response getAllAdditionalInformationLabelForComponent(NodeTypeEnum nodeType, String uniqueId, HttpServletRequest request, String userId) {
-
+    protected Response getAllAdditionalInformationLabelForComponent(NodeTypeEnum nodeType, String uniqueId, HttpServletRequest request,
+                                                                    String userId) {
         ServletContext context = request.getSession().getServletContext();
-
         String url = request.getMethod() + " " + request.getRequestURI();
         log.debug(START_HANDLE_REQUEST_OF, url);
         log.debug(MODIFIER_ID_IS, userId);
-
         try {
-
-            
-
             Either<AdditionalInformationDefinition, ResponseFormat> either = businessLogic.getAllAdditionalInformation(nodeType, uniqueId, userId);
             if (either.isRight()) {
                 ResponseFormat responseFormat = either.right().value();
                 log.info(FAILED_TO_UPDATE_ADDITIONAL_INFO_PROPERTY, responseFormat);
                 return buildErrorResponse(responseFormat);
             }
-
             AdditionalInformationDefinition additionalInformationDefinition = either.left().value();
-
             log.debug("All Additional information retrieved for component {} is {}", uniqueId, additionalInformationDefinition);
-
             ResponseFormat responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.OK);
             return buildOkResponse(responseFormat, additionalInformationDefinition);
-
         } catch (Exception e) {
             BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Get All Additional Information");
             log.debug("Get all addiotanl information properties failed with exception", e);
             ResponseFormat responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR);
             return buildErrorResponse(responseFormat);
         }
-
     }
-
 }
index 1ab30b1..f293061 100644 (file)
@@ -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.
@@ -17,7 +17,6 @@
  * limitations under the License.
  * ============LICENSE_END=========================================================
  */
-
 package org.openecomp.sdc.be.servlets;
 
 import com.jcabi.aspects.Loggable;
@@ -30,6 +29,20 @@ import io.swagger.v3.oas.annotations.servers.Server;
 import io.swagger.v3.oas.annotations.servers.Servers;
 import io.swagger.v3.oas.annotations.tags.Tag;
 import io.swagger.v3.oas.annotations.tags.Tags;
+import java.util.HashMap;
+import java.util.LinkedList;
+import java.util.List;
+import java.util.Map;
+import javax.inject.Inject;
+import javax.ws.rs.Consumes;
+import javax.ws.rs.GET;
+import javax.ws.rs.HeaderParam;
+import javax.ws.rs.POST;
+import javax.ws.rs.Path;
+import javax.ws.rs.PathParam;
+import javax.ws.rs.Produces;
+import javax.ws.rs.core.MediaType;
+import javax.ws.rs.core.Response;
 import org.openecomp.sdc.be.components.impl.ArchiveBusinessLogic;
 import org.openecomp.sdc.be.components.impl.aaf.AafPermission;
 import org.openecomp.sdc.be.components.impl.aaf.PermissionAllowed;
@@ -44,22 +57,6 @@ import org.openecomp.sdc.common.log.enums.StatusCode;
 import org.springframework.stereotype.Controller;
 import org.springframework.web.bind.annotation.RequestBody;
 
-import javax.inject.Inject;
-import javax.ws.rs.Consumes;
-import javax.ws.rs.GET;
-import javax.ws.rs.HeaderParam;
-import javax.ws.rs.POST;
-import javax.ws.rs.Path;
-import javax.ws.rs.PathParam;
-import javax.ws.rs.Produces;
-import javax.ws.rs.core.MediaType;
-import javax.ws.rs.core.Response;
-import java.util.HashMap;
-import java.util.LinkedList;
-import java.util.List;
-import java.util.Map;
-
-
 @Loggable(prepend = true, value = Loggable.DEBUG, trim = false)
 @Path("/v1/catalog")
 @Tags({@Tag(name = "SDC Internal APIs")})
@@ -67,148 +64,132 @@ import java.util.Map;
 @Controller
 @Consumes(MediaType.APPLICATION_JSON)
 @Produces(MediaType.APPLICATION_JSON)
-public class ArchiveEndpoint extends BeGenericServlet{
+public class ArchiveEndpoint extends BeGenericServlet {
 
     private static final String COMPONENT_ID = "Component ID= ";
-    private final ArchiveBusinessLogic archiveBusinessLogic;
     private static final LoggerSupportability loggerSupportability = LoggerSupportability.getLogger(ArchiveEndpoint.class.getName());
+    private final ArchiveBusinessLogic archiveBusinessLogic;
 
     @Inject
-    public ArchiveEndpoint(UserBusinessLogic userBusinessLogic,
-                           ComponentsUtils componentsUtils, ArchiveBusinessLogic archiveBusinessLogic) {
+    public ArchiveEndpoint(UserBusinessLogic userBusinessLogic, ComponentsUtils componentsUtils, ArchiveBusinessLogic archiveBusinessLogic) {
         super(userBusinessLogic, componentsUtils);
         this.archiveBusinessLogic = archiveBusinessLogic;
     }
 
     @POST
     @Path("/resources/{componentId}/archive")
-    @Operation(description = "Archive Resource", method = "POST",
-            summary = "Marks a resource as archived. Can be restored with restore action", responses = {
-            @ApiResponse(content = @Content(array = @ArraySchema(schema = @Schema(implementation = String.class)))),
-            @ApiResponse(responseCode = "200", description = "Archive successful"),
-            @ApiResponse(responseCode = "400", description = "Bad request"),
-            @ApiResponse(responseCode = "403", description = "Restricted operation"),
-            @ApiResponse(responseCode = "404", description = "Resource not found"),
-            @ApiResponse(responseCode = "500", description = "Internal Error")})
+    @Operation(description = "Archive Resource", method = "POST", summary = "Marks a resource as archived. Can be restored with restore action", responses = {
+        @ApiResponse(content = @Content(array = @ArraySchema(schema = @Schema(implementation = String.class)))),
+        @ApiResponse(responseCode = "200", description = "Archive successful"), @ApiResponse(responseCode = "400", description = "Bad request"),
+        @ApiResponse(responseCode = "403", description = "Restricted operation"),
+        @ApiResponse(responseCode = "404", description = "Resource not found"), @ApiResponse(responseCode = "500", description = "Internal Error")})
     @PermissionAllowed(AafPermission.PermNames.INTERNAL_ALL_VALUE)
-    public Response archiveResources(@PathParam("componentId") final String componentId, @HeaderParam(value = Constants.USER_ID_HEADER) String userId) {
-        loggerSupportability.log(LoggerSupportabilityActions.ARCHIVE,StatusCode.STARTED,"Archive Resource " + COMPONENT_ID + " " + componentId + " by "+ userId);
+    public Response archiveResources(@PathParam("componentId") final String componentId,
+                                     @HeaderParam(value = Constants.USER_ID_HEADER) String userId) {
+        loggerSupportability
+            .log(LoggerSupportabilityActions.ARCHIVE, StatusCode.STARTED, "Archive Resource " + COMPONENT_ID + " " + componentId + " by " + userId);
         archiveBusinessLogic.archiveComponent(ComponentTypeEnum.RESOURCE_PARAM_NAME, userId, componentId);
-        loggerSupportability.log(LoggerSupportabilityActions.ARCHIVE,StatusCode.COMPLETE,"Archive Resource " + COMPONENT_ID + " " + componentId + " by "+ userId);
+        loggerSupportability
+            .log(LoggerSupportabilityActions.ARCHIVE, StatusCode.COMPLETE, "Archive Resource " + COMPONENT_ID + " " + componentId + " by " + userId);
         return Response.ok().build();
     }
 
     @POST
     @Path("/resources/{componentId}/restore")
-    @Operation(description = "Restore Resource", method = "POST", summary = "Restores a resource from archive.",
-            responses = {@ApiResponse(
-                    content = @Content(array = @ArraySchema(schema = @Schema(implementation = String.class)))),
-                    @ApiResponse(responseCode = "200", description = "Restore successful"),
-                    @ApiResponse(responseCode = "400", description = "Bad request"),
-                    @ApiResponse(responseCode = "403", description = "Restricted operation"),
-                    @ApiResponse(responseCode = "404", description = "Resource not found"),
-                    @ApiResponse(responseCode = "500", description = "Internal Error")})
+    @Operation(description = "Restore Resource", method = "POST", summary = "Restores a resource from archive.", responses = {
+        @ApiResponse(content = @Content(array = @ArraySchema(schema = @Schema(implementation = String.class)))),
+        @ApiResponse(responseCode = "200", description = "Restore successful"), @ApiResponse(responseCode = "400", description = "Bad request"),
+        @ApiResponse(responseCode = "403", description = "Restricted operation"),
+        @ApiResponse(responseCode = "404", description = "Resource not found"), @ApiResponse(responseCode = "500", description = "Internal Error")})
     @PermissionAllowed(AafPermission.PermNames.INTERNAL_ALL_VALUE)
-    public Response restoreResource(@PathParam("componentId") final String componentId, @HeaderParam(value = Constants.USER_ID_HEADER) String userId) {
-        loggerSupportability.log(LoggerSupportabilityActions.RESTORE_FROM_ARCHIVE,StatusCode.STARTED,"Restore resource from archive " + COMPONENT_ID + " " + componentId + " by "+ userId);
+    public Response restoreResource(@PathParam("componentId") final String componentId,
+                                    @HeaderParam(value = Constants.USER_ID_HEADER) String userId) {
+        loggerSupportability.log(LoggerSupportabilityActions.RESTORE_FROM_ARCHIVE, StatusCode.STARTED,
+            "Restore resource from archive " + COMPONENT_ID + " " + componentId + " by " + userId);
         archiveBusinessLogic.restoreComponent(ComponentTypeEnum.RESOURCE_PARAM_NAME, userId, componentId);
-        loggerSupportability.log(LoggerSupportabilityActions.RESTORE_FROM_ARCHIVE,StatusCode.COMPLETE,"Restore resource from archive " + COMPONENT_ID + " " + componentId + " by "+ userId);
+        loggerSupportability.log(LoggerSupportabilityActions.RESTORE_FROM_ARCHIVE, StatusCode.COMPLETE,
+            "Restore resource from archive " + COMPONENT_ID + " " + componentId + " by " + userId);
         return Response.ok().build();
     }
 
     @POST
     @Path("/services/{componentId}/archive")
-    @Operation(description = "Archive Service", method = "POST",
-            summary = "Marks a service as archived. Can be restored with restore action", responses = {
-            @ApiResponse(content = @Content(array = @ArraySchema(schema = @Schema(implementation = String.class)))),
-            @ApiResponse(responseCode = "200", description = "Archive successful"),
-            @ApiResponse(responseCode = "400", description = "Bad request"),
-            @ApiResponse(responseCode = "403", description = "Restricted operation"),
-            @ApiResponse(responseCode = "404", description = "Service not found"),
-            @ApiResponse(responseCode = "500", description = "Internal Error")})
+    @Operation(description = "Archive Service", method = "POST", summary = "Marks a service as archived. Can be restored with restore action", responses = {
+        @ApiResponse(content = @Content(array = @ArraySchema(schema = @Schema(implementation = String.class)))),
+        @ApiResponse(responseCode = "200", description = "Archive successful"), @ApiResponse(responseCode = "400", description = "Bad request"),
+        @ApiResponse(responseCode = "403", description = "Restricted operation"),
+        @ApiResponse(responseCode = "404", description = "Service not found"), @ApiResponse(responseCode = "500", description = "Internal Error")})
     @PermissionAllowed(AafPermission.PermNames.INTERNAL_ALL_VALUE)
     public Response archiveService(@PathParam("componentId") final String componentId, @HeaderParam(value = Constants.USER_ID_HEADER) String userId) {
-        loggerSupportability.log(LoggerSupportabilityActions.ARCHIVE, StatusCode.STARTED, "Archive Service for " + COMPONENT_ID + " " + componentId + " by " + userId);
+        loggerSupportability.log(LoggerSupportabilityActions.ARCHIVE, StatusCode.STARTED,
+            "Archive Service for " + COMPONENT_ID + " " + componentId + " by " + userId);
         archiveBusinessLogic.archiveComponent(ComponentTypeEnum.SERVICE_PARAM_NAME, userId, componentId);
-        loggerSupportability.log(LoggerSupportabilityActions.ARCHIVE,StatusCode.COMPLETE, "Archive Service for " + COMPONENT_ID + " " + componentId + " by " + userId);
+        loggerSupportability.log(LoggerSupportabilityActions.ARCHIVE, StatusCode.COMPLETE,
+            "Archive Service for " + COMPONENT_ID + " " + componentId + " by " + userId);
         return Response.ok().build();
     }
 
-
     @POST
     @Path("/services/{componentId}/restore")
-    @Operation(description = "Restore Service", method = "POST", summary = "Restores a service from archive.",
-            responses = {@ApiResponse(
-                    content = @Content(array = @ArraySchema(schema = @Schema(implementation = String.class)))),
-                    @ApiResponse(responseCode = "200", description = "Restore successful"),
-                    @ApiResponse(responseCode = "400", description = "Bad request"),
-                    @ApiResponse(responseCode = "403", description = "Restricted operation"),
-                    @ApiResponse(responseCode = "404", description = "Service not found"),
-                    @ApiResponse(responseCode = "500", description = "Internal Error")})
+    @Operation(description = "Restore Service", method = "POST", summary = "Restores a service from archive.", responses = {
+        @ApiResponse(content = @Content(array = @ArraySchema(schema = @Schema(implementation = String.class)))),
+        @ApiResponse(responseCode = "200", description = "Restore successful"), @ApiResponse(responseCode = "400", description = "Bad request"),
+        @ApiResponse(responseCode = "403", description = "Restricted operation"),
+        @ApiResponse(responseCode = "404", description = "Service not found"), @ApiResponse(responseCode = "500", description = "Internal Error")})
     @PermissionAllowed(AafPermission.PermNames.INTERNAL_ALL_VALUE)
     public Response restoreService(@PathParam("componentId") final String componentId, @HeaderParam(value = Constants.USER_ID_HEADER) String userId) {
-        loggerSupportability.log(LoggerSupportabilityActions.RESTORE_FROM_ARCHIVE,StatusCode.STARTED,"Restore service from archive " + COMPONENT_ID + " " + componentId + " by "+ userId);
+        loggerSupportability.log(LoggerSupportabilityActions.RESTORE_FROM_ARCHIVE, StatusCode.STARTED,
+            "Restore service from archive " + COMPONENT_ID + " " + componentId + " by " + userId);
         archiveBusinessLogic.restoreComponent(ComponentTypeEnum.SERVICE_PARAM_NAME, userId, componentId);
-        loggerSupportability.log(LoggerSupportabilityActions.RESTORE_FROM_ARCHIVE,StatusCode.COMPLETE,"Restore service from archive " + COMPONENT_ID + " " + componentId + " by "+ userId);
+        loggerSupportability.log(LoggerSupportabilityActions.RESTORE_FROM_ARCHIVE, StatusCode.COMPLETE,
+            "Restore service from archive " + COMPONENT_ID + " " + componentId + " by " + userId);
         return Response.ok().build();
     }
 
     @GET
     @Path("/archive")
-    @Operation(description = "Get all Archived Components", method = "GET", summary = "Get all Archived Components",
-            responses = {@ApiResponse(
-                    content = @Content(array = @ArraySchema(schema = @Schema(implementation = String.class)))),
-                    @ApiResponse(responseCode = "200", description = "Success"),
-                    @ApiResponse(responseCode = "400", description = "Bad request"),
-                    @ApiResponse(responseCode = "403", description = "Restricted operation"),
-                    @ApiResponse(responseCode = "500", description = "Internal Error")})
+    @Operation(description = "Get all Archived Components", method = "GET", summary = "Get all Archived Components", responses = {
+        @ApiResponse(content = @Content(array = @ArraySchema(schema = @Schema(implementation = String.class)))),
+        @ApiResponse(responseCode = "200", description = "Success"), @ApiResponse(responseCode = "400", description = "Bad request"),
+        @ApiResponse(responseCode = "403", description = "Restricted operation"), @ApiResponse(responseCode = "500", description = "Internal Error")})
     @PermissionAllowed(AafPermission.PermNames.INTERNAL_ALL_VALUE)
-    public Map<String, List<CatalogComponent>> getArchivedComponents(@HeaderParam(value = Constants.USER_ID_HEADER) String userId){
+    public Map<String, List<CatalogComponent>> getArchivedComponents(@HeaderParam(value = Constants.USER_ID_HEADER) String userId) {
         return this.archiveBusinessLogic.getArchiveComponents(userId, new LinkedList<>());
     }
 
     @POST
     @Path("/notif/vsp/archived")
-    @Operation(
-            description = "Notify about an archived VSP. All VFs with relation to the given CSAR IDs will be martked as vspArchived=true",
-            method = "POST", responses = {@ApiResponse(responseCode = "200", description = "Success"),
-            @ApiResponse(responseCode = "400", description = "Bad request"),
-            @ApiResponse(responseCode = "403", description = "Restricted operation"), @ApiResponse(responseCode = "500",
-            description = "Internal Error. A list of the failed CSAR IDs may be returned.")})
+    @Operation(description = "Notify about an archived VSP. All VFs with relation to the given CSAR IDs will be martked as vspArchived=true", method = "POST", responses = {
+        @ApiResponse(responseCode = "200", description = "Success"), @ApiResponse(responseCode = "400", description = "Bad request"),
+        @ApiResponse(responseCode = "403", description = "Restricted operation"),
+        @ApiResponse(responseCode = "500", description = "Internal Error. A list of the failed CSAR IDs may be returned.")})
     @PermissionAllowed(AafPermission.PermNames.INTERNAL_ALL_VALUE)
-    public Response onVspArchived(@HeaderParam(value = Constants.USER_ID_HEADER) String userId, @RequestBody List<String> csarIds){
+    public Response onVspArchived(@HeaderParam(value = Constants.USER_ID_HEADER) String userId, @RequestBody List<String> csarIds) {
         List<String> failedCsarIds = this.archiveBusinessLogic.onVspArchive(userId, csarIds);
-        if (!failedCsarIds.isEmpty()){
+        if (!failedCsarIds.isEmpty()) {
             //There are some failed CSAR IDs, return 500 and the list of failed CSAR IDs
             Map<String, List<String>> entity = new HashMap<>();
             entity.put("failedIds", failedCsarIds);
-            return Response.status(Response.Status.INTERNAL_SERVER_ERROR)
-                    .entity(entity)
-                    .build();
+            return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(entity).build();
         }
         return Response.ok().build();
     }
 
     @POST
     @Path("/notif/vsp/restored")
-    @Operation(
-            description = "Notify about a restored VSP. All VFs with relation to the given CSAR IDs will be martked as vspArchived=false",
-            method = "POST", responses = {@ApiResponse(responseCode = "200", description = "Success"),
-            @ApiResponse(responseCode = "400", description = "Bad request"),
-            @ApiResponse(responseCode = "403", description = "Restricted operation"), @ApiResponse(responseCode = "500",
-            description = "Internal Error. A list of the failed CSAR IDs may be returned.")})
+    @Operation(description = "Notify about a restored VSP. All VFs with relation to the given CSAR IDs will be martked as vspArchived=false", method = "POST", responses = {
+        @ApiResponse(responseCode = "200", description = "Success"), @ApiResponse(responseCode = "400", description = "Bad request"),
+        @ApiResponse(responseCode = "403", description = "Restricted operation"),
+        @ApiResponse(responseCode = "500", description = "Internal Error. A list of the failed CSAR IDs may be returned.")})
     @PermissionAllowed(AafPermission.PermNames.INTERNAL_ALL_VALUE)
-    public Response onVspRestored(@HeaderParam(value = Constants.USER_ID_HEADER) String userId, @RequestBody List<String> csarIds){
+    public Response onVspRestored(@HeaderParam(value = Constants.USER_ID_HEADER) String userId, @RequestBody List<String> csarIds) {
         List<String> failedCsarIds = this.archiveBusinessLogic.onVspRestore(userId, csarIds);
-        if (!failedCsarIds.isEmpty()){
+        if (!failedCsarIds.isEmpty()) {
             //There are some failed CSAR IDs, return 500 and the list of failed CSAR IDs
             Map<String, List<String>> entity = new HashMap<>();
             entity.put("failedIds", failedCsarIds);
-            return Response.status(Response.Status.INTERNAL_SERVER_ERROR)
-                    .entity(entity)
-                    .build();
+            return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(entity).build();
         }
         return Response.ok().build();
     }
-
 }
index 037ca47..93f9fff 100644 (file)
@@ -17,7 +17,6 @@
  * limitations under the License.
  * ============LICENSE_END=========================================================
  */
-
 package org.openecomp.sdc.be.servlets;
 
 import com.jcabi.aspects.Loggable;
@@ -32,6 +31,20 @@ import io.swagger.v3.oas.annotations.servers.Server;
 import io.swagger.v3.oas.annotations.servers.Servers;
 import io.swagger.v3.oas.annotations.tags.Tag;
 import io.swagger.v3.oas.annotations.tags.Tags;
+import java.util.Map;
+import javax.inject.Inject;
+import javax.servlet.http.HttpServletRequest;
+import javax.ws.rs.Consumes;
+import javax.ws.rs.DELETE;
+import javax.ws.rs.GET;
+import javax.ws.rs.HeaderParam;
+import javax.ws.rs.POST;
+import javax.ws.rs.Path;
+import javax.ws.rs.PathParam;
+import javax.ws.rs.Produces;
+import javax.ws.rs.core.Context;
+import javax.ws.rs.core.MediaType;
+import javax.ws.rs.core.Response;
 import org.apache.commons.codec.binary.Base64;
 import org.apache.commons.lang3.tuple.ImmutablePair;
 import org.openecomp.sdc.be.components.impl.ArtifactsBusinessLogic;
@@ -55,21 +68,6 @@ import org.openecomp.sdc.common.log.wrappers.Logger;
 import org.openecomp.sdc.exception.ResponseFormat;
 import org.springframework.stereotype.Controller;
 
-import javax.inject.Inject;
-import javax.servlet.http.HttpServletRequest;
-import javax.ws.rs.Consumes;
-import javax.ws.rs.DELETE;
-import javax.ws.rs.GET;
-import javax.ws.rs.HeaderParam;
-import javax.ws.rs.POST;
-import javax.ws.rs.Path;
-import javax.ws.rs.PathParam;
-import javax.ws.rs.Produces;
-import javax.ws.rs.core.Context;
-import javax.ws.rs.core.MediaType;
-import javax.ws.rs.core.Response;
-import java.util.Map;
-
 /**
  * Root resource (exposed at "/" path)
  */
@@ -80,42 +78,37 @@ import java.util.Map;
 @Controller
 public class ArtifactServlet extends BeGenericServlet {
 
+    private static final Logger log = Logger.getLogger(ArtifactServlet.class);
+    private static final LoggerSupportability loggerSupportability = LoggerSupportability.getLogger(ArtifactServlet.class.getName());
+    private static final String START_HANDLE_REQUEST_OF = "Start handle request of {}";
+    private static final String DOWNLOAD_RESOURCE_INSTANCE_ARTIFACT_BASE64 = "downloadResourceInstanceArtifactBase64";
+    private static final String DOWNLOAD_RESOURCE_INSTANCE_ARTIFACT_BASE64_EXCEPTION = "downloadResourceInstanceArtifactBase64 unexpected exception";
     private final ArtifactsBusinessLogic artifactsBusinessLogic;
 
     @Inject
-    public ArtifactServlet(UserBusinessLogic userBusinessLogic,
-        ComponentsUtils componentsUtils, ArtifactsBusinessLogic artifactsBusinessLogic) {
+    public ArtifactServlet(UserBusinessLogic userBusinessLogic, ComponentsUtils componentsUtils, ArtifactsBusinessLogic artifactsBusinessLogic) {
         super(userBusinessLogic, componentsUtils);
         this.artifactsBusinessLogic = artifactsBusinessLogic;
     }
 
-    private static final Logger log = Logger.getLogger(ArtifactServlet.class);
-    private static final LoggerSupportability loggerSupportability = LoggerSupportability.getLogger(ArtifactServlet.class.getName());
-
-    private static final String START_HANDLE_REQUEST_OF = "Start handle request of {}";
-    private static final String DOWNLOAD_RESOURCE_INSTANCE_ARTIFACT_BASE64 = "downloadResourceInstanceArtifactBase64";
-    private static final String DOWNLOAD_RESOURCE_INSTANCE_ARTIFACT_BASE64_EXCEPTION = "downloadResourceInstanceArtifactBase64 unexpected exception";
-
     // *************** Resources
     @POST
     @Path("/resources/{resourceId}/artifacts")
     @Consumes(MediaType.APPLICATION_JSON)
     @Produces(MediaType.APPLICATION_JSON)
-    @Operation(description = "Create Artifact", method = "POST", summary = "Returns created ArtifactDefinition",
-            responses = {@ApiResponse(
-                    content = @Content(array = @ArraySchema(schema = @Schema(implementation = Response.class)))),
-                    @ApiResponse(responseCode = "201", description = "Resource created"),
-                    @ApiResponse(responseCode = "403", description = "Restricted operation"),
-                    @ApiResponse(responseCode = "400", description = "Invalid content / Missing content"),
-                    @ApiResponse(responseCode = "409", description = "Artifact already exist")})
+    @Operation(description = "Create Artifact", method = "POST", summary = "Returns created ArtifactDefinition", responses = {
+        @ApiResponse(content = @Content(array = @ArraySchema(schema = @Schema(implementation = Response.class)))),
+        @ApiResponse(responseCode = "201", description = "Resource created"),
+        @ApiResponse(responseCode = "403", description = "Restricted operation"),
+        @ApiResponse(responseCode = "400", description = "Invalid content / Missing content"),
+        @ApiResponse(responseCode = "409", description = "Artifact already exist")})
     @PermissionAllowed(AafPermission.PermNames.INTERNAL_ALL_VALUE)
     public Response loadArtifact(@PathParam("resourceId") final String resourceId,
-            @Parameter(description = "json describe the artifact", required = true) String data,
-            @Context final HttpServletRequest request) {
-
+                                 @Parameter(description = "json describe the artifact", required = true) String data,
+                                 @Context final HttpServletRequest request) {
         String url = request.getMethod() + " " + request.getRequestURI();
         log.debug(START_HANDLE_REQUEST_OF, url);
-            return handleUploadRequest(data, request, resourceId, ComponentTypeEnum.RESOURCE);
+        return handleUploadRequest(data, request, resourceId, ComponentTypeEnum.RESOURCE);
     }
 
     @POST
@@ -123,16 +116,14 @@ public class ArtifactServlet extends BeGenericServlet {
     @Consumes(MediaType.APPLICATION_JSON)
     @Produces(MediaType.APPLICATION_JSON)
     @Operation(description = "Update Artifact", method = "POST", summary = "Returns updated artifact", responses = {
-            @ApiResponse(content = @Content(array = @ArraySchema(schema = @Schema(implementation = Response.class)))),
-            @ApiResponse(responseCode = "201", description = "Resource created"),
-            @ApiResponse(responseCode = "403", description = "Restricted operation"),
-            @ApiResponse(responseCode = "400", description = "Invalid content / Missing content")})
+        @ApiResponse(content = @Content(array = @ArraySchema(schema = @Schema(implementation = Response.class)))),
+        @ApiResponse(responseCode = "201", description = "Resource created"),
+        @ApiResponse(responseCode = "403", description = "Restricted operation"),
+        @ApiResponse(responseCode = "400", description = "Invalid content / Missing content")})
     @PermissionAllowed(AafPermission.PermNames.INTERNAL_ALL_VALUE)
-    public Response updateArtifact(@PathParam("resourceId") final String resourceId,
-            @PathParam("artifactId") final String artifactId,
-            @Parameter(description = "json describe the artifact", required = true) String data,
-            @Context final HttpServletRequest request) {
-
+    public Response updateArtifact(@PathParam("resourceId") final String resourceId, @PathParam("artifactId") final String artifactId,
+                                   @Parameter(description = "json describe the artifact", required = true) String data,
+                                   @Context final HttpServletRequest request) {
         String url = request.getMethod() + " " + request.getRequestURI();
         log.debug(START_HANDLE_REQUEST_OF, url);
         try {
@@ -149,14 +140,13 @@ public class ArtifactServlet extends BeGenericServlet {
     @Consumes(MediaType.APPLICATION_JSON)
     @Produces(MediaType.APPLICATION_JSON)
     @Operation(description = "Delete Artifact", method = "DELETE", summary = "Returns delete artifact", responses = {
-            @ApiResponse(content = @Content(array = @ArraySchema(schema = @Schema(implementation = Response.class)))),
-            @ApiResponse(responseCode = "201", description = "Resource created"),
-            @ApiResponse(responseCode = "403", description = "Restricted operation"),
-            @ApiResponse(responseCode = "400", description = "Invalid content / Missing content")})
+        @ApiResponse(content = @Content(array = @ArraySchema(schema = @Schema(implementation = Response.class)))),
+        @ApiResponse(responseCode = "201", description = "Resource created"),
+        @ApiResponse(responseCode = "403", description = "Restricted operation"),
+        @ApiResponse(responseCode = "400", description = "Invalid content / Missing content")})
     @PermissionAllowed(AafPermission.PermNames.INTERNAL_ALL_VALUE)
-    public Response deleteArtifact(@PathParam("resourceId") final String resourceId,
-            @PathParam("artifactId") final String artifactId, @Context final HttpServletRequest request) {
-
+    public Response deleteArtifact(@PathParam("resourceId") final String resourceId, @PathParam("artifactId") final String artifactId,
+                                   @Context final HttpServletRequest request) {
         String url = request.getMethod() + " " + request.getRequestURI();
         log.debug(START_HANDLE_REQUEST_OF, url);
         try {
@@ -172,18 +162,16 @@ public class ArtifactServlet extends BeGenericServlet {
     @Path("/services/{serviceId}/artifacts")
     @Consumes(MediaType.APPLICATION_JSON)
     @Produces(MediaType.APPLICATION_JSON)
-    @Operation(description = "Create Artifact", method = "POST", summary = "Returns created ArtifactDefinition",
-            responses = {@ApiResponse(
-                    content = @Content(array = @ArraySchema(schema = @Schema(implementation = Response.class)))),
-                    @ApiResponse(responseCode = "201", description = "Resource created"),
-                    @ApiResponse(responseCode = "403", description = "Restricted operation"),
-                    @ApiResponse(responseCode = "400", description = "Invalid content / Missing content"),
-                    @ApiResponse(responseCode = "409", description = "Artifact already exist")})
+    @Operation(description = "Create Artifact", method = "POST", summary = "Returns created ArtifactDefinition", responses = {
+        @ApiResponse(content = @Content(array = @ArraySchema(schema = @Schema(implementation = Response.class)))),
+        @ApiResponse(responseCode = "201", description = "Resource created"),
+        @ApiResponse(responseCode = "403", description = "Restricted operation"),
+        @ApiResponse(responseCode = "400", description = "Invalid content / Missing content"),
+        @ApiResponse(responseCode = "409", description = "Artifact already exist")})
     @PermissionAllowed(AafPermission.PermNames.INTERNAL_ALL_VALUE)
     public Response loadInformationArtifact(@PathParam("serviceId") final String serviceId,
-            @Parameter(description = "json describe the artifact", required = true) String data,
-            @Context final HttpServletRequest request) {
-
+                                            @Parameter(description = "json describe the artifact", required = true) String data,
+                                            @Context final HttpServletRequest request) {
         String url = request.getMethod() + " " + request.getRequestURI();
         log.debug(START_HANDLE_REQUEST_OF, url);
         try {
@@ -200,15 +188,13 @@ public class ArtifactServlet extends BeGenericServlet {
     @Consumes(MediaType.APPLICATION_JSON)
     @Produces(MediaType.APPLICATION_JSON)
     @Operation(description = "Update Artifact", method = "POST", summary = "Returns updated artifact", responses = {
-            @ApiResponse(content = @Content(array = @ArraySchema(schema = @Schema(implementation = Response.class)))),
-            @ApiResponse(responseCode = "201", description = "Service artifact created"),
-            @ApiResponse(responseCode = "403", description = "Restricted operation"),
-            @ApiResponse(responseCode = "400", description = "Invalid content / Missing content")})
-    public Response updateInformationArtifact(@PathParam("serviceId") final String serviceId,
-            @PathParam("artifactId") final String artifactId,
-            @Parameter(description = "json describe the artifact", required = true) String data,
-            @Context final HttpServletRequest request) {
-
+        @ApiResponse(content = @Content(array = @ArraySchema(schema = @Schema(implementation = Response.class)))),
+        @ApiResponse(responseCode = "201", description = "Service artifact created"),
+        @ApiResponse(responseCode = "403", description = "Restricted operation"),
+        @ApiResponse(responseCode = "400", description = "Invalid content / Missing content")})
+    public Response updateInformationArtifact(@PathParam("serviceId") final String serviceId, @PathParam("artifactId") final String artifactId,
+                                              @Parameter(description = "json describe the artifact", required = true) String data,
+                                              @Context final HttpServletRequest request) {
         String url = request.getMethod() + " " + request.getRequestURI();
         log.debug(START_HANDLE_REQUEST_OF, url);
         try {
@@ -225,19 +211,16 @@ public class ArtifactServlet extends BeGenericServlet {
     @Path("/services/{serviceId}/artifacts/api/{artifactId}")
     @Consumes(MediaType.APPLICATION_JSON)
     @Produces(MediaType.APPLICATION_JSON)
-    @Operation(description = "Update Api Artifact", method = "POST", summary = "Returns created ArtifactDefinition",
-            responses = {@ApiResponse(
-                    content = @Content(array = @ArraySchema(schema = @Schema(implementation = Response.class)))),
-                    @ApiResponse(responseCode = "200", description = "Api Artifact Updated"),
-                    @ApiResponse(responseCode = "403", description = "Restricted operation"),
-                    @ApiResponse(responseCode = "400", description = "Invalid content / Missing content")})
+    @Operation(description = "Update Api Artifact", method = "POST", summary = "Returns created ArtifactDefinition", responses = {
+        @ApiResponse(content = @Content(array = @ArraySchema(schema = @Schema(implementation = Response.class)))),
+        @ApiResponse(responseCode = "200", description = "Api Artifact Updated"),
+        @ApiResponse(responseCode = "403", description = "Restricted operation"),
+        @ApiResponse(responseCode = "400", description = "Invalid content / Missing content")})
     @PermissionAllowed(AafPermission.PermNames.INTERNAL_ALL_VALUE)
-    public Response updateApiArtifact(@PathParam("serviceId") final String serviceId,
-            @PathParam("artifactId") final String artifactId,
-            @Parameter(description = "json describe the artifact", required = true) String data,
-            @Context final HttpServletRequest request, @HeaderParam(value = Constants.USER_ID_HEADER) String userId,
-            @HeaderParam(value = Constants.MD5_HEADER) String origMd5) {
-
+    public Response updateApiArtifact(@PathParam("serviceId") final String serviceId, @PathParam("artifactId") final String artifactId,
+                                      @Parameter(description = "json describe the artifact", required = true) String data,
+                                      @Context final HttpServletRequest request, @HeaderParam(value = Constants.USER_ID_HEADER) String userId,
+                                      @HeaderParam(value = Constants.MD5_HEADER) String origMd5) {
         String url = request.getMethod() + " " + request.getRequestURI();
         log.debug(START_HANDLE_REQUEST_OF, url);
         try {
@@ -253,17 +236,14 @@ public class ArtifactServlet extends BeGenericServlet {
     @Path("/services/{serviceId}/artifacts/api/{artifactId}")
     @Consumes(MediaType.APPLICATION_JSON)
     @Produces(MediaType.APPLICATION_JSON)
-    @Operation(description = "Delete Api Artifact", method = "DELETE", summary = "Returns Deleted ArtifactDefinition",
-            responses = {@ApiResponse(
-                    content = @Content(array = @ArraySchema(schema = @Schema(implementation = Response.class)))),
-                    @ApiResponse(responseCode = "204", description = "Api Artifact deleted"),
-                    @ApiResponse(responseCode = "403", description = "Restricted operation")})
+    @Operation(description = "Delete Api Artifact", method = "DELETE", summary = "Returns Deleted ArtifactDefinition", responses = {
+        @ApiResponse(content = @Content(array = @ArraySchema(schema = @Schema(implementation = Response.class)))),
+        @ApiResponse(responseCode = "204", description = "Api Artifact deleted"),
+        @ApiResponse(responseCode = "403", description = "Restricted operation")})
     @PermissionAllowed(AafPermission.PermNames.INTERNAL_ALL_VALUE)
-    public Response deleteApiArtifact(@PathParam("serviceId") final String serviceId,
-            @PathParam("artifactId") final String artifactId, @Context final HttpServletRequest request,
-            @HeaderParam(value = Constants.USER_ID_HEADER) String userId,
-            @HeaderParam(value = Constants.MD5_HEADER) String origMd5) {
-
+    public Response deleteApiArtifact(@PathParam("serviceId") final String serviceId, @PathParam("artifactId") final String artifactId,
+                                      @Context final HttpServletRequest request, @HeaderParam(value = Constants.USER_ID_HEADER) String userId,
+                                      @HeaderParam(value = Constants.MD5_HEADER) String origMd5) {
         String url = request.getMethod() + " " + request.getRequestURI();
         log.debug(START_HANDLE_REQUEST_OF, url);
         try {
@@ -280,14 +260,13 @@ public class ArtifactServlet extends BeGenericServlet {
     @Consumes(MediaType.APPLICATION_JSON)
     @Produces(MediaType.APPLICATION_JSON)
     @Operation(description = "Delete Artifact", method = "DELETE", summary = "Returns delete artifact", responses = {
-            @ApiResponse(content = @Content(array = @ArraySchema(schema = @Schema(implementation = Response.class)))),
-            @ApiResponse(responseCode = "201", description = "Service artifact deleted"),
-            @ApiResponse(responseCode = "403", description = "Restricted operation"),
-            @ApiResponse(responseCode = "400", description = "Invalid content / Missing content")})
+        @ApiResponse(content = @Content(array = @ArraySchema(schema = @Schema(implementation = Response.class)))),
+        @ApiResponse(responseCode = "201", description = "Service artifact deleted"),
+        @ApiResponse(responseCode = "403", description = "Restricted operation"),
+        @ApiResponse(responseCode = "400", description = "Invalid content / Missing content")})
     @PermissionAllowed(AafPermission.PermNames.INTERNAL_ALL_VALUE)
-    public Response deleteInformationalArtifact(@PathParam("serviceId") final String serviceId,
-            @PathParam("artifactId") final String artifactId, @Context final HttpServletRequest request) {
-
+    public Response deleteInformationalArtifact(@PathParam("serviceId") final String serviceId, @PathParam("artifactId") final String artifactId,
+                                                @Context final HttpServletRequest request) {
         String url = request.getMethod() + " " + request.getRequestURI();
         log.debug(START_HANDLE_REQUEST_OF, url);
         try {
@@ -302,32 +281,28 @@ public class ArtifactServlet extends BeGenericServlet {
     /*
      * DOWNLOAD Artifacts by json body in base 64 (because of userId problem with href)
      */
-
     @GET
     @Path("/services/{serviceId}/artifacts/{artifactId}")
     @Consumes(MediaType.APPLICATION_JSON)
     @Produces(MediaType.APPLICATION_JSON)
-    @Operation(description = "Download service Artifact in Base64", method = "GET",
-            summary = "Returns downloaded artifact", responses = {
-            @ApiResponse(content = @Content(array = @ArraySchema(schema = @Schema(implementation = Response.class)))),
-            @ApiResponse(responseCode = "200", description = "Service artifact downloaded"),
-            @ApiResponse(responseCode = "404", description = "Service/Artifact not found")})
+    @Operation(description = "Download service Artifact in Base64", method = "GET", summary = "Returns downloaded artifact", responses = {
+        @ApiResponse(content = @Content(array = @ArraySchema(schema = @Schema(implementation = Response.class)))),
+        @ApiResponse(responseCode = "200", description = "Service artifact downloaded"),
+        @ApiResponse(responseCode = "404", description = "Service/Artifact not found")})
     @PermissionAllowed(AafPermission.PermNames.INTERNAL_ALL_VALUE)
-    public Response downloadServiceArtifactBase64(@PathParam("serviceId") final String serviceId,
-            @PathParam("artifactId") final String artifactId, @Context final HttpServletRequest request) {
-
+    public Response downloadServiceArtifactBase64(@PathParam("serviceId") final String serviceId, @PathParam("artifactId") final String artifactId,
+                                                  @Context final HttpServletRequest request) {
         String url = request.getMethod() + " " + request.getRequestURI();
         Response response;
         log.debug(START_HANDLE_REQUEST_OF, url);
         try {
-            response =  handleDownloadRequest(request, serviceId, artifactId, null, ComponentTypeEnum.SERVICE, null);
+            response = handleDownloadRequest(request, serviceId, artifactId, null, ComponentTypeEnum.SERVICE, null);
         } catch (Exception e) {
             BeEcompErrorManager.getInstance().logBeRestApiGeneralError("downloadServiceArtifactBase64");
             log.debug("downloadServiceArtifactBase64 unexpected exception", e);
             throw e;
-        }
-        finally {
-            loggerSupportability.log(LoggerSupportabilityActions.DOWNLOAD_ARTIFACTS,StatusCode.COMPLETE,"Ended download Service Artifact ");
+        } finally {
+            loggerSupportability.log(LoggerSupportabilityActions.DOWNLOAD_ARTIFACTS, StatusCode.COMPLETE, "Ended download Service Artifact ");
         }
         return response;
     }
@@ -336,14 +311,12 @@ public class ArtifactServlet extends BeGenericServlet {
     @Path("/resources/{resourceId}/artifacts/{artifactId}")
     @Consumes(MediaType.APPLICATION_JSON)
     @Produces(MediaType.APPLICATION_JSON)
-    @Operation(description = "Download resource Artifact in Base64", method = "GET",
-            summary = "Returns downloaded artifact", responses = {
-            @ApiResponse(content = @Content(array = @ArraySchema(schema = @Schema(implementation = Response.class)))),
-            @ApiResponse(responseCode = "200", description = "Resource artifact downloaded"),
-            @ApiResponse(responseCode = "404", description = "Resource/Artifact not found")})
-    public Response downloadResourceArtifactBase64(@PathParam("resourceId") final String resourceId,
-            @PathParam("artifactId") final String artifactId, @Context final HttpServletRequest request) {
-
+    @Operation(description = "Download resource Artifact in Base64", method = "GET", summary = "Returns downloaded artifact", responses = {
+        @ApiResponse(content = @Content(array = @ArraySchema(schema = @Schema(implementation = Response.class)))),
+        @ApiResponse(responseCode = "200", description = "Resource artifact downloaded"),
+        @ApiResponse(responseCode = "404", description = "Resource/Artifact not found")})
+    public Response downloadResourceArtifactBase64(@PathParam("resourceId") final String resourceId, @PathParam("artifactId") final String artifactId,
+                                                   @Context final HttpServletRequest request) {
         String url = request.getMethod() + " " + request.getRequestURI();
         log.debug(START_HANDLE_REQUEST_OF, url);
         Response response;
@@ -353,10 +326,9 @@ public class ArtifactServlet extends BeGenericServlet {
             BeEcompErrorManager.getInstance().logBeRestApiGeneralError("downloadResourceArtifactBase64");
             log.debug("downloadResourceArtifactBase64 unexpected exception", e);
             throw e;
-        }
-        finally {
-            loggerSupportability.log(LoggerSupportabilityActions.DOWNLOAD_ARTIFACTS,null, StatusCode.COMPLETE,"Ended download artifact {}", artifactId);
-
+        } finally {
+            loggerSupportability
+                .log(LoggerSupportabilityActions.DOWNLOAD_ARTIFACTS, null, StatusCode.COMPLETE, "Ended download artifact {}", artifactId);
         }
         return response;
     }
@@ -365,86 +337,79 @@ public class ArtifactServlet extends BeGenericServlet {
     @Path("/{containerComponentType}/{componentId}/resourceInstances/{componentInstanceId}/artifacts/{artifactId}")
     @Consumes(MediaType.APPLICATION_JSON)
     @Produces(MediaType.APPLICATION_JSON)
-    @Operation(description = "Download component Artifact in Base64", method = "GET",
-            summary = "Returns downloaded artifact", responses = {
-            @ApiResponse(content = @Content(array = @ArraySchema(schema = @Schema(implementation = Response.class)))),
-            @ApiResponse(responseCode = "200", description = "ResourceInstance artifact downloaded"),
-            @ApiResponse(responseCode = "404", description = "ResourceInstance/Artifact not found")})
+    @Operation(description = "Download component Artifact in Base64", method = "GET", summary = "Returns downloaded artifact", responses = {
+        @ApiResponse(content = @Content(array = @ArraySchema(schema = @Schema(implementation = Response.class)))),
+        @ApiResponse(responseCode = "200", description = "ResourceInstance artifact downloaded"),
+        @ApiResponse(responseCode = "404", description = "ResourceInstance/Artifact not found")})
     @PermissionAllowed(AafPermission.PermNames.INTERNAL_ALL_VALUE)
-    public Response downloadResourceInstanceArtifactBase64(@Parameter(
-            description = "valid values: resources / services",
-            schema = @Schema(allowableValues = {ComponentTypeEnum.RESOURCE_PARAM_NAME ,
-                     ComponentTypeEnum.SERVICE_PARAM_NAME})) @PathParam("containerComponentType") final String containerComponentType,
-            @PathParam("componentId") final String componentId,
-            @PathParam("componentInstanceId") final String componentInstanceId,
-            @PathParam("artifactId") final String artifactId, @Context final HttpServletRequest request) {
-
+    public Response downloadResourceInstanceArtifactBase64(
+        @Parameter(description = "valid values: resources / services", schema = @Schema(allowableValues = {ComponentTypeEnum.RESOURCE_PARAM_NAME,
+            ComponentTypeEnum.SERVICE_PARAM_NAME})) @PathParam("containerComponentType") final String containerComponentType,
+        @PathParam("componentId") final String componentId, @PathParam("componentInstanceId") final String componentInstanceId,
+        @PathParam("artifactId") final String artifactId, @Context final HttpServletRequest request) {
         Response response;
         String url = request.getMethod() + " " + request.getRequestURI();
         log.debug(START_HANDLE_REQUEST_OF, url);
-        loggerSupportability.log(LoggerSupportabilityActions.DOWNLOAD_ARTIFACTS, StatusCode.STARTED," Starting to download Resource Instance Artifact for component {} ", componentId);
+        loggerSupportability.log(LoggerSupportabilityActions.DOWNLOAD_ARTIFACTS, StatusCode.STARTED,
+            " Starting to download Resource Instance Artifact for component {} ", componentId);
         try {
-            response = handleDownloadRequest(request, componentInstanceId, artifactId, componentId, ComponentTypeEnum.RESOURCE_INSTANCE, containerComponentType);
+            response = handleDownloadRequest(request, componentInstanceId, artifactId, componentId, ComponentTypeEnum.RESOURCE_INSTANCE,
+                containerComponentType);
         } catch (Exception e) {
             BeEcompErrorManager.getInstance().logBeRestApiGeneralError(DOWNLOAD_RESOURCE_INSTANCE_ARTIFACT_BASE64);
             log.debug(DOWNLOAD_RESOURCE_INSTANCE_ARTIFACT_BASE64_EXCEPTION, e);
             throw e;
-        }
-        finally {
-            loggerSupportability.log(LoggerSupportabilityActions.DOWNLOAD_ARTIFACTS, StatusCode.COMPLETE,"Ended download Resource Instance Artifact for component {} ", componentId);
+        } finally {
+            loggerSupportability.log(LoggerSupportabilityActions.DOWNLOAD_ARTIFACTS, StatusCode.COMPLETE,
+                "Ended download Resource Instance Artifact for component {} ", componentId);
         }
         return response;
     }
 
     // *************** Resource lifecycle ( interfces )
-
     @POST
     @Path("/resources/{resourceId}/{interfaceType}/{operation}/artifacts")
     @Consumes(MediaType.APPLICATION_JSON)
     @Produces(MediaType.APPLICATION_JSON)
-    @Operation(description = "Create Artifact and Attach to interface", method = "POST",
-            summary = "Returns created resource", responses = {
-            @ApiResponse(content = @Content(array = @ArraySchema(schema = @Schema(implementation = Response.class)))),
-            @ApiResponse(responseCode = "201", description = "Resource created"),
-            @ApiResponse(responseCode = "403", description = "Restricted operation"),
-            @ApiResponse(responseCode = "400", description = "Invalid content / Missing content"),
-            @ApiResponse(responseCode = "409", description = "Artifact already exist")})
+    @Operation(description = "Create Artifact and Attach to interface", method = "POST", summary = "Returns created resource", responses = {
+        @ApiResponse(content = @Content(array = @ArraySchema(schema = @Schema(implementation = Response.class)))),
+        @ApiResponse(responseCode = "201", description = "Resource created"),
+        @ApiResponse(responseCode = "403", description = "Restricted operation"),
+        @ApiResponse(responseCode = "400", description = "Invalid content / Missing content"),
+        @ApiResponse(responseCode = "409", description = "Artifact already exist")})
     @PermissionAllowed(AafPermission.PermNames.INTERNAL_ALL_VALUE)
-    public Response loadArtifactToInterface(@PathParam("resourceId") final String resourceId,
-            @PathParam("interfaceType") final String interfaceType, @PathParam("operation") final String operation,
-            @HeaderParam(value = Constants.USER_ID_HEADER) String userId,
-            @HeaderParam(value = Constants.MD5_HEADER) String origMd5,
-            @Parameter(description = "json describe the artifact", required = true) String data,
-            @Context final HttpServletRequest request) {
-
+    public Response loadArtifactToInterface(@PathParam("resourceId") final String resourceId, @PathParam("interfaceType") final String interfaceType,
+                                            @PathParam("operation") final String operation,
+                                            @HeaderParam(value = Constants.USER_ID_HEADER) String userId,
+                                            @HeaderParam(value = Constants.MD5_HEADER) String origMd5,
+                                            @Parameter(description = "json describe the artifact", required = true) String data,
+                                            @Context final HttpServletRequest request) {
         String url = request.getMethod() + " " + request.getRequestURI();
         log.debug(START_HANDLE_REQUEST_OF, url);
         try {
-            return handleArtifactRequest(data, request, resourceId, interfaceType, operation, null, ComponentTypeEnum.RESOURCE, ArtifactOperationEnum.CREATE, null, null, false);
+            return handleArtifactRequest(data, request, resourceId, interfaceType, operation, null, ComponentTypeEnum.RESOURCE,
+                ArtifactOperationEnum.CREATE, null, null, false);
         } catch (Exception e) {
             BeEcompErrorManager.getInstance().logBeRestApiGeneralError("loadArtifactToInterface");
             log.debug("loadArtifactToInterface unexpected exception", e);
             throw e;
         }
-
     }
 
     @DELETE
     @Path("/resources/{resourceId}/{interfaceType}/{operation}/artifacts/{artifactId}")
     @Consumes(MediaType.APPLICATION_JSON)
     @Produces(MediaType.APPLICATION_JSON)
-    @Operation(description = "delete Artifact from interface", method = "delete",
-            summary = "delete matching artifact from interface", responses = {
-            @ApiResponse(content = @Content(array = @ArraySchema(schema = @Schema(implementation = Response.class)))),
-            @ApiResponse(responseCode = "201", description = "delete artifact under interface deleted"),
-            @ApiResponse(responseCode = "403", description = "Restricted operation"),
-            @ApiResponse(responseCode = "400", description = "Invalid content / Missing content"),
-            @ApiResponse(responseCode = "409", description = "Artifact already exist")})
+    @Operation(description = "delete Artifact from interface", method = "delete", summary = "delete matching artifact from interface", responses = {
+        @ApiResponse(content = @Content(array = @ArraySchema(schema = @Schema(implementation = Response.class)))),
+        @ApiResponse(responseCode = "201", description = "delete artifact under interface deleted"),
+        @ApiResponse(responseCode = "403", description = "Restricted operation"),
+        @ApiResponse(responseCode = "400", description = "Invalid content / Missing content"),
+        @ApiResponse(responseCode = "409", description = "Artifact already exist")})
     @PermissionAllowed(AafPermission.PermNames.INTERNAL_ALL_VALUE)
     public Response deleteArtifactToInterface(@PathParam("resourceId") final String resourceId,
-            @PathParam("interfaceType") final String interfaceType, @PathParam("operation") final String operation,
-            @PathParam("artifactId") final String artifactId, @Context final HttpServletRequest request) {
-
+                                              @PathParam("interfaceType") final String interfaceType, @PathParam("operation") final String operation,
+                                              @PathParam("artifactId") final String artifactId, @Context final HttpServletRequest request) {
         String url = request.getMethod() + " " + request.getRequestURI();
         log.debug(START_HANDLE_REQUEST_OF, url);
         try {
@@ -460,25 +425,24 @@ public class ArtifactServlet extends BeGenericServlet {
     @Path("/resources/{resourceId}/{interfaceType}/{operation}/artifacts/{artifactId}")
     @Consumes(MediaType.APPLICATION_JSON)
     @Produces(MediaType.APPLICATION_JSON)
-    @Operation(description = "update Artifact  Attach to interface", method = "post",
-            summary = "updates artifact by interface", responses = {
-            @ApiResponse(content = @Content(array = @ArraySchema(schema = @Schema(implementation = Response.class)))),
-            @ApiResponse(responseCode = "201", description = "delete artifact under interface deleted"),
-            @ApiResponse(responseCode = "403", description = "Restricted operation"),
-            @ApiResponse(responseCode = "400", description = "Invalid content / Missing content"),
-            @ApiResponse(responseCode = "409", description = "Artifact already exist")})
+    @Operation(description = "update Artifact  Attach to interface", method = "post", summary = "updates artifact by interface", responses = {
+        @ApiResponse(content = @Content(array = @ArraySchema(schema = @Schema(implementation = Response.class)))),
+        @ApiResponse(responseCode = "201", description = "delete artifact under interface deleted"),
+        @ApiResponse(responseCode = "403", description = "Restricted operation"),
+        @ApiResponse(responseCode = "400", description = "Invalid content / Missing content"),
+        @ApiResponse(responseCode = "409", description = "Artifact already exist")})
     @PermissionAllowed(AafPermission.PermNames.INTERNAL_ALL_VALUE)
     public Response updateArtifactToInterface(@PathParam("resourceId") final String resourceId,
-            @PathParam("interfaceType") final String interfaceType, @PathParam("operation") final String operation,
-            @PathParam("artifactId") final String artifactId,
-            @HeaderParam(value = Constants.USER_ID_HEADER) String userId,
-            @HeaderParam(value = Constants.MD5_HEADER) String origMd5, @Context final HttpServletRequest request,
-            @Parameter(description = "json describe the artifact", required = true) String data) {
-
+                                              @PathParam("interfaceType") final String interfaceType, @PathParam("operation") final String operation,
+                                              @PathParam("artifactId") final String artifactId,
+                                              @HeaderParam(value = Constants.USER_ID_HEADER) String userId,
+                                              @HeaderParam(value = Constants.MD5_HEADER) String origMd5, @Context final HttpServletRequest request,
+                                              @Parameter(description = "json describe the artifact", required = true) String data) {
         String url = request.getMethod() + " " + request.getRequestURI();
         log.debug(START_HANDLE_REQUEST_OF, url);
         try {
-            return handleArtifactRequest(data, request, resourceId, interfaceType, operation, artifactId, ComponentTypeEnum.RESOURCE, ArtifactOperationEnum.UPDATE, null, null, false);
+            return handleArtifactRequest(data, request, resourceId, interfaceType, operation, artifactId, ComponentTypeEnum.RESOURCE,
+                ArtifactOperationEnum.UPDATE, null, null, false);
         } catch (Exception e) {
             BeEcompErrorManager.getInstance().logBeRestApiGeneralError("updateArtifactToInterface");
             log.debug("updateArtifactToInterface unexpected exception", e);
@@ -490,35 +454,31 @@ public class ArtifactServlet extends BeGenericServlet {
     @Path("/{containerComponentType}/{componentId}/resourceInstance/{componentInstanceId}/artifacts/{artifactId}/heatParams")
     @Consumes(MediaType.APPLICATION_JSON)
     @Produces(MediaType.APPLICATION_JSON)
-    @Operation(description = "Update Resource Instance HEAT_ENV parameters", method = "POST",
-            summary = "Returns updated artifact", responses = {
-            @ApiResponse(content = @Content(array = @ArraySchema(schema = @Schema(implementation = Response.class)))),
-            @ApiResponse(responseCode = "200", description = "Artifact updated"),
-            @ApiResponse(responseCode = "403", description = "Restricted operation"),
-            @ApiResponse(responseCode = "400", description = "Invalid content / Missing content")})
+    @Operation(description = "Update Resource Instance HEAT_ENV parameters", method = "POST", summary = "Returns updated artifact", responses = {
+        @ApiResponse(content = @Content(array = @ArraySchema(schema = @Schema(implementation = Response.class)))),
+        @ApiResponse(responseCode = "200", description = "Artifact updated"),
+        @ApiResponse(responseCode = "403", description = "Restricted operation"),
+        @ApiResponse(responseCode = "400", description = "Invalid content / Missing content")})
     @PermissionAllowed(AafPermission.PermNames.INTERNAL_ALL_VALUE)
-    public Response updateRIArtifact(@Parameter(description = "valid values: resources / services",
-            schema = @Schema(allowableValues = {ComponentTypeEnum.RESOURCE_PARAM_NAME ,
-                     ComponentTypeEnum.SERVICE_PARAM_NAME})) @PathParam("containerComponentType") final String containerComponentType,
-            @PathParam("componentId") final String componentId,
-            @PathParam("componentInstanceId") final String componentInstanceId,
-            @PathParam("artifactId") final String artifactId,
-            @Parameter(description = "json describe the artifact", required = true) String data,
-            @Context final HttpServletRequest request) {
-
+    public Response updateRIArtifact(
+        @Parameter(description = "valid values: resources / services", schema = @Schema(allowableValues = {ComponentTypeEnum.RESOURCE_PARAM_NAME,
+            ComponentTypeEnum.SERVICE_PARAM_NAME})) @PathParam("containerComponentType") final String containerComponentType,
+        @PathParam("componentId") final String componentId, @PathParam("componentInstanceId") final String componentInstanceId,
+        @PathParam("artifactId") final String artifactId, @Parameter(description = "json describe the artifact", required = true) String data,
+        @Context final HttpServletRequest request) {
         String url = request.getMethod() + " " + request.getRequestURI();
         log.debug(START_HANDLE_REQUEST_OF, url);
-        loggerSupportability.log(LoggerSupportabilityActions.UPDATE_HEAT, StatusCode.STARTED,"Starting update RI Artifact {}" ,artifactId);
+        loggerSupportability.log(LoggerSupportabilityActions.UPDATE_HEAT, StatusCode.STARTED, "Starting update RI Artifact {}", artifactId);
         Response response;
         try {
-            response = handleArtifactRequest(data, request, componentInstanceId, null, null, artifactId, ComponentTypeEnum.RESOURCE_INSTANCE, ArtifactOperationEnum.UPDATE, componentId, containerComponentType, false);
+            response = handleArtifactRequest(data, request, componentInstanceId, null, null, artifactId, ComponentTypeEnum.RESOURCE_INSTANCE,
+                ArtifactOperationEnum.UPDATE, componentId, containerComponentType, false);
         } catch (Exception e) {
             BeEcompErrorManager.getInstance().logBeRestApiGeneralError("updateRIArtifact");
             log.debug("updateRIArtifact unexpected exception", e);
             throw e;
-        }
-        finally {
-            loggerSupportability.log(LoggerSupportabilityActions.UPDATE_HEAT, StatusCode.COMPLETE,"Ending update RI Artifact {}" , artifactId);
+        } finally {
+            loggerSupportability.log(LoggerSupportabilityActions.UPDATE_HEAT, StatusCode.COMPLETE, "Ending update RI Artifact {}", artifactId);
         }
         return response;
     }
@@ -527,28 +487,27 @@ public class ArtifactServlet extends BeGenericServlet {
     @Path("/{containerComponentType}/{componentId}/resourceInstance/{componentInstanceId}/artifacts/{artifactId}")
     @Consumes(MediaType.APPLICATION_JSON)
     @Produces(MediaType.APPLICATION_JSON)
-    @Operation(description = "Update Resource Instance artifact payload", method = "POST",
-            summary = "Returns updated artifact", responses = {
-            @ApiResponse(content = @Content(array = @ArraySchema(schema = @Schema(implementation = Response.class)))),
-            @ApiResponse(responseCode = "200", description = "Artifact updated"),
-            @ApiResponse(responseCode = "403", description = "Restricted operation"),
-            @ApiResponse(responseCode = "400", description = "Invalid content / Missing content")})
+    @Operation(description = "Update Resource Instance artifact payload", method = "POST", summary = "Returns updated artifact", responses = {
+        @ApiResponse(content = @Content(array = @ArraySchema(schema = @Schema(implementation = Response.class)))),
+        @ApiResponse(responseCode = "200", description = "Artifact updated"),
+        @ApiResponse(responseCode = "403", description = "Restricted operation"),
+        @ApiResponse(responseCode = "400", description = "Invalid content / Missing content")})
     @PermissionAllowed(AafPermission.PermNames.INTERNAL_ALL_VALUE)
     public Response updateComponentInstanceArtifact(@HeaderParam(value = Constants.USER_ID_HEADER) String userId,
-            @HeaderParam(value = Constants.MD5_HEADER) String origMd5,
-            @Parameter(description = "valid values: resources / services",
-                    schema = @Schema(allowableValues = {ComponentTypeEnum.RESOURCE_PARAM_NAME ,
-                             ComponentTypeEnum.SERVICE_PARAM_NAME})) @PathParam("containerComponentType") final String containerComponentType,
-            @PathParam("componentId") final String componentId,
-            @PathParam("componentInstanceId") final String componentInstanceId,
-            @PathParam("artifactId") final String artifactId,
-            @Parameter(description = "json describe the artifact", required = true) String data,
-            @Context final HttpServletRequest request) {
-
+                                                    @HeaderParam(value = Constants.MD5_HEADER) String origMd5,
+                                                    @Parameter(description = "valid values: resources / services", schema = @Schema(allowableValues = {
+                                                        ComponentTypeEnum.RESOURCE_PARAM_NAME,
+                                                        ComponentTypeEnum.SERVICE_PARAM_NAME})) @PathParam("containerComponentType") final String containerComponentType,
+                                                    @PathParam("componentId") final String componentId,
+                                                    @PathParam("componentInstanceId") final String componentInstanceId,
+                                                    @PathParam("artifactId") final String artifactId,
+                                                    @Parameter(description = "json describe the artifact", required = true) String data,
+                                                    @Context final HttpServletRequest request) {
         String url = request.getMethod() + " " + request.getRequestURI();
         log.debug(START_HANDLE_REQUEST_OF, url);
         try {
-            return handleArtifactRequest(data, request, componentInstanceId, null, null, artifactId, ComponentTypeEnum.RESOURCE_INSTANCE, ArtifactOperationEnum.UPDATE, componentId, containerComponentType, true);
+            return handleArtifactRequest(data, request, componentInstanceId, null, null, artifactId, ComponentTypeEnum.RESOURCE_INSTANCE,
+                ArtifactOperationEnum.UPDATE, componentId, containerComponentType, true);
         } catch (Exception e) {
             log.debug("loadResourceInstanceHeatEnvArtifact unexpected exception", e);
             throw e;
@@ -559,27 +518,26 @@ public class ArtifactServlet extends BeGenericServlet {
     @Path("/{containerComponentType}/{componentId}/resourceInstance/{componentInstanceId}/artifacts")
     @Consumes(MediaType.APPLICATION_JSON)
     @Produces(MediaType.APPLICATION_JSON)
-    @Operation(description = "Load Resource Instance artifact payload", method = "POST",
-            summary = "Returns updated artifact", responses = {
-            @ApiResponse(content = @Content(array = @ArraySchema(schema = @Schema(implementation = Response.class)))),
-            @ApiResponse(responseCode = "200", description = "Artifact updated"),
-            @ApiResponse(responseCode = "403", description = "Restricted operation"),
-            @ApiResponse(responseCode = "400", description = "Invalid content / Missing content")})
+    @Operation(description = "Load Resource Instance artifact payload", method = "POST", summary = "Returns updated artifact", responses = {
+        @ApiResponse(content = @Content(array = @ArraySchema(schema = @Schema(implementation = Response.class)))),
+        @ApiResponse(responseCode = "200", description = "Artifact updated"),
+        @ApiResponse(responseCode = "403", description = "Restricted operation"),
+        @ApiResponse(responseCode = "400", description = "Invalid content / Missing content")})
     @PermissionAllowed(AafPermission.PermNames.INTERNAL_ALL_VALUE)
     public Response loadComponentInstanceArtifact(@HeaderParam(value = Constants.USER_ID_HEADER) String userId,
-            @HeaderParam(value = Constants.MD5_HEADER) String origMd5,
-            @Parameter(description = "valid values: resources / services",
-                    schema = @Schema(allowableValues = {ComponentTypeEnum.RESOURCE_PARAM_NAME ,
-                             ComponentTypeEnum.SERVICE_PARAM_NAME})) @PathParam("containerComponentType") final String containerComponentType,
-            @PathParam("componentId") final String componentId,
-            @PathParam("componentInstanceId") final String componentInstanceId,
-            @Parameter(description = "json describe the artifact", required = true) String data,
-            @Context final HttpServletRequest request) {
-
+                                                  @HeaderParam(value = Constants.MD5_HEADER) String origMd5,
+                                                  @Parameter(description = "valid values: resources / services", schema = @Schema(allowableValues = {
+                                                      ComponentTypeEnum.RESOURCE_PARAM_NAME,
+                                                      ComponentTypeEnum.SERVICE_PARAM_NAME})) @PathParam("containerComponentType") final String containerComponentType,
+                                                  @PathParam("componentId") final String componentId,
+                                                  @PathParam("componentInstanceId") final String componentInstanceId,
+                                                  @Parameter(description = "json describe the artifact", required = true) String data,
+                                                  @Context final HttpServletRequest request) {
         String url = request.getMethod() + " " + request.getRequestURI();
         log.debug(START_HANDLE_REQUEST_OF, url);
         try {
-            return handleArtifactRequest(data, request, componentInstanceId, null, null, null, ComponentTypeEnum.RESOURCE_INSTANCE, ArtifactOperationEnum.CREATE, componentId, containerComponentType, false);
+            return handleArtifactRequest(data, request, componentInstanceId, null, null, null, ComponentTypeEnum.RESOURCE_INSTANCE,
+                ArtifactOperationEnum.CREATE, componentId, containerComponentType, false);
         } catch (Exception e) {
             log.debug("loadResourceInstanceHeatEnvArtifact unexpected exception", e);
             throw e;
@@ -590,57 +548,53 @@ public class ArtifactServlet extends BeGenericServlet {
     @Path("/{containerComponentType}/{componentId}/resourceInstance/{componentInstanceId}/artifacts/{artifactId}")
     @Consumes(MediaType.APPLICATION_JSON)
     @Produces(MediaType.APPLICATION_JSON)
-    @Operation(description = "Delete Resource Instance artifact", method = "POST", summary = "Returns deleted artifact",
-            responses = {@ApiResponse(
-                    content = @Content(array = @ArraySchema(schema = @Schema(implementation = Response.class)))),
-                    @ApiResponse(responseCode = "200", description = "Artifact updated"),
-                    @ApiResponse(responseCode = "403", description = "Restricted operation"),
-                    @ApiResponse(responseCode = "400", description = "Invalid content / Missing content")})
+    @Operation(description = "Delete Resource Instance artifact", method = "POST", summary = "Returns deleted artifact", responses = {
+        @ApiResponse(content = @Content(array = @ArraySchema(schema = @Schema(implementation = Response.class)))),
+        @ApiResponse(responseCode = "200", description = "Artifact updated"),
+        @ApiResponse(responseCode = "403", description = "Restricted operation"),
+        @ApiResponse(responseCode = "400", description = "Invalid content / Missing content")})
     @PermissionAllowed(AafPermission.PermNames.INTERNAL_ALL_VALUE)
     public Response deleteComponentInstanceArtifact(@HeaderParam(value = Constants.USER_ID_HEADER) String userId,
-            @HeaderParam(value = Constants.MD5_HEADER) String origMd5,
-            @Parameter(description = "valid values: resources / services",
-                    schema = @Schema(allowableValues = {ComponentTypeEnum.RESOURCE_PARAM_NAME ,
-                             ComponentTypeEnum.SERVICE_PARAM_NAME})) @PathParam("containerComponentType") final String containerComponentType,
-            @PathParam("componentId") final String componentId,
-            @PathParam("componentInstanceId") final String componentInstanceId,
-            @PathParam("artifactId") final String artifactId,
-            @Parameter(description = "json describe the artifact", required = true) String data,
-            @Context final HttpServletRequest request) {
-
+                                                    @HeaderParam(value = Constants.MD5_HEADER) String origMd5,
+                                                    @Parameter(description = "valid values: resources / services", schema = @Schema(allowableValues = {
+                                                        ComponentTypeEnum.RESOURCE_PARAM_NAME,
+                                                        ComponentTypeEnum.SERVICE_PARAM_NAME})) @PathParam("containerComponentType") final String containerComponentType,
+                                                    @PathParam("componentId") final String componentId,
+                                                    @PathParam("componentInstanceId") final String componentInstanceId,
+                                                    @PathParam("artifactId") final String artifactId,
+                                                    @Parameter(description = "json describe the artifact", required = true) String data,
+                                                    @Context final HttpServletRequest request) {
         String url = request.getMethod() + " " + request.getRequestURI();
         log.debug(START_HANDLE_REQUEST_OF, url);
-        loggerSupportability.log(LoggerSupportabilityActions.DELETE_COMPONENT_INSTANCE_ARTIFACT,null, StatusCode.STARTED,"Starting delete component instance artifact {}" ,artifactId);
+        loggerSupportability.log(LoggerSupportabilityActions.DELETE_COMPONENT_INSTANCE_ARTIFACT, null, StatusCode.STARTED,
+            "Starting delete component instance artifact {}", artifactId);
         Response response;
         try {
             response = handleDeleteRequest(request, componentInstanceId, artifactId, ComponentTypeEnum.RESOURCE_INSTANCE, null, null, componentId);
         } catch (Exception e) {
             log.debug("deleteArtifact unexpected exception", e);
             throw e;
-        }
-        finally {
-            loggerSupportability.log(LoggerSupportabilityActions.DELETE_COMPONENT_INSTANCE_ARTIFACT,null, StatusCode.COMPLETE,"Ending delete component instance artifact {}" ,artifactId);
+        } finally {
+            loggerSupportability.log(LoggerSupportabilityActions.DELETE_COMPONENT_INSTANCE_ARTIFACT, null, StatusCode.COMPLETE,
+                "Ending delete component instance artifact {}", artifactId);
         }
         return response;
-
     }
 
-
     @GET
     @Path("/{containerComponentType}/{componentId}/artifactsByType/{artifactGroupType}")
     @Consumes(MediaType.APPLICATION_JSON)
     @Produces(MediaType.APPLICATION_JSON)
     @Operation(description = "Get component Artifacts", method = "GET", summary = "Returns artifacts", responses = {
-            @ApiResponse(content = @Content(array = @ArraySchema(schema = @Schema(implementation = Response.class)))),
-            @ApiResponse(responseCode = "200", description = "Component artifacts"),
-            @ApiResponse(responseCode = "404", description = "Resource/Artifact not found")})
+        @ApiResponse(content = @Content(array = @ArraySchema(schema = @Schema(implementation = Response.class)))),
+        @ApiResponse(responseCode = "200", description = "Component artifacts"),
+        @ApiResponse(responseCode = "404", description = "Resource/Artifact not found")})
     @PermissionAllowed(AafPermission.PermNames.INTERNAL_ALL_VALUE)
-    public Response getComponentArtifacts(@Parameter(description = "valid values: resources / services",
-            schema = @Schema(allowableValues = {ComponentTypeEnum.RESOURCE_PARAM_NAME ,
-                     ComponentTypeEnum.SERVICE_PARAM_NAME})) @PathParam("containerComponentType") final String containerComponentType,
-            @PathParam("componentId") final String componentId,
-            @PathParam("artifactGroupType") final String artifactGroupType, @Context final HttpServletRequest request) {
-
+    public Response getComponentArtifacts(
+        @Parameter(description = "valid values: resources / services", schema = @Schema(allowableValues = {ComponentTypeEnum.RESOURCE_PARAM_NAME,
+            ComponentTypeEnum.SERVICE_PARAM_NAME})) @PathParam("containerComponentType") final String containerComponentType,
+        @PathParam("componentId") final String componentId, @PathParam("artifactGroupType") final String artifactGroupType,
+        @Context final HttpServletRequest request) {
         String url = request.getMethod() + " " + request.getRequestURI();
         log.debug(START_HANDLE_REQUEST_OF, url);
         try {
@@ -657,17 +611,15 @@ public class ArtifactServlet extends BeGenericServlet {
     @Consumes(MediaType.APPLICATION_JSON)
     @Produces(MediaType.APPLICATION_JSON)
     @Operation(description = "Get component Artifacts", method = "GET", summary = "Returns artifacts", responses = {
-            @ApiResponse(content = @Content(array = @ArraySchema(schema = @Schema(implementation = Response.class)))),
-            @ApiResponse(responseCode = "200", description = "Component artifacts"),
-            @ApiResponse(responseCode = "404", description = "Resource/Artifact not found")})
+        @ApiResponse(content = @Content(array = @ArraySchema(schema = @Schema(implementation = Response.class)))),
+        @ApiResponse(responseCode = "200", description = "Component artifacts"),
+        @ApiResponse(responseCode = "404", description = "Resource/Artifact not found")})
     @PermissionAllowed(AafPermission.PermNames.INTERNAL_ALL_VALUE)
-    public Response getComponentInstanceArtifacts(@Parameter(description = "valid values: resources / services",
-            schema = @Schema(allowableValues = {ComponentTypeEnum.RESOURCE_PARAM_NAME ,
-                     ComponentTypeEnum.SERVICE_PARAM_NAME})) @PathParam("containerComponentType") final String containerComponentType,
-            @PathParam("componentId") final String componentId,
-            @PathParam("componentInstanceId") final String componentInstanceId,
-            @PathParam("artifactGroupType") final String artifactGroupType, @Context final HttpServletRequest request) {
-
+    public Response getComponentInstanceArtifacts(
+        @Parameter(description = "valid values: resources / services", schema = @Schema(allowableValues = {ComponentTypeEnum.RESOURCE_PARAM_NAME,
+            ComponentTypeEnum.SERVICE_PARAM_NAME})) @PathParam("containerComponentType") final String containerComponentType,
+        @PathParam("componentId") final String componentId, @PathParam("componentInstanceId") final String componentInstanceId,
+        @PathParam("artifactGroupType") final String artifactGroupType, @Context final HttpServletRequest request) {
         String url = request.getMethod() + " " + request.getRequestURI();
         log.debug(START_HANDLE_REQUEST_OF, url);
         try {
@@ -679,76 +631,64 @@ public class ArtifactServlet extends BeGenericServlet {
         }
     }
 
-
     @POST
     @Path("/{assetType}/{uuid}/interfaces/{interfaceUUID}/operations/{operationUUID}/artifacts/{artifactUUID}")
     @Consumes(MediaType.APPLICATION_JSON)
     @Produces(MediaType.APPLICATION_JSON)
-    @Operation(description = "uploads of artifact to component operation workflow", method = "POST",
-            summary = "uploads of artifact to component operation workflow", responses = {
-            @ApiResponse(responseCode = "200", description = "Artifact uploaded", content = @Content(
-                    array = @ArraySchema(schema = @Schema(implementation = ArtifactDefinition.class)))),
-            @ApiResponse(responseCode = "404", description = "Specified resource is not found - SVC4063"),
-            @ApiResponse(responseCode = "400", description = "Invalid artifactType was defined as input - SVC4122"),
-            @ApiResponse(responseCode = "400",
-                    description = "Artifact type (mandatory field) is missing in request - SVC4124"),
-            @ApiResponse(responseCode = "400",
-                    description = "Artifact name given in input already exists in the context of the asset - SVC4125"),
-            @ApiResponse(responseCode = "400", description = "Artifact name is missing in input - SVC4128"),
-            @ApiResponse(responseCode = "400",
-                    description = "Asset is being edited by different user. Only one user can checkout and edit an asset on given time. The asset will be available for checkout after the other user will checkin the asset - SVC4086"),
-            @ApiResponse(responseCode = "400",
-                    description = "Restricted Operation â€“ the user provided does not have role of Designer or the asset is being used by another designer - SVC4301")})
-    public Response uploadInterfaceOperationArtifact(
-            @Parameter(description = "Asset type") @PathParam("assetType") String assetType,
-            @Parameter(description = "The uuid of the asset as published in the metadata", required = true)@PathParam("uuid") final String uuid,
-            @Parameter(description = "The uuid of the interface", required = true)@PathParam("interfaceUUID") final String interfaceUUID,
-            @Parameter(description = "The uuid of the operation", required = true)@PathParam("operationUUID") final String operationUUID,
-            @Parameter(description = "The uuid of the artifact", required = true)@PathParam("artifactUUID") final String artifactUUID,
-            @Parameter( hidden = true) String data,
-            @HeaderParam(value = Constants.USER_ID_HEADER) String userId,
-            @HeaderParam(value = Constants.MD5_HEADER) String origMd5,
-            @Context final HttpServletRequest request) {
-
+    @Operation(description = "uploads of artifact to component operation workflow", method = "POST", summary = "uploads of artifact to component operation workflow", responses = {
+        @ApiResponse(responseCode = "200", description = "Artifact uploaded", content = @Content(array = @ArraySchema(schema = @Schema(implementation = ArtifactDefinition.class)))),
+        @ApiResponse(responseCode = "404", description = "Specified resource is not found - SVC4063"),
+        @ApiResponse(responseCode = "400", description = "Invalid artifactType was defined as input - SVC4122"),
+        @ApiResponse(responseCode = "400", description = "Artifact type (mandatory field) is missing in request - SVC4124"),
+        @ApiResponse(responseCode = "400", description = "Artifact name given in input already exists in the context of the asset - SVC4125"),
+        @ApiResponse(responseCode = "400", description = "Artifact name is missing in input - SVC4128"),
+        @ApiResponse(responseCode = "400", description = "Asset is being edited by different user. Only one user can checkout and edit an asset on given time. The asset will be available for checkout after the other user will checkin the asset - SVC4086"),
+        @ApiResponse(responseCode = "400", description = "Restricted Operation â€“ the user provided does not have role of Designer or the asset is being used by another designer - SVC4301")})
+    public Response uploadInterfaceOperationArtifact(@Parameter(description = "Asset type") @PathParam("assetType") String assetType,
+                                                     @Parameter(description = "The uuid of the asset as published in the metadata", required = true) @PathParam("uuid") final String uuid,
+                                                     @Parameter(description = "The uuid of the interface", required = true) @PathParam("interfaceUUID") final String interfaceUUID,
+                                                     @Parameter(description = "The uuid of the operation", required = true) @PathParam("operationUUID") final String operationUUID,
+                                                     @Parameter(description = "The uuid of the artifact", required = true) @PathParam("artifactUUID") final String artifactUUID,
+                                                     @Parameter(hidden = true) String data,
+                                                     @HeaderParam(value = Constants.USER_ID_HEADER) String userId,
+                                                     @HeaderParam(value = Constants.MD5_HEADER) String origMd5,
+                                                     @Context final HttpServletRequest request) {
         String url = request.getMethod() + " " + request.getRequestURI();
-        log.debug("Start handle request of {}" , url);
-
+        log.debug("Start handle request of {}", url);
         try {
-            Either<ArtifactDefinition, ResponseFormat> uploadArtifactEither =
-                artifactsBusinessLogic.updateArtifactOnInterfaceOperationByResourceUUID(data, request,
-                            ComponentTypeEnum.findByParamName(assetType), uuid, interfaceUUID, operationUUID, artifactUUID,
-                            new ResourceCommonInfo(assetType), new ArtifactOperationInfo(true,
-                                    false, ArtifactOperationEnum.UPDATE));
+            Either<ArtifactDefinition, ResponseFormat> uploadArtifactEither = artifactsBusinessLogic
+                .updateArtifactOnInterfaceOperationByResourceUUID(data, request, ComponentTypeEnum.findByParamName(assetType), uuid, interfaceUUID,
+                    operationUUID, artifactUUID, new ResourceCommonInfo(assetType),
+                    new ArtifactOperationInfo(true, false, ArtifactOperationEnum.UPDATE));
             if (uploadArtifactEither.isRight()) {
                 log.debug("failed to update artifact");
                 return buildErrorResponse(uploadArtifactEither.right().value());
             }
             return buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), uploadArtifactEither.left().value());
-        }
-        catch (Exception e) {
+        } catch (Exception e) {
             final String message = "failed to update artifact on a resource or service";
             BeEcompErrorManager.getInstance().logBeRestApiGeneralError(message);
             log.debug(message, e);
             return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR));
         }
     }
-
     // ////////// API END ///////////////////////////
 
     // ************ private *********************
-
     private Response handleUploadRequest(String data, HttpServletRequest request, String componentId, ComponentTypeEnum componentType) {
         return handleArtifactRequest(data, componentId, null, componentType, ArtifactOperationEnum.CREATE);
     }
 
-    private Response handleUpdateRequest(String data, HttpServletRequest request, String componentId, String artifactId, ComponentTypeEnum componentType) {
+    private Response handleUpdateRequest(String data, HttpServletRequest request, String componentId, String artifactId,
+                                         ComponentTypeEnum componentType) {
         return handleArtifactRequest(data, componentId, artifactId, componentType, ArtifactOperationEnum.UPDATE);
     }
 
-    private Response handleDownloadRequest(HttpServletRequest request, String componentId, String artifactId, String parentId, ComponentTypeEnum componentType, String containerComponentType) {
+    private Response handleDownloadRequest(HttpServletRequest request, String componentId, String artifactId, String parentId,
+                                           ComponentTypeEnum componentType, String containerComponentType) {
         String userId = request.getHeader(Constants.USER_ID_HEADER);
-        ImmutablePair<String, byte[]> actionResult = artifactsBusinessLogic.handleDownloadRequestById(componentId, artifactId, userId, componentType, parentId, containerComponentType);
-
+        ImmutablePair<String, byte[]> actionResult = artifactsBusinessLogic
+            .handleDownloadRequestById(componentId, artifactId, userId, componentType, parentId, containerComponentType);
         Response response;
         byte[] file = actionResult.getRight();
         String base64Contents = new String(Base64.encodeBase64(file));
@@ -761,25 +701,28 @@ public class ArtifactServlet extends BeGenericServlet {
         return response;
     }
 
-    private Response handleGetArtifactsRequest(HttpServletRequest request, String componentId, String parentId, String artifactGroupType, String containerComponentType) {
+    private Response handleGetArtifactsRequest(HttpServletRequest request, String componentId, String parentId, String artifactGroupType,
+                                               String containerComponentType) {
         String userId = request.getHeader(Constants.USER_ID_HEADER);
-        ComponentTypeEnum componentTypeEnum = parentId == null || parentId.isEmpty() ? ComponentTypeEnum.findByParamName(containerComponentType) : ComponentTypeEnum.RESOURCE_INSTANCE;
-        Map<String, ArtifactDefinition> actionResult = artifactsBusinessLogic.handleGetArtifactsByType(containerComponentType, parentId, componentTypeEnum, componentId, artifactGroupType, userId);
-
+        ComponentTypeEnum componentTypeEnum =
+            parentId == null || parentId.isEmpty() ? ComponentTypeEnum.findByParamName(containerComponentType) : ComponentTypeEnum.RESOURCE_INSTANCE;
+        Map<String, ArtifactDefinition> actionResult = artifactsBusinessLogic
+            .handleGetArtifactsByType(containerComponentType, parentId, componentTypeEnum, componentId, artifactGroupType, userId);
         return buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), actionResult);
     }
 
-
-    private Response handleDeleteRequest(HttpServletRequest request, String componentId, String artifactId, ComponentTypeEnum componentType, String interfaceType, String operationName) {
+    private Response handleDeleteRequest(HttpServletRequest request, String componentId, String artifactId, ComponentTypeEnum componentType,
+                                         String interfaceType, String operationName) {
         return handleDeleteRequest(request, componentId, artifactId, componentType, interfaceType, operationName, null);
     }
 
-    private Response handleDeleteRequest(HttpServletRequest request, String componentId, String artifactId, ComponentTypeEnum componentType, String interfaceType, String operationName, String parentId) {
+    private Response handleDeleteRequest(HttpServletRequest request, String componentId, String artifactId, ComponentTypeEnum componentType,
+                                         String interfaceType, String operationName, String parentId) {
         String userId = request.getHeader(Constants.USER_ID_HEADER);
-        Either<ArtifactDefinition, org.openecomp.sdc.be.model.Operation> actionResult = artifactsBusinessLogic.handleArtifactRequest(componentId, userId, componentType, new ArtifactOperationInfo(false, false, ArtifactOperationEnum.DELETE), artifactId, null, null, null, interfaceType, operationName,
-                parentId, null);
+        Either<ArtifactDefinition, org.openecomp.sdc.be.model.Operation> actionResult = artifactsBusinessLogic
+            .handleArtifactRequest(componentId, userId, componentType, new ArtifactOperationInfo(false, false, ArtifactOperationEnum.DELETE),
+                artifactId, null, null, null, interfaceType, operationName, parentId, null);
         Response response;
-
         Either<ArtifactDefinition, org.openecomp.sdc.be.model.Operation> result = actionResult;
         if (result.isLeft()) {
             response = buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), result.left().value());
@@ -787,34 +730,32 @@ public class ArtifactServlet extends BeGenericServlet {
             response = buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), result.right().value());
         }
         return response;
-
     }
 
-    private Response handleArtifactRequest(String data, HttpServletRequest request, String componentId, String interfaceName, String operationName, String artifactId, ComponentTypeEnum componentType, ArtifactOperationEnum operationEnum, String parentId,
+    private Response handleArtifactRequest(String data, HttpServletRequest request, String componentId, String interfaceName, String operationName,
+                                           String artifactId, ComponentTypeEnum componentType, ArtifactOperationEnum operationEnum, String parentId,
                                            String containerComponentType, boolean validateTimeout) {
-        loggerSupportability.log(LoggerSupportabilityActions.UPDATE_ARTIFACT, StatusCode.STARTED,"Starting to update artifact {} " ,artifactId + " for component " + componentId);
+        loggerSupportability.log(LoggerSupportabilityActions.UPDATE_ARTIFACT, StatusCode.STARTED, "Starting to update artifact {} ",
+            artifactId + " for component " + componentId);
         ArtifactDefinition artifactInfo = RepresentationUtils.convertJsonToArtifactDefinition(data, ArtifactDefinition.class, validateTimeout);
         String origMd5 = request.getHeader(Constants.MD5_HEADER);
-
         String userId = request.getHeader(Constants.USER_ID_HEADER);
-
-        Either<ArtifactDefinition, org.openecomp.sdc.be.model.Operation> result = artifactsBusinessLogic.handleArtifactRequest(componentId, userId, componentType,
-                new ArtifactOperationInfo(false, false, operationEnum), artifactId, artifactInfo, origMd5, data, interfaceName, operationName, parentId,
-                containerComponentType);
+        Either<ArtifactDefinition, org.openecomp.sdc.be.model.Operation> result = artifactsBusinessLogic
+            .handleArtifactRequest(componentId, userId, componentType, new ArtifactOperationInfo(false, false, operationEnum), artifactId,
+                artifactInfo, origMd5, data, interfaceName, operationName, parentId, containerComponentType);
         Response response;
         if (result.isLeft()) {
             response = buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), result.left().value());
         } else {
             response = buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), result.right().value());
         }
-
-        loggerSupportability.log(LoggerSupportabilityActions.UPDATE_ARTIFACT, StatusCode.COMPLETE,"Ended update artifact {} " ,artifactId + " for component " + componentId);
+        loggerSupportability.log(LoggerSupportabilityActions.UPDATE_ARTIFACT, StatusCode.COMPLETE, "Ended update artifact {} ",
+            artifactId + " for component " + componentId);
         return response;
-
     }
 
-    private Response handleArtifactRequest(String data, String componentId, String artifactId, ComponentTypeEnum componentType, ArtifactOperationEnum operation) {
+    private Response handleArtifactRequest(String data, String componentId, String artifactId, ComponentTypeEnum componentType,
+                                           ArtifactOperationEnum operation) {
         return handleArtifactRequest(data, servletRequest, componentId, null, null, artifactId, componentType, operation, null, null, false);
     }
-
 }
index 2276273..c9af806 100644 (file)
  * limitations under the License.
  * ============LICENSE_END=========================================================
  */
-
 package org.openecomp.sdc.be.servlets;
 
 import com.fasterxml.jackson.databind.ObjectMapper;
-import com.google.gson.Gson;
-import com.google.gson.GsonBuilder;
 import com.jcabi.aspects.Loggable;
 import fj.data.Either;
 import io.swagger.v3.oas.annotations.Operation;
@@ -55,7 +52,6 @@ import org.openecomp.sdc.be.components.impl.aaf.AafPermission;
 import org.openecomp.sdc.be.components.impl.aaf.PermissionAllowed;
 import org.openecomp.sdc.be.config.BeEcompErrorManager;
 import org.openecomp.sdc.be.dao.api.ActionStatus;
-import org.openecomp.sdc.be.datatypes.elements.AttributeDataDefinition;
 import org.openecomp.sdc.be.impl.ComponentsUtils;
 import org.openecomp.sdc.be.impl.ServletUtils;
 import org.openecomp.sdc.be.model.AttributeDefinition;
@@ -84,10 +80,8 @@ public class AttributeServlet extends AbstractValidationsServlet {
     private static final String ATTRIBUTE_CONTENT_IS_INVALID = "Attribute content is invalid - {}";
 
     @Inject
-    public AttributeServlet(UserBusinessLogic userBusinessLogic,
-                            ComponentInstanceBusinessLogic componentInstanceBL,
-                            ComponentsUtils componentsUtils, ServletUtils servletUtils,
-                            ResourceImportManager resourceImportManager) {
+    public AttributeServlet(UserBusinessLogic userBusinessLogic, ComponentInstanceBusinessLogic componentInstanceBL, ComponentsUtils componentsUtils,
+                            ServletUtils servletUtils, ResourceImportManager resourceImportManager) {
         super(userBusinessLogic, componentInstanceBL, componentsUtils, servletUtils, resourceImportManager);
     }
 
@@ -104,8 +98,7 @@ public class AttributeServlet extends AbstractValidationsServlet {
     @Path("resources/{resourceId}/attributes")
     @Consumes(MediaType.APPLICATION_JSON)
     @Produces(MediaType.APPLICATION_JSON)
-    @Operation(description = "Create Resource Attribute", method = "POST",
-        summary = "Returns created resource attribute", responses = {
+    @Operation(description = "Create Resource Attribute", method = "POST", summary = "Returns created resource attribute", responses = {
         @ApiResponse(content = @Content(array = @ArraySchema(schema = @Schema(implementation = Response.class)))),
         @ApiResponse(responseCode = "201", description = "Resource property created"),
         @ApiResponse(responseCode = "403", description = "Restricted operation"),
@@ -113,32 +106,25 @@ public class AttributeServlet extends AbstractValidationsServlet {
         @ApiResponse(responseCode = "409", description = "Resource attribute already exist")})
     @PermissionAllowed(AafPermission.PermNames.INTERNAL_ALL_VALUE)
     public Response createAttribute(
-        @Parameter(description = "resource id to update with new attribute",
-            required = true) @PathParam("resourceId") final String resourceId,
-        @Parameter(description = "Resource attribute to be created", required = true) String data,
-        @Context final HttpServletRequest request, @HeaderParam(value = Constants.USER_ID_HEADER) String userId)
-        throws IOException {
-
+        @Parameter(description = "resource id to update with new attribute", required = true) @PathParam("resourceId") final String resourceId,
+        @Parameter(description = "Resource attribute to be created", required = true) String data, @Context final HttpServletRequest request,
+        @HeaderParam(value = Constants.USER_ID_HEADER) String userId) throws IOException {
         ServletContext context = request.getSession().getServletContext();
-
         String url = request.getMethod() + " " + request.getRequestURI();
         log.debug("Start handle request of {} modifier id is {} data is {}", url, userId, data);
-
         try {
             final Wrapper<ResponseFormat> errorWrapper = new Wrapper<>();
             AttributeDefinition attributeDataDefinition = convertJsonToObject(data, errorWrapper);
-
             if (errorWrapper.isEmpty()) {
                 AttributeBusinessLogic businessLogic = getClassFromWebAppContext(context, () -> AttributeBusinessLogic.class);
-                Either<AttributeDefinition, ResponseFormat> createAttribute = businessLogic.
-                    createAttribute(resourceId, attributeDataDefinition, userId);
+                Either<AttributeDefinition, ResponseFormat> createAttribute = businessLogic
+                    .createAttribute(resourceId, attributeDataDefinition, userId);
                 if (createAttribute.isRight()) {
                     errorWrapper.setInnerElement(createAttribute.right().value());
                 } else {
                     attributeDataDefinition = createAttribute.left().value();
                 }
             }
-
             if (!errorWrapper.isEmpty()) {
                 log.info("Failed to create Attribute. Reason - ", errorWrapper.getInnerElement());
                 return buildErrorResponse(errorWrapper.getInnerElement());
@@ -147,7 +133,6 @@ public class AttributeServlet extends AbstractValidationsServlet {
                 ResponseFormat responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.CREATED);
                 return buildOkResponse(responseFormat, RepresentationUtils.toRepresentation(attributeDataDefinition));
             }
-
         } catch (Exception e) {
             BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Create Attribute");
             log.debug("create property failed with exception", e);
@@ -169,46 +154,37 @@ public class AttributeServlet extends AbstractValidationsServlet {
     @Path("resources/{resourceId}/attributes/{attributeId}")
     @Consumes(MediaType.APPLICATION_JSON)
     @Produces(MediaType.APPLICATION_JSON)
-    @Operation(description = "Update Resource Attribute", method = "PUT", summary = "Returns updated attribute",
-        responses = {@ApiResponse(
-            content = @Content(array = @ArraySchema(schema = @Schema(implementation = Response.class)))),
-            @ApiResponse(responseCode = "200", description = "Resource attribute updated"),
-            @ApiResponse(responseCode = "403", description = "Restricted operation"),
-            @ApiResponse(responseCode = "400", description = "Invalid content / Missing content")})
+    @Operation(description = "Update Resource Attribute", method = "PUT", summary = "Returns updated attribute", responses = {
+        @ApiResponse(content = @Content(array = @ArraySchema(schema = @Schema(implementation = Response.class)))),
+        @ApiResponse(responseCode = "200", description = "Resource attribute updated"),
+        @ApiResponse(responseCode = "403", description = "Restricted operation"),
+        @ApiResponse(responseCode = "400", description = "Invalid content / Missing content")})
     @PermissionAllowed(AafPermission.PermNames.INTERNAL_ALL_VALUE)
     public Response updateAttribute(
-        @Parameter(description = "resource id to update with new attribute",
-            required = true) @PathParam("resourceId") final String resourceId,
-        @Parameter(description = "attribute id to update",
-            required = true) @PathParam("attributeId") final String attributeId,
-        @Parameter(description = "Resource attribute to update", required = true) String data,
-        @Context final HttpServletRequest request, @HeaderParam(value = Constants.USER_ID_HEADER) String userId)
-        throws IOException {
-
+        @Parameter(description = "resource id to update with new attribute", required = true) @PathParam("resourceId") final String resourceId,
+        @Parameter(description = "attribute id to update", required = true) @PathParam("attributeId") final String attributeId,
+        @Parameter(description = "Resource attribute to update", required = true) String data, @Context final HttpServletRequest request,
+        @HeaderParam(value = Constants.USER_ID_HEADER) String userId) throws IOException {
         ServletContext context = request.getSession().getServletContext();
-
         String url = request.getMethod() + " " + request.getRequestURI();
         log.debug("Start handle request of {}", url);
-
         // get modifier id
         User modifier = new User();
         modifier.setUserId(userId);
         log.debug("modifier id is {}", userId);
-
         try {
             final Wrapper<ResponseFormat> errorWrapper = new Wrapper<>();
             AttributeDefinition attributeDataDefinition = convertJsonToObject(data, errorWrapper);
             if (errorWrapper.isEmpty()) {
                 AttributeBusinessLogic businessLogic = getClassFromWebAppContext(context, () -> AttributeBusinessLogic.class);
-                Either<AttributeDefinition, ResponseFormat> eitherUpdateAttribute
-                    = businessLogic.updateAttribute(resourceId, attributeId, attributeDataDefinition, userId);
+                Either<AttributeDefinition, ResponseFormat> eitherUpdateAttribute = businessLogic
+                    .updateAttribute(resourceId, attributeId, attributeDataDefinition, userId);
                 if (eitherUpdateAttribute.isRight()) {
                     errorWrapper.setInnerElement(eitherUpdateAttribute.right().value());
                 } else {
                     attributeDataDefinition = eitherUpdateAttribute.left().value();
                 }
             }
-
             if (!errorWrapper.isEmpty()) {
                 log.info("Failed to update Attribute. Reason - ", errorWrapper.getInnerElement());
                 return buildErrorResponse(errorWrapper.getInnerElement());
@@ -217,7 +193,6 @@ public class AttributeServlet extends AbstractValidationsServlet {
                 ResponseFormat responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.OK);
                 return buildOkResponse(responseFormat, RepresentationUtils.toRepresentation(attributeDataDefinition));
             }
-
         } catch (Exception e) {
             BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Update Attribute");
             log.debug("update attribute failed with exception", e);
@@ -238,45 +213,34 @@ public class AttributeServlet extends AbstractValidationsServlet {
     @Path("resources/{resourceId}/attributes/{attributeId}")
     @Consumes(MediaType.APPLICATION_JSON)
     @Produces(MediaType.APPLICATION_JSON)
-    @Operation(description = "Create Resource Attribute", method = "DELETE", summary = "Returns deleted attribute",
-        responses = {@ApiResponse(
-            content = @Content(array = @ArraySchema(schema = @Schema(implementation = Response.class)))),
-            @ApiResponse(responseCode = "204", description = "deleted attribute"),
-            @ApiResponse(responseCode = "403", description = "Restricted operation"),
-            @ApiResponse(responseCode = "400", description = "Invalid content / Missing content"),
-            @ApiResponse(responseCode = "404", description = "Resource property not found")})
+    @Operation(description = "Create Resource Attribute", method = "DELETE", summary = "Returns deleted attribute", responses = {
+        @ApiResponse(content = @Content(array = @ArraySchema(schema = @Schema(implementation = Response.class)))),
+        @ApiResponse(responseCode = "204", description = "deleted attribute"),
+        @ApiResponse(responseCode = "403", description = "Restricted operation"),
+        @ApiResponse(responseCode = "400", description = "Invalid content / Missing content"),
+        @ApiResponse(responseCode = "404", description = "Resource property not found")})
     @PermissionAllowed(AafPermission.PermNames.INTERNAL_ALL_VALUE)
     public Response deleteAttribute(
-        @Parameter(description = "resource id of attribute",
-            required = true) @PathParam("resourceId") final String resourceId,
-        @Parameter(description = "Attribute id to delete",
-            required = true) @PathParam("attributeId") final String attributeId,
-        @Context final HttpServletRequest request, @HeaderParam(value = Constants.USER_ID_HEADER) String userId)
-        throws IOException {
-
+        @Parameter(description = "resource id of attribute", required = true) @PathParam("resourceId") final String resourceId,
+        @Parameter(description = "Attribute id to delete", required = true) @PathParam("attributeId") final String attributeId,
+        @Context final HttpServletRequest request, @HeaderParam(value = Constants.USER_ID_HEADER) String userId) throws IOException {
         ServletContext context = request.getSession().getServletContext();
-
         String url = request.getMethod() + " " + request.getRequestURI();
         log.debug("Start handle request of {}", url);
         log.debug("modifier id is {}", userId);
-
         try {
             // delete the property
-            AttributeBusinessLogic businessLogic = getClassFromWebAppContext(context,
-                () -> AttributeBusinessLogic.class);
-            Either<AttributeDefinition, ResponseFormat> eitherAttribute = businessLogic
-                .deleteAttribute(resourceId, attributeId, userId);
+            AttributeBusinessLogic businessLogic = getClassFromWebAppContext(context, () -> AttributeBusinessLogic.class);
+            Either<AttributeDefinition, ResponseFormat> eitherAttribute = businessLogic.deleteAttribute(resourceId, attributeId, userId);
             if (eitherAttribute.isRight()) {
                 log.debug("Failed to delete Attribute. Reason - ", eitherAttribute.right().value());
                 return buildErrorResponse(eitherAttribute.right().value());
             }
             AttributeDefinition attributeDefinition = eitherAttribute.left().value();
             String name = attributeDefinition.getName();
-
             log.debug("Attribute {} deleted successfully with id {}", name, attributeDefinition.getUniqueId());
             ResponseFormat responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.NO_CONTENT);
             return buildOkResponse(responseFormat, RepresentationUtils.toRepresentation(attributeDefinition));
-
         } catch (Exception e) {
             BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Delete Attribute");
             log.debug("delete attribute failed with exception", e);
@@ -284,9 +248,7 @@ public class AttributeServlet extends AbstractValidationsServlet {
         }
     }
 
-    private AttributeDefinition convertJsonToObject(final String data,
-                                                    final Wrapper<ResponseFormat> errorWrapper) {
-
+    private AttributeDefinition convertJsonToObject(final String data, final Wrapper<ResponseFormat> errorWrapper) {
         final ObjectMapper mapper = new ObjectMapper();
         try {
             return mapper.readValue(data, AttributeDefinition.class);
index 3602003..8a16c43 100644 (file)
@@ -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.
@@ -17,7 +17,6 @@
  * limitations under the License.
  * ============LICENSE_END=========================================================
  */
-
 package org.openecomp.sdc.be.servlets;
 
 import com.jcabi.aspects.Loggable;
@@ -31,19 +30,7 @@ import io.swagger.v3.oas.annotations.servers.Server;
 import io.swagger.v3.oas.annotations.servers.Servers;
 import io.swagger.v3.oas.annotations.tags.Tag;
 import io.swagger.v3.oas.annotations.tags.Tags;
-import org.openecomp.sdc.be.components.impl.aaf.AafPermission;
-import org.openecomp.sdc.be.components.impl.aaf.PermissionAllowed;
-import org.openecomp.sdc.be.components.upgrade.UpgradeBusinessLogic;
-import org.openecomp.sdc.be.components.upgrade.UpgradeRequest;
-import org.openecomp.sdc.be.components.upgrade.UpgradeStatus;
-import org.openecomp.sdc.be.dao.api.ActionStatus;
-import org.openecomp.sdc.be.dao.jsongraph.utils.JsonParserUtils;
-import org.openecomp.sdc.be.impl.ComponentsUtils;
-import org.openecomp.sdc.be.user.UserBusinessLogic;
-import org.openecomp.sdc.common.api.Constants;
-import org.openecomp.sdc.common.log.wrappers.Logger;
-import org.springframework.stereotype.Controller;
-
+import java.util.List;
 import javax.inject.Inject;
 import javax.servlet.http.HttpServletRequest;
 import javax.ws.rs.Consumes;
@@ -56,7 +43,18 @@ import javax.ws.rs.Produces;
 import javax.ws.rs.core.Context;
 import javax.ws.rs.core.MediaType;
 import javax.ws.rs.core.Response;
-import java.util.List;
+import org.openecomp.sdc.be.components.impl.aaf.AafPermission;
+import org.openecomp.sdc.be.components.impl.aaf.PermissionAllowed;
+import org.openecomp.sdc.be.components.upgrade.UpgradeBusinessLogic;
+import org.openecomp.sdc.be.components.upgrade.UpgradeRequest;
+import org.openecomp.sdc.be.components.upgrade.UpgradeStatus;
+import org.openecomp.sdc.be.dao.api.ActionStatus;
+import org.openecomp.sdc.be.dao.jsongraph.utils.JsonParserUtils;
+import org.openecomp.sdc.be.impl.ComponentsUtils;
+import org.openecomp.sdc.be.user.UserBusinessLogic;
+import org.openecomp.sdc.common.api.Constants;
+import org.openecomp.sdc.common.log.wrappers.Logger;
+import org.springframework.stereotype.Controller;
 
 @Loggable(prepend = true, value = Loggable.DEBUG, trim = false)
 @Path("/v1/catalog")
@@ -66,14 +64,12 @@ import java.util.List;
 @Consumes(MediaType.APPLICATION_JSON)
 @Produces(MediaType.APPLICATION_JSON)
 public class AutomatedUpgradeEndpoint extends BeGenericServlet {
-    private static final Logger log = Logger.getLogger(PolicyTypesEndpoint.class);
 
+    private static final Logger log = Logger.getLogger(PolicyTypesEndpoint.class);
     private final UpgradeBusinessLogic businessLogic;
 
     @Inject
-    public AutomatedUpgradeEndpoint(UserBusinessLogic userBusinessLogic,
-        ComponentsUtils componentsUtils,
-        UpgradeBusinessLogic businessLogic) {
+    public AutomatedUpgradeEndpoint(UserBusinessLogic userBusinessLogic, ComponentsUtils componentsUtils, UpgradeBusinessLogic businessLogic) {
         super(userBusinessLogic, componentsUtils);
         this.businessLogic = businessLogic;
     }
@@ -83,57 +79,45 @@ public class AutomatedUpgradeEndpoint extends BeGenericServlet {
     @Consumes(MediaType.APPLICATION_JSON)
     @Produces(MediaType.APPLICATION_JSON)
     @Operation(description = "Autometed upgrade", method = "POST", summary = "....", responses = {
-            @ApiResponse(content = @Content(array = @ArraySchema(schema = @Schema(implementation = Response.class)))),
-            @ApiResponse(responseCode = "200", description = "Component found"),
-            @ApiResponse(responseCode = "403", description = "Restricted operation"),
-            @ApiResponse(responseCode = "404", description = "Component not found")})
+        @ApiResponse(content = @Content(array = @ArraySchema(schema = @Schema(implementation = Response.class)))),
+        @ApiResponse(responseCode = "200", description = "Component found"), @ApiResponse(responseCode = "403", description = "Restricted operation"),
+        @ApiResponse(responseCode = "404", description = "Component not found")})
     @PermissionAllowed(AafPermission.PermNames.INTERNAL_ALL_VALUE)
-    public Response autometedUpgrade(@PathParam("componentType") final String componentType,
-            @Context final HttpServletRequest request, @PathParam("componentId") final String componentId,
-            @HeaderParam(value = Constants.USER_ID_HEADER) String userId,
-            @Parameter(description = "json describes upgrade request", required = true) String data) {
-
-     
+    public Response autometedUpgrade(@PathParam("componentType") final String componentType, @Context final HttpServletRequest request,
+                                     @PathParam("componentId") final String componentId, @HeaderParam(value = Constants.USER_ID_HEADER) String userId,
+                                     @Parameter(description = "json describes upgrade request", required = true) String data) {
         String url = request.getMethod() + " " + request.getRequestURI();
         log.debug("(POST) Start handle request of {}", url);
-
         try {
-            
             List<UpgradeRequest> inputsToUpdate = JsonParserUtils.toList(data, UpgradeRequest.class);
-            
             if (log.isDebugEnabled()) {
                 log.debug("Received upgrade requests size is {}", inputsToUpdate == null ? 0 : inputsToUpdate.size());
             }
             UpgradeStatus actionResponse = businessLogic.automatedUpgrade(componentId, inputsToUpdate, userId);
-            
             return actionResponse.getStatus() == ActionStatus.OK ? buildOkResponse(actionResponse) : buildErrorResponse(actionResponse.getError());
-
         } catch (Exception e) {
             log.error("#autometedUpgrade - Exception occurred during autometed Upgrade", e);
             throw e;
         }
     }
-    
+
     @GET
     @Path("/{componentType}/{componentId}/dependencies")
     @Consumes(MediaType.APPLICATION_JSON)
     @Produces(MediaType.APPLICATION_JSON)
     @Operation(description = "Autometed upgrade", method = "POST", summary = "....", responses = {
-            @ApiResponse(content = @Content(array = @ArraySchema(schema = @Schema(implementation = Response.class)))),
-            @ApiResponse(responseCode = "200", description = "Component found"),
-            @ApiResponse(responseCode = "403", description = "Restricted operation"),
-            @ApiResponse(responseCode = "404", description = "Component not found")})
+        @ApiResponse(content = @Content(array = @ArraySchema(schema = @Schema(implementation = Response.class)))),
+        @ApiResponse(responseCode = "200", description = "Component found"), @ApiResponse(responseCode = "403", description = "Restricted operation"),
+        @ApiResponse(responseCode = "404", description = "Component not found")})
     @PermissionAllowed(AafPermission.PermNames.INTERNAL_ALL_VALUE)
-    public Response getComponentDependencies(@PathParam("componentType") final String componentType,
-            @Context final HttpServletRequest request, @PathParam("componentId") final String componentId,
-            @HeaderParam(value = Constants.USER_ID_HEADER) String userId,
-            @Parameter(description = "Consumer Object to be created", required = true) List<String> data) {
+    public Response getComponentDependencies(@PathParam("componentType") final String componentType, @Context final HttpServletRequest request,
+                                             @PathParam("componentId") final String componentId,
+                                             @HeaderParam(value = Constants.USER_ID_HEADER) String userId,
+                                             @Parameter(description = "Consumer Object to be created", required = true) List<String> data) {
         String url = request.getMethod() + " " + request.getRequestURI();
         log.debug("(GET) Start handle request of {}", url);
-
         try {
-            return  businessLogic.getComponentDependencies(componentId, userId)
-                    .either(this::buildOkResponse, this::buildErrorResponse);  
+            return businessLogic.getComponentDependencies(componentId, userId).either(this::buildOkResponse, this::buildErrorResponse);
         } catch (Exception e) {
             log.error("#getServicesForComponent - Exception occurred during autometed Upgrade", e);
             throw e;
index ffaf8a8..43f5166 100644 (file)
@@ -17,7 +17,6 @@
  * limitations under the License.
  * ============LICENSE_END=========================================================
  */
-
 package org.openecomp.sdc.be.servlets;
 
 import com.fasterxml.jackson.databind.DeserializationFeature;
@@ -31,6 +30,21 @@ import fj.data.Either;
 import io.swagger.v3.oas.annotations.OpenAPIDefinition;
 import io.swagger.v3.oas.annotations.info.Info;
 import io.swagger.v3.oas.annotations.servers.Server;
+import java.io.IOException;
+import java.lang.reflect.Type;
+import java.util.HashMap;
+import java.util.Iterator;
+import java.util.List;
+import java.util.Map;
+import java.util.Map.Entry;
+import java.util.Objects;
+import java.util.Set;
+import java.util.function.Supplier;
+import javax.servlet.ServletContext;
+import javax.servlet.http.HttpServletRequest;
+import javax.ws.rs.core.Context;
+import javax.ws.rs.core.Response;
+import javax.ws.rs.core.Response.ResponseBuilder;
 import org.json.simple.JSONArray;
 import org.json.simple.JSONObject;
 import org.json.simple.parser.JSONParser;
@@ -55,9 +69,9 @@ import org.openecomp.sdc.be.datatypes.tosca.ToscaDataDefinition;
 import org.openecomp.sdc.be.impl.ComponentsUtils;
 import org.openecomp.sdc.be.impl.WebAppContextWrapper;
 import org.openecomp.sdc.be.model.ComponentInstInputsMap;
+import org.openecomp.sdc.be.model.InputDefinition;
 import org.openecomp.sdc.be.model.PropertyConstraint;
 import org.openecomp.sdc.be.model.PropertyDefinition;
-import org.openecomp.sdc.be.model.InputDefinition;
 import org.openecomp.sdc.be.model.User;
 import org.openecomp.sdc.be.model.operations.impl.PropertyOperation;
 import org.openecomp.sdc.be.model.operations.impl.PropertyOperation.PropertyConstraintJacksonDeserializer;
@@ -70,46 +84,28 @@ import org.openecomp.sdc.common.servlets.BasicServlet;
 import org.openecomp.sdc.exception.ResponseFormat;
 import org.springframework.web.context.WebApplicationContext;
 
-import javax.servlet.ServletContext;
-import javax.servlet.http.HttpServletRequest;
-import javax.ws.rs.core.Context;
-import javax.ws.rs.core.Response;
-import javax.ws.rs.core.Response.ResponseBuilder;
-import java.io.IOException;
-import java.lang.reflect.Type;
-import java.util.HashMap;
-import java.util.Iterator;
-import java.util.List;
-import java.util.Map;
-import java.util.Map.Entry;
-import java.util.Objects;
-import java.util.Set;
-import java.util.function.Supplier;
-
-@OpenAPIDefinition(info = @Info(title = "SDC API", description = "SDC External, Distribution and Internal APIs"),
-        servers = {@Server(url = "/sdc", description = "SDC External and Distribution APIs"),
-                @Server(url = "/sdc2/rest", description = "SDC Internal APIs")})
+@OpenAPIDefinition(info = @Info(title = "SDC API", description = "SDC External, Distribution and Internal APIs"), servers = {
+    @Server(url = "/sdc", description = "SDC External and Distribution APIs"), @Server(url = "/sdc2/rest", description = "SDC Internal APIs")})
 public class BeGenericServlet extends BasicServlet {
 
-    public BeGenericServlet(UserBusinessLogic userAdminManager,
-        ComponentsUtils componentsUtils) {
-        this.userAdminManager = userAdminManager;
-        this.componentsUtils = componentsUtils;
-    }
-
+    private static final Logger log = Logger.getLogger(BeGenericServlet.class);
+    private static final String PROPERTY_NAME_REGEX = "[\\w,\\d,_]+";
     @Context
     protected HttpServletRequest servletRequest;
+    protected ComponentsUtils componentsUtils;
+    private UserBusinessLogic userAdminManager;
 
-    private static final Logger log = Logger.getLogger(BeGenericServlet.class);
-
-    private static final String PROPERTY_NAME_REGEX = "[\\w,\\d,_]+";
+    public BeGenericServlet(UserBusinessLogic userAdminManager, ComponentsUtils componentsUtils) {
+        this.userAdminManager = userAdminManager;
+        this.componentsUtils = componentsUtils;
+    }
 
-    private UserBusinessLogic userAdminManager;
-    protected ComponentsUtils componentsUtils;
+    private static Response buildOkResponseStatic(Object entity) {
+        return Response.status(Response.Status.OK).entity(entity).build();
+    }
 
     /******************** New error response mechanism
      * @param requestErrorWrapper **************/
-
     protected Response buildErrorResponse(ResponseFormat requestErrorWrapper) {
         return Response.status(requestErrorWrapper.getStatus()).entity(gson.toJson(requestErrorWrapper.getRequestError())).build();
     }
@@ -122,18 +118,14 @@ public class BeGenericServlet extends BasicServlet {
         return buildOkResponseStatic(entity);
     }
 
-    private static Response buildOkResponseStatic(Object entity) {
-        return Response.status(Response.Status.OK)
-            .entity(entity)
-            .build();
-    }
-
     public HttpServletRequest getServletRequest() {
         return servletRequest;
     }
 
     @VisibleForTesting
-    public void setRequestServlet(HttpServletRequest request) {this.servletRequest = request;}
+    public void setRequestServlet(HttpServletRequest request) {
+        this.servletRequest = request;
+    }
 
     protected Response buildOkResponse(ResponseFormat errorResponseWrapper, Object entity) {
         return buildOkResponse(errorResponseWrapper, entity, null);
@@ -143,16 +135,18 @@ public class BeGenericServlet extends BasicServlet {
         int status = errorResponseWrapper.getStatus();
         ResponseBuilder responseBuilder = Response.status(status);
         if (entity != null) {
-            if (log.isTraceEnabled())
+            if (log.isTraceEnabled()) {
                 log.trace("returned entity is {}", entity.toString());
+            }
             responseBuilder = responseBuilder.entity(entity);
         }
         if (additionalHeaders != null) {
             for (Entry<String, String> additionalHeader : additionalHeaders.entrySet()) {
                 String headerName = additionalHeader.getKey();
                 String headerValue = additionalHeader.getValue();
-                if (log.isTraceEnabled())
+                if (log.isTraceEnabled()) {
                     log.trace("Adding header {} with value {} to the response", headerName, headerValue);
+                }
                 responseBuilder.header(headerName, headerValue);
             }
         }
@@ -212,8 +206,7 @@ public class BeGenericServlet extends BasicServlet {
     }
 
     /**
-     * Used to support Unit Test.<br>
-     * Header Params are not supported in Unit Tests
+     * Used to support Unit Test.<br> Header Params are not supported in Unit Tests
      *
      * @return
      */
@@ -233,16 +226,13 @@ public class BeGenericServlet extends BasicServlet {
 
     <T> T convertJsonToObjectOfClass(String json, Class<T> clazz) {
         T object = null;
-        ObjectMapper mapper = new ObjectMapper()
-            .configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false)
+        ObjectMapper mapper = new ObjectMapper().configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false)
             .configure(DeserializationFeature.ACCEPT_SINGLE_VALUE_AS_ARRAY, true);
         try {
             log.trace("Starting to convert json to object. Json=\n{}", json);
-
             SimpleModule module = new SimpleModule("customDeserializationModule");
             module.addDeserializer(PropertyConstraint.class, new PropertyConstraintJacksonDeserializer());
             mapper.registerModule(module);
-
             object = mapper.readValue(json, clazz);
             if (object != null) {
                 return object;
@@ -264,28 +254,21 @@ public class BeGenericServlet extends BasicServlet {
         try {
             Map<String, PropertyDefinition> properties = new HashMap<>();
             root = (JSONObject) parser.parse(data);
-
             Set entrySet = root.entrySet();
             Iterator iterator = entrySet.iterator();
             while (iterator.hasNext()) {
                 Entry next = (Entry) iterator.next();
                 String propertyName = (String) next.getKey();
-
-                if(!isPropertyNameValid(propertyName)) {
+                if (!isPropertyNameValid(propertyName)) {
                     return Either.right(ActionStatus.INVALID_PROPERTY_NAME);
                 }
-
                 JSONObject value = (JSONObject) next.getValue();
-                Either<PropertyDefinition, ActionStatus> propertyDefinitionEither =
-                        getPropertyDefinitionFromJson(componentId, propertyName, value);
-
-                if(propertyDefinitionEither.isRight()) {
+                Either<PropertyDefinition, ActionStatus> propertyDefinitionEither = getPropertyDefinitionFromJson(componentId, propertyName, value);
+                if (propertyDefinitionEither.isRight()) {
                     return Either.right(propertyDefinitionEither.right().value());
                 }
-
                 properties.put(propertyName, propertyDefinitionEither.left().value());
             }
-
             return Either.left(properties);
         } catch (ParseException e) {
             log.info("Property conetnt is invalid - {}", data);
@@ -294,9 +277,7 @@ public class BeGenericServlet extends BasicServlet {
     }
 
     protected boolean isPropertyNameValid(String propertyName) {
-        return Objects.nonNull(propertyName)
-                       && propertyName.matches(PROPERTY_NAME_REGEX);
-
+        return Objects.nonNull(propertyName) && propertyName.matches(PROPERTY_NAME_REGEX);
     }
 
     private Either<PropertyDefinition, ActionStatus> getPropertyDefinitionFromJson(String componentId, String propertyName, JSONObject value) {
@@ -308,7 +289,6 @@ public class BeGenericServlet extends BasicServlet {
         PropertyDefinition propertyDefinition = convertJsonToObject.left().value();
         String uniqueId = UniqueIdBuilder.buildPropertyUniqueId(componentId, propertyName);
         propertyDefinition.setUniqueId(uniqueId);
-
         return Either.left(propertyDefinition);
     }
 
@@ -321,36 +301,29 @@ public class BeGenericServlet extends BasicServlet {
         InputDefinition inputDefinition = convertJsonToObject.left().value();
         String uniqueId = UniqueIdBuilder.buildPropertyUniqueId(componentId, inputName);
         inputDefinition.setUniqueId(uniqueId);
-
         return Either.left(inputDefinition);
     }
 
     protected Either<Map<String, PropertyDefinition>, ActionStatus> getPropertiesListForUpdate(String data) {
-
         Map<String, PropertyDefinition> properties = new HashMap<>();
         JSONParser parser = new JSONParser();
         JSONArray jsonArray;
-
         try {
             jsonArray = (JSONArray) parser.parse(data);
             for (Object jsonElement : jsonArray) {
                 String propertyAsString = jsonElement.toString();
                 Either<PropertyDefinition, ActionStatus> convertJsonToObject = convertJsonToObject(propertyAsString, PropertyDefinition.class);
-
                 if (convertJsonToObject.isRight()) {
                     return Either.right(convertJsonToObject.right().value());
                 }
-
                 PropertyDefinition propertyDefinition = convertJsonToObject.left().value();
                 properties.put(propertyDefinition.getName(), propertyDefinition);
             }
-
             return Either.left(properties);
         } catch (Exception e) {
             log.info("Property content is invalid - {}", data);
             return Either.right(ActionStatus.INVALID_CONTENT);
         }
-
     }
 
     protected String propertyToJson(Map.Entry<String, PropertyDefinition> property) {
@@ -364,27 +337,24 @@ public class BeGenericServlet extends BasicServlet {
     }
 
     private JSONObject getPropertyDefinitionJSONObject(PropertyDefinition propertyDefinition) {
-
         Either<String, ActionStatus> either = convertObjectToJson(propertyDefinition);
         if (either.isRight()) {
             return new JSONObject();
         }
         try {
-            return  (JSONObject) new JSONParser().parse(either.left().value());
+            return (JSONObject) new JSONParser().parse(either.left().value());
         } catch (ParseException e) {
             log.info("failed to convert input to json");
             log.error("failed to convert to json", e);
             return new JSONObject();
         }
-
     }
 
-    protected  <T> Either<T, ActionStatus> convertJsonToObject(String data, Class<T> clazz) {
+    protected <T> Either<T, ActionStatus> convertJsonToObject(String data, Class<T> clazz) {
         T t = null;
         Type constraintType = new TypeToken<PropertyConstraint>() {
         }.getType();
-        Gson
-            gson = new GsonBuilder().registerTypeAdapter(constraintType, new PropertyOperation.PropertyConstraintDeserialiser()).create();
+        Gson gson = new GsonBuilder().registerTypeAdapter(constraintType, new PropertyOperation.PropertyConstraintDeserialiser()).create();
         try {
             log.trace("convert json to object. json=\n {}", data);
             t = gson.fromJson(data, clazz);
@@ -419,7 +389,6 @@ public class BeGenericServlet extends BasicServlet {
             log.debug("failed to convert fto json", e);
             return Either.right(ActionStatus.INVALID_CONTENT);
         }
-
     }
 
     private OutputsBusinessLogic getOutputBL(final ServletContext context) {
@@ -438,46 +407,38 @@ public class BeGenericServlet extends BasicServlet {
         return ((WebAppContextWrapper) context.getAttribute(Constants.WEB_APPLICATION_CONTEXT_WRAPPER_ATTR)).getWebAppContext(context);
     }
 
-    protected <T> Either<T, ResponseFormat> parseToComponentInstanceMap(final String componentJson,
-                                                                        final User user,
-                                                                        final ComponentTypeEnum componentType,
-                                                                        final Class<T> clazz) {
+    protected <T> Either<T, ResponseFormat> parseToComponentInstanceMap(final String componentJson, final User user,
+                                                                        final ComponentTypeEnum componentType, final Class<T> clazz) {
         return getComponentsUtils()
             .convertJsonToObjectUsingObjectMapper(componentJson, user, clazz, AuditingActionEnum.CREATE_RESOURCE, componentType);
     }
 
-    protected Response declareProperties(String userId, String componentId, String componentType,
-                                         String componentInstInputsMapObj, DeclarationTypeEnum typeEnum, HttpServletRequest request) {
+    protected Response declareProperties(String userId, String componentId, String componentType, String componentInstInputsMapObj,
+                                         DeclarationTypeEnum typeEnum, HttpServletRequest request) {
         ServletContext context = request.getSession().getServletContext();
         String url = request.getMethod() + " " + request.getRequestURI();
         log.debug("(get) Start handle request of {}", url);
-
         try {
             BaseBusinessLogic businessLogic = getBlForDeclaration(typeEnum, context);
-
             // get modifier id
             User modifier = new User();
             modifier.setUserId(userId);
             log.debug("modifier id is {}", userId);
             ComponentTypeEnum componentTypeEnum = ComponentTypeEnum.findByParamName(componentType);
-            Either<ComponentInstInputsMap, ResponseFormat> componentInstInputsMapRes = parseToComponentInstanceMap(
-                componentInstInputsMapObj, modifier, componentTypeEnum, ComponentInstInputsMap.class);
+            Either<ComponentInstInputsMap, ResponseFormat> componentInstInputsMapRes = parseToComponentInstanceMap(componentInstInputsMapObj,
+                modifier, componentTypeEnum, ComponentInstInputsMap.class);
             if (componentInstInputsMapRes.isRight()) {
                 log.debug("failed to parse componentInstInputsMap");
                 return buildErrorResponse(componentInstInputsMapRes.right().value());
             }
-
             Either<List<ToscaDataDefinition>, ResponseFormat> propertiesAfterDeclaration = businessLogic
-                .declareProperties(userId, componentId,
-                    componentTypeEnum,
-                    componentInstInputsMapRes.left().value());
+                .declareProperties(userId, componentId, componentTypeEnum, componentInstInputsMapRes.left().value());
             if (propertiesAfterDeclaration.isRight()) {
                 log.debug("failed to create inputs  for service: {}", componentId);
                 return buildErrorResponse(propertiesAfterDeclaration.right().value());
             }
             Object properties = RepresentationUtils.toRepresentation(propertiesAfterDeclaration.left().value());
             return buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), properties);
-
         } catch (Exception e) {
             BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Create inputs for service with id: " + componentId);
             log.debug("Properties declaration failed with exception", e);
@@ -485,8 +446,7 @@ public class BeGenericServlet extends BasicServlet {
         }
     }
 
-    public BaseBusinessLogic getBlForDeclaration(final DeclarationTypeEnum typeEnum,
-                                                 final ServletContext context) {
+    public BaseBusinessLogic getBlForDeclaration(final DeclarationTypeEnum typeEnum, final ServletContext context) {
         switch (typeEnum) {
             case OUTPUT:
                 return getOutputBL(context);
@@ -505,28 +465,21 @@ public class BeGenericServlet extends BasicServlet {
         try {
             Map<String, InputDefinition> inputs = new HashMap<>();
             root = (JSONObject) parser.parse(data);
-
             Set entrySet = root.entrySet();
             Iterator iterator = entrySet.iterator();
             while (iterator.hasNext()) {
                 Entry next = (Entry) iterator.next();
                 String inputName = (String) next.getKey();
-
-                if(!isInputNameValid(inputName)) {
+                if (!isInputNameValid(inputName)) {
                     return Either.right(ActionStatus.INVALID_INPUT_NAME);
                 }
-
                 JSONObject value = (JSONObject) next.getValue();
-                Either<InputDefinition, ActionStatus> inputDefinitionEither =
-                        getInputDefinitionFromJson(componentId, inputName, value);
-
-                if(inputDefinitionEither.isRight()) {
+                Either<InputDefinition, ActionStatus> inputDefinitionEither = getInputDefinitionFromJson(componentId, inputName, value);
+                if (inputDefinitionEither.isRight()) {
                     return Either.right(inputDefinitionEither.right().value());
                 }
-
                 inputs.put(inputName, inputDefinitionEither.left().value());
             }
-
             return Either.left(inputs);
         } catch (ParseException e) {
             log.warn("Input content is invalid - {}", data, e);
@@ -535,8 +488,6 @@ public class BeGenericServlet extends BasicServlet {
     }
 
     protected boolean isInputNameValid(String inputName) {
-        return Objects.nonNull(inputName)
-                && inputName.matches(PROPERTY_NAME_REGEX);
-
+        return Objects.nonNull(inputName) && inputName.matches(PROPERTY_NAME_REGEX);
     }
 }
index fb32038..afb037f 100644 (file)
@@ -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.
@@ -17,7 +17,6 @@
  * limitations under the License.
  * ============LICENSE_END=========================================================
  */
-
 package org.openecomp.sdc.be.servlets;
 
 import com.google.gson.Gson;
@@ -30,6 +29,17 @@ import io.swagger.v3.oas.annotations.media.Schema;
 import io.swagger.v3.oas.annotations.responses.ApiResponse;
 import io.swagger.v3.oas.annotations.servers.Server;
 import io.swagger.v3.oas.annotations.tags.Tag;
+import java.util.List;
+import javax.inject.Inject;
+import javax.servlet.ServletContext;
+import javax.servlet.http.HttpServletRequest;
+import javax.ws.rs.Consumes;
+import javax.ws.rs.GET;
+import javax.ws.rs.Path;
+import javax.ws.rs.Produces;
+import javax.ws.rs.core.Context;
+import javax.ws.rs.core.MediaType;
+import javax.ws.rs.core.Response;
 import org.apache.commons.lang3.tuple.Pair;
 import org.openecomp.sdc.be.components.health.HealthCheckBusinessLogic;
 import org.openecomp.sdc.be.config.BeEcompErrorManager;
@@ -42,18 +52,6 @@ import org.openecomp.sdc.common.api.HealthCheckWrapper;
 import org.openecomp.sdc.common.log.wrappers.Logger;
 import org.springframework.stereotype.Controller;
 
-import javax.inject.Inject;
-import javax.servlet.ServletContext;
-import javax.servlet.http.HttpServletRequest;
-import javax.ws.rs.Consumes;
-import javax.ws.rs.GET;
-import javax.ws.rs.Path;
-import javax.ws.rs.Produces;
-import javax.ws.rs.core.Context;
-import javax.ws.rs.core.MediaType;
-import javax.ws.rs.core.Response;
-import java.util.List;
-
 @Loggable(prepend = true, value = Loggable.TRACE, trim = false)
 @Path("/")
 @Tag(name = "SDC Internal APIs")
@@ -61,15 +59,13 @@ import java.util.List;
 @Controller
 public class BeMonitoringServlet extends BeGenericServlet {
 
-    private final Gson prettyGson = new GsonBuilder().setPrettyPrinting().create();
-
     private static final Logger log = Logger.getLogger(BeMonitoringServlet.class);
+    private final Gson prettyGson = new GsonBuilder().setPrettyPrinting().create();
     private final HealthCheckBusinessLogic healthCheckBusinessLogic;
 
     @Inject
-    public BeMonitoringServlet(UserBusinessLogic userBusinessLogic,
-        ComponentsUtils componentsUtils,
-        HealthCheckBusinessLogic healthCheckBusinessLogic){
+    public BeMonitoringServlet(UserBusinessLogic userBusinessLogic, ComponentsUtils componentsUtils,
+                               HealthCheckBusinessLogic healthCheckBusinessLogic) {
         super(userBusinessLogic, componentsUtils);
         this.healthCheckBusinessLogic = healthCheckBusinessLogic;
     }
@@ -78,11 +74,10 @@ public class BeMonitoringServlet extends BeGenericServlet {
     @Path("/healthCheck")
     @Consumes(MediaType.APPLICATION_JSON)
     @Produces(MediaType.APPLICATION_JSON)
-    @Operation(description = "Return aggregate BE health check of SDC BE components",
-            summary = "return BE health check", responses = {
-            @ApiResponse(content = @Content(array = @ArraySchema(schema = @Schema(implementation = String.class)))),
-            @ApiResponse(responseCode = "200", description = "SDC BE components are all up"),
-            @ApiResponse(responseCode = "500", description = "One or more SDC BE components are down")})
+    @Operation(description = "Return aggregate BE health check of SDC BE components", summary = "return BE health check", responses = {
+        @ApiResponse(content = @Content(array = @ArraySchema(schema = @Schema(implementation = String.class)))),
+        @ApiResponse(responseCode = "200", description = "SDC BE components are all up"),
+        @ApiResponse(responseCode = "500", description = "One or more SDC BE components are down")})
     public Response getHealthCheck(@Context final HttpServletRequest request) {
         try {
             Pair<Boolean, List<HealthCheckInfo>> beHealthCheckInfosStatus = healthCheckBusinessLogic.getBeHealthCheckInfosStatus();
@@ -95,11 +90,10 @@ public class BeMonitoringServlet extends BeGenericServlet {
             String siteMode = healthCheckBusinessLogic.getSiteMode();
             HealthCheckWrapper healthCheck = new HealthCheckWrapper(beHealthCheckInfosStatus.getRight(), sdcVersion, siteMode);
             // The response can be either with 200 or 500 aggregate status - the
-            // body of individual statuses is returned either way
 
+            // body of individual statuses is returned either way
             String healthCheckStr = prettyGson.toJson(healthCheck);
             return buildOkResponse(getComponentsUtils().getResponseFormat(status), healthCheckStr);
-
         } catch (Exception e) {
             BeEcompErrorManager.getInstance().logBeHealthCheckError("BeHealthCheck");
             log.debug("BE health check unexpected exception", e);
@@ -111,5 +105,4 @@ public class BeMonitoringServlet extends BeGenericServlet {
         ServletContext servletContext = request.getSession().getServletContext();
         return (String) servletContext.getAttribute(Constants.ASDC_RELEASE_VERSION_ATTR);
     }
-
 }
index a7f2230..3470d9f 100644 (file)
@@ -13,7 +13,6 @@
  * See the License for the specific language governing permissions and
  * limitations under the License.
  */
-
 package org.openecomp.sdc.be.servlets;
 
 import com.jcabi.aspects.Loggable;
@@ -28,6 +27,23 @@ import io.swagger.v3.oas.annotations.servers.Server;
 import io.swagger.v3.oas.annotations.servers.Servers;
 import io.swagger.v3.oas.annotations.tags.Tag;
 import io.swagger.v3.oas.annotations.tags.Tags;
+import java.util.List;
+import java.util.Optional;
+import javax.inject.Inject;
+import javax.servlet.ServletContext;
+import javax.servlet.http.HttpServletRequest;
+import javax.ws.rs.Consumes;
+import javax.ws.rs.DELETE;
+import javax.ws.rs.GET;
+import javax.ws.rs.HeaderParam;
+import javax.ws.rs.POST;
+import javax.ws.rs.PUT;
+import javax.ws.rs.Path;
+import javax.ws.rs.PathParam;
+import javax.ws.rs.Produces;
+import javax.ws.rs.core.Context;
+import javax.ws.rs.core.MediaType;
+import javax.ws.rs.core.Response;
 import org.openecomp.sdc.be.components.impl.CapabilitiesBusinessLogic;
 import org.openecomp.sdc.be.components.impl.ComponentInstanceBusinessLogic;
 import org.openecomp.sdc.be.components.impl.ResourceImportManager;
@@ -48,24 +64,6 @@ import org.openecomp.sdc.common.log.wrappers.Logger;
 import org.openecomp.sdc.exception.ResponseFormat;
 import org.springframework.stereotype.Controller;
 
-import javax.inject.Inject;
-import javax.servlet.ServletContext;
-import javax.servlet.http.HttpServletRequest;
-import javax.ws.rs.Consumes;
-import javax.ws.rs.DELETE;
-import javax.ws.rs.GET;
-import javax.ws.rs.HeaderParam;
-import javax.ws.rs.POST;
-import javax.ws.rs.PUT;
-import javax.ws.rs.Path;
-import javax.ws.rs.PathParam;
-import javax.ws.rs.Produces;
-import javax.ws.rs.core.Context;
-import javax.ws.rs.core.MediaType;
-import javax.ws.rs.core.Response;
-import java.util.List;
-import java.util.Optional;
-
 @Loggable(prepend = true, value = Loggable.DEBUG, trim = false)
 @Path("/v1/catalog")
 @Consumes(MediaType.APPLICATION_JSON)
@@ -74,78 +72,65 @@ import java.util.Optional;
 @Servers({@Server(url = "/sdc2/rest")})
 @Controller
 public class CapabilityServlet extends AbstractValidationsServlet {
+
     private static final Logger LOGGER = Logger.getLogger(CapabilityServlet.class);
     private final CapabilitiesBusinessLogic capabilitiesBusinessLogic;
 
     @Inject
-    public CapabilityServlet(UserBusinessLogic userBusinessLogic,
-        ComponentInstanceBusinessLogic componentInstanceBL,
-        ComponentsUtils componentsUtils, ServletUtils servletUtils,
-        ResourceImportManager resourceImportManager,
-        CapabilitiesBusinessLogic capabilitiesBusinessLogic) {
+    public CapabilityServlet(UserBusinessLogic userBusinessLogic, ComponentInstanceBusinessLogic componentInstanceBL, ComponentsUtils componentsUtils,
+                             ServletUtils servletUtils, ResourceImportManager resourceImportManager,
+                             CapabilitiesBusinessLogic capabilitiesBusinessLogic) {
         super(userBusinessLogic, componentInstanceBL, componentsUtils, servletUtils, resourceImportManager);
         this.capabilitiesBusinessLogic = capabilitiesBusinessLogic;
     }
 
-
     @POST
     @Consumes(MediaType.APPLICATION_JSON)
     @Produces(MediaType.APPLICATION_JSON)
     @Path("/resources/{resourceId}/capabilities")
-    @Operation(description = "Create Capabilities on resource", method = "POST",
-            summary = "Create Capabilities on resource", responses = {
-            @ApiResponse(content = @Content(array = @ArraySchema(schema = @Schema(implementation = Response.class)))),
-            @ApiResponse(responseCode = "201", description = "Create Capabilities"),
-            @ApiResponse(responseCode = "403", description = "Restricted operation"),
-            @ApiResponse(responseCode = "400", description = "Invalid content / Missing content"),
-            @ApiResponse(responseCode = "409", description = "Capability already exist")})
+    @Operation(description = "Create Capabilities on resource", method = "POST", summary = "Create Capabilities on resource", responses = {
+        @ApiResponse(content = @Content(array = @ArraySchema(schema = @Schema(implementation = Response.class)))),
+        @ApiResponse(responseCode = "201", description = "Create Capabilities"),
+        @ApiResponse(responseCode = "403", description = "Restricted operation"),
+        @ApiResponse(responseCode = "400", description = "Invalid content / Missing content"),
+        @ApiResponse(responseCode = "409", description = "Capability already exist")})
     @PermissionAllowed(AafPermission.PermNames.INTERNAL_ALL_VALUE)
-    public Response createCapabilitiesOnResource(
-            @Parameter(description = "Capability to create", required = true) String data,
-            @Parameter(description = "Resource Id") @PathParam("resourceId") String resourceId,
-            @Context final HttpServletRequest request,
-            @HeaderParam(value = Constants.USER_ID_HEADER) String userId) {
-        return createOrUpdate(data, "resources" , resourceId,
-                request, userId, false, "createCapabilities");
+    public Response createCapabilitiesOnResource(@Parameter(description = "Capability to create", required = true) String data,
+                                                 @Parameter(description = "Resource Id") @PathParam("resourceId") String resourceId,
+                                                 @Context final HttpServletRequest request,
+                                                 @HeaderParam(value = Constants.USER_ID_HEADER) String userId) {
+        return createOrUpdate(data, "resources", resourceId, request, userId, false, "createCapabilities");
     }
 
     @PUT
     @Consumes(MediaType.APPLICATION_JSON)
     @Produces(MediaType.APPLICATION_JSON)
     @Path("/resources/{resourceId}/capabilities")
-    @Operation(description = "Update Capabilities on resource", method = "PUT",
-            summary = "Update Capabilities on resource", responses = {@ApiResponse(
-            content = @Content(array = @ArraySchema(schema = @Schema(implementation = CapabilityDefinition.class)))),
-            @ApiResponse(responseCode = "201", description = "Update Capabilities"),
-            @ApiResponse(responseCode = "403", description = "Restricted operation"),
-            @ApiResponse(responseCode = "400", description = "Invalid content / Missing content")})
+    @Operation(description = "Update Capabilities on resource", method = "PUT", summary = "Update Capabilities on resource", responses = {
+        @ApiResponse(content = @Content(array = @ArraySchema(schema = @Schema(implementation = CapabilityDefinition.class)))),
+        @ApiResponse(responseCode = "201", description = "Update Capabilities"),
+        @ApiResponse(responseCode = "403", description = "Restricted operation"),
+        @ApiResponse(responseCode = "400", description = "Invalid content / Missing content")})
     @PermissionAllowed(AafPermission.PermNames.INTERNAL_ALL_VALUE)
-    public Response updateCapabilitiesOnResource(
-            @Parameter(description = "Capabilities to update", required = true) String data,
-            @Parameter(description = "Component Id") @PathParam("resourceId") String resourceId,
-            @Context final HttpServletRequest request,
-            @HeaderParam(value = Constants.USER_ID_HEADER) String userId) {
-        return createOrUpdate(data, "resources", resourceId,
-                request, userId, true, "updateCapabilities");
+    public Response updateCapabilitiesOnResource(@Parameter(description = "Capabilities to update", required = true) String data,
+                                                 @Parameter(description = "Component Id") @PathParam("resourceId") String resourceId,
+                                                 @Context final HttpServletRequest request,
+                                                 @HeaderParam(value = Constants.USER_ID_HEADER) String userId) {
+        return createOrUpdate(data, "resources", resourceId, request, userId, true, "updateCapabilities");
     }
 
     @GET
     @Consumes(MediaType.APPLICATION_JSON)
     @Produces(MediaType.APPLICATION_JSON)
     @Path("/resources/{resourceId}/capabilities/{capabilityId}")
-    @Operation(description = "Get Capability from resource", method = "GET", summary = "GET Capability from resource",
-            responses = {@ApiResponse(content = @Content(
-                    array = @ArraySchema(schema = @Schema(implementation = CapabilityDefinition.class)))),
-                    @ApiResponse(responseCode = "201", description = "GET Capability"),
-                    @ApiResponse(responseCode = "403", description = "Restricted operation"),
-                    @ApiResponse(responseCode = "400", description = "Invalid content / Missing content")})
+    @Operation(description = "Get Capability from resource", method = "GET", summary = "GET Capability from resource", responses = {
+        @ApiResponse(content = @Content(array = @ArraySchema(schema = @Schema(implementation = CapabilityDefinition.class)))),
+        @ApiResponse(responseCode = "201", description = "GET Capability"), @ApiResponse(responseCode = "403", description = "Restricted operation"),
+        @ApiResponse(responseCode = "400", description = "Invalid content / Missing content")})
     @PermissionAllowed(AafPermission.PermNames.INTERNAL_ALL_VALUE)
-    public Response getCapabilityOnResource(
-            @Parameter(description = "Resource Id") @PathParam("resourceId") String resourceId,
-            @Parameter(description = "Capability Id") @PathParam("capabilityId") String capabilityId,
-            @Context final HttpServletRequest request,
-            @HeaderParam(value = Constants.USER_ID_HEADER) String userId) {
-
+    public Response getCapabilityOnResource(@Parameter(description = "Resource Id") @PathParam("resourceId") String resourceId,
+                                            @Parameter(description = "Capability Id") @PathParam("capabilityId") String capabilityId,
+                                            @Context final HttpServletRequest request, @HeaderParam(value = Constants.USER_ID_HEADER) String userId) {
         return get(capabilityId, resourceId, request, userId);
     }
 
@@ -153,18 +138,16 @@ public class CapabilityServlet extends AbstractValidationsServlet {
     @Consumes(MediaType.APPLICATION_JSON)
     @Produces(MediaType.APPLICATION_JSON)
     @Path("/resources/{resourceId}/capabilities/{capabilityId}")
-    @Operation(description = "Delete capability from resource", method = "DELETE",
-            summary = "Delete capability from resource", responses = {@ApiResponse(
-            content = @Content(array = @ArraySchema(schema = @Schema(implementation = CapabilityDefinition.class)))),
-            @ApiResponse(responseCode = "201", description = "Delete capability"),
-            @ApiResponse(responseCode = "403", description = "Restricted operation"),
-            @ApiResponse(responseCode = "400", description = "Invalid content / Missing content")})
+    @Operation(description = "Delete capability from resource", method = "DELETE", summary = "Delete capability from resource", responses = {
+        @ApiResponse(content = @Content(array = @ArraySchema(schema = @Schema(implementation = CapabilityDefinition.class)))),
+        @ApiResponse(responseCode = "201", description = "Delete capability"),
+        @ApiResponse(responseCode = "403", description = "Restricted operation"),
+        @ApiResponse(responseCode = "400", description = "Invalid content / Missing content")})
     @PermissionAllowed(AafPermission.PermNames.INTERNAL_ALL_VALUE)
-    public Response deleteCapabilityOnResource(
-            @Parameter(description = "capability Id") @PathParam("capabilityId") String capabilityId,
-            @Parameter(description = "Resource Id") @PathParam("resourceId") String resourceId,
-            @Context final HttpServletRequest request,
-            @HeaderParam(value = Constants.USER_ID_HEADER) String userId) {
+    public Response deleteCapabilityOnResource(@Parameter(description = "capability Id") @PathParam("capabilityId") String capabilityId,
+                                               @Parameter(description = "Resource Id") @PathParam("resourceId") String resourceId,
+                                               @Context final HttpServletRequest request,
+                                               @HeaderParam(value = Constants.USER_ID_HEADER) String userId) {
         return delete(capabilityId, resourceId, request, userId);
     }
 
@@ -172,60 +155,49 @@ public class CapabilityServlet extends AbstractValidationsServlet {
     @Consumes(MediaType.APPLICATION_JSON)
     @Produces(MediaType.APPLICATION_JSON)
     @Path("/services/{serviceId}/capabilities")
-    @Operation(description = "Create Capabilities on service", method = "POST",
-            summary = "Create Capabilities on service", responses = {
-            @ApiResponse(content = @Content(array = @ArraySchema(schema = @Schema(implementation = Response.class)))),
-            @ApiResponse(responseCode = "201", description = "Create Capabilities"),
-            @ApiResponse(responseCode = "403", description = "Restricted operation"),
-            @ApiResponse(responseCode = "400", description = "Invalid content / Missing content"),
-            @ApiResponse(responseCode = "409", description = "Capability already exist")})
+    @Operation(description = "Create Capabilities on service", method = "POST", summary = "Create Capabilities on service", responses = {
+        @ApiResponse(content = @Content(array = @ArraySchema(schema = @Schema(implementation = Response.class)))),
+        @ApiResponse(responseCode = "201", description = "Create Capabilities"),
+        @ApiResponse(responseCode = "403", description = "Restricted operation"),
+        @ApiResponse(responseCode = "400", description = "Invalid content / Missing content"),
+        @ApiResponse(responseCode = "409", description = "Capability already exist")})
     @PermissionAllowed(AafPermission.PermNames.INTERNAL_ALL_VALUE)
-    public Response createCapabilitiesOnService(
-            @Parameter(description = "Capability to create", required = true) String data,
-            @Parameter(description = "Service Id") @PathParam("serviceId") String serviceId,
-            @Context final HttpServletRequest request,
-            @HeaderParam(value = Constants.USER_ID_HEADER) String userId) {
-        return createOrUpdate(data, "services" , serviceId,
-                request, userId, false, "createCapabilities");
+    public Response createCapabilitiesOnService(@Parameter(description = "Capability to create", required = true) String data,
+                                                @Parameter(description = "Service Id") @PathParam("serviceId") String serviceId,
+                                                @Context final HttpServletRequest request,
+                                                @HeaderParam(value = Constants.USER_ID_HEADER) String userId) {
+        return createOrUpdate(data, "services", serviceId, request, userId, false, "createCapabilities");
     }
 
     @PUT
     @Consumes(MediaType.APPLICATION_JSON)
     @Produces(MediaType.APPLICATION_JSON)
     @Path("/services/{serviceId}/capabilities")
-    @Operation(description = "Update Capabilities on service", method = "PUT",
-            summary = "Update Capabilities on service", responses = {@ApiResponse(
-            content = @Content(array = @ArraySchema(schema = @Schema(implementation = CapabilityDefinition.class)))),
-            @ApiResponse(responseCode = "201", description = "Update Capabilities"),
-            @ApiResponse(responseCode = "403", description = "Restricted operation"),
-            @ApiResponse(responseCode = "400", description = "Invalid content / Missing content")})
+    @Operation(description = "Update Capabilities on service", method = "PUT", summary = "Update Capabilities on service", responses = {
+        @ApiResponse(content = @Content(array = @ArraySchema(schema = @Schema(implementation = CapabilityDefinition.class)))),
+        @ApiResponse(responseCode = "201", description = "Update Capabilities"),
+        @ApiResponse(responseCode = "403", description = "Restricted operation"),
+        @ApiResponse(responseCode = "400", description = "Invalid content / Missing content")})
     @PermissionAllowed(AafPermission.PermNames.INTERNAL_ALL_VALUE)
-    public Response updateCapabilitiesOnService(
-            @Parameter(description = "Capabilities to update", required = true) String data,
-            @Parameter(description = "Component Id") @PathParam("serviceId") String serviceId,
-            @Context final HttpServletRequest request,
-            @HeaderParam(value = Constants.USER_ID_HEADER) String userId) {
-        return createOrUpdate(data, "services", serviceId,
-                request, userId, true, "updateCapabilities");
+    public Response updateCapabilitiesOnService(@Parameter(description = "Capabilities to update", required = true) String data,
+                                                @Parameter(description = "Component Id") @PathParam("serviceId") String serviceId,
+                                                @Context final HttpServletRequest request,
+                                                @HeaderParam(value = Constants.USER_ID_HEADER) String userId) {
+        return createOrUpdate(data, "services", serviceId, request, userId, true, "updateCapabilities");
     }
 
     @GET
     @Consumes(MediaType.APPLICATION_JSON)
     @Produces(MediaType.APPLICATION_JSON)
     @Path("/services/{serviceId}/capabilities/{capabilityId}")
-    @Operation(description = "Get Capability from service", method = "GET", summary = "GET Capability from service",
-            responses = {@ApiResponse(content = @Content(
-                    array = @ArraySchema(schema = @Schema(implementation = CapabilityDefinition.class)))),
-                    @ApiResponse(responseCode = "201", description = "GET Capability"),
-                    @ApiResponse(responseCode = "403", description = "Restricted operation"),
-                    @ApiResponse(responseCode = "400", description = "Invalid content / Missing content")})
+    @Operation(description = "Get Capability from service", method = "GET", summary = "GET Capability from service", responses = {
+        @ApiResponse(content = @Content(array = @ArraySchema(schema = @Schema(implementation = CapabilityDefinition.class)))),
+        @ApiResponse(responseCode = "201", description = "GET Capability"), @ApiResponse(responseCode = "403", description = "Restricted operation"),
+        @ApiResponse(responseCode = "400", description = "Invalid content / Missing content")})
     @PermissionAllowed(AafPermission.PermNames.INTERNAL_ALL_VALUE)
-    public Response getCapabilityOnService(
-            @Parameter(description = "Service Id") @PathParam("serviceId") String serviceId,
-            @Parameter(description = "Capability Id") @PathParam("capabilityId") String capabilityId,
-            @Context final HttpServletRequest request,
-            @HeaderParam(value = Constants.USER_ID_HEADER) String userId) {
-
+    public Response getCapabilityOnService(@Parameter(description = "Service Id") @PathParam("serviceId") String serviceId,
+                                           @Parameter(description = "Capability Id") @PathParam("capabilityId") String capabilityId,
+                                           @Context final HttpServletRequest request, @HeaderParam(value = Constants.USER_ID_HEADER) String userId) {
         return get(capabilityId, serviceId, request, userId);
     }
 
@@ -233,56 +205,46 @@ public class CapabilityServlet extends AbstractValidationsServlet {
     @Consumes(MediaType.APPLICATION_JSON)
     @Produces(MediaType.APPLICATION_JSON)
     @Path("/services/{serviceId}/capabilities/{capabilityId}")
-    @Operation(description = "Delete capability from service", method = "DELETE",
-            summary = "Delete capability from service", responses = {@ApiResponse(
-            content = @Content(array = @ArraySchema(schema = @Schema(implementation = CapabilityDefinition.class)))),
-            @ApiResponse(responseCode = "201", description = "Delete capability"),
-            @ApiResponse(responseCode = "403", description = "Restricted operation"),
-            @ApiResponse(responseCode = "400", description = "Invalid content / Missing content")})
+    @Operation(description = "Delete capability from service", method = "DELETE", summary = "Delete capability from service", responses = {
+        @ApiResponse(content = @Content(array = @ArraySchema(schema = @Schema(implementation = CapabilityDefinition.class)))),
+        @ApiResponse(responseCode = "201", description = "Delete capability"),
+        @ApiResponse(responseCode = "403", description = "Restricted operation"),
+        @ApiResponse(responseCode = "400", description = "Invalid content / Missing content")})
     @PermissionAllowed(AafPermission.PermNames.INTERNAL_ALL_VALUE)
-    public Response deleteCapabilityOnService(
-            @Parameter(description = "capability Id") @PathParam("capabilityId") String capabilityId,
-            @Parameter(description = "Service Id") @PathParam("serviceId") String serviceId,
-            @Context final HttpServletRequest request,
-            @HeaderParam(value = Constants.USER_ID_HEADER) String userId) {
+    public Response deleteCapabilityOnService(@Parameter(description = "capability Id") @PathParam("capabilityId") String capabilityId,
+                                              @Parameter(description = "Service Id") @PathParam("serviceId") String serviceId,
+                                              @Context final HttpServletRequest request,
+                                              @HeaderParam(value = Constants.USER_ID_HEADER) String userId) {
         return delete(capabilityId, serviceId, request, userId);
     }
 
-    private Response createOrUpdate (String data, String componentType, String componentId,
-                                     HttpServletRequest request,
-                                     String userId,
-                                     boolean isUpdate,
-                                     String errorContext) {
+    private Response createOrUpdate(String data, String componentType, String componentId, HttpServletRequest request, String userId,
+                                    boolean isUpdate, String errorContext) {
         ServletContext context = request.getSession().getServletContext();
         String url = request.getMethod() + " " + request.getRequestURI();
-
         User modifier = new User();
         modifier.setUserId(userId);
         LOGGER.debug("Start create or update request of {} with modifier id {}", url, userId);
         try {
             String componentIdLower = componentId.toLowerCase();
-
-            Either<List<CapabilityDefinition>, ResponseFormat> mappedCapabilitiesDataEither
-                    = getMappedCapabilitiesData(data, modifier, ComponentTypeEnum.findByParamName(componentType));
-            if(mappedCapabilitiesDataEither.isRight()) {
+            Either<List<CapabilityDefinition>, ResponseFormat> mappedCapabilitiesDataEither = getMappedCapabilitiesData(data, modifier,
+                ComponentTypeEnum.findByParamName(componentType));
+            if (mappedCapabilitiesDataEither.isRight()) {
                 LOGGER.error("Failed to create or update capabilities");
                 return buildErrorResponse(mappedCapabilitiesDataEither.right().value());
             }
             List<CapabilityDefinition> mappedCapabilitiesData = mappedCapabilitiesDataEither.left().value();
             Either<List<CapabilityDefinition>, ResponseFormat> actionResponse;
-            if(isUpdate) {
-                actionResponse = capabilitiesBusinessLogic.updateCapabilities(componentIdLower,
-                        mappedCapabilitiesData, modifier, errorContext, true);
+            if (isUpdate) {
+                actionResponse = capabilitiesBusinessLogic.updateCapabilities(componentIdLower, mappedCapabilitiesData, modifier, errorContext, true);
             } else {
-                actionResponse = capabilitiesBusinessLogic.createCapabilities(componentIdLower,
-                        mappedCapabilitiesData, modifier, errorContext, true);
+                actionResponse = capabilitiesBusinessLogic.createCapabilities(componentIdLower, mappedCapabilitiesData, modifier, errorContext, true);
             }
             if (actionResponse.isRight()) {
                 LOGGER.error("Failed to create or update capabilities");
                 return buildErrorResponse(actionResponse.right().value());
             }
-            return buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK),
-                    actionResponse.left().value());
+            return buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), actionResponse.left().value());
         } catch (Exception e) {
             BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Capabilities create or update");
             LOGGER.error("Failed to create or update capabilities with an error", e);
@@ -290,20 +252,16 @@ public class CapabilityServlet extends AbstractValidationsServlet {
         }
     }
 
-    private Response get (String capabilityIdToGet,  String componentId,
-                          HttpServletRequest request, String userId){
+    private Response get(String capabilityIdToGet, String componentId, HttpServletRequest request, String userId) {
         ServletContext context = request.getSession().getServletContext();
         String url = request.getMethod() + " " + request.getRequestURI();
-
         User modifier = new User();
         modifier.setUserId(userId);
         LOGGER.debug("Start get request of {} with modifier id {}", url, userId);
-
         try {
             String componentIdLower = componentId.toLowerCase();
-
             Either<CapabilityDefinition, ResponseFormat> actionResponse = capabilitiesBusinessLogic
-                    .getCapability(componentIdLower, capabilityIdToGet, modifier, true);
+                .getCapability(componentIdLower, capabilityIdToGet, modifier, true);
             if (actionResponse.isRight()) {
                 LOGGER.error("failed to get capability");
                 return buildErrorResponse(actionResponse.right().value());
@@ -317,21 +275,16 @@ public class CapabilityServlet extends AbstractValidationsServlet {
         }
     }
 
-    private Response delete (String capabilityId, String componentId, HttpServletRequest
-            request, String userId){
-
+    private Response delete(String capabilityId, String componentId, HttpServletRequest request, String userId) {
         ServletContext context = request.getSession().getServletContext();
         String url = request.getMethod() + " " + request.getRequestURI();
-
         User modifier = new User();
         modifier.setUserId(userId);
         LOGGER.debug("Start delete request of {} with modifier id {}", url, userId);
-
         try {
             String componentIdLower = componentId.toLowerCase();
-
             Either<CapabilityDefinition, ResponseFormat> actionResponse = capabilitiesBusinessLogic
-                    .deleteCapability(componentIdLower, capabilityId, modifier, true);
+                .deleteCapability(componentIdLower, capabilityId, modifier, true);
             if (actionResponse.isRight()) {
                 LOGGER.error("failed to delete capability");
                 return buildErrorResponse(actionResponse.right().value());
@@ -346,18 +299,15 @@ public class CapabilityServlet extends AbstractValidationsServlet {
     }
 
     private Either<List<CapabilityDefinition>, ResponseFormat> getMappedCapabilitiesData(String inputJson, User user,
-                                                                 ComponentTypeEnum componentTypeEnum){
+                                                                                         ComponentTypeEnum componentTypeEnum) {
         Either<UiComponentDataTransfer, ResponseFormat> mappedData = getComponentsUtils()
-                .convertJsonToObjectUsingObjectMapper(inputJson, user, UiComponentDataTransfer.class,
-                        AuditingActionEnum.CREATE_RESOURCE, componentTypeEnum);
+            .convertJsonToObjectUsingObjectMapper(inputJson, user, UiComponentDataTransfer.class, AuditingActionEnum.CREATE_RESOURCE,
+                componentTypeEnum);
         if (mappedData.isRight()) {
-            return Either.right(getComponentsUtils()
-                .getResponseFormat(ActionStatus.INVALID_CONTENT));
+            return Either.right(getComponentsUtils().getResponseFormat(ActionStatus.INVALID_CONTENT));
         }
-        Optional<List<CapabilityDefinition>> capabilityDefinitionList =
-                mappedData.left().value().getCapabilities().values().stream().findFirst();
-        return capabilityDefinitionList.<Either<List<CapabilityDefinition>, ResponseFormat>>
-                map(Either::left).orElseGet(() -> Either.right(getComponentsUtils()
-                .getResponseFormat(ActionStatus.GENERAL_ERROR)));
+        Optional<List<CapabilityDefinition>> capabilityDefinitionList = mappedData.left().value().getCapabilities().values().stream().findFirst();
+        return capabilityDefinitionList.<Either<List<CapabilityDefinition>, ResponseFormat>>map(Either::left)
+            .orElseGet(() -> Either.right(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR)));
     }
 }
index 19df0e2..461ddef 100644 (file)
@@ -17,7 +17,6 @@
  * limitations under the License.
  * ============LICENSE_END=========================================================
  */
-
 package org.openecomp.sdc.be.servlets;
 
 import com.jcabi.aspects.Loggable;
@@ -63,37 +62,31 @@ import org.slf4j.LoggerFactory;
 @Singleton
 public class ComponentAttributeServlet extends BeGenericServlet {
 
+    private static final Logger log = LoggerFactory.getLogger(ComponentAttributeServlet.class);
+    private static final String CREATE_ATTRIBUTE = "Create Attribute";
+    private static final String DEBUG_MESSAGE = "Start handle request of {} modifier id is {}";
     private final AttributeBusinessLogic attributeBusinessLogic;
 
     @Inject
-    public ComponentAttributeServlet(final UserBusinessLogic userBusinessLogic,
-                                     final ComponentsUtils componentsUtils,
+    public ComponentAttributeServlet(final UserBusinessLogic userBusinessLogic, final ComponentsUtils componentsUtils,
                                      final AttributeBusinessLogic attributeBusinessLogic) {
         super(userBusinessLogic, componentsUtils);
         this.attributeBusinessLogic = attributeBusinessLogic;
     }
 
-    private static final Logger log = LoggerFactory.getLogger(ComponentAttributeServlet.class);
-    private static final String CREATE_ATTRIBUTE = "Create Attribute";
-    private static final String DEBUG_MESSAGE = "Start handle request of {} modifier id is {}";
-
     @GET
     @Path("services/{serviceId}/attributes")
     @Consumes(MediaType.APPLICATION_JSON)
     @Produces(MediaType.APPLICATION_JSON)
-    @Operation(description = "Get Service Attribute", method = "GET", summary = "Returns attribute list of service",
-        responses = {@ApiResponse(
-            content = @Content(array = @ArraySchema(schema = @Schema(implementation = Response.class)))),
-            @ApiResponse(responseCode = "200", description = "attribute"),
-            @ApiResponse(responseCode = "403", description = "Restricted operation"),
-            @ApiResponse(responseCode = "400", description = "Invalid content / Missing content"),
-            @ApiResponse(responseCode = "404", description = "Service attribute not found")})
+    @Operation(description = "Get Service Attribute", method = "GET", summary = "Returns attribute list of service", responses = {
+        @ApiResponse(content = @Content(array = @ArraySchema(schema = @Schema(implementation = Response.class)))),
+        @ApiResponse(responseCode = "200", description = "attribute"), @ApiResponse(responseCode = "403", description = "Restricted operation"),
+        @ApiResponse(responseCode = "400", description = "Invalid content / Missing content"),
+        @ApiResponse(responseCode = "404", description = "Service attribute not found")})
     @PermissionAllowed(AafPermission.PermNames.INTERNAL_ALL_VALUE)
     public Response getAttributeListInService(
-        @Parameter(description = "service id of attribute",
-            required = true) @PathParam("serviceId") final String serviceId,
+        @Parameter(description = "service id of attribute", required = true) @PathParam("serviceId") final String serviceId,
         @Context final HttpServletRequest request, @HeaderParam(value = Constants.USER_ID_HEADER) final String userId) {
-
         return getAttributeList(serviceId, request, userId);
     }
 
@@ -101,42 +94,31 @@ public class ComponentAttributeServlet extends BeGenericServlet {
     @Path("resources/{resourceId}/attributes")
     @Consumes(MediaType.APPLICATION_JSON)
     @Produces(MediaType.APPLICATION_JSON)
-    @Operation(description = "Get Resource Attribute", method = "GET", summary = "Returns attribute list of resource",
-        responses = {@ApiResponse(
-            content = @Content(array = @ArraySchema(schema = @Schema(implementation = Response.class)))),
-            @ApiResponse(responseCode = "200", description = "attribute"),
-            @ApiResponse(responseCode = "403", description = "Restricted operation"),
-            @ApiResponse(responseCode = "400", description = "Invalid content / Missing content"),
-            @ApiResponse(responseCode = "404", description = "Resource attribute not found")})
+    @Operation(description = "Get Resource Attribute", method = "GET", summary = "Returns attribute list of resource", responses = {
+        @ApiResponse(content = @Content(array = @ArraySchema(schema = @Schema(implementation = Response.class)))),
+        @ApiResponse(responseCode = "200", description = "attribute"), @ApiResponse(responseCode = "403", description = "Restricted operation"),
+        @ApiResponse(responseCode = "400", description = "Invalid content / Missing content"),
+        @ApiResponse(responseCode = "404", description = "Resource attribute not found")})
     @PermissionAllowed(AafPermission.PermNames.INTERNAL_ALL_VALUE)
     public Response getAttributeListInResource(
-        @Parameter(description = "resource id of attribute",
-            required = true) @PathParam("resourceId") final String resourceId,
+        @Parameter(description = "resource id of attribute", required = true) @PathParam("resourceId") final String resourceId,
         @Context final HttpServletRequest request, @HeaderParam(value = Constants.USER_ID_HEADER) final String userId) {
-
         return getAttributeList(resourceId, request, userId);
     }
 
     private Response getAttributeList(final String componentId, final HttpServletRequest request, final String userId) {
-
         final String url = request.getMethod() + " " + request.getRequestURI();
         log.debug(DEBUG_MESSAGE, url, userId);
-
         try {
-            final Either<List<AttributeDefinition>, ResponseFormat> attributesList =
-                attributeBusinessLogic.getAttributesList(componentId, userId);
-
+            final Either<List<AttributeDefinition>, ResponseFormat> attributesList = attributeBusinessLogic.getAttributesList(componentId, userId);
             if (attributesList.isRight()) {
                 return buildErrorResponse(attributesList.right().value());
             }
-
             return buildOkResponse(attributesList.left().value());
-
         } catch (final Exception e) {
             BeEcompErrorManager.getInstance().logBeRestApiGeneralError(CREATE_ATTRIBUTE);
             log.debug("get attribute failed with exception", e);
             return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR));
         }
     }
-
 }
index 49d89c1..84cb10b 100644 (file)
@@ -17,7 +17,6 @@
  * limitations under the License.
  * ============LICENSE_END=========================================================
  */
-
 package org.openecomp.sdc.be.servlets;
 
 import com.fasterxml.jackson.core.JsonProcessingException;
@@ -117,34 +116,32 @@ import org.springframework.stereotype.Controller;
 public class ComponentInstanceServlet extends AbstractValidationsServlet {
 
     private static final String FAILED_TO_GET_PROPERTIES_OF_COMPONENT_INSTANCE_ID_IN_WITH_ID = "Failed to get properties of component instance ID: {} in {} with ID: {}";
-       private static final String GET_GROUP_ARTIFACT_BY_ID = "getGroupArtifactById";
-       private static final String GET_GROUP_ARTIFACT_BY_ID_UNEXPECTED_EXCEPTION = "getGroupArtifactById unexpected exception";
-       private static final String GET_START_HANDLE_REQUEST_OF = "(GET) Start handle request of {}";
-       private static final String START_HANDLE_REQUEST_OF_UPDATE_RESOURCE_INSTANCE_PROPERTY_RECEIVED_PROPERTY_IS = "Start handle request of updateResourceInstanceProperty. Received property is {}";
-       private static final String UPDATE_RESOURCE_INSTANCE = "Update Resource Instance";
-       private static final String RESOURCE_INSTANCE_UPDATE_RESOURCE_INSTANCE = "Resource Instance - updateResourceInstance";
-       private static final String UPDATE_RESOURCE_INSTANCE_WITH_EXCEPTION = "update resource instance with exception";
-       private static final String FAILED_TO_CONVERT_RECEIVED_DATA_TO_BE_FORMAT = "Failed to convert received data to BE format.";
-       private static final String EMPTY_BODY_WAS_SENT = "Empty body was sent.";
-       private static final String START_HANDLE_REQUEST_OF = "Start handle request of {}";
-       private static final String UNSUPPORTED_COMPONENT_TYPE = "Unsupported component type {}";
+    private static final String GET_GROUP_ARTIFACT_BY_ID = "getGroupArtifactById";
+    private static final String GET_GROUP_ARTIFACT_BY_ID_UNEXPECTED_EXCEPTION = "getGroupArtifactById unexpected exception";
+    private static final String GET_START_HANDLE_REQUEST_OF = "(GET) Start handle request of {}";
+    private static final String START_HANDLE_REQUEST_OF_UPDATE_RESOURCE_INSTANCE_PROPERTY_RECEIVED_PROPERTY_IS = "Start handle request of updateResourceInstanceProperty. Received property is {}";
+    private static final String UPDATE_RESOURCE_INSTANCE = "Update Resource Instance";
+    private static final String RESOURCE_INSTANCE_UPDATE_RESOURCE_INSTANCE = "Resource Instance - updateResourceInstance";
+    private static final String UPDATE_RESOURCE_INSTANCE_WITH_EXCEPTION = "update resource instance with exception";
+    private static final String FAILED_TO_CONVERT_RECEIVED_DATA_TO_BE_FORMAT = "Failed to convert received data to BE format.";
+    private static final String EMPTY_BODY_WAS_SENT = "Empty body was sent.";
+    private static final String START_HANDLE_REQUEST_OF = "Start handle request of {}";
+    private static final String UNSUPPORTED_COMPONENT_TYPE = "Unsupported component type {}";
     private static final String CREATE_AND_ASSOCIATE_RI_FAILED_WITH_EXCEPTION = "create and associate RI failed with exception: {}";
-       private static final Logger log = Logger.getLogger(ComponentInstanceServlet.class);
-    private static final Type PROPERTY_CONSTRAINT_TYPE = new TypeToken<PropertyConstraint>() {}.getType();
-    private static final Gson gsonDeserializer = new GsonBuilder().registerTypeAdapter(PROPERTY_CONSTRAINT_TYPE, new PropertyConstraintDeserialiser()).create();
+    private static final Logger log = Logger.getLogger(ComponentInstanceServlet.class);
+    private static final Type PROPERTY_CONSTRAINT_TYPE = new TypeToken<PropertyConstraint>() {
+    }.getType();
+    private static final Gson gsonDeserializer = new GsonBuilder().registerTypeAdapter(PROPERTY_CONSTRAINT_TYPE, new PropertyConstraintDeserialiser())
+        .create();
     private static final LoggerSupportability loggerSupportability = LoggerSupportability.getLogger(ComponentInstanceServlet.class.getName());
     private static final String SERVICES = "services";
-
     private final GroupBusinessLogic groupBL;
     private final ComponentNodeFilterBusinessLogic nodeFilterBusinessLogic;
 
-
     @Inject
-    public ComponentInstanceServlet(UserBusinessLogic userBusinessLogic,
-                                    GroupBusinessLogic groupBL, ComponentInstanceBusinessLogic componentInstanceBL,
-                                    ComponentsUtils componentsUtils, ServletUtils servletUtils,
-                                    ResourceImportManager resourceImportManager,
-                                    ComponentNodeFilterBusinessLogic nodeFilterBusinessLogic) {
+    public ComponentInstanceServlet(UserBusinessLogic userBusinessLogic, GroupBusinessLogic groupBL,
+                                    ComponentInstanceBusinessLogic componentInstanceBL, ComponentsUtils componentsUtils, ServletUtils servletUtils,
+                                    ResourceImportManager resourceImportManager, ComponentNodeFilterBusinessLogic nodeFilterBusinessLogic) {
         super(userBusinessLogic, componentInstanceBL, componentsUtils, servletUtils, resourceImportManager);
         this.groupBL = groupBL;
         this.nodeFilterBusinessLogic = nodeFilterBusinessLogic;
@@ -154,23 +151,20 @@ public class ComponentInstanceServlet extends AbstractValidationsServlet {
     @Path("/{containerComponentType}/{componentId}/resourceInstance")
     @Consumes(MediaType.APPLICATION_JSON)
     @Produces(MediaType.APPLICATION_JSON)
-    @Operation(description = "Create ComponentInstance", method = "POST", summary = "Returns created ComponentInstance",
-            responses = {@ApiResponse(
-                    content = @Content(array = @ArraySchema(schema = @Schema(implementation = Response.class)))),
-                    @ApiResponse(responseCode = "201", description = "Component created"),
-                    @ApiResponse(responseCode = "403", description = "Restricted operation"),
-                    @ApiResponse(responseCode = "400", description = "Invalid content / Missing content"),
-                    @ApiResponse(responseCode = "409", description = "Component instance already exist")})
+    @Operation(description = "Create ComponentInstance", method = "POST", summary = "Returns created ComponentInstance", responses = {
+        @ApiResponse(content = @Content(array = @ArraySchema(schema = @Schema(implementation = Response.class)))),
+        @ApiResponse(responseCode = "201", description = "Component created"),
+        @ApiResponse(responseCode = "403", description = "Restricted operation"),
+        @ApiResponse(responseCode = "400", description = "Invalid content / Missing content"),
+        @ApiResponse(responseCode = "409", description = "Component instance already exist")})
     @PermissionAllowed(AafPermission.PermNames.INTERNAL_ALL_VALUE)
     public Response createComponentInstance(@Parameter(description = "RI object to be created", required = true) String data,
-            @PathParam("componentId") final String containerComponentId,
-            @Parameter(description = "valid values: resources / services",
-                    schema = @Schema(allowableValues = {ComponentTypeEnum.RESOURCE_PARAM_NAME ,
-                            ComponentTypeEnum.SERVICE_PARAM_NAME})) @PathParam("containerComponentType") final String containerComponentType,
-            @HeaderParam(value = Constants.USER_ID_HEADER) @Parameter(description = "USER_ID of modifier user",
-                    required = true) String userId,
-            @Context final HttpServletRequest request) {
-
+                                            @PathParam("componentId") final String containerComponentId,
+                                            @Parameter(description = "valid values: resources / services", schema = @Schema(allowableValues = {
+                                                ComponentTypeEnum.RESOURCE_PARAM_NAME,
+                                                ComponentTypeEnum.SERVICE_PARAM_NAME})) @PathParam("containerComponentType") final String containerComponentType,
+                                            @HeaderParam(value = Constants.USER_ID_HEADER) @Parameter(description = "USER_ID of modifier user", required = true) String userId,
+                                            @Context final HttpServletRequest request) {
         validateNotEmptyBody(data);
         final ComponentInstance componentInstance;
         try {
@@ -180,64 +174,53 @@ public class ComponentInstanceServlet extends AbstractValidationsServlet {
         } catch (final Exception e) {
             BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Create Component Instance");
             log.debug("create component instance failed with exception", e);
-            return buildErrorResponse(
-                getComponentsUtils().getResponseFormat(ActionStatus.INVALID_CONTENT, containerComponentType));
+            return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.INVALID_CONTENT, containerComponentType));
         }
-
-        loggerSupportability.log(LoggerSupportabilityActions.CREATE_INSTANCE, StatusCode.STARTED,
-            "Starting to create component instance by {}", userId);
+        loggerSupportability
+            .log(LoggerSupportabilityActions.CREATE_INSTANCE, StatusCode.STARTED, "Starting to create component instance by {}", userId);
         if (componentInstanceBusinessLogic == null) {
             log.debug(UNSUPPORTED_COMPONENT_TYPE, containerComponentType);
-            return buildErrorResponse(
-                getComponentsUtils().getResponseFormat(ActionStatus.UNSUPPORTED_ERROR, containerComponentType));
+            return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.UNSUPPORTED_ERROR, containerComponentType));
         }
-        final ComponentInstance actionResponse = componentInstanceBusinessLogic.
-            createComponentInstance(containerComponentType, containerComponentId, userId, componentInstance);
-        loggerSupportability
-            .log(LoggerSupportabilityActions.CREATE_INSTANCE, actionResponse.getComponentMetadataForSupportLog(),
-                StatusCode.COMPLETE, "Ending to create component instance by user {}", userId);
+        final ComponentInstance actionResponse = componentInstanceBusinessLogic
+            .createComponentInstance(containerComponentType, containerComponentId, userId, componentInstance);
+        loggerSupportability.log(LoggerSupportabilityActions.CREATE_INSTANCE, actionResponse.getComponentMetadataForSupportLog(), StatusCode.COMPLETE,
+            "Ending to create component instance by user {}", userId);
         return buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.CREATED), actionResponse);
-
     }
 
     @POST
     @Path("/{containerComponentType}/{componentId}/resourceInstance/{componentInstanceId}")
     @Consumes(MediaType.APPLICATION_JSON)
     @Produces(MediaType.APPLICATION_JSON)
-    @Operation(description = "Update resource instance", method = "POST", summary = "Returns updated resource instance",
-            responses = {@ApiResponse(
-                    content = @Content(array = @ArraySchema(schema = @Schema(implementation = Response.class)))),
-                    @ApiResponse(responseCode = "200", description = "Resource instance updated"),
-                    @ApiResponse(responseCode = "403", description = "Restricted operation"),
-                    @ApiResponse(responseCode = "400", description = "Invalid content / Missing content")})
+    @Operation(description = "Update resource instance", method = "POST", summary = "Returns updated resource instance", responses = {
+        @ApiResponse(content = @Content(array = @ArraySchema(schema = @Schema(implementation = Response.class)))),
+        @ApiResponse(responseCode = "200", description = "Resource instance updated"),
+        @ApiResponse(responseCode = "403", description = "Restricted operation"),
+        @ApiResponse(responseCode = "400", description = "Invalid content / Missing content")})
     @PermissionAllowed(AafPermission.PermNames.INTERNAL_ALL_VALUE)
     public Response updateComponentInstanceMetadata(@PathParam("componentId") final String componentId,
-            @PathParam("componentInstanceId") final String componentInstanceId,
-            @Parameter(description = "valid values: resources / services / products",
-                    schema = @Schema(allowableValues = {ComponentTypeEnum.RESOURCE_PARAM_NAME,
-                            ComponentTypeEnum.SERVICE_PARAM_NAME,
-                            ComponentTypeEnum.PRODUCT_PARAM_NAME})) @PathParam("containerComponentType") final String containerComponentType,
-            @Context final HttpServletRequest request) throws IOException, BusinessLogicException {
-
+                                                    @PathParam("componentInstanceId") final String componentInstanceId,
+                                                    @Parameter(description = "valid values: resources / services / products", schema = @Schema(allowableValues = {
+                                                        ComponentTypeEnum.RESOURCE_PARAM_NAME, ComponentTypeEnum.SERVICE_PARAM_NAME,
+                                                        ComponentTypeEnum.PRODUCT_PARAM_NAME})) @PathParam("containerComponentType") final String containerComponentType,
+                                                    @Context final HttpServletRequest request) throws IOException, BusinessLogicException {
         final String url = request.getMethod() + " " + request.getRequestURI();
         log.debug(START_HANDLE_REQUEST_OF, url);
-        loggerSupportability.log(LoggerSupportabilityActions.UPDATE_COMPONENT_INSTANCE,StatusCode.STARTED,"update Component Instance Metadata");
+        loggerSupportability.log(LoggerSupportabilityActions.UPDATE_COMPONENT_INSTANCE, StatusCode.STARTED, "update Component Instance Metadata");
         final String userId = request.getHeader(Constants.USER_ID_HEADER);
-         try {
+        try {
             if (componentInstanceBusinessLogic == null) {
                 log.debug(UNSUPPORTED_COMPONENT_TYPE, containerComponentType);
-                return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.UNSUPPORTED_ERROR,
-                                                                                 containerComponentType));
+                return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.UNSUPPORTED_ERROR, containerComponentType));
             }
             componentInstanceBusinessLogic.validateUser(userId);
             log.debug(START_HANDLE_REQUEST_OF, url);
             final byte[] bytes = IOUtils.toByteArray(request.getInputStream());
-
             if (bytes == null || bytes.length == 0) {
                 log.info(EMPTY_BODY_WAS_SENT);
                 return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.INVALID_CONTENT));
             }
-
             final String data = new String(bytes);
             final ComponentTypeEnum componentTypeEnum = ComponentTypeEnum.findByParamName(containerComponentType);
             final Either<ComponentInstance, ResponseFormat> convertResponse = convertToResourceInstance(data);
@@ -246,25 +229,21 @@ public class ComponentInstanceServlet extends AbstractValidationsServlet {
                 log.debug(FAILED_TO_CONVERT_RECEIVED_DATA_TO_BE_FORMAT);
                 return buildErrorResponse(convertResponse.right().value());
             }
-
-
             final ComponentInstance componentInstance = convertResponse.left().value();
             final Either<ComponentInstance, ResponseFormat> actionResponse = componentInstanceBusinessLogic
                 .updateComponentInstanceMetadata(containerComponentType, componentId, componentInstanceId, userId, componentInstance);
-            loggerSupportability.log(LoggerSupportabilityActions.UPDATE_COMPONENT_INSTANCE,actionResponse.left().value()
-                .getComponentMetadataForSupportLog(),StatusCode.COMPLETE,"update Component Instance Metadata by {}", userId);
+            loggerSupportability
+                .log(LoggerSupportabilityActions.UPDATE_COMPONENT_INSTANCE, actionResponse.left().value().getComponentMetadataForSupportLog(),
+                    StatusCode.COMPLETE, "update Component Instance Metadata by {}", userId);
             if (actionResponse.isRight()) {
                 return buildErrorResponse(actionResponse.right().value());
             }
-
             final ComponentInstance resultValue = actionResponse.left().value();
-            if (ComponentTypeEnum.SERVICE.equals(componentTypeEnum) ||
-                ComponentTypeEnum.RESOURCE.equals(componentTypeEnum)) {
-                if(CollectionUtils.isNotEmpty(componentInstance.getDirectives())) {
-                    final Optional<CINodeFilterDataDefinition> nodeFilterDataDefinition =
-                            nodeFilterBusinessLogic.createNodeFilterIfNotExist(componentId, componentInstanceId,
-                                true,  componentTypeEnum);
-                    if (!nodeFilterDataDefinition.isPresent()){
+            if (ComponentTypeEnum.SERVICE.equals(componentTypeEnum) || ComponentTypeEnum.RESOURCE.equals(componentTypeEnum)) {
+                if (CollectionUtils.isNotEmpty(componentInstance.getDirectives())) {
+                    final Optional<CINodeFilterDataDefinition> nodeFilterDataDefinition = nodeFilterBusinessLogic
+                        .createNodeFilterIfNotExist(componentId, componentInstanceId, true, componentTypeEnum);
+                    if (!nodeFilterDataDefinition.isPresent()) {
                         BeEcompErrorManager.getInstance().logBeSystemError("Failed to create node filter.");
                         log.error("Failed to create node filter.");
                         return buildErrorResponse(convertResponse.right().value());
@@ -272,8 +251,8 @@ public class ComponentInstanceServlet extends AbstractValidationsServlet {
                     resultValue.setNodeFilter(nodeFilterDataDefinition.get());
                 } else {
                     final Optional<String> result = nodeFilterBusinessLogic
-                        .deleteNodeFilterIfExists(componentId, componentInstanceId,  true, componentTypeEnum);
-                    if (!result.isPresent()){
+                        .deleteNodeFilterIfExists(componentId, componentInstanceId, true, componentTypeEnum);
+                    if (!result.isPresent()) {
                         BeEcompErrorManager.getInstance().logBeSystemError("Failed to delete node filter.");
                         log.error("Failed to delete node filter.");
                         return buildErrorResponse(convertResponse.right().value());
@@ -281,97 +260,78 @@ public class ComponentInstanceServlet extends AbstractValidationsServlet {
                     resultValue.setNodeFilter(null);
                 }
             }
-
             return buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), actionResponse.left().value());
-
         } catch (final Exception e) {
             BeEcompErrorManager.getInstance().logBeRestApiGeneralError(UPDATE_RESOURCE_INSTANCE);
             log.debug(UPDATE_RESOURCE_INSTANCE_WITH_EXCEPTION, e);
             throw e;
         }
-
     }
 
     @POST
     @Path("/{containerComponentType}/{componentId}/resourceInstance/multipleComponentInstance")
     @Consumes(MediaType.APPLICATION_JSON)
     @Produces(MediaType.APPLICATION_JSON)
-    @Operation(description = "Update resource instance multiple component", method = "POST",
-            summary = "Returns updated resource instance", responses = {
-            @ApiResponse(content = @Content(array = @ArraySchema(schema = @Schema(implementation = Response.class)))),
-            @ApiResponse(responseCode = "200", description = "Resource instance updated"),
-            @ApiResponse(responseCode = "403", description = "Restricted operation"),
-            @ApiResponse(responseCode = "400", description = "Invalid content / Missing content")})
+    @Operation(description = "Update resource instance multiple component", method = "POST", summary = "Returns updated resource instance", responses = {
+        @ApiResponse(content = @Content(array = @ArraySchema(schema = @Schema(implementation = Response.class)))),
+        @ApiResponse(responseCode = "200", description = "Resource instance updated"),
+        @ApiResponse(responseCode = "403", description = "Restricted operation"),
+        @ApiResponse(responseCode = "400", description = "Invalid content / Missing content")})
     @PermissionAllowed(AafPermission.PermNames.INTERNAL_ALL_VALUE)
-    public Response updateMultipleComponentInstance(@PathParam("componentId") final String componentId, @Parameter(
-            description = "valid values: resources / services / products",
-            schema = @Schema(allowableValues = {ComponentTypeEnum.RESOURCE_PARAM_NAME,
-                    ComponentTypeEnum.SERVICE_PARAM_NAME,
-                    ComponentTypeEnum.PRODUCT_PARAM_NAME})) @PathParam("containerComponentType") final String containerComponentType,
-            @Context final HttpServletRequest request, @Parameter(description = "Component Instance JSON Array",
-                    required = true) final String componentInstanceJsonArray) {
-
+    public Response updateMultipleComponentInstance(@PathParam("componentId") final String componentId,
+                                                    @Parameter(description = "valid values: resources / services / products", schema = @Schema(allowableValues = {
+                                                        ComponentTypeEnum.RESOURCE_PARAM_NAME, ComponentTypeEnum.SERVICE_PARAM_NAME,
+                                                        ComponentTypeEnum.PRODUCT_PARAM_NAME})) @PathParam("containerComponentType") final String containerComponentType,
+                                                    @Context final HttpServletRequest request,
+                                                    @Parameter(description = "Component Instance JSON Array", required = true) final String componentInstanceJsonArray) {
         String url = request.getMethod() + " " + request.getRequestURI();
         log.debug(START_HANDLE_REQUEST_OF, url);
-
         try {
             log.debug(START_HANDLE_REQUEST_OF, url);
-
             if (componentInstanceJsonArray == null || componentInstanceJsonArray.length() == 0) {
                 log.info("Empty JSON list was sent.");
                 return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.INVALID_CONTENT));
             }
-
             String userId = request.getHeader(Constants.USER_ID_HEADER);
-
             if (componentInstanceBusinessLogic == null) {
                 log.debug(UNSUPPORTED_COMPONENT_TYPE, containerComponentType);
                 return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.UNSUPPORTED_ERROR, containerComponentType));
             }
-
             Either<List<ComponentInstance>, ResponseFormat> convertResponse = convertToMultipleResourceInstance(componentInstanceJsonArray);
-
             if (convertResponse.isRight()) {
                 // Using both ECOMP error methods, show to Sofer
                 BeEcompErrorManager.getInstance().logBeSystemError(RESOURCE_INSTANCE_UPDATE_RESOURCE_INSTANCE);
                 log.debug(FAILED_TO_CONVERT_RECEIVED_DATA_TO_BE_FORMAT);
                 return buildErrorResponse(convertResponse.right().value());
             }
-
             List<ComponentInstance> componentInstanceList = convertResponse.left().value();
-
-            List<ComponentInstance> actionResponse = componentInstanceBusinessLogic.updateComponentInstance(containerComponentType, null, componentId, userId, componentInstanceList, true);
+            List<ComponentInstance> actionResponse = componentInstanceBusinessLogic
+                .updateComponentInstance(containerComponentType, null, componentId, userId, componentInstanceList, true);
             return buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), actionResponse);
-
         } catch (Exception e) {
             BeEcompErrorManager.getInstance().logBeRestApiGeneralError(UPDATE_RESOURCE_INSTANCE);
             log.debug(UPDATE_RESOURCE_INSTANCE_WITH_EXCEPTION, e);
             throw e;
         }
-
     }
 
     @DELETE
     @Path("/{containerComponentType}/{componentId}/resourceInstance/{resourceInstanceId}")
     @Consumes(MediaType.APPLICATION_JSON)
     @Produces(MediaType.APPLICATION_JSON)
-    @Operation(description = "Delete ResourceInstance", method = "DELETE", summary = "Returns delete resourceInstance",
-            responses = {@ApiResponse(
-                    content = @Content(array = @ArraySchema(schema = @Schema(implementation = Response.class)))),
-                    @ApiResponse(responseCode = "201", description = "ResourceInstance deleted"),
-                    @ApiResponse(responseCode = "403", description = "Restricted operation"),
-                    @ApiResponse(responseCode = "400", description = "Invalid content / Missing content")})
+    @Operation(description = "Delete ResourceInstance", method = "DELETE", summary = "Returns delete resourceInstance", responses = {
+        @ApiResponse(content = @Content(array = @ArraySchema(schema = @Schema(implementation = Response.class)))),
+        @ApiResponse(responseCode = "201", description = "ResourceInstance deleted"),
+        @ApiResponse(responseCode = "403", description = "Restricted operation"),
+        @ApiResponse(responseCode = "400", description = "Invalid content / Missing content")})
     @PermissionAllowed(AafPermission.PermNames.INTERNAL_ALL_VALUE)
     public Response deleteResourceInstance(@PathParam("componentId") final String componentId,
-            @PathParam("resourceInstanceId") final String resourceInstanceId,
-            @Parameter(description = "valid values: resources / services / products",
-                    schema = @Schema(allowableValues = {ComponentTypeEnum.RESOURCE_PARAM_NAME,
-                            ComponentTypeEnum.SERVICE_PARAM_NAME,
-                            ComponentTypeEnum.PRODUCT_PARAM_NAME})) @PathParam("containerComponentType") final String containerComponentType,
-            @Context final HttpServletRequest request) {
-
+                                           @PathParam("resourceInstanceId") final String resourceInstanceId,
+                                           @Parameter(description = "valid values: resources / services / products", schema = @Schema(allowableValues = {
+                                               ComponentTypeEnum.RESOURCE_PARAM_NAME, ComponentTypeEnum.SERVICE_PARAM_NAME,
+                                               ComponentTypeEnum.PRODUCT_PARAM_NAME})) @PathParam("containerComponentType") final String containerComponentType,
+                                           @Context final HttpServletRequest request) {
         String url = request.getMethod() + " " + request.getRequestURI();
-
         try {
             log.debug(START_HANDLE_REQUEST_OF, url);
             if (componentInstanceBusinessLogic == null) {
@@ -379,9 +339,14 @@ public class ComponentInstanceServlet extends AbstractValidationsServlet {
                 return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.UNSUPPORTED_ERROR, containerComponentType));
             }
             String userId = request.getHeader(Constants.USER_ID_HEADER);
-            ComponentInstance actionResponse = componentInstanceBusinessLogic.deleteComponentInstance(containerComponentType, componentId, resourceInstanceId, userId);
-            loggerSupportability.log(LoggerSupportabilityActions.DELETE_COMPONENT_INSTANCE,actionResponse.getComponentMetadataForSupportLog(),StatusCode.STARTED,"DELETE_COMPONENT_INSTANCE by user {}", userId);
-            loggerSupportability.log(LoggerSupportabilityActions.DELETE_COMPONENT_INSTANCE,actionResponse.getComponentMetadataForSupportLog(),StatusCode.COMPLETE,"DELETE_COMPONENT_INSTANCE by user {}", userId);
+            ComponentInstance actionResponse = componentInstanceBusinessLogic
+                .deleteComponentInstance(containerComponentType, componentId, resourceInstanceId, userId);
+            loggerSupportability
+                .log(LoggerSupportabilityActions.DELETE_COMPONENT_INSTANCE, actionResponse.getComponentMetadataForSupportLog(), StatusCode.STARTED,
+                    "DELETE_COMPONENT_INSTANCE by user {}", userId);
+            loggerSupportability
+                .log(LoggerSupportabilityActions.DELETE_COMPONENT_INSTANCE, actionResponse.getComponentMetadataForSupportLog(), StatusCode.COMPLETE,
+                    "DELETE_COMPONENT_INSTANCE by user {}", userId);
             return buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), actionResponse);
         } catch (Exception e) {
             BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Delete Resource Instance");
@@ -390,55 +355,48 @@ public class ComponentInstanceServlet extends AbstractValidationsServlet {
         }
     }
 
-    @Parameter(description = "allowed values are resources /services / products",
-            schema = @Schema(allowableValues = {ComponentTypeEnum.RESOURCE_PARAM_NAME,
-                    ComponentTypeEnum.SERVICE_PARAM_NAME,
-                    ComponentTypeEnum.PRODUCT_PARAM_NAME}),
-            required = true)
+    @Parameter(description = "allowed values are resources /services / products", schema = @Schema(allowableValues = {
+        ComponentTypeEnum.RESOURCE_PARAM_NAME, ComponentTypeEnum.SERVICE_PARAM_NAME, ComponentTypeEnum.PRODUCT_PARAM_NAME}), required = true)
     @POST
     @Path("/{containerComponentType}/{componentId}/resourceInstance/associate")
     @Consumes(MediaType.APPLICATION_JSON)
     @Produces(MediaType.APPLICATION_JSON)
-    @Operation(description = "Associate RI to RI", method = "POST", summary = "Returns created RelationshipInfo",
-            responses = {@ApiResponse(
-                    content = @Content(array = @ArraySchema(schema = @Schema(implementation = Response.class)))),
-                    @ApiResponse(responseCode = "201", description = "Relationship created"),
-                    @ApiResponse(responseCode = "403", description = "Missing information"),
-                    @ApiResponse(responseCode = "400", description = "Invalid content / Missing content"),
-                    @ApiResponse(responseCode = "409", description = "Relationship already exist")})
+    @Operation(description = "Associate RI to RI", method = "POST", summary = "Returns created RelationshipInfo", responses = {
+        @ApiResponse(content = @Content(array = @ArraySchema(schema = @Schema(implementation = Response.class)))),
+        @ApiResponse(responseCode = "201", description = "Relationship created"),
+        @ApiResponse(responseCode = "403", description = "Missing information"),
+        @ApiResponse(responseCode = "400", description = "Invalid content / Missing content"),
+        @ApiResponse(responseCode = "409", description = "Relationship already exist")})
     @PermissionAllowed(AafPermission.PermNames.INTERNAL_ALL_VALUE)
-    public Response associateRIToRI(@Parameter(
-            description = "unique id of the container component") @PathParam("componentId") final String componentId,
-            @Parameter(description = "allowed values are resources /services / products",
-                    schema = @Schema(allowableValues = {ComponentTypeEnum.RESOURCE_PARAM_NAME,
-                            ComponentTypeEnum.SERVICE_PARAM_NAME, ComponentTypeEnum.PRODUCT_PARAM_NAME}),
-                    required = true) @PathParam("containerComponentType") final String containerComponentType,
-            @HeaderParam(value = Constants.USER_ID_HEADER) String userId,
-            @Parameter(description = "RelationshipInfo", required = true) String data,
-            @Context final HttpServletRequest request) {
-
+    public Response associateRIToRI(
+        @Parameter(description = "unique id of the container component") @PathParam("componentId") final String componentId,
+        @Parameter(description = "allowed values are resources /services / products", schema = @Schema(allowableValues = {
+            ComponentTypeEnum.RESOURCE_PARAM_NAME, ComponentTypeEnum.SERVICE_PARAM_NAME,
+            ComponentTypeEnum.PRODUCT_PARAM_NAME}), required = true) @PathParam("containerComponentType") final String containerComponentType,
+        @HeaderParam(value = Constants.USER_ID_HEADER) String userId, @Parameter(description = "RelationshipInfo", required = true) String data,
+        @Context final HttpServletRequest request) {
         String url = request.getMethod() + " " + request.getRequestURI();
         log.debug(START_HANDLE_REQUEST_OF, url);
-        loggerSupportability.log(LoggerSupportabilityActions.ASSOCIATE_RI_TO_RI, StatusCode.STARTED,"Starting to associate RI To RI for component {} ",componentId + " by " +  userId );
+        loggerSupportability
+            .log(LoggerSupportabilityActions.ASSOCIATE_RI_TO_RI, StatusCode.STARTED, "Starting to associate RI To RI for component {} ",
+                componentId + " by " + userId);
         try {
-
             log.debug(START_HANDLE_REQUEST_OF, url);
-
             ComponentTypeEnum componentTypeEnum = ComponentTypeEnum.findByParamName(containerComponentType);
             if (componentInstanceBusinessLogic == null) {
                 log.debug(UNSUPPORTED_COMPONENT_TYPE, containerComponentType);
                 return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.UNSUPPORTED_ERROR, containerComponentType));
             }
-
             RequirementCapabilityRelDef requirementDef = convertToRequirementCapabilityRelDef(data);
             requirementDef.setOriginUI(true);
-
-            RequirementCapabilityRelDef actionResponse = componentInstanceBusinessLogic.associateRIToRI(componentId, userId, requirementDef, componentTypeEnum);
-            loggerSupportability.log(LoggerSupportabilityActions.ASSOCIATE_RI_TO_RI, StatusCode.COMPLETE,"Ended associate RI To RI for component {} ",componentId + " by " +  userId );
+            RequirementCapabilityRelDef actionResponse = componentInstanceBusinessLogic
+                .associateRIToRI(componentId, userId, requirementDef, componentTypeEnum);
+            loggerSupportability
+                .log(LoggerSupportabilityActions.ASSOCIATE_RI_TO_RI, StatusCode.COMPLETE, "Ended associate RI To RI for component {} ",
+                    componentId + " by " + userId);
             return buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), actionResponse);
-
         } catch (Exception e) {
-            if(!e.getClass().equals(ComponentException.class)) {
+            if (!e.getClass().equals(ComponentException.class)) {
                 BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Associate Resource Instance");
                 log.debug("associate resource instance to another RI with exception", e);
                 return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR));
@@ -451,42 +409,38 @@ public class ComponentInstanceServlet extends AbstractValidationsServlet {
     @Path("/{containerComponentType}/{componentId}/resourceInstance/dissociate")
     @Consumes(MediaType.APPLICATION_JSON)
     @Produces(MediaType.APPLICATION_JSON)
-    @Operation(description = "Dissociate RI from RI", method = "PUT", summary = "Returns deleted RelationshipInfo",
-            responses = {@ApiResponse(
-                    content = @Content(array = @ArraySchema(schema = @Schema(implementation = Response.class)))),
-                    @ApiResponse(responseCode = "201", description = "Relationship deleted"),
-                    @ApiResponse(responseCode = "403", description = "Missing information"),
-                    @ApiResponse(responseCode = "400", description = "Invalid content / Missing content")})
+    @Operation(description = "Dissociate RI from RI", method = "PUT", summary = "Returns deleted RelationshipInfo", responses = {
+        @ApiResponse(content = @Content(array = @ArraySchema(schema = @Schema(implementation = Response.class)))),
+        @ApiResponse(responseCode = "201", description = "Relationship deleted"),
+        @ApiResponse(responseCode = "403", description = "Missing information"),
+        @ApiResponse(responseCode = "400", description = "Invalid content / Missing content")})
     @PermissionAllowed(AafPermission.PermNames.INTERNAL_ALL_VALUE)
     public Response dissociateRIFromRI(
-            @Parameter(description = "allowed values are resources /services / products",
-                    schema = @Schema(allowableValues = {ComponentTypeEnum.RESOURCE_PARAM_NAME,
-                            ComponentTypeEnum.SERVICE_PARAM_NAME, ComponentTypeEnum.PRODUCT_PARAM_NAME}),
-                    required = true) @PathParam("containerComponentType") final String containerComponentType,
-            @Parameter(
-                    description = "unique id of the container component") @PathParam("componentId") final String componentId,
-            @HeaderParam(value = Constants.USER_ID_HEADER) String userId,
-            @Parameter(description = "RelationshipInfo", required = true) String data,
-            @Context final HttpServletRequest request) {
-
+        @Parameter(description = "allowed values are resources /services / products", schema = @Schema(allowableValues = {
+            ComponentTypeEnum.RESOURCE_PARAM_NAME, ComponentTypeEnum.SERVICE_PARAM_NAME,
+            ComponentTypeEnum.PRODUCT_PARAM_NAME}), required = true) @PathParam("containerComponentType") final String containerComponentType,
+        @Parameter(description = "unique id of the container component") @PathParam("componentId") final String componentId,
+        @HeaderParam(value = Constants.USER_ID_HEADER) String userId, @Parameter(description = "RelationshipInfo", required = true) String data,
+        @Context final HttpServletRequest request) {
         String url = request.getMethod() + " " + request.getRequestURI();
         log.debug(START_HANDLE_REQUEST_OF, url);
-        loggerSupportability.log(LoggerSupportabilityActions.UN_ASSOCIATE_RI_TO_RI, StatusCode.STARTED,"Starting to undo associate RI To RI for component {} ",componentId + " by " +  userId );
+        loggerSupportability
+            .log(LoggerSupportabilityActions.UN_ASSOCIATE_RI_TO_RI, StatusCode.STARTED, "Starting to undo associate RI To RI for component {} ",
+                componentId + " by " + userId);
         try {
-
             log.debug(START_HANDLE_REQUEST_OF, url);
-
             ComponentTypeEnum componentTypeEnum = ComponentTypeEnum.findByParamName(containerComponentType);
             if (componentInstanceBusinessLogic == null) {
                 log.debug(UNSUPPORTED_COMPONENT_TYPE, containerComponentType);
                 return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.UNSUPPORTED_ERROR, containerComponentType));
             }
-
             RequirementCapabilityRelDef requirementDef = convertToRequirementCapabilityRelDef(data);
-            RequirementCapabilityRelDef actionResponse = componentInstanceBusinessLogic.dissociateRIFromRI(componentId, userId, requirementDef, componentTypeEnum);
-            loggerSupportability.log(LoggerSupportabilityActions.UN_ASSOCIATE_RI_TO_RI, StatusCode.COMPLETE,"Ended undo associate RI To RI for component {} ",componentId + " by " +  userId );
+            RequirementCapabilityRelDef actionResponse = componentInstanceBusinessLogic
+                .dissociateRIFromRI(componentId, userId, requirementDef, componentTypeEnum);
+            loggerSupportability
+                .log(LoggerSupportabilityActions.UN_ASSOCIATE_RI_TO_RI, StatusCode.COMPLETE, "Ended undo associate RI To RI for component {} ",
+                    componentId + " by " + userId);
             return buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), actionResponse);
-
         } catch (Exception e) {
             BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Dissociate Resource Instance");
             log.debug("dissociate resource instance from service failed with exception", e);
@@ -498,56 +452,46 @@ public class ComponentInstanceServlet extends AbstractValidationsServlet {
     @Path("/{containerComponentType}/{componentId}/resourceInstance/createAndAssociate")
     @Consumes(MediaType.APPLICATION_JSON)
     @Produces(MediaType.APPLICATION_JSON)
-    @Operation(description = "Create RI and associate RI to RI", method = "POST",
-            summary = "Returns created RI and RelationshipInfo", responses = {
-            @ApiResponse(content = @Content(array = @ArraySchema(schema = @Schema(implementation = Response.class)))),
-            @ApiResponse(responseCode = "201", description = "RI created"),
-            @ApiResponse(responseCode = "403", description = "Restricted operation"),
-            @ApiResponse(responseCode = "400", description = "Invalid content / Missing content"),
-            @ApiResponse(responseCode = "409", description = "Relationship already exist")})
+    @Operation(description = "Create RI and associate RI to RI", method = "POST", summary = "Returns created RI and RelationshipInfo", responses = {
+        @ApiResponse(content = @Content(array = @ArraySchema(schema = @Schema(implementation = Response.class)))),
+        @ApiResponse(responseCode = "201", description = "RI created"), @ApiResponse(responseCode = "403", description = "Restricted operation"),
+        @ApiResponse(responseCode = "400", description = "Invalid content / Missing content"),
+        @ApiResponse(responseCode = "409", description = "Relationship already exist")})
     @PermissionAllowed(AafPermission.PermNames.INTERNAL_ALL_VALUE)
-    public Response createAndAssociateRIToRI(@PathParam("componentId") final String componentId, @Parameter(
-            description = "valid values: resources / services",
-                    schema = @Schema(allowableValues = {ComponentTypeEnum.RESOURCE_PARAM_NAME,
-                            ComponentTypeEnum.SERVICE_PARAM_NAME, ComponentTypeEnum.PRODUCT_PARAM_NAME})) @PathParam("containerComponentType") final String containerComponentType,
-            @Context final HttpServletRequest request) throws IOException {
-
+    public Response createAndAssociateRIToRI(@PathParam("componentId") final String componentId,
+                                             @Parameter(description = "valid values: resources / services", schema = @Schema(allowableValues = {
+                                                 ComponentTypeEnum.RESOURCE_PARAM_NAME, ComponentTypeEnum.SERVICE_PARAM_NAME,
+                                                 ComponentTypeEnum.PRODUCT_PARAM_NAME})) @PathParam("containerComponentType") final String containerComponentType,
+                                             @Context final HttpServletRequest request) throws IOException {
         String url = request.getMethod() + " " + request.getRequestURI();
         log.debug(START_HANDLE_REQUEST_OF, url);
         try {
-
             log.debug(START_HANDLE_REQUEST_OF, url);
-
             InputStream inputStream = request.getInputStream();
-
             byte[] bytes = IOUtils.toByteArray(inputStream);
-
             if (bytes == null || bytes.length == 0) {
                 log.info(EMPTY_BODY_WAS_SENT);
                 return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.INVALID_CONTENT));
             }
-
             String userId = request.getHeader(Constants.USER_ID_HEADER);
             String data = new String(bytes);
-
             if (componentInstanceBusinessLogic == null) {
                 log.debug(UNSUPPORTED_COMPONENT_TYPE, containerComponentType);
                 return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.UNSUPPORTED_ERROR, containerComponentType));
             }
-
             Either<CreateAndAssotiateInfo, ActionStatus> convertStatus = convertJsonToObject(data, CreateAndAssotiateInfo.class);
             if (convertStatus.isRight()) {
                 BeEcompErrorManager.getInstance().logBeSystemError("Resource Instance - createAndAssociateRIToRI");
                 log.debug(FAILED_TO_CONVERT_RECEIVED_DATA_TO_BE_FORMAT);
-                Either<Object, ResponseFormat> formattedResponse = Either.right(getComponentsUtils().getResponseFormat(convertStatus.right().value()));
+                Either<Object, ResponseFormat> formattedResponse = Either
+                    .right(getComponentsUtils().getResponseFormat(convertStatus.right().value()));
                 return buildErrorResponse(formattedResponse.right().value());
             }
-
             CreateAndAssotiateInfo createAndAssotiateInfo = convertStatus.left().value();
             RequirementCapabilityRelDef requirementDef = createAndAssotiateInfo.getAssociate();
             requirementDef.setOriginUI(true);
-            Either<CreateAndAssotiateInfo, ResponseFormat> actionResponse = componentInstanceBusinessLogic.createAndAssociateRIToRI(containerComponentType, componentId, userId, createAndAssotiateInfo);
-
+            Either<CreateAndAssotiateInfo, ResponseFormat> actionResponse = componentInstanceBusinessLogic
+                .createAndAssociateRIToRI(containerComponentType, componentId, userId, createAndAssotiateInfo);
             if (actionResponse.isRight()) {
                 return buildErrorResponse(actionResponse.right().value());
             }
@@ -563,65 +507,62 @@ public class ComponentInstanceServlet extends AbstractValidationsServlet {
     @Path("/{containerComponentType}/{componentId}/resourceInstance/{componentInstanceId}/properties")
     @Consumes(MediaType.APPLICATION_JSON)
     @Produces(MediaType.APPLICATION_JSON)
-    @Operation(description = "Update resource instance property", method = "POST",
-            summary = "Returns updated resource instance property", responses = {
-            @ApiResponse(content = @Content(array = @ArraySchema(schema = @Schema(implementation = Response.class)))),
-            @ApiResponse(responseCode = "201", description = "Resource instance created"),
-            @ApiResponse(responseCode = "403", description = "Restricted operation"),
-            @ApiResponse(responseCode = "400", description = "Invalid content / Missing content")})
+    @Operation(description = "Update resource instance property", method = "POST", summary = "Returns updated resource instance property", responses = {
+        @ApiResponse(content = @Content(array = @ArraySchema(schema = @Schema(implementation = Response.class)))),
+        @ApiResponse(responseCode = "201", description = "Resource instance created"),
+        @ApiResponse(responseCode = "403", description = "Restricted operation"),
+        @ApiResponse(responseCode = "400", description = "Invalid content / Missing content")})
     @PermissionAllowed(AafPermission.PermNames.INTERNAL_ALL_VALUE)
-    public Response updateResourceInstanceProperties(
-            @Parameter(description = "service id") @PathParam("componentId") final String componentId,
-            @Parameter(description = "valid values: resources / services",
-                    schema = @Schema(allowableValues = {ComponentTypeEnum.RESOURCE_PARAM_NAME,
-                            ComponentTypeEnum.SERVICE_PARAM_NAME})) @PathParam("containerComponentType") final String containerComponentType,
-            @Parameter(
-                    description = "resource instance id") @PathParam("componentInstanceId") final String componentInstanceId,
-            @Parameter(description = "id of user initiating the operation") @HeaderParam(
-                    value = Constants.USER_ID_HEADER) String userId,
-            @Context final HttpServletRequest request,
-            @Parameter(description = "Component Instance Properties JSON Array",
-                    required = true) final String componentInstancePropertiesJsonArray) {
-
+    public Response updateResourceInstanceProperties(@Parameter(description = "service id") @PathParam("componentId") final String componentId,
+                                                     @Parameter(description = "valid values: resources / services", schema = @Schema(allowableValues = {
+                                                         ComponentTypeEnum.RESOURCE_PARAM_NAME,
+                                                         ComponentTypeEnum.SERVICE_PARAM_NAME})) @PathParam("containerComponentType") final String containerComponentType,
+                                                     @Parameter(description = "resource instance id") @PathParam("componentInstanceId") final String componentInstanceId,
+                                                     @Parameter(description = "id of user initiating the operation") @HeaderParam(value = Constants.USER_ID_HEADER) String userId,
+                                                     @Context final HttpServletRequest request,
+                                                     @Parameter(description = "Component Instance Properties JSON Array", required = true) final String componentInstancePropertiesJsonArray) {
         String url = request.getMethod() + " " + request.getRequestURI();
         log.debug(START_HANDLE_REQUEST_OF, url);
-        loggerSupportability.log(LoggerSupportabilityActions.UPDATE_COMPONENT_INSTANCE, StatusCode.STARTED,"Starting to update Resource Instance Properties for component {} ",componentId + " by " +  userId );
-
+        loggerSupportability.log(LoggerSupportabilityActions.UPDATE_COMPONENT_INSTANCE, StatusCode.STARTED,
+            "Starting to update Resource Instance Properties for component {} ", componentId + " by " + userId);
         Wrapper<ResponseFormat> errorWrapper = new Wrapper<>();
         List<ComponentInstanceProperty> propertiesToUpdate = new ArrayList<>();
         if (errorWrapper.isEmpty()) {
-                Either<List<ComponentInstanceProperty>, ResponseFormat> propertiesToUpdateEither = convertMultipleProperties(componentInstancePropertiesJsonArray);
-                if (propertiesToUpdateEither.isRight()) {
-                    errorWrapper.setInnerElement(propertiesToUpdateEither.right().value());
-                } else {
-                    propertiesToUpdate = propertiesToUpdateEither.left().value();
-                }
+            Either<List<ComponentInstanceProperty>, ResponseFormat> propertiesToUpdateEither = convertMultipleProperties(
+                componentInstancePropertiesJsonArray);
+            if (propertiesToUpdateEither.isRight()) {
+                errorWrapper.setInnerElement(propertiesToUpdateEither.right().value());
+            } else {
+                propertiesToUpdate = propertiesToUpdateEither.left().value();
+            }
         }
         if (!errorWrapper.isEmpty()) {
-                return buildErrorResponse(errorWrapper.getInnerElement());
+            return buildErrorResponse(errorWrapper.getInnerElement());
         }
         log.debug(START_HANDLE_REQUEST_OF_UPDATE_RESOURCE_INSTANCE_PROPERTY_RECEIVED_PROPERTY_IS, propertiesToUpdate);
-
         ComponentTypeEnum componentTypeEnum = ComponentTypeEnum.findByParamName(containerComponentType);
         if (componentInstanceBusinessLogic == null) {
-                log.debug(UNSUPPORTED_COMPONENT_TYPE, containerComponentType);
-                return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.UNSUPPORTED_ERROR, containerComponentType));
+            log.debug(UNSUPPORTED_COMPONENT_TYPE, containerComponentType);
+            return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.UNSUPPORTED_ERROR, containerComponentType));
         }
-        Either<List<ComponentInstanceProperty>, ResponseFormat> actionResponse = componentInstanceBusinessLogic.createOrUpdatePropertiesValues(componentTypeEnum, componentId, componentInstanceId, propertiesToUpdate, userId);
+        Either<List<ComponentInstanceProperty>, ResponseFormat> actionResponse = componentInstanceBusinessLogic
+            .createOrUpdatePropertiesValues(componentTypeEnum, componentId, componentInstanceId, propertiesToUpdate, userId);
         if (actionResponse.isRight()) {
-                return buildErrorResponse(actionResponse.right().value());
+            return buildErrorResponse(actionResponse.right().value());
         }
         List<ComponentInstanceProperty> resourceInstanceProperties = actionResponse.left().value();
         ObjectMapper mapper = new ObjectMapper();
         String result;
-            loggerSupportability.log(LoggerSupportabilityActions.UPDATE_COMPONENT_INSTANCE, StatusCode.COMPLETE,"Ended update Resource Instance Properties for component {} ",componentId + " by " +  userId );
+        loggerSupportability.log(LoggerSupportabilityActions.UPDATE_COMPONENT_INSTANCE, StatusCode.COMPLETE,
+            "Ended update Resource Instance Properties for component {} ", componentId + " by " + userId);
         try {
             result = mapper.writeValueAsString(resourceInstanceProperties);
         } catch (JsonProcessingException e) {
             log.error(UPDATE_RESOURCE_INSTANCE_WITH_EXCEPTION, e.getMessage(), e);
             throw new ByActionStatusComponentException(ActionStatus.GENERAL_ERROR);
         }
-        loggerSupportability.log(LoggerSupportabilityActions.UPDATE_COMPONENT_INSTANCE, StatusCode.COMPLETE,"Ended update Resource Instance Properties for component {} ",componentId + " by user " +  userId );
+        loggerSupportability.log(LoggerSupportabilityActions.UPDATE_COMPONENT_INSTANCE, StatusCode.COMPLETE,
+            "Ended update Resource Instance Properties for component {} ", componentId + " by user " + userId);
         return buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), result);
     }
 
@@ -629,66 +570,62 @@ public class ComponentInstanceServlet extends AbstractValidationsServlet {
     @Path("/{containerComponentType}/{componentId}/resourceInstance/{componentInstanceId}/inputs")
     @Consumes(MediaType.APPLICATION_JSON)
     @Produces(MediaType.APPLICATION_JSON)
-    @Operation(description = "Update resource instance property", method = "POST",
-            summary = "Returns updated resource instance property", responses = {
-            @ApiResponse(content = @Content(array = @ArraySchema(schema = @Schema(implementation = Response.class)))),
-            @ApiResponse(responseCode = "201", description = "Resource instance created"),
-            @ApiResponse(responseCode = "403", description = "Restricted operation"),
-            @ApiResponse(responseCode = "400", description = "Invalid content / Missing content")})
+    @Operation(description = "Update resource instance property", method = "POST", summary = "Returns updated resource instance property", responses = {
+        @ApiResponse(content = @Content(array = @ArraySchema(schema = @Schema(implementation = Response.class)))),
+        @ApiResponse(responseCode = "201", description = "Resource instance created"),
+        @ApiResponse(responseCode = "403", description = "Restricted operation"),
+        @ApiResponse(responseCode = "400", description = "Invalid content / Missing content")})
     @PermissionAllowed(AafPermission.PermNames.INTERNAL_ALL_VALUE)
-    public Response updateResourceInstanceInput(
-            @Parameter(description = "service id") @PathParam("componentId") final String componentId,
-            @Parameter(description = "valid values: resources / services",
-                    schema = @Schema(allowableValues = {ComponentTypeEnum.RESOURCE_PARAM_NAME,
-                            ComponentTypeEnum.SERVICE_PARAM_NAME})) @PathParam("containerComponentType") final String containerComponentType,
-            @Parameter(
-                    description = "resource instance id") @PathParam("componentInstanceId") final String componentInstanceId,
-            @Parameter(description = "id of user initiating the operation") @HeaderParam(
-                    value = Constants.USER_ID_HEADER) String userId,
-            @Context final HttpServletRequest request,
-            @Parameter(description = "Component Instance Properties JSON Array",
-                    required = true) final String componentInstanceInputsJsonArray) {
-
+    public Response updateResourceInstanceInput(@Parameter(description = "service id") @PathParam("componentId") final String componentId,
+                                                @Parameter(description = "valid values: resources / services", schema = @Schema(allowableValues = {
+                                                    ComponentTypeEnum.RESOURCE_PARAM_NAME,
+                                                    ComponentTypeEnum.SERVICE_PARAM_NAME})) @PathParam("containerComponentType") final String containerComponentType,
+                                                @Parameter(description = "resource instance id") @PathParam("componentInstanceId") final String componentInstanceId,
+                                                @Parameter(description = "id of user initiating the operation") @HeaderParam(value = Constants.USER_ID_HEADER) String userId,
+                                                @Context final HttpServletRequest request,
+                                                @Parameter(description = "Component Instance Properties JSON Array", required = true) final String componentInstanceInputsJsonArray) {
         String url = request.getMethod() + " " + request.getRequestURI();
         log.debug(START_HANDLE_REQUEST_OF, url);
-
         Wrapper<ResponseFormat> errorWrapper = new Wrapper<>();
         List<ComponentInstanceInput> inputsToUpdate = new ArrayList<>();
         if (errorWrapper.isEmpty()) {
-                Either<List<ComponentInstanceInput>, ResponseFormat> inputsToUpdateEither = convertMultipleInputs(componentInstanceInputsJsonArray);
-                if (inputsToUpdateEither.isRight()) {
-                    errorWrapper.setInnerElement(inputsToUpdateEither.right().value());
-                } else {
-                    inputsToUpdate = inputsToUpdateEither.left().value();
-                }
+            Either<List<ComponentInstanceInput>, ResponseFormat> inputsToUpdateEither = convertMultipleInputs(componentInstanceInputsJsonArray);
+            if (inputsToUpdateEither.isRight()) {
+                errorWrapper.setInnerElement(inputsToUpdateEither.right().value());
+            } else {
+                inputsToUpdate = inputsToUpdateEither.left().value();
+            }
         }
         if (!errorWrapper.isEmpty()) {
-                return buildErrorResponse(errorWrapper.getInnerElement());
+            return buildErrorResponse(errorWrapper.getInnerElement());
         }
         log.debug(START_HANDLE_REQUEST_OF_UPDATE_RESOURCE_INSTANCE_PROPERTY_RECEIVED_PROPERTY_IS, inputsToUpdate);
-
         ComponentTypeEnum componentTypeEnum = ComponentTypeEnum.findByParamName(containerComponentType);
         if (componentInstanceBusinessLogic == null) {
-                log.debug(UNSUPPORTED_COMPONENT_TYPE, containerComponentType);
-                return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.UNSUPPORTED_ERROR, containerComponentType));
+            log.debug(UNSUPPORTED_COMPONENT_TYPE, containerComponentType);
+            return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.UNSUPPORTED_ERROR, containerComponentType));
         }
-        Either<List<ComponentInstanceInput>, ResponseFormat> actionResponse =
-                componentInstanceBusinessLogic.createOrUpdateInstanceInputValues(componentTypeEnum, componentId, componentInstanceId, inputsToUpdate, userId);
+        Either<List<ComponentInstanceInput>, ResponseFormat> actionResponse = componentInstanceBusinessLogic
+            .createOrUpdateInstanceInputValues(componentTypeEnum, componentId, componentInstanceId, inputsToUpdate, userId);
         if (actionResponse.isRight()) {
-                return buildErrorResponse(actionResponse.right().value());
+            return buildErrorResponse(actionResponse.right().value());
         }
         List<ComponentInstanceInput> resourceInstanceInput = actionResponse.left().value();
         ObjectMapper mapper = new ObjectMapper();
         mapper.configure(SerializationFeature.FAIL_ON_EMPTY_BEANS, false);
         String result;
-            loggerSupportability.log(LoggerSupportabilityActions.UPDATE_PROPERTIES, StatusCode.COMPLETE,"Ending update Resource Instance Input for component {} ",componentId + " by " +  userId );
+        loggerSupportability
+            .log(LoggerSupportabilityActions.UPDATE_PROPERTIES, StatusCode.COMPLETE, "Ending update Resource Instance Input for component {} ",
+                componentId + " by " + userId);
         try {
             result = mapper.writeValueAsString(resourceInstanceInput);
         } catch (JsonProcessingException e) {
             log.error(UPDATE_RESOURCE_INSTANCE_WITH_EXCEPTION, e.getMessage(), e);
             return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR));
         }
-        loggerSupportability.log(LoggerSupportabilityActions.UPDATE_PROPERTIES, StatusCode.COMPLETE, "Ending update Resource Instance Input for component {} ", componentId + " by user " + userId);
+        loggerSupportability
+            .log(LoggerSupportabilityActions.UPDATE_PROPERTIES, StatusCode.COMPLETE, "Ending update Resource Instance Input for component {} ",
+                componentId + " by user " + userId);
         return buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), result);
     }
 
@@ -706,102 +643,92 @@ public class ComponentInstanceServlet extends AbstractValidationsServlet {
     @Path("/{containerComponentType}/{componentId}/resourceInstance/{componentInstanceId}/attribute")
     @Consumes(MediaType.APPLICATION_JSON)
     @Produces(MediaType.APPLICATION_JSON)
-    @Operation(description = "Update resource instance attribute", method = "POST",
-            summary = "Returns updated resource instance attribute", responses = {
-            @ApiResponse(content = @Content(array = @ArraySchema(schema = @Schema(implementation = Response.class)))),
-            @ApiResponse(responseCode = "201", description = "Resource instance created"),
-            @ApiResponse(responseCode = "403", description = "Restricted operation"),
-            @ApiResponse(responseCode = "400", description = "Invalid content / Missing content")})
+    @Operation(description = "Update resource instance attribute", method = "POST", summary = "Returns updated resource instance attribute", responses = {
+        @ApiResponse(content = @Content(array = @ArraySchema(schema = @Schema(implementation = Response.class)))),
+        @ApiResponse(responseCode = "201", description = "Resource instance created"),
+        @ApiResponse(responseCode = "403", description = "Restricted operation"),
+        @ApiResponse(responseCode = "400", description = "Invalid content / Missing content")})
     @PermissionAllowed(AafPermission.PermNames.INTERNAL_ALL_VALUE)
-    public Response updateResourceInstanceAttribute(
-            @Parameter(description = "service id") @PathParam("componentId") final String componentId,
-            @Parameter(description = "valid values: resources / services",
-                    schema = @Schema(allowableValues = {ComponentTypeEnum.RESOURCE_PARAM_NAME,
-                            ComponentTypeEnum.SERVICE_PARAM_NAME})) @PathParam("containerComponentType") final String containerComponentType,
-            @Parameter(
-                    description = "resource instance id") @PathParam("componentInstanceId") final String componentInstanceId,
-            @Parameter(description = "id of user initiating the operation") @HeaderParam(
-                    value = Constants.USER_ID_HEADER) String userId,
-            @Context final HttpServletRequest request) throws IOException {
-
+    public Response updateResourceInstanceAttribute(@Parameter(description = "service id") @PathParam("componentId") final String componentId,
+                                                    @Parameter(description = "valid values: resources / services", schema = @Schema(allowableValues = {
+                                                        ComponentTypeEnum.RESOURCE_PARAM_NAME,
+                                                        ComponentTypeEnum.SERVICE_PARAM_NAME})) @PathParam("containerComponentType") final String containerComponentType,
+                                                    @Parameter(description = "resource instance id") @PathParam("componentInstanceId") final String componentInstanceId,
+                                                    @Parameter(description = "id of user initiating the operation") @HeaderParam(value = Constants.USER_ID_HEADER) String userId,
+                                                    @Context final HttpServletRequest request) throws IOException {
         String url = request.getMethod() + " " + request.getRequestURI();
         log.debug(START_HANDLE_REQUEST_OF, url);
-        loggerSupportability.log(LoggerSupportabilityActions.UPDATE_RESOURCE, StatusCode.STARTED,"Starting to update Resource Instance Attribute for component {} ",componentId + " by " +  userId );
+        loggerSupportability
+            .log(LoggerSupportabilityActions.UPDATE_RESOURCE, StatusCode.STARTED, "Starting to update Resource Instance Attribute for component {} ",
+                componentId + " by " + userId);
         try {
-
             Wrapper<ResponseFormat> errorWrapper = new Wrapper<>();
             Wrapper<String> dataWrapper = new Wrapper<>();
             Wrapper<ComponentInstanceProperty> attributeWrapper = new Wrapper<>();
             Wrapper<ComponentInstanceBusinessLogic> blWrapper = new Wrapper<>();
-
             validateInputStream(request, dataWrapper, errorWrapper);
-
             if (errorWrapper.isEmpty()) {
                 validateClassParse(dataWrapper.getInnerElement(), attributeWrapper, () -> ComponentInstanceProperty.class, errorWrapper);
             }
-
             if (errorWrapper.isEmpty()) {
                 validateComponentInstanceBusinessLogic(request, containerComponentType, blWrapper, errorWrapper);
             }
-
             if (errorWrapper.isEmpty()) {
                 ComponentInstanceBusinessLogic componentInstanceLogic = blWrapper.getInnerElement();
                 ComponentTypeEnum componentTypeEnum = ComponentTypeEnum.findByParamName(containerComponentType);
                 log.debug("Start handle request of ComponentInstanceAttribute. Received attribute is {}", attributeWrapper.getInnerElement());
-                Either<ComponentInstanceProperty, ResponseFormat> eitherAttribute = componentInstanceLogic.createOrUpdateAttributeValue(componentTypeEnum, componentId, componentInstanceId, attributeWrapper.getInnerElement(), userId);
+                Either<ComponentInstanceProperty, ResponseFormat> eitherAttribute = componentInstanceLogic
+                    .createOrUpdateAttributeValue(componentTypeEnum, componentId, componentInstanceId, attributeWrapper.getInnerElement(), userId);
                 if (eitherAttribute.isRight()) {
                     errorWrapper.setInnerElement(eitherAttribute.right().value());
                 } else {
                     attributeWrapper.setInnerElement(eitherAttribute.left().value());
                 }
             }
-            loggerSupportability.log(LoggerSupportabilityActions.UPDATE_RESOURCE, StatusCode.COMPLETE,"Ended update Resource Instance Attribute for component {} ",componentId + " by " +  userId );
+            loggerSupportability
+                .log(LoggerSupportabilityActions.UPDATE_RESOURCE, StatusCode.COMPLETE, "Ended update Resource Instance Attribute for component {} ",
+                    componentId + " by " + userId);
             return buildResponseFromElement(errorWrapper, attributeWrapper);
-
         } catch (Exception e) {
             log.error(CREATE_AND_ASSOCIATE_RI_FAILED_WITH_EXCEPTION, e.getMessage(), e);
             throw e;
         }
-
     }
 
     @DELETE
     @Path("/{containerComponentType}/{componentId}/resourceInstance/{componentInstanceId}/property/{propertyId}")
     @Consumes(MediaType.APPLICATION_JSON)
     @Produces(MediaType.APPLICATION_JSON)
-    @Operation(description = "Update resource instance", method = "DELETE",
-            summary = "Returns deleted resource instance property", responses = {
-            @ApiResponse(content = @Content(array = @ArraySchema(schema = @Schema(implementation = Response.class)))),
-            @ApiResponse(responseCode = "201", description = "Resource instance created"),
-            @ApiResponse(responseCode = "403", description = "Restricted operation"),
-            @ApiResponse(responseCode = "400", description = "Invalid content / Missing content")})
+    @Operation(description = "Update resource instance", method = "DELETE", summary = "Returns deleted resource instance property", responses = {
+        @ApiResponse(content = @Content(array = @ArraySchema(schema = @Schema(implementation = Response.class)))),
+        @ApiResponse(responseCode = "201", description = "Resource instance created"),
+        @ApiResponse(responseCode = "403", description = "Restricted operation"),
+        @ApiResponse(responseCode = "400", description = "Invalid content / Missing content")})
     @PermissionAllowed(AafPermission.PermNames.INTERNAL_ALL_VALUE)
-    public Response deleteResourceInstanceProperty(
-            @Parameter(description = "service id") @PathParam("componentId") final String componentId,
-            @Parameter(description = "valid values: resources / services",
-                    schema = @Schema(allowableValues = {ComponentTypeEnum.RESOURCE_PARAM_NAME,
-                            ComponentTypeEnum.SERVICE_PARAM_NAME})) @PathParam("containerComponentType") final String containerComponentType,
-            @Parameter(
-                    description = "resource instance id") @PathParam("componentInstanceId") final String componentInstanceId,
-            @Parameter(description = "property id") @PathParam("propertyId") final String propertyId,
-            @Parameter(description = "id of user initiating the operation") @HeaderParam(
-                    value = Constants.USER_ID_HEADER) String userId,
-            @Context final HttpServletRequest request) {
-
-
-        loggerSupportability.log(LoggerSupportabilityActions.UPDATE_PROPERTIES, StatusCode.STARTED,"Starting to delete Resource Instance Property for component {} ",componentId + " by " +  userId );
+    public Response deleteResourceInstanceProperty(@Parameter(description = "service id") @PathParam("componentId") final String componentId,
+                                                   @Parameter(description = "valid values: resources / services", schema = @Schema(allowableValues = {
+                                                       ComponentTypeEnum.RESOURCE_PARAM_NAME,
+                                                       ComponentTypeEnum.SERVICE_PARAM_NAME})) @PathParam("containerComponentType") final String containerComponentType,
+                                                   @Parameter(description = "resource instance id") @PathParam("componentInstanceId") final String componentInstanceId,
+                                                   @Parameter(description = "property id") @PathParam("propertyId") final String propertyId,
+                                                   @Parameter(description = "id of user initiating the operation") @HeaderParam(value = Constants.USER_ID_HEADER) String userId,
+                                                   @Context final HttpServletRequest request) {
+        loggerSupportability
+            .log(LoggerSupportabilityActions.UPDATE_PROPERTIES, StatusCode.STARTED, "Starting to delete Resource Instance Property for component {} ",
+                componentId + " by " + userId);
         String url = request.getMethod() + " " + request.getRequestURI();
         log.debug(START_HANDLE_REQUEST_OF, url);
         try {
-
             ComponentTypeEnum componentTypeEnum = ComponentTypeEnum.findByParamName(containerComponentType);
-            loggerSupportability.log(LoggerSupportabilityActions.UPDATE_PROPERTIES, StatusCode.COMPLETE,"Ended delete Resource Instance Property for component {} ",componentId + " by " +  userId );
+            loggerSupportability
+                .log(LoggerSupportabilityActions.UPDATE_PROPERTIES, StatusCode.COMPLETE, "Ended delete Resource Instance Property for component {} ",
+                    componentId + " by " + userId);
             if (componentInstanceBusinessLogic == null) {
                 log.debug(UNSUPPORTED_COMPONENT_TYPE, containerComponentType);
                 return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.UNSUPPORTED_ERROR, containerComponentType));
             }
-
-            Either<ComponentInstanceProperty, ResponseFormat> actionResponse = componentInstanceBusinessLogic.deletePropertyValue(componentTypeEnum, componentId, componentInstanceId, propertyId, userId);
+            Either<ComponentInstanceProperty, ResponseFormat> actionResponse = componentInstanceBusinessLogic
+                .deletePropertyValue(componentTypeEnum, componentId, componentInstanceId, propertyId, userId);
             if (actionResponse.isRight()) {
                 return buildErrorResponse(actionResponse.right().value());
             }
@@ -810,133 +737,108 @@ public class ComponentInstanceServlet extends AbstractValidationsServlet {
             log.error(CREATE_AND_ASSOCIATE_RI_FAILED_WITH_EXCEPTION, e.getMessage(), e);
             throw e;
         }
-
     }
 
     @POST
     @Path("/{containerComponentType}/{componentId}/resourceInstance/{componentInstanceId}/changeVersion")
     @Consumes(MediaType.APPLICATION_JSON)
     @Produces(MediaType.APPLICATION_JSON)
-    @Operation(description = "Update resource instance", method = "POST", summary = "Returns updated resource instance",
-            responses = {@ApiResponse(
-                    content = @Content(array = @ArraySchema(schema = @Schema(implementation = Response.class)))),
-                    @ApiResponse(responseCode = "201", description = "Resource instance created"),
-                    @ApiResponse(responseCode = "403", description = "Restricted operation"),
-                    @ApiResponse(responseCode = "400", description = "Invalid content / Missing content")})
+    @Operation(description = "Update resource instance", method = "POST", summary = "Returns updated resource instance", responses = {
+        @ApiResponse(content = @Content(array = @ArraySchema(schema = @Schema(implementation = Response.class)))),
+        @ApiResponse(responseCode = "201", description = "Resource instance created"),
+        @ApiResponse(responseCode = "403", description = "Restricted operation"),
+        @ApiResponse(responseCode = "400", description = "Invalid content / Missing content")})
     @PermissionAllowed(AafPermission.PermNames.INTERNAL_ALL_VALUE)
     public Response changeResourceInstanceVersion(@PathParam("componentId") final String componentId,
-            @PathParam("componentInstanceId") final String componentInstanceId,
-            @Parameter(description = "valid values: resources / services",
-                    schema = @Schema(allowableValues = {ComponentTypeEnum.RESOURCE_PARAM_NAME,
-                            ComponentTypeEnum.SERVICE_PARAM_NAME})) @PathParam("containerComponentType") final String containerComponentType,
-            @Context final HttpServletRequest request) throws IOException {
-
+                                                  @PathParam("componentInstanceId") final String componentInstanceId,
+                                                  @Parameter(description = "valid values: resources / services", schema = @Schema(allowableValues = {
+                                                      ComponentTypeEnum.RESOURCE_PARAM_NAME,
+                                                      ComponentTypeEnum.SERVICE_PARAM_NAME})) @PathParam("containerComponentType") final String containerComponentType,
+                                                  @Context final HttpServletRequest request) throws IOException {
         String url = request.getMethod() + " " + request.getRequestURI();
         log.debug(START_HANDLE_REQUEST_OF, url);
-        try (
-            InputStream inputStream = request.getInputStream()) {
-
+        try (InputStream inputStream = request.getInputStream()) {
             byte[] bytes = IOUtils.toByteArray(inputStream);
-
             if (bytes == null || bytes.length == 0) {
                 log.info(EMPTY_BODY_WAS_SENT);
                 return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.INVALID_CONTENT));
             }
-
             String userId = request.getHeader(Constants.USER_ID_HEADER);
             String data = new String(bytes);
-
             if (componentInstanceBusinessLogic == null) {
                 log.debug(UNSUPPORTED_COMPONENT_TYPE, containerComponentType);
                 return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.UNSUPPORTED_ERROR, containerComponentType));
             }
-
             Either<ComponentInstance, ResponseFormat> convertResponse = convertToResourceInstance(data);
-
             if (convertResponse.isRight()) {
                 BeEcompErrorManager.getInstance().logBeSystemError(RESOURCE_INSTANCE_UPDATE_RESOURCE_INSTANCE);
                 log.debug(FAILED_TO_CONVERT_RECEIVED_DATA_TO_BE_FORMAT);
                 return buildErrorResponse(convertResponse.right().value());
             }
-
             ComponentInstance newResourceInstance = convertResponse.left().value();
-            ComponentInstance actionResponse = componentInstanceBusinessLogic.changeComponentInstanceVersion(containerComponentType, componentId, componentInstanceId, userId, newResourceInstance);
-
+            ComponentInstance actionResponse = componentInstanceBusinessLogic
+                .changeComponentInstanceVersion(containerComponentType, componentId, componentInstanceId, userId, newResourceInstance);
             return buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), actionResponse);
-
         } catch (Exception e) {
             BeEcompErrorManager.getInstance().logBeRestApiGeneralError(UPDATE_RESOURCE_INSTANCE);
             log.debug(UPDATE_RESOURCE_INSTANCE_WITH_EXCEPTION, e);
             throw e;
         }
-
     }
 
     @POST
     @Path("/{containerComponentType}/{componentId}/resourceInstance/{componentInstanceId}/groupInstance/{groupInstanceId}/property")
     @Consumes(MediaType.APPLICATION_JSON)
     @Produces(MediaType.APPLICATION_JSON)
-    @Operation(description = "Update resource instance property", method = "POST",
-            summary = "Returns updated resource instance property", responses = {
-            @ApiResponse(content = @Content(array = @ArraySchema(schema = @Schema(implementation = Response.class)))),
-            @ApiResponse(responseCode = "201", description = "Resource instance created"),
-            @ApiResponse(responseCode = "403", description = "Restricted operation"),
-            @ApiResponse(responseCode = "400", description = "Invalid content / Missing content")})
+    @Operation(description = "Update resource instance property", method = "POST", summary = "Returns updated resource instance property", responses = {
+        @ApiResponse(content = @Content(array = @ArraySchema(schema = @Schema(implementation = Response.class)))),
+        @ApiResponse(responseCode = "201", description = "Resource instance created"),
+        @ApiResponse(responseCode = "403", description = "Restricted operation"),
+        @ApiResponse(responseCode = "400", description = "Invalid content / Missing content")})
     @PermissionAllowed(AafPermission.PermNames.INTERNAL_ALL_VALUE)
-    public Response updateGroupInstanceProperty(
-            @Parameter(description = "service id") @PathParam("componentId") final String componentId,
-            @Parameter(description = "valid values: resources / services",
-                    schema = @Schema(allowableValues = {ComponentTypeEnum.RESOURCE_PARAM_NAME,
-                            ComponentTypeEnum.SERVICE_PARAM_NAME})) @PathParam("containerComponentType") final String containerComponentType,
-            @Parameter(
-                    description = "resource instance id") @PathParam("componentInstanceId") final String componentInstanceId,
-            @Parameter(description = "group instance id") @PathParam("groupInstanceId") final String groupInstanceId,
-            @Parameter(description = "id of user initiating the operation") @HeaderParam(
-                    value = Constants.USER_ID_HEADER) String userId,
-            @Context final HttpServletRequest request) throws IOException {
-
+    public Response updateGroupInstanceProperty(@Parameter(description = "service id") @PathParam("componentId") final String componentId,
+                                                @Parameter(description = "valid values: resources / services", schema = @Schema(allowableValues = {
+                                                    ComponentTypeEnum.RESOURCE_PARAM_NAME,
+                                                    ComponentTypeEnum.SERVICE_PARAM_NAME})) @PathParam("containerComponentType") final String containerComponentType,
+                                                @Parameter(description = "resource instance id") @PathParam("componentInstanceId") final String componentInstanceId,
+                                                @Parameter(description = "group instance id") @PathParam("groupInstanceId") final String groupInstanceId,
+                                                @Parameter(description = "id of user initiating the operation") @HeaderParam(value = Constants.USER_ID_HEADER) String userId,
+                                                @Context final HttpServletRequest request) throws IOException {
         String url = request.getMethod() + " " + request.getRequestURI();
         log.debug(START_HANDLE_REQUEST_OF, url);
-
         try {
-            loggerSupportability.log(LoggerSupportabilityActions.UPDATE_PROPERTIES, StatusCode.STARTED,"Starting update Group Instance Property for component {} ",componentId + " by " +  userId );
+            loggerSupportability
+                .log(LoggerSupportabilityActions.UPDATE_PROPERTIES, StatusCode.STARTED, "Starting update Group Instance Property for component {} ",
+                    componentId + " by " + userId);
             Wrapper<String> dataWrapper = new Wrapper<>();
             Wrapper<ResponseFormat> errorWrapper = new Wrapper<>();
             Wrapper<ComponentInstanceProperty> propertyWrapper = new Wrapper<>();
-
             validateInputStream(request, dataWrapper, errorWrapper);
-
             if (errorWrapper.isEmpty()) {
                 validateClassParse(dataWrapper.getInnerElement(), propertyWrapper, () -> ComponentInstanceProperty.class, errorWrapper);
             }
-
             if (!errorWrapper.isEmpty()) {
                 return buildErrorResponse(errorWrapper.getInnerElement());
             }
-
             ComponentInstanceProperty property = propertyWrapper.getInnerElement();
-
             log.debug(START_HANDLE_REQUEST_OF_UPDATE_RESOURCE_INSTANCE_PROPERTY_RECEIVED_PROPERTY_IS, property);
-
-
-
             ComponentTypeEnum componentTypeEnum = ComponentTypeEnum.findByParamName(containerComponentType);
             if (componentInstanceBusinessLogic == null) {
                 log.debug(UNSUPPORTED_COMPONENT_TYPE, containerComponentType);
                 return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.UNSUPPORTED_ERROR, containerComponentType));
             }
-
-            Either<ComponentInstanceProperty, ResponseFormat> actionResponse = componentInstanceBusinessLogic.createOrUpdateGroupInstancePropertyValue(componentTypeEnum, componentId, componentInstanceId, groupInstanceId, property, userId);
+            Either<ComponentInstanceProperty, ResponseFormat> actionResponse = componentInstanceBusinessLogic
+                .createOrUpdateGroupInstancePropertyValue(componentTypeEnum, componentId, componentInstanceId, groupInstanceId, property, userId);
             if (actionResponse.isRight()) {
                 return buildErrorResponse(actionResponse.right().value());
             }
-
             ComponentInstanceProperty resourceInstanceProperty = actionResponse.left().value();
             ObjectMapper mapper = new ObjectMapper();
             String result = mapper.writeValueAsString(resourceInstanceProperty);
-            loggerSupportability.log(LoggerSupportabilityActions.UPDATE_PROPERTIES, StatusCode.COMPLETE,"Ended update Group Instance Property for component {} ",componentId + " by " +  userId );
+            loggerSupportability
+                .log(LoggerSupportabilityActions.UPDATE_PROPERTIES, StatusCode.COMPLETE, "Ended update Group Instance Property for component {} ",
+                    componentId + " by " + userId);
             return buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), result);
-
         } catch (Exception e) {
             log.error(CREATE_AND_ASSOCIATE_RI_FAILED_WITH_EXCEPTION, e.getMessage(), e);
             throw e;
@@ -947,39 +849,32 @@ public class ComponentInstanceServlet extends AbstractValidationsServlet {
     @Path("/{containerComponentType}/{componentId}/resourceInstance/{componentInstanceId}/groupInstance/{groupInstId}")
     @Consumes(MediaType.APPLICATION_JSON)
     @Produces(MediaType.APPLICATION_JSON)
-    @Operation(description = "Get group artifacts ", method = "GET",
-            summary = "Returns artifacts metadata according to groupInstId", responses = {
-            @ApiResponse(content = @Content(array = @ArraySchema(schema = @Schema(implementation = Response.class)))),
-            @ApiResponse(responseCode = "200", description = "group found"),
-            @ApiResponse(responseCode = "403", description = "Restricted operation"),
-            @ApiResponse(responseCode = "404", description = "Group not found")})
+    @Operation(description = "Get group artifacts ", method = "GET", summary = "Returns artifacts metadata according to groupInstId", responses = {
+        @ApiResponse(content = @Content(array = @ArraySchema(schema = @Schema(implementation = Response.class)))),
+        @ApiResponse(responseCode = "200", description = "group found"), @ApiResponse(responseCode = "403", description = "Restricted operation"),
+        @ApiResponse(responseCode = "404", description = "Group not found")})
     @PermissionAllowed(AafPermission.PermNames.INTERNAL_ALL_VALUE)
     public Response getGroupArtifactById(@PathParam("containerComponentType") final String containerComponentType,
-            @PathParam("componentId") final String componentId,
-            @PathParam("componentInstanceId") final String componentInstanceId,
-            @PathParam("groupInstId") final String groupInstId, @Context final HttpServletRequest request,
-            @HeaderParam(value = Constants.USER_ID_HEADER) String userId) {
+                                         @PathParam("componentId") final String componentId,
+                                         @PathParam("componentInstanceId") final String componentInstanceId,
+                                         @PathParam("groupInstId") final String groupInstId, @Context final HttpServletRequest request,
+                                         @HeaderParam(value = Constants.USER_ID_HEADER) String userId) {
         String url = request.getMethod() + " " + request.getRequestURI();
         log.debug(GET_START_HANDLE_REQUEST_OF, url);
-
         try {
-
             ComponentTypeEnum componentTypeEnum = ComponentTypeEnum.findByParamName(containerComponentType);
-            Either<GroupDefinitionInfo, ResponseFormat> actionResponse = groupBL.getGroupInstWithArtifactsById(componentTypeEnum, componentId, componentInstanceId, groupInstId, userId, false);
-
+            Either<GroupDefinitionInfo, ResponseFormat> actionResponse = groupBL
+                .getGroupInstWithArtifactsById(componentTypeEnum, componentId, componentInstanceId, groupInstId, userId, false);
             if (actionResponse.isRight()) {
                 log.debug("failed to get all non abstract {}", containerComponentType);
                 return buildErrorResponse(actionResponse.right().value());
             }
-
             return buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), actionResponse.left().value());
-
         } catch (Exception e) {
             BeEcompErrorManager.getInstance().logBeRestApiGeneralError(GET_GROUP_ARTIFACT_BY_ID);
             log.debug(GET_GROUP_ARTIFACT_BY_ID_UNEXPECTED_EXCEPTION, e);
             throw e;
         }
-
     }
 
     // US831698
@@ -987,23 +882,21 @@ public class ComponentInstanceServlet extends AbstractValidationsServlet {
     @Path("/{containerComponentType}/{containerComponentId}/componentInstances/{componentInstanceUniqueId}/properties")
     @Consumes(MediaType.APPLICATION_JSON)
     @Produces(MediaType.APPLICATION_JSON)
-    @Operation(description = "Get component instance properties", method = "GET",
-            summary = "Returns component instance properties", responses = {
-            @ApiResponse(content = @Content(array = @ArraySchema(schema = @Schema(implementation = Response.class)))),
-            @ApiResponse(responseCode = "200", description = "Properties found"),
-            @ApiResponse(responseCode = "403", description = "Restricted operation"),
-            @ApiResponse(responseCode = "404", description = "Component/Component Instance - not found")})
+    @Operation(description = "Get component instance properties", method = "GET", summary = "Returns component instance properties", responses = {
+        @ApiResponse(content = @Content(array = @ArraySchema(schema = @Schema(implementation = Response.class)))),
+        @ApiResponse(responseCode = "200", description = "Properties found"),
+        @ApiResponse(responseCode = "403", description = "Restricted operation"),
+        @ApiResponse(responseCode = "404", description = "Component/Component Instance - not found")})
     @PermissionAllowed(AafPermission.PermNames.INTERNAL_ALL_VALUE)
     public Response getInstancePropertiesById(@PathParam("containerComponentType") final String containerComponentType,
-            @PathParam("containerComponentId") final String containerComponentId,
-            @PathParam("componentInstanceUniqueId") final String componentInstanceUniqueId,
-            @Context final HttpServletRequest request, @HeaderParam(value = Constants.USER_ID_HEADER) String userId) {
-
-
+                                              @PathParam("containerComponentId") final String containerComponentId,
+                                              @PathParam("componentInstanceUniqueId") final String componentInstanceUniqueId,
+                                              @Context final HttpServletRequest request,
+                                              @HeaderParam(value = Constants.USER_ID_HEADER) String userId) {
         String url = request.getMethod() + " " + request.getRequestURI();
         log.debug(GET_START_HANDLE_REQUEST_OF, url);
-
-        List<ComponentInstanceProperty> componentInstancePropertiesById = componentInstanceBusinessLogic.getComponentInstancePropertiesById(containerComponentType, containerComponentId, componentInstanceUniqueId, userId);
+        List<ComponentInstanceProperty> componentInstancePropertiesById = componentInstanceBusinessLogic
+            .getComponentInstancePropertiesById(containerComponentType, containerComponentId, componentInstanceUniqueId, userId);
         return buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), componentInstancePropertiesById);
     }
 
@@ -1011,21 +904,19 @@ public class ComponentInstanceServlet extends AbstractValidationsServlet {
     @Path("/{containerComponentType}/{containerComponentId}/componentInstances/{componentInstanceUniqueId}/attributes")
     @Consumes(MediaType.APPLICATION_JSON)
     @Produces(MediaType.APPLICATION_JSON)
-    @Operation(description = "Get component instance attributes", method = "GET",
-            summary = "Returns component instance attributes", responses = {
-            @ApiResponse(content = @Content(array = @ArraySchema(schema = @Schema(implementation = Response.class)))),
-            @ApiResponse(responseCode = "200", description = "Attributes found"),
-            @ApiResponse(responseCode = "403", description = "Restricted operation"),
-            @ApiResponse(responseCode = "404", description = "Component/Component Instance - not found")})
+    @Operation(description = "Get component instance attributes", method = "GET", summary = "Returns component instance attributes", responses = {
+        @ApiResponse(content = @Content(array = @ArraySchema(schema = @Schema(implementation = Response.class)))),
+        @ApiResponse(responseCode = "200", description = "Attributes found"),
+        @ApiResponse(responseCode = "403", description = "Restricted operation"),
+        @ApiResponse(responseCode = "404", description = "Component/Component Instance - not found")})
     @PermissionAllowed(AafPermission.PermNames.INTERNAL_ALL_VALUE)
     public Response getInstanceAttributesById(@PathParam("containerComponentType") final String containerComponentType,
-            @PathParam("containerComponentId") final String containerComponentId,
-            @PathParam("componentInstanceUniqueId") final String componentInstanceUniqueId,
-            @Context final HttpServletRequest request, @HeaderParam(value = Constants.USER_ID_HEADER) final String userId) {
-
+                                              @PathParam("containerComponentId") final String containerComponentId,
+                                              @PathParam("componentInstanceUniqueId") final String componentInstanceUniqueId,
+                                              @Context final HttpServletRequest request,
+                                              @HeaderParam(value = Constants.USER_ID_HEADER) final String userId) {
         final String url = request.getMethod() + " " + request.getRequestURI();
         log.debug(GET_START_HANDLE_REQUEST_OF, url);
-
         final List<ComponentInstanceAttribute> componentInstanceAttributesById = componentInstanceBusinessLogic
             .getComponentInstanceAttributesById(containerComponentType, containerComponentId, componentInstanceUniqueId, userId);
         return buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), componentInstanceAttributesById);
@@ -1036,36 +927,31 @@ public class ComponentInstanceServlet extends AbstractValidationsServlet {
     @Path("/{containerComponentType}/{containerComponentId}/componentInstances/{componentInstanceUniqueId}/capability/{capabilityType}/capabilityName/{capabilityName}/ownerId/{ownerId}/properties")
     @Consumes(MediaType.APPLICATION_JSON)
     @Produces(MediaType.APPLICATION_JSON)
-    @Operation(description = "Get component instance capability properties", method = "GET",
-            summary = "Returns component instance capability properties", responses = {
-            @ApiResponse(content = @Content(array = @ArraySchema(schema = @Schema(implementation = Response.class)))),
-            @ApiResponse(responseCode = "200", description = "Properties found"),
-            @ApiResponse(responseCode = "403", description = "Restricted operation"),
-            @ApiResponse(responseCode = "404", description = "Component/Component Instance/Capability - not found")})
+    @Operation(description = "Get component instance capability properties", method = "GET", summary = "Returns component instance capability properties", responses = {
+        @ApiResponse(content = @Content(array = @ArraySchema(schema = @Schema(implementation = Response.class)))),
+        @ApiResponse(responseCode = "200", description = "Properties found"),
+        @ApiResponse(responseCode = "403", description = "Restricted operation"),
+        @ApiResponse(responseCode = "404", description = "Component/Component Instance/Capability - not found")})
     @PermissionAllowed(AafPermission.PermNames.INTERNAL_ALL_VALUE)
-    public Response getInstanceCapabilityPropertiesById(
-            @PathParam("containerComponentType") final String containerComponentType,
-            @PathParam("containerComponentId") final String containerComponentId,
-            @PathParam("componentInstanceUniqueId") final String componentInstanceUniqueId,
-            @PathParam("capabilityType") final String capabilityType,
-            @PathParam("capabilityName") final String capabilityName, @PathParam("ownerId") final String ownerId,
-            @Context final HttpServletRequest request, @HeaderParam(value = Constants.USER_ID_HEADER) String userId) {
-
-
+    public Response getInstanceCapabilityPropertiesById(@PathParam("containerComponentType") final String containerComponentType,
+                                                        @PathParam("containerComponentId") final String containerComponentId,
+                                                        @PathParam("componentInstanceUniqueId") final String componentInstanceUniqueId,
+                                                        @PathParam("capabilityType") final String capabilityType,
+                                                        @PathParam("capabilityName") final String capabilityName,
+                                                        @PathParam("ownerId") final String ownerId, @Context final HttpServletRequest request,
+                                                        @HeaderParam(value = Constants.USER_ID_HEADER) String userId) {
         String url = request.getMethod() + " " + request.getRequestURI();
         log.debug(GET_START_HANDLE_REQUEST_OF, url);
-
         try {
-            List<ComponentInstanceProperty> componentInstancePropertiesById = componentInstanceBusinessLogic.getComponentInstanceCapabilityPropertiesById(containerComponentType, containerComponentId, componentInstanceUniqueId,
-                    capabilityType, capabilityName, ownerId, userId);
-
+            List<ComponentInstanceProperty> componentInstancePropertiesById = componentInstanceBusinessLogic
+                .getComponentInstanceCapabilityPropertiesById(containerComponentType, containerComponentId, componentInstanceUniqueId, capabilityType,
+                    capabilityName, ownerId, userId);
             return buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), componentInstancePropertiesById);
         } catch (Exception e) {
             BeEcompErrorManager.getInstance().logBeRestApiGeneralError(GET_GROUP_ARTIFACT_BY_ID);
             log.debug(GET_GROUP_ARTIFACT_BY_ID_UNEXPECTED_EXCEPTION, e);
             throw e;
         }
-
     }
 
     //US 331281
@@ -1073,25 +959,26 @@ public class ComponentInstanceServlet extends AbstractValidationsServlet {
     @Path("/{containerComponentType}/{containerComponentId}/componentInstances/{componentInstanceUniqueId}/capability/{capabilityType}/capabilityName/{capabilityName}/ownerId/{ownerId}/properties")
     @Consumes(MediaType.APPLICATION_JSON)
     @Produces(MediaType.APPLICATION_JSON)
-    @Operation(description = "Update Instance Capabilty  Property", method = "PUT",
-            summary = "Returns updated property", responses = {
-            @ApiResponse(content = @Content(array = @ArraySchema(schema = @Schema(implementation = Response.class)))),
-            @ApiResponse(responseCode = "200", description = "Resource instance capabilty property updated"),
-            @ApiResponse(responseCode = "403", description = "Restricted operation"),
-            @ApiResponse(responseCode = "400", description = "Invalid content / Missing content"),
-            @ApiResponse(responseCode = "404", description = "Component/Component Instance/Capability - not found")})
+    @Operation(description = "Update Instance Capabilty  Property", method = "PUT", summary = "Returns updated property", responses = {
+        @ApiResponse(content = @Content(array = @ArraySchema(schema = @Schema(implementation = Response.class)))),
+        @ApiResponse(responseCode = "200", description = "Resource instance capabilty property updated"),
+        @ApiResponse(responseCode = "403", description = "Restricted operation"),
+        @ApiResponse(responseCode = "400", description = "Invalid content / Missing content"),
+        @ApiResponse(responseCode = "404", description = "Component/Component Instance/Capability - not found")})
     @PermissionAllowed(AafPermission.PermNames.INTERNAL_ALL_VALUE)
-    public Response updateInstanceCapabilityProperty(
-            @PathParam("containerComponentType") final String containerComponentType,
-            @PathParam("containerComponentId") final String containerComponentId,
-            @PathParam("componentInstanceUniqueId") final String componentInstanceUniqueId,
-            @PathParam("capabilityType") final String capabilityType,
-            @PathParam("capabilityName") final String capabilityName, @PathParam("ownerId") final String ownerId,
-            @Parameter(description = "Instance capabilty property to update", required = true) String data,
-            @Context final HttpServletRequest request, @HeaderParam(value = Constants.USER_ID_HEADER) String userId) {
+    public Response updateInstanceCapabilityProperty(@PathParam("containerComponentType") final String containerComponentType,
+                                                     @PathParam("containerComponentId") final String containerComponentId,
+                                                     @PathParam("componentInstanceUniqueId") final String componentInstanceUniqueId,
+                                                     @PathParam("capabilityType") final String capabilityType,
+                                                     @PathParam("capabilityName") final String capabilityName,
+                                                     @PathParam("ownerId") final String ownerId,
+                                                     @Parameter(description = "Instance capabilty property to update", required = true) String data,
+                                                     @Context final HttpServletRequest request,
+                                                     @HeaderParam(value = Constants.USER_ID_HEADER) String userId) {
         String url = request.getMethod() + " " + request.getRequestURI();
         log.debug("(PUT) Start handle request of {}", url);
-        loggerSupportability.log(LoggerSupportabilityActions.UPDATE_INSTANCE_CAPABILITY_PROPERTY, StatusCode.STARTED," Starting to update Instance Capability Property for component instance {} " , componentInstanceUniqueId + " by " + userId);
+        loggerSupportability.log(LoggerSupportabilityActions.UPDATE_INSTANCE_CAPABILITY_PROPERTY, StatusCode.STARTED,
+            " Starting to update Instance Capability Property for component instance {} ", componentInstanceUniqueId + " by " + userId);
         try {
             Wrapper<ResponseFormat> errorWrapper = new Wrapper<>();
             List<ComponentInstanceProperty> propertiesToUpdate = new ArrayList<>();
@@ -1103,20 +990,20 @@ public class ComponentInstanceServlet extends AbstractValidationsServlet {
                     propertiesToUpdate = propertiesToUpdateEither.left().value();
                 }
             }
-
             if (!errorWrapper.isEmpty()) {
                 return buildErrorResponse(errorWrapper.getInnerElement());
             }
-
             ComponentTypeEnum componentTypeEnum = ComponentTypeEnum.findByParamName(containerComponentType);
-
-            Either<List<ComponentInstanceProperty>, ResponseFormat> updateCICapProperty = componentInstanceBusinessLogic.updateInstanceCapabilityProperties(componentTypeEnum, containerComponentId, componentInstanceUniqueId, capabilityType, capabilityName, propertiesToUpdate, userId);
-
+            Either<List<ComponentInstanceProperty>, ResponseFormat> updateCICapProperty = componentInstanceBusinessLogic
+                .updateInstanceCapabilityProperties(componentTypeEnum, containerComponentId, componentInstanceUniqueId, capabilityType,
+                    capabilityName, propertiesToUpdate, userId);
             if (updateCICapProperty.isRight()) {
-                log.debug(FAILED_TO_GET_PROPERTIES_OF_COMPONENT_INSTANCE_ID_IN_WITH_ID, componentInstanceUniqueId, containerComponentType, containerComponentId);
+                log.debug(FAILED_TO_GET_PROPERTIES_OF_COMPONENT_INSTANCE_ID_IN_WITH_ID, componentInstanceUniqueId, containerComponentType,
+                    containerComponentId);
                 return buildErrorResponse(updateCICapProperty.right().value());
             }
-            loggerSupportability.log(LoggerSupportabilityActions.UPDATE_INSTANCE_CAPABILITY_PROPERTY, StatusCode.COMPLETE," Ended to update Instance Capability Property for component instance {} " , componentInstanceUniqueId + " by " + userId);
+            loggerSupportability.log(LoggerSupportabilityActions.UPDATE_INSTANCE_CAPABILITY_PROPERTY, StatusCode.COMPLETE,
+                " Ended to update Instance Capability Property for component instance {} ", componentInstanceUniqueId + " by " + userId);
             return buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), updateCICapProperty.left().value());
         } catch (Exception e) {
             BeEcompErrorManager.getInstance().logBeRestApiGeneralError(GET_GROUP_ARTIFACT_BY_ID);
@@ -1124,55 +1011,50 @@ public class ComponentInstanceServlet extends AbstractValidationsServlet {
             throw e;
         }
     }
-    
+
     @PUT
     @Path("/{containerComponentType}/{containerComponentId}/componentInstances/{componentInstanceUniqueId}/requirement/{capabilityType}/requirementName/{requirementName}")
     @Consumes(MediaType.APPLICATION_JSON)
     @Produces(MediaType.APPLICATION_JSON)
-    @Operation(description = "Update Instance Requirement", method = "PUT",
-            summary = "Returns updated requirement", responses = {
-            @ApiResponse(content = @Content(array = @ArraySchema(schema = @Schema(implementation = Response.class)))),
-            @ApiResponse(responseCode = "200", description = "Resource instance requirement updated"),
-            @ApiResponse(responseCode = "403", description = "Restricted operation"),
-            @ApiResponse(responseCode = "400", description = "Invalid content / Missing content"),
-            @ApiResponse(responseCode = "404", description = "Component/Component Instance/Requirement - not found")})
+    @Operation(description = "Update Instance Requirement", method = "PUT", summary = "Returns updated requirement", responses = {
+        @ApiResponse(content = @Content(array = @ArraySchema(schema = @Schema(implementation = Response.class)))),
+        @ApiResponse(responseCode = "200", description = "Resource instance requirement updated"),
+        @ApiResponse(responseCode = "403", description = "Restricted operation"),
+        @ApiResponse(responseCode = "400", description = "Invalid content / Missing content"),
+        @ApiResponse(responseCode = "404", description = "Component/Component Instance/Requirement - not found")})
     @PermissionAllowed(AafPermission.PermNames.INTERNAL_ALL_VALUE)
-    public Response updateInstanceRequirement(
-        @PathParam("containerComponentType") final String containerComponentType,
-        @PathParam("containerComponentId") final String containerComponentId,
-        @PathParam("componentInstanceUniqueId") final String componentInstanceUniqueId,
-            @PathParam("capabilityType") final String capabilityType,
-        @PathParam("requirementName") final String requirementName,
-        @Parameter(description = "Instance capabilty requirement to update", required = true) String data,
-        @Context final HttpServletRequest request, @HeaderParam(value = Constants.USER_ID_HEADER) String userId) {
+    public Response updateInstanceRequirement(@PathParam("containerComponentType") final String containerComponentType,
+                                              @PathParam("containerComponentId") final String containerComponentId,
+                                              @PathParam("componentInstanceUniqueId") final String componentInstanceUniqueId,
+                                              @PathParam("capabilityType") final String capabilityType,
+                                              @PathParam("requirementName") final String requirementName,
+                                              @Parameter(description = "Instance capabilty requirement to update", required = true) String data,
+                                              @Context final HttpServletRequest request,
+                                              @HeaderParam(value = Constants.USER_ID_HEADER) String userId) {
         String url = request.getMethod() + " " + request.getRequestURI();
         log.debug(START_HANDLE_REQUEST_OF, url);
-        loggerSupportability.log(LoggerSupportabilityActions.UPDATE_INSTANCE_REQUIREMENT, StatusCode.STARTED,"Starting to update requirement {} in component instance {} by {}", requirementName, componentInstanceUniqueId, userId );
+        loggerSupportability.log(LoggerSupportabilityActions.UPDATE_INSTANCE_REQUIREMENT, StatusCode.STARTED,
+            "Starting to update requirement {} in component instance {} by {}", requirementName, componentInstanceUniqueId, userId);
         try {
-
             log.debug(START_HANDLE_REQUEST_OF, url);
-
             ComponentTypeEnum componentTypeEnum = ComponentTypeEnum.findByParamName(containerComponentType);
             if (componentInstanceBusinessLogic == null) {
                 log.debug(UNSUPPORTED_COMPONENT_TYPE, containerComponentType);
                 return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.UNSUPPORTED_ERROR, containerComponentType));
             }
-            
-            Either<RequirementDefinition, ResponseFormat>  mappedRequirementDataEither = getMappedRequirementData(data, new User(userId), componentTypeEnum);
-            if(mappedRequirementDataEither.isRight()) {
+            Either<RequirementDefinition, ResponseFormat> mappedRequirementDataEither = getMappedRequirementData(data, new User(userId),
+                componentTypeEnum);
+            if (mappedRequirementDataEither.isRight()) {
                 log.debug("Failed to update requirements");
                 return buildErrorResponse(mappedRequirementDataEither.right().value());
             }
             RequirementDefinition requirementDef = mappedRequirementDataEither.left().value();
-            
-            Either<RequirementDefinition, ResponseFormat> response = componentInstanceBusinessLogic.updateInstanceRequirement(componentTypeEnum, containerComponentId, componentInstanceUniqueId,
-                requirementDef, userId);
-            
+            Either<RequirementDefinition, ResponseFormat> response = componentInstanceBusinessLogic
+                .updateInstanceRequirement(componentTypeEnum, containerComponentId, componentInstanceUniqueId, requirementDef, userId);
             if (response.isRight()) {
                 return buildErrorResponse(response.right().value());
             }
             return buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), response.left().value());
-            
         } catch (ComponentException e) {
             throw e;
         } catch (Exception e) {
@@ -1181,35 +1063,32 @@ public class ComponentInstanceServlet extends AbstractValidationsServlet {
             return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR));
         }
     }
-    
-    private Either<RequirementDefinition, ResponseFormat>  getMappedRequirementData(String inputJson, User user,
-            ComponentTypeEnum componentTypeEnum){
-        return getComponentsUtils().convertJsonToObjectUsingObjectMapper(inputJson, user, RequirementDefinition.class, AuditingActionEnum.GET_TOSCA_MODEL, componentTypeEnum);
+
+    private Either<RequirementDefinition, ResponseFormat> getMappedRequirementData(String inputJson, User user, ComponentTypeEnum componentTypeEnum) {
+        return getComponentsUtils()
+            .convertJsonToObjectUsingObjectMapper(inputJson, user, RequirementDefinition.class, AuditingActionEnum.GET_TOSCA_MODEL,
+                componentTypeEnum);
     }
 
     @POST
     @Path("/{containerComponentType}/{containerComponentId}/serviceProxy")
     @Consumes(MediaType.APPLICATION_JSON)
     @Produces(MediaType.APPLICATION_JSON)
-    @Operation(description = "Create service proxy", method = "POST", summary = "Returns created service proxy",
-            responses = {@ApiResponse(
-                    content = @Content(array = @ArraySchema(schema = @Schema(implementation = Response.class)))),
-                    @ApiResponse(responseCode = "201", description = "Service proxy created"),
-                    @ApiResponse(responseCode = "403", description = "Restricted operation"),
-                    @ApiResponse(responseCode = "400", description = "Invalid content / Missing content"),
-                    @ApiResponse(responseCode = "409", description = "Service proxy already exist")})
+    @Operation(description = "Create service proxy", method = "POST", summary = "Returns created service proxy", responses = {
+        @ApiResponse(content = @Content(array = @ArraySchema(schema = @Schema(implementation = Response.class)))),
+        @ApiResponse(responseCode = "201", description = "Service proxy created"),
+        @ApiResponse(responseCode = "403", description = "Restricted operation"),
+        @ApiResponse(responseCode = "400", description = "Invalid content / Missing content"),
+        @ApiResponse(responseCode = "409", description = "Service proxy already exist")})
     @PermissionAllowed(AafPermission.PermNames.INTERNAL_ALL_VALUE)
     public Response createServiceProxy(@Parameter(description = "RI object to be created", required = true) String data,
-            @PathParam("containerComponentId") final String containerComponentId,
-            @Parameter(description = "valid values: resources / services",
-                    schema = @Schema(allowableValues = {ComponentTypeEnum.RESOURCE_PARAM_NAME,
-                            ComponentTypeEnum.SERVICE_PARAM_NAME})) @PathParam("containerComponentType") final String containerComponentType,
-            @HeaderParam(value = Constants.USER_ID_HEADER) @Parameter(description = "USER_ID of modifier user",
-                    required = true) String userId,
-            @Context final HttpServletRequest request) {
-
+                                       @PathParam("containerComponentId") final String containerComponentId,
+                                       @Parameter(description = "valid values: resources / services", schema = @Schema(allowableValues = {
+                                           ComponentTypeEnum.RESOURCE_PARAM_NAME,
+                                           ComponentTypeEnum.SERVICE_PARAM_NAME})) @PathParam("containerComponentType") final String containerComponentType,
+                                       @HeaderParam(value = Constants.USER_ID_HEADER) @Parameter(description = "USER_ID of modifier user", required = true) String userId,
+                                       @Context final HttpServletRequest request) {
         try {
-
             ComponentInstance componentInstance = RepresentationUtils.fromRepresentation(data, ComponentInstance.class);
             componentInstance.setInvariantName(null);
             ComponentTypeEnum componentTypeEnum = ComponentTypeEnum.findByParamName(containerComponentType);
@@ -1222,12 +1101,10 @@ public class ComponentInstanceServlet extends AbstractValidationsServlet {
                 return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.UNSUPPORTED_ERROR, containerComponentType));
             }
             Either<ComponentInstance, ResponseFormat> actionResponse = componentInstanceBusinessLogic.createServiceProxy();
-
             if (actionResponse.isRight()) {
                 return buildErrorResponse(actionResponse.right().value());
             }
             return buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.CREATED), actionResponse.left().value());
-
         } catch (Exception e) {
             BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Create service proxy");
             log.debug("Create service proxy failed with exception", e);
@@ -1239,20 +1116,18 @@ public class ComponentInstanceServlet extends AbstractValidationsServlet {
     @Path("/{containerComponentType}/{containerComponentId}/serviceProxy/{serviceProxyId}")
     @Consumes(MediaType.APPLICATION_JSON)
     @Produces(MediaType.APPLICATION_JSON)
-    @Operation(description = "Delete service proxy", method = "DELETE", summary = "Returns delete service proxy",
-            responses = {@ApiResponse(
-                    content = @Content(array = @ArraySchema(schema = @Schema(implementation = Response.class)))),
-                    @ApiResponse(responseCode = "201", description = "Service proxy deleted"),
-                    @ApiResponse(responseCode = "403", description = "Restricted operation"),
-                    @ApiResponse(responseCode = "400", description = "Invalid content / Missing content")})
+    @Operation(description = "Delete service proxy", method = "DELETE", summary = "Returns delete service proxy", responses = {
+        @ApiResponse(content = @Content(array = @ArraySchema(schema = @Schema(implementation = Response.class)))),
+        @ApiResponse(responseCode = "201", description = "Service proxy deleted"),
+        @ApiResponse(responseCode = "403", description = "Restricted operation"),
+        @ApiResponse(responseCode = "400", description = "Invalid content / Missing content")})
     @PermissionAllowed(AafPermission.PermNames.INTERNAL_ALL_VALUE)
     public Response deleteServiceProxy(@PathParam("containerComponentId") final String containerComponentId,
-            @PathParam("serviceProxyId") final String serviceProxyId,
-            @Parameter(description = "valid values: resources / services / products",
-                    schema = @Schema(allowableValues = {ComponentTypeEnum.RESOURCE_PARAM_NAME,
-                            ComponentTypeEnum.SERVICE_PARAM_NAME})) @PathParam("containerComponentType") final String containerComponentType,
-            @Context final HttpServletRequest request) {
-
+                                       @PathParam("serviceProxyId") final String serviceProxyId,
+                                       @Parameter(description = "valid values: resources / services / products", schema = @Schema(allowableValues = {
+                                           ComponentTypeEnum.RESOURCE_PARAM_NAME,
+                                           ComponentTypeEnum.SERVICE_PARAM_NAME})) @PathParam("containerComponentType") final String containerComponentType,
+                                       @Context final HttpServletRequest request) {
         String url = request.getMethod() + " " + request.getRequestURI();
         try {
             log.debug(START_HANDLE_REQUEST_OF, url);
@@ -1261,7 +1136,6 @@ public class ComponentInstanceServlet extends AbstractValidationsServlet {
                 return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.UNSUPPORTED_ERROR, containerComponentType));
             }
             Either<ComponentInstance, ResponseFormat> actionResponse = componentInstanceBusinessLogic.deleteServiceProxy();
-
             if (actionResponse.isRight()) {
                 return buildErrorResponse(actionResponse.right().value());
             } else {
@@ -1278,21 +1152,18 @@ public class ComponentInstanceServlet extends AbstractValidationsServlet {
     @Path("/{containerComponentType}/{containerComponentId}/serviceProxy/{serviceProxyId}/changeVersion/{newServiceId}")
     @Consumes(MediaType.APPLICATION_JSON)
     @Produces(MediaType.APPLICATION_JSON)
-    @Operation(description = "Update service proxy with new version", method = "POST",
-            summary = "Returns updated service proxy", responses = {
-            @ApiResponse(content = @Content(array = @ArraySchema(schema = @Schema(implementation = Response.class)))),
-            @ApiResponse(responseCode = "201", description = "Service proxy created"),
-            @ApiResponse(responseCode = "403", description = "Restricted operation"),
-            @ApiResponse(responseCode = "400", description = "Invalid content / Missing content")})
+    @Operation(description = "Update service proxy with new version", method = "POST", summary = "Returns updated service proxy", responses = {
+        @ApiResponse(content = @Content(array = @ArraySchema(schema = @Schema(implementation = Response.class)))),
+        @ApiResponse(responseCode = "201", description = "Service proxy created"),
+        @ApiResponse(responseCode = "403", description = "Restricted operation"),
+        @ApiResponse(responseCode = "400", description = "Invalid content / Missing content")})
     @PermissionAllowed(AafPermission.PermNames.INTERNAL_ALL_VALUE)
     public Response changeServiceProxyVersion(@PathParam("containerComponentId") final String containerComponentId,
-            @PathParam("serviceProxyId") final String serviceProxyId,
-            @Parameter(description = "valid values: resources / services",
-                    schema = @Schema(allowableValues = {ComponentTypeEnum.RESOURCE_PARAM_NAME,
-                            ComponentTypeEnum.SERVICE_PARAM_NAME})) @PathParam("containerComponentType") final String containerComponentType,
-            @Context final HttpServletRequest request) {
-
-
+                                              @PathParam("serviceProxyId") final String serviceProxyId,
+                                              @Parameter(description = "valid values: resources / services", schema = @Schema(allowableValues = {
+                                                  ComponentTypeEnum.RESOURCE_PARAM_NAME,
+                                                  ComponentTypeEnum.SERVICE_PARAM_NAME})) @PathParam("containerComponentType") final String containerComponentType,
+                                              @Context final HttpServletRequest request) {
         String url = request.getMethod() + " " + request.getRequestURI();
         log.debug(START_HANDLE_REQUEST_OF, url);
         try {
@@ -1301,21 +1172,20 @@ public class ComponentInstanceServlet extends AbstractValidationsServlet {
                 return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.UNSUPPORTED_ERROR, containerComponentType));
             }
             Either<ComponentInstance, ResponseFormat> actionResponse = componentInstanceBusinessLogic.changeServiceProxyVersion();
-
             if (actionResponse.isRight()) {
                 return buildErrorResponse(actionResponse.right().value());
             }
             return buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), actionResponse.left().value());
-
         } catch (Exception e) {
             BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Update service proxy with new version");
             log.debug("Update service proxy with new version failed with exception", e);
             throw e;
         }
     }
+
     /**
-     * REST API GET relation by Id
-     * Allows to get relation contained in specified component according to received Id
+     * REST API GET relation by Id Allows to get relation contained in specified component according to received Id
+     *
      * @param containerComponentType
      * @param componentId
      * @param relationId
@@ -1327,18 +1197,14 @@ public class ComponentInstanceServlet extends AbstractValidationsServlet {
     @Path("/{containerComponentType}/{componentId}/relationId/{relationId}")
     @Consumes(MediaType.APPLICATION_JSON)
     @Produces(MediaType.APPLICATION_JSON)
-    @Operation(description = "Get relation", method = "GET",
-            summary = "Returns relation metadata according to relationId", responses = {
-            @ApiResponse(content = @Content(array = @ArraySchema(schema = @Schema(implementation = Response.class)))),
-            @ApiResponse(responseCode = "200", description = "relation found"),
-            @ApiResponse(responseCode = "403", description = "Restricted operation"),
-            @ApiResponse(responseCode = "404", description = "Relation not found")})
+    @Operation(description = "Get relation", method = "GET", summary = "Returns relation metadata according to relationId", responses = {
+        @ApiResponse(content = @Content(array = @ArraySchema(schema = @Schema(implementation = Response.class)))),
+        @ApiResponse(responseCode = "200", description = "relation found"), @ApiResponse(responseCode = "403", description = "Restricted operation"),
+        @ApiResponse(responseCode = "404", description = "Relation not found")})
     @PermissionAllowed(AafPermission.PermNames.INTERNAL_ALL_VALUE)
     public Response getRelationById(@PathParam("containerComponentType") final String containerComponentType,
-            @PathParam("componentId") final String componentId, @PathParam("relationId") final String relationId,
-            @Context final HttpServletRequest request, @HeaderParam(value = Constants.USER_ID_HEADER) String userId) {
-
-
+                                    @PathParam("componentId") final String componentId, @PathParam("relationId") final String relationId,
+                                    @Context final HttpServletRequest request, @HeaderParam(value = Constants.USER_ID_HEADER) String userId) {
         String url = request.getMethod() + " " + request.getRequestURI();
         log.debug(GET_START_HANDLE_REQUEST_OF, url);
         try {
@@ -1347,8 +1213,8 @@ public class ComponentInstanceServlet extends AbstractValidationsServlet {
                 log.debug(UNSUPPORTED_COMPONENT_TYPE, containerComponentType);
                 return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.UNSUPPORTED_ERROR, containerComponentType));
             }
-
-            Either<RequirementCapabilityRelDef, ResponseFormat> actionResponse = componentInstanceBusinessLogic.getRelationById(componentId, relationId, userId, componentTypeEnum);
+            Either<RequirementCapabilityRelDef, ResponseFormat> actionResponse = componentInstanceBusinessLogic
+                .getRelationById(componentId, relationId, userId, componentTypeEnum);
             if (actionResponse.isRight()) {
                 return buildErrorResponse(actionResponse.right().value());
             }
@@ -1361,23 +1227,21 @@ public class ComponentInstanceServlet extends AbstractValidationsServlet {
     }
 
     private Either<ComponentInstance, ResponseFormat> convertToResourceInstance(String data) {
-
-        Either<ComponentInstance, ResponseFormat> convertStatus = getComponentsUtils().convertJsonToObjectUsingObjectMapper(data, new User(), ComponentInstance.class, null, ComponentTypeEnum.RESOURCE_INSTANCE);
+        Either<ComponentInstance, ResponseFormat> convertStatus = getComponentsUtils()
+            .convertJsonToObjectUsingObjectMapper(data, new User(), ComponentInstance.class, null, ComponentTypeEnum.RESOURCE_INSTANCE);
         if (convertStatus.isRight()) {
             return Either.right(convertStatus.right().value());
         }
         ComponentInstance resourceInstanceInfo = convertStatus.left().value();
-
         return Either.left(resourceInstanceInfo);
     }
 
     private Either<List<ComponentInstance>, ResponseFormat> convertToMultipleResourceInstance(String dataList) {
-
-        Either<ComponentInstance[], ResponseFormat> convertStatus = getComponentsUtils().convertJsonToObjectUsingObjectMapper(dataList, new User(), ComponentInstance[].class, null, ComponentTypeEnum.RESOURCE_INSTANCE);
+        Either<ComponentInstance[], ResponseFormat> convertStatus = getComponentsUtils()
+            .convertJsonToObjectUsingObjectMapper(dataList, new User(), ComponentInstance[].class, null, ComponentTypeEnum.RESOURCE_INSTANCE);
         if (convertStatus.isRight()) {
             return Either.right(convertStatus.right().value());
         }
-
         return Either.left(Arrays.asList(convertStatus.left().value()));
     }
 
@@ -1385,7 +1249,8 @@ public class ComponentInstanceServlet extends AbstractValidationsServlet {
         if (StringUtils.isEmpty(dataList)) {
             return Either.right(getComponentsUtils().getResponseFormat(ActionStatus.MISSING_BODY));
         }
-        Either<ComponentInstanceProperty[], ResponseFormat> convertStatus = getComponentsUtils().convertJsonToObjectUsingObjectMapper(dataList, new User(), ComponentInstanceProperty[].class, null, ComponentTypeEnum.RESOURCE_INSTANCE);
+        Either<ComponentInstanceProperty[], ResponseFormat> convertStatus = getComponentsUtils()
+            .convertJsonToObjectUsingObjectMapper(dataList, new User(), ComponentInstanceProperty[].class, null, ComponentTypeEnum.RESOURCE_INSTANCE);
         if (convertStatus.isRight()) {
             return Either.right(convertStatus.right().value());
         }
@@ -1396,16 +1261,15 @@ public class ComponentInstanceServlet extends AbstractValidationsServlet {
         if (StringUtils.isEmpty(dataList)) {
             return Either.right(getComponentsUtils().getResponseFormat(ActionStatus.MISSING_BODY));
         }
-        Either<ComponentInstanceInput[], ResponseFormat> convertStatus = getComponentsUtils().convertJsonToObjectUsingObjectMapper(dataList, new User(), ComponentInstanceInput[].class, null, ComponentTypeEnum.RESOURCE_INSTANCE);
+        Either<ComponentInstanceInput[], ResponseFormat> convertStatus = getComponentsUtils()
+            .convertJsonToObjectUsingObjectMapper(dataList, new User(), ComponentInstanceInput[].class, null, ComponentTypeEnum.RESOURCE_INSTANCE);
         if (convertStatus.isRight()) {
             return Either.right(convertStatus.right().value());
         }
         return Either.left(Arrays.asList(convertStatus.left().value()));
     }
 
-
     private RequirementCapabilityRelDef convertToRequirementCapabilityRelDef(String data) {
-
         Either<RequirementCapabilityRelDef, ActionStatus> convertStatus = convertJsonToObject(data, RequirementCapabilityRelDef.class);
         if (convertStatus.isRight()) {
             throw new ByActionStatusComponentException(convertStatus.right().value());
@@ -1433,29 +1297,24 @@ public class ComponentInstanceServlet extends AbstractValidationsServlet {
         }
     }
 
-
     @GET
     @Path("/{containerComponentType}/{componentId}/paths-to-delete")
     @Produces(MediaType.APPLICATION_JSON)
-    @Operation(description = "Check if forwarding path to delete on version change", method = "GET",
-            summary = "Returns forwarding paths to delete", responses = {
-            @ApiResponse(content = @Content(array = @ArraySchema(schema = @Schema(implementation = Response.class))))})
-    public Response changeResourceInstanceVersion( @PathParam("componentId") String componentId,
-        @QueryParam("componentInstanceId") final String oldComponentInstanceId,
-        @QueryParam("newComponentInstanceId") final String newComponentInstanceId,
-        @Parameter(description = "valid values: resources / services",
-                schema = @Schema(allowableValues = {ComponentTypeEnum.RESOURCE_PARAM_NAME,
-                        ComponentTypeEnum.SERVICE_PARAM_NAME}))
-        @PathParam("containerComponentType") final String containerComponentType,
-        @Context final HttpServletRequest request) {
-        if (oldComponentInstanceId == null){
-            return  buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.MISSING_OLD_COMPONENT_INSTANCE));
+    @Operation(description = "Check if forwarding path to delete on version change", method = "GET", summary = "Returns forwarding paths to delete", responses = {
+        @ApiResponse(content = @Content(array = @ArraySchema(schema = @Schema(implementation = Response.class))))})
+    public Response changeResourceInstanceVersion(@PathParam("componentId") String componentId,
+                                                  @QueryParam("componentInstanceId") final String oldComponentInstanceId,
+                                                  @QueryParam("newComponentInstanceId") final String newComponentInstanceId,
+                                                  @Parameter(description = "valid values: resources / services", schema = @Schema(allowableValues = {
+                                                      ComponentTypeEnum.RESOURCE_PARAM_NAME,
+                                                      ComponentTypeEnum.SERVICE_PARAM_NAME})) @PathParam("containerComponentType") final String containerComponentType,
+                                                  @Context final HttpServletRequest request) {
+        if (oldComponentInstanceId == null) {
+            return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.MISSING_OLD_COMPONENT_INSTANCE));
         }
-        if (newComponentInstanceId == null){
-            return  buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.MISSING_NEW_COMPONENT_INSTANCE));
+        if (newComponentInstanceId == null) {
+            return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.MISSING_NEW_COMPONENT_INSTANCE));
         }
-
-
         String url = request.getMethod() + " " + request.getRequestURI();
         log.debug(START_HANDLE_REQUEST_OF, url);
         if (componentInstanceBusinessLogic == null) {
@@ -1463,43 +1322,39 @@ public class ComponentInstanceServlet extends AbstractValidationsServlet {
             return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.UNSUPPORTED_ERROR, containerComponentType));
         }
         ComponentInstance newComponentInstance;
-        if(StringUtils.isNotEmpty(newComponentInstanceId)){
-            newComponentInstance=new ComponentInstance();
-            newComponentInstance.setToscaPresentationValue(JsonPresentationFields.CI_COMPONENT_UID,newComponentInstanceId);
-        }else{
+        if (StringUtils.isNotEmpty(newComponentInstanceId)) {
+            newComponentInstance = new ComponentInstance();
+            newComponentInstance.setToscaPresentationValue(JsonPresentationFields.CI_COMPONENT_UID, newComponentInstanceId);
+        } else {
             log.error("missing component id");
             return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.MISSING_DATA));
         }
-        Either<Set<String>,ResponseFormat> actionResponse= componentInstanceBusinessLogic.forwardingPathOnVersionChange(
-            containerComponentType,componentId,oldComponentInstanceId,newComponentInstance);
+        Either<Set<String>, ResponseFormat> actionResponse = componentInstanceBusinessLogic
+            .forwardingPathOnVersionChange(containerComponentType, componentId, oldComponentInstanceId, newComponentInstance);
         if (actionResponse.isRight()) {
             return buildErrorResponse(actionResponse.right().value());
         }
-        ForwardingPaths forwardingPaths=new ForwardingPaths();
+        ForwardingPaths forwardingPaths = new ForwardingPaths();
         forwardingPaths.setForwardingPathToDelete(actionResponse.left().value());
         return buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), forwardingPaths);
-
     }
 
     @POST
     @Path("/services/{componentId}/copyComponentInstance/{componentInstanceId}")
     @Consumes(MediaType.APPLICATION_JSON)
     @Produces((MediaType.APPLICATION_JSON))
-    @Operation(description = "Copy Component Instance", method = "POST",
-            summary = "Returns updated service information", responses = {
-            @ApiResponse(content = @Content(array = @ArraySchema(schema = @Schema(implementation = Service.class)))),
-            @ApiResponse(responseCode = "201", description = "Copy and Paste Success"),
-            @ApiResponse(responseCode = "403", description = "Restricted Operation"),
-            @ApiResponse(responseCode = "400", description = "Invalid Content / Missing content")})
+    @Operation(description = "Copy Component Instance", method = "POST", summary = "Returns updated service information", responses = {
+        @ApiResponse(content = @Content(array = @ArraySchema(schema = @Schema(implementation = Service.class)))),
+        @ApiResponse(responseCode = "201", description = "Copy and Paste Success"),
+        @ApiResponse(responseCode = "403", description = "Restricted Operation"),
+        @ApiResponse(responseCode = "400", description = "Invalid Content / Missing content")})
     public Response copyComponentInstance(
-            @Parameter(description = "service unique id in pasted canvas") @PathParam("componentId") final String containerComponentId,
-            @Parameter(description = "Data for copying", required = true) String data, @PathParam("componentInstanceId") final String componentInstanceId,
-            @Context final HttpServletRequest request) {
+        @Parameter(description = "service unique id in pasted canvas") @PathParam("componentId") final String containerComponentId,
+        @Parameter(description = "Data for copying", required = true) String data, @PathParam("componentInstanceId") final String componentInstanceId,
+        @Context final HttpServletRequest request) {
         log.info("Start to copy component instance");
-
         String userId = request.getHeader(Constants.USER_ID_HEADER);
         final String CNTAINER_CMPT_TYPE = SERVICES;
-
         try {
             ComponentInstance inputComponentInstance = RepresentationUtils.fromRepresentation(data, ComponentInstance.class);
             inputComponentInstance.setInvariantName(null);
@@ -1508,20 +1363,17 @@ public class ComponentInstanceServlet extends AbstractValidationsServlet {
                 log.debug(UNSUPPORTED_COMPONENT_TYPE, componentTypeEnum);
                 return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.UNSUPPORTED_ERROR, SERVICES));
             }
-            Either<Map<String, ComponentInstance>, ResponseFormat> copyComponentInstance = componentInstanceBusinessLogic.copyComponentInstance(
-                    inputComponentInstance, containerComponentId, componentInstanceId, userId);
-
+            Either<Map<String, ComponentInstance>, ResponseFormat> copyComponentInstance = componentInstanceBusinessLogic
+                .copyComponentInstance(inputComponentInstance, containerComponentId, componentInstanceId, userId);
             if (copyComponentInstance.isRight()) {
                 log.error("Failed to copy ComponentInstance {}", copyComponentInstance.right().value());
                 return buildErrorResponse(copyComponentInstance.right().value());
             }
-
-            return buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK),
-                    copyComponentInstance.left().value());
+            return buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), copyComponentInstance.left().value());
         } catch (Exception e) {
             log.error("Failed to convert json to Map { }", data, e);
-            return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.USER_DEFINED,
-                    "Failed to get the copied component instance information"));
+            return buildErrorResponse(
+                getComponentsUtils().getResponseFormat(ActionStatus.USER_DEFINED, "Failed to get the copied component instance information"));
         }
     }
 
@@ -1529,101 +1381,79 @@ public class ComponentInstanceServlet extends AbstractValidationsServlet {
     @Path("/{containerComponentType}/{componentId}/batchDeleteResourceInstances/")
     @Consumes(MediaType.APPLICATION_JSON)
     @Produces(MediaType.APPLICATION_JSON)
-    @Operation(description = "Batch Delete ResourceInstances", method = "POST",
-            responses = {@ApiResponse(responseCode = "203", description = "ResourceInstances deleted"),
-                    @ApiResponse(responseCode = "403", description = "Restricted Operation"),
-                    @ApiResponse(responseCode = "400", description = "Invalid Content / Missing Content")})
+    @Operation(description = "Batch Delete ResourceInstances", method = "POST", responses = {
+        @ApiResponse(responseCode = "203", description = "ResourceInstances deleted"),
+        @ApiResponse(responseCode = "403", description = "Restricted Operation"),
+        @ApiResponse(responseCode = "400", description = "Invalid Content / Missing Content")})
     public Response batchDeleteResourceInstances(
-            @Parameter(description = "valid values: resources / services / products", schema = @Schema(allowableValues = {ComponentTypeEnum.RESOURCE_PARAM_NAME,
-                    ComponentTypeEnum.SERVICE_PARAM_NAME,
-                    ComponentTypeEnum.PRODUCT_PARAM_NAME}))
-            @PathParam("containerComponentType") final String containerComponentType,
-            @PathParam("componentId") final String componentId,
-            @Context final HttpServletRequest request,
-            @Parameter(description = "Component Instance Id List", required = true) final String componentInstanceIdLisStr) {
+        @Parameter(description = "valid values: resources / services / products", schema = @Schema(allowableValues = {
+            ComponentTypeEnum.RESOURCE_PARAM_NAME, ComponentTypeEnum.SERVICE_PARAM_NAME,
+            ComponentTypeEnum.PRODUCT_PARAM_NAME})) @PathParam("containerComponentType") final String containerComponentType,
+        @PathParam("componentId") final String componentId, @Context final HttpServletRequest request,
+        @Parameter(description = "Component Instance Id List", required = true) final String componentInstanceIdLisStr) {
         try {
             if (componentInstanceIdLisStr == null || componentInstanceIdLisStr.isEmpty()) {
-                log.error("Empty JSON List was sent",componentInstanceIdLisStr);
+                log.error("Empty JSON List was sent", componentInstanceIdLisStr);
                 return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.INVALID_CONTENT));
             }
-
-
             if (componentInstanceBusinessLogic == null) {
                 log.error(UNSUPPORTED_COMPONENT_TYPE, containerComponentType);
                 return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.UNSUPPORTED_ERROR, containerComponentType));
             }
-
             Either<List<String>, ResponseFormat> convertResponse = convertToStringList(componentInstanceIdLisStr);
-
             if (convertResponse.isRight()) {
                 BeEcompErrorManager.getInstance().logBeSystemError("Resource Instance - batchDeleteResourceInstances");
                 log.error(FAILED_TO_CONVERT_RECEIVED_DATA_TO_BE_FORMAT);
                 return buildErrorResponse(convertResponse.right().value());
             }
-
             String userId = request.getHeader(Constants.USER_ID_HEADER);
             List<String> componentInstanceIdList = convertResponse.left().value();
             log.debug("batchDeleteResourceInstances componentInstanceIdList is {}", componentInstanceIdList);
-            Map<String, List<String>> deleteErrorMap = componentInstanceBusinessLogic.batchDeleteComponentInstance(containerComponentType,
-                    componentId, componentInstanceIdList, userId);
-
+            Map<String, List<String>> deleteErrorMap = componentInstanceBusinessLogic
+                .batchDeleteComponentInstance(containerComponentType, componentId, componentInstanceIdList, userId);
             return buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), deleteErrorMap);
         } catch (Exception e) {
             BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Batch Delete ResourceInstances");
-            log.error("batch delete resource instances with exception" , e);
+            log.error("batch delete resource instances with exception", e);
             return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR));
         }
-
     }
 
     @PUT
     @Path("/{containerComponentType}/{componentId}/resourceInstance/batchDissociate")
     @Consumes(MediaType.APPLICATION_JSON)
     @Produces(MediaType.APPLICATION_JSON)
-    @Operation(description = "Batch Dissociate RI from RI", method = "PUT",
-            summary = "Returns deleted RelationShip Info", responses = {
-            @ApiResponse(content = @Content(array = @ArraySchema(schema = @Schema(implementation = Response.class)))),
-            @ApiResponse(responseCode = "201", description = "Relationship deleted"),
-            @ApiResponse(responseCode = "403", description = "Missing Information"),
-            @ApiResponse(responseCode = "400", description = "Invalid Content / Missing Content")})
+    @Operation(description = "Batch Dissociate RI from RI", method = "PUT", summary = "Returns deleted RelationShip Info", responses = {
+        @ApiResponse(content = @Content(array = @ArraySchema(schema = @Schema(implementation = Response.class)))),
+        @ApiResponse(responseCode = "201", description = "Relationship deleted"),
+        @ApiResponse(responseCode = "403", description = "Missing Information"),
+        @ApiResponse(responseCode = "400", description = "Invalid Content / Missing Content")})
     public Response batchDissociateRIFromRI(
-            @Parameter(description = "allowed values are resources/services/products",
-                    schema = @Schema(allowableValues = {ComponentTypeEnum.RESOURCE_PARAM_NAME,
-                            ComponentTypeEnum.SERVICE_PARAM_NAME,
-                            ComponentTypeEnum.PRODUCT_PARAM_NAME}),
-                    required = true) @PathParam("containerComponentType") final String containerComponentType,
-            @Parameter(
-                    description = "unique id of the container component") @PathParam("componentId") final String componentId,
-            @HeaderParam(value = Constants.USER_ID_HEADER) String userId,
-            @Parameter(description = "RelationshipInfo", required = true) String data,
-            @Context final HttpServletRequest request) {
-
-
+        @Parameter(description = "allowed values are resources/services/products", schema = @Schema(allowableValues = {
+            ComponentTypeEnum.RESOURCE_PARAM_NAME, ComponentTypeEnum.SERVICE_PARAM_NAME,
+            ComponentTypeEnum.PRODUCT_PARAM_NAME}), required = true) @PathParam("containerComponentType") final String containerComponentType,
+        @Parameter(description = "unique id of the container component") @PathParam("componentId") final String componentId,
+        @HeaderParam(value = Constants.USER_ID_HEADER) String userId, @Parameter(description = "RelationshipInfo", required = true) String data,
+        @Context final HttpServletRequest request) {
         try {
             if (data == null || data.length() == 0) {
                 log.info("Empty JSON list was sent");
                 return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.INVALID_CONTENT));
             }
-
             ComponentTypeEnum componentTypeEnum = ComponentTypeEnum.findByParamName(containerComponentType);
-
             if (componentInstanceBusinessLogic == null) {
                 log.debug(UNSUPPORTED_COMPONENT_TYPE, containerComponentType);
                 return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.UNSUPPORTED_ERROR, containerComponentType));
             }
-
             Either<List<RequirementCapabilityRelDef>, ResponseFormat> regInfoWs = convertToRequirementCapabilityRelDefList(data);
-
             if (regInfoWs.isRight()) {
                 BeEcompErrorManager.getInstance().logBeSystemError("Resource Instance - batch dissociateRIFromRI");
                 log.debug("Failed to convert received data to BE format");
                 return buildErrorResponse(regInfoWs.right().value());
             }
-
             List<RequirementCapabilityRelDef> requirementDefList = regInfoWs.left().value();
-            List<RequirementCapabilityRelDef> delOkResult = componentInstanceBusinessLogic.batchDissociateRIFromRI(
-                    componentId, userId, requirementDefList, componentTypeEnum);
-
+            List<RequirementCapabilityRelDef> delOkResult = componentInstanceBusinessLogic
+                .batchDissociateRIFromRI(componentId, userId, requirementDefList, componentTypeEnum);
             return buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), delOkResult);
         } catch (Exception e) {
             BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Batch Dissociate Resource Instance");
@@ -1633,79 +1463,59 @@ public class ComponentInstanceServlet extends AbstractValidationsServlet {
     }
 
     private Either<List<String>, ResponseFormat> convertToStringList(String datalist) {
-        Either<String[], ResponseFormat> convertStatus = getComponentsUtils().convertJsonToObjectUsingObjectMapper(datalist, new User(), String[].class, null, null);
-
+        Either<String[], ResponseFormat> convertStatus = getComponentsUtils()
+            .convertJsonToObjectUsingObjectMapper(datalist, new User(), String[].class, null, null);
         if (convertStatus.isRight()) {
             return Either.right(convertStatus.right().value());
         }
-
         return Either.left(Arrays.asList(convertStatus.left().value()));
     }
 
     private Either<List<RequirementCapabilityRelDef>, ResponseFormat> convertToRequirementCapabilityRelDefList(String data) {
-        Either<RequirementCapabilityRelDef[], ResponseFormat> convertStatus = getComponentsUtils().convertJsonToObjectUsingObjectMapper(data, new User(), RequirementCapabilityRelDef[].class, null, null);
-
+        Either<RequirementCapabilityRelDef[], ResponseFormat> convertStatus = getComponentsUtils()
+            .convertJsonToObjectUsingObjectMapper(data, new User(), RequirementCapabilityRelDef[].class, null, null);
         if (convertStatus.isRight()) {
             return Either.right(convertStatus.right().value());
         }
-
         return Either.left(Arrays.asList(convertStatus.left().value()));
     }
 
     @POST
     @Path("/services/replaceVNF")
-    @Operation(description = "Replace new VNF based on the existing VNF", method = "POST",
-            summary = "Return whether the replace VNF is successful", responses = {
-            @ApiResponse(responseCode = "200", description = "ECOMP component is authenticated and list of Catalog Assets Metadata is returned",
-                    content = @Content(array = @ArraySchema(schema = @Schema(implementation = ReplaceVNFInfo.class)))),
-            @ApiResponse(responseCode = "400", description = "Missing  'X-ECOMP-InstanceID'  HTTP header - POL5001"),
-            @ApiResponse(responseCode = "401",
-                    description = "ECOMP component  should authenticate itself  and  to  re-send  again  HTTP  request  with its Basic Authentication credentials - POL5002"),
-            @ApiResponse(responseCode = "403", description = "ECOMP component is not authorized - POL5003"),
-            @ApiResponse(responseCode = "404",
-                    description = "Error: Requested '%1' (uuid) resource was not found - SVC4063"),
-            @ApiResponse(responseCode = "405",
-                    description = "Method  Not Allowed  :  Invalid HTTP method type used ( PUT,DELETE,POST will be rejected) - POL4050"),
-            @ApiResponse(responseCode = "500",
-                    description = "The GET request failed either due to internal SDC problem. ECOMP Component should continue the attempts to get the needed information - POL5000"),
-            @ApiResponse(responseCode = "409", description = "Service already exist")})
+    @Operation(description = "Replace new VNF based on the existing VNF", method = "POST", summary = "Return whether the replace VNF is successful", responses = {
+        @ApiResponse(responseCode = "200", description = "ECOMP component is authenticated and list of Catalog Assets Metadata is returned", content = @Content(array = @ArraySchema(schema = @Schema(implementation = ReplaceVNFInfo.class)))),
+        @ApiResponse(responseCode = "400", description = "Missing  'X-ECOMP-InstanceID'  HTTP header - POL5001"),
+        @ApiResponse(responseCode = "401", description = "ECOMP component  should authenticate itself  and  to  re-send  again  HTTP  request  with its Basic Authentication credentials - POL5002"),
+        @ApiResponse(responseCode = "403", description = "ECOMP component is not authorized - POL5003"),
+        @ApiResponse(responseCode = "404", description = "Error: Requested '%1' (uuid) resource was not found - SVC4063"),
+        @ApiResponse(responseCode = "405", description = "Method  Not Allowed  :  Invalid HTTP method type used ( PUT,DELETE,POST will be rejected) - POL4050"),
+        @ApiResponse(responseCode = "500", description = "The GET request failed either due to internal SDC problem. ECOMP Component should continue the attempts to get the needed information - POL5000"),
+        @ApiResponse(responseCode = "409", description = "Service already exist")})
     @PermissionAllowed(AafPermission.PermNames.INTERNAL_ALL_VALUE)
-    public Response replaceVNF(
-            @Parameter(description = "The user id",
-                    required = true) @HeaderParam(value = Constants.USER_ID_HEADER) String userId,
-            @Parameter(description = "X-ECOMP-RequestID header",
-                    required = false) @HeaderParam(value = Constants.X_ECOMP_REQUEST_ID_HEADER) String requestId,
-            @Parameter(description = "X-ECOMP-InstanceID header", required = true)
-            @HeaderParam(value = Constants.X_ECOMP_INSTANCE_ID_HEADER) final String instanceIdHeader,
-            @Parameter(description = "Determines the format of the body of the response",
-                    required = false) @HeaderParam(value = Constants.ACCEPT_HEADER) String accept,
-            @Parameter(description = "The username and password",
-                    required = true) @HeaderParam(value = Constants.AUTHORIZATION_HEADER) String authorization,
-            @Context final HttpServletRequest request,
-            @Parameter(description = "Resource object to be created", required = true) String data) {
-
+    public Response replaceVNF(@Parameter(description = "The user id", required = true) @HeaderParam(value = Constants.USER_ID_HEADER) String userId,
+                               @Parameter(description = "X-ECOMP-RequestID header", required = false) @HeaderParam(value = Constants.X_ECOMP_REQUEST_ID_HEADER) String requestId,
+                               @Parameter(description = "X-ECOMP-InstanceID header", required = true) @HeaderParam(value = Constants.X_ECOMP_INSTANCE_ID_HEADER) final String instanceIdHeader,
+                               @Parameter(description = "Determines the format of the body of the response", required = false) @HeaderParam(value = Constants.ACCEPT_HEADER) String accept,
+                               @Parameter(description = "The username and password", required = true) @HeaderParam(value = Constants.AUTHORIZATION_HEADER) String authorization,
+                               @Context final HttpServletRequest request,
+                               @Parameter(description = "Resource object to be created", required = true) String data) {
         String url = request.getMethod() + " " + request.getRequestURI();
         log.debug("replaceVNF: Start handle request of {}", url);
         User modifier = new User();
         modifier.setUserId(userId);
         log.debug("replaceVNF:modifier id is {}", userId);
         validateNotEmptyBody(data);
-
         Either<ReplaceVNFInfo, ResponseFormat> convertResponse = parseToReplaceVNFInfo(data, modifier);
         if (convertResponse.isRight()) {
             throw new ByResponseFormatComponentException(convertResponse.right().value());
         }
-
         log.debug("replaceVNF:get ReplaceVNFInfo success");
-
         String containerComponentType = SERVICES;
         ReplaceVNFInfo replaceVNFInfo = convertResponse.left().value();
         String serviceUniqueId = replaceVNFInfo.getServiceUniqueId();
         String abstractResourceUniqueId = replaceVNFInfo.getAbstractResourceUniqueId();
-
         ComponentInstance componentInstance = replaceVNFInfo.getRealVNFComponentInstance();
-        log.debug("replaceVNF:get ReplaceVNFInfo,serviceUniqueId:{},abstractResourceUniqueId:{}",
-                serviceUniqueId,abstractResourceUniqueId);
+        log.debug("replaceVNF:get ReplaceVNFInfo,serviceUniqueId:{},abstractResourceUniqueId:{}", serviceUniqueId, abstractResourceUniqueId);
         try {
             /**
              * delete vnf
@@ -1714,7 +1524,8 @@ public class ComponentInstanceServlet extends AbstractValidationsServlet {
                 log.debug("replaceVNF:Unsupported component type {}", containerComponentType);
                 return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.UNSUPPORTED_ERROR, containerComponentType));
             }
-            Either<ComponentInstance, ResponseFormat> componentInstanceEither = componentInstanceBusinessLogic.deleteAbstractComponentInstance(containerComponentType, serviceUniqueId, abstractResourceUniqueId, userId);
+            Either<ComponentInstance, ResponseFormat> componentInstanceEither = componentInstanceBusinessLogic
+                .deleteAbstractComponentInstance(containerComponentType, serviceUniqueId, abstractResourceUniqueId, userId);
             if (componentInstanceEither.isRight()) {
                 log.debug("replaceVNF:delete Abstract ComponentInstance field");
                 return buildErrorResponse(componentInstanceEither.right().value());
@@ -1725,15 +1536,14 @@ public class ComponentInstanceServlet extends AbstractValidationsServlet {
             log.debug("replaceVNF,start add vnf");
             componentInstance.setInvariantName(null);
             componentInstance.setCreatedFrom(CreatedFrom.UI);
-
-            Either<ComponentInstance, ResponseFormat> realComponentInstance = componentInstanceBusinessLogic.createRealComponentInstance(containerComponentType, serviceUniqueId, userId, componentInstance);
+            Either<ComponentInstance, ResponseFormat> realComponentInstance = componentInstanceBusinessLogic
+                .createRealComponentInstance(containerComponentType, serviceUniqueId, userId, componentInstance);
             if (realComponentInstance.isRight()) {
                 log.debug("replaceVNF:filed to add vnf");
                 return buildErrorResponse(realComponentInstance.right().value());
             }
             ComponentInstance newComponentInstance = realComponentInstance.left().value();
             log.debug("replaceVNF:success to add vnf");
-            
             return buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), newComponentInstance);
         } catch (Exception e) {
             BeEcompErrorManager.getInstance().logBeRestApiGeneralError("replaceVNF");
@@ -1743,8 +1553,8 @@ public class ComponentInstanceServlet extends AbstractValidationsServlet {
     }
 
     private Either<ReplaceVNFInfo, ResponseFormat> parseToReplaceVNFInfo(String serviceJson, User user) {
-        log.debug("enter parseToReplaceVNFInfo,get serviceJson:{}",serviceJson);
-        return getComponentsUtils().convertJsonToObjectUsingObjectMapper(serviceJson, user, ReplaceVNFInfo.class, AuditingActionEnum.CREATE_RESOURCE, ComponentTypeEnum.SERVICE);
+        log.debug("enter parseToReplaceVNFInfo,get serviceJson:{}", serviceJson);
+        return getComponentsUtils().convertJsonToObjectUsingObjectMapper(serviceJson, user, ReplaceVNFInfo.class, AuditingActionEnum.CREATE_RESOURCE,
+            ComponentTypeEnum.SERVICE);
     }
-
 }
index c2e668c..4d94ffc 100644 (file)
@@ -18,7 +18,6 @@
  *  SPDX-License-Identifier: Apache-2.0
  *  ============LICENSE_END=========================================================
  */
-
 package org.openecomp.sdc.be.servlets;
 
 import fj.data.Either;
@@ -74,24 +73,17 @@ public class ComponentInterfaceOperationServlet extends AbstractValidationsServl
     private static final Logger LOGGER = LoggerFactory.getLogger(ComponentInterfaceOperationServlet.class);
     private static final String START_HANDLE_REQUEST_OF = "Start handle {} request of {}";
     private static final String MODIFIER_ID_IS = "modifier id is {}";
-
-    private static final String FAILED_TO_UPDATE_INTERFACE_OPERATION =
-        "failed to update Interface Operation on component instance {}";
+    private static final String FAILED_TO_UPDATE_INTERFACE_OPERATION = "failed to update Interface Operation on component instance {}";
     private static final String UPDATE_INTERFACE_OPERATION = "Update Interface Operation on Component Instance";
-    private static final String FAILED_TO_UPDATE_INTERFACE_OPERATION_WITH_ERROR =
-        "Failed to update Interface Operation with an error";
+    private static final String FAILED_TO_UPDATE_INTERFACE_OPERATION_WITH_ERROR = "Failed to update Interface Operation with an error";
     private static final String INTERFACE_OPERATION_CONTENT_INVALID = "Interface Operation content is invalid - {}";
     private static final String UNSUPPORTED_COMPONENT_TYPE = "Unsupported component type {}";
-    private static final String INTERFACE_OPERATION_SUCCESSFULLY_UPDATED =
-        "Interface Operation successfully updated on component instance with id {}";
-
+    private static final String INTERFACE_OPERATION_SUCCESSFULLY_UPDATED = "Interface Operation successfully updated on component instance with id {}";
     private final ComponentInterfaceOperationBusinessLogic componentInterfaceOperationBusinessLogic;
 
     @Autowired
-    public ComponentInterfaceOperationServlet(final UserBusinessLogic userBusinessLogic,
-                                              final ComponentInstanceBusinessLogic componentInstanceBL,
-                                              final ComponentsUtils componentsUtils,
-                                              final ServletUtils servletUtils,
+    public ComponentInterfaceOperationServlet(final UserBusinessLogic userBusinessLogic, final ComponentInstanceBusinessLogic componentInstanceBL,
+                                              final ComponentsUtils componentsUtils, final ServletUtils servletUtils,
                                               final ResourceImportManager resourceImportManager,
                                               final ComponentInterfaceOperationBusinessLogic componentInterfaceOperationBusinessLogic) {
         super(userBusinessLogic, componentInstanceBL, componentsUtils, servletUtils, resourceImportManager);
@@ -101,43 +93,32 @@ public class ComponentInterfaceOperationServlet extends AbstractValidationsServl
     @PUT
     @Consumes(MediaType.APPLICATION_JSON)
     @Produces(MediaType.APPLICATION_JSON)
-    @Operation(description = "Update Interface Operation", method = "PUT",
-        summary = "Update Interface Operation on ComponentInstance", responses = {
+    @Operation(description = "Update Interface Operation", method = "PUT", summary = "Update Interface Operation on ComponentInstance", responses = {
         @ApiResponse(content = @Content(array = @ArraySchema(schema = @Schema(implementation = Response.class)))),
         @ApiResponse(responseCode = "201", description = "Update Interface Operation"),
         @ApiResponse(responseCode = "403", description = "Restricted operation"),
         @ApiResponse(responseCode = "400", description = "Invalid content / Missing content")})
     @PermissionAllowed(AafPermission.PermNames.INTERNAL_ALL_VALUE)
     public Response updateComponentInstanceInterfaceOperation(
-        @Parameter(description = "valid values: resources / services",
-            schema = @Schema(allowableValues = {
-                ComponentTypeEnum.RESOURCE_PARAM_NAME,
-                ComponentTypeEnum.SERVICE_PARAM_NAME}))
-        @PathParam("componentType") final String componentType,
-        @Parameter(description = "Component Id")
-        @PathParam("componentId") String componentId,
-        @Parameter(description = "Component Instance Id")
-        @PathParam("componentInstanceId") String componentInstanceId,
-        @Context final HttpServletRequest request, @HeaderParam(value = Constants.USER_ID_HEADER) String userId)
-        throws IOException {
-
+        @Parameter(description = "valid values: resources / services", schema = @Schema(allowableValues = {ComponentTypeEnum.RESOURCE_PARAM_NAME,
+            ComponentTypeEnum.SERVICE_PARAM_NAME})) @PathParam("componentType") final String componentType,
+        @Parameter(description = "Component Id") @PathParam("componentId") String componentId,
+        @Parameter(description = "Component Instance Id") @PathParam("componentInstanceId") String componentInstanceId,
+        @Context final HttpServletRequest request, @HeaderParam(value = Constants.USER_ID_HEADER) String userId) throws IOException {
         LOGGER.debug(START_HANDLE_REQUEST_OF, request.getMethod(), request.getRequestURI());
         LOGGER.debug(MODIFIER_ID_IS, userId);
-
         final User userModifier = componentInterfaceOperationBusinessLogic.validateUser(userId);
         final ComponentTypeEnum componentTypeEnum = ComponentTypeEnum.findByParamName(componentType);
         if (componentTypeEnum == null) {
             LOGGER.debug(UNSUPPORTED_COMPONENT_TYPE, componentType);
             return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.UNSUPPORTED_ERROR, componentType));
         }
-
         final byte[] bytes = IOUtils.toByteArray(request.getInputStream());
         if (bytes == null || bytes.length == 0) {
             LOGGER.error(INTERFACE_OPERATION_CONTENT_INVALID);
             return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.INVALID_CONTENT));
         }
         final String data = new String(bytes);
-
         final Optional<InterfaceDefinition> mappedInterfaceOperationData = getMappedInterfaceData(data, userModifier, componentTypeEnum);
         if (mappedInterfaceOperationData.isEmpty()) {
             LOGGER.error(INTERFACE_OPERATION_CONTENT_INVALID, data);
@@ -145,10 +126,9 @@ public class ComponentInterfaceOperationServlet extends AbstractValidationsServl
         }
         final Wrapper<ResponseFormat> errorWrapper = new Wrapper<>();
         try {
-             final Optional<ComponentInstance> actionResponse = componentInterfaceOperationBusinessLogic
-                .updateComponentInstanceInterfaceOperation(componentId, componentInstanceId, mappedInterfaceOperationData.get(),
-                    componentTypeEnum, errorWrapper, true);
-
+            final Optional<ComponentInstance> actionResponse = componentInterfaceOperationBusinessLogic
+                .updateComponentInstanceInterfaceOperation(componentId, componentInstanceId, mappedInterfaceOperationData.get(), componentTypeEnum,
+                    errorWrapper, true);
             final Response response;
             if (actionResponse.isEmpty()) {
                 LOGGER.error(FAILED_TO_UPDATE_INTERFACE_OPERATION, componentInstanceId);
@@ -157,9 +137,7 @@ public class ComponentInterfaceOperationServlet extends AbstractValidationsServl
                 LOGGER.debug(INTERFACE_OPERATION_SUCCESSFULLY_UPDATED, componentInstanceId);
                 response = buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.CREATED), actionResponse.get());
             }
-
             return response;
-
         } catch (final Exception e) {
             BeEcompErrorManager.getInstance().logBeRestApiGeneralError(UPDATE_INTERFACE_OPERATION);
             LOGGER.error(FAILED_TO_UPDATE_INTERFACE_OPERATION_WITH_ERROR, e);
@@ -167,13 +145,10 @@ public class ComponentInterfaceOperationServlet extends AbstractValidationsServl
         }
     }
 
-    private Optional<InterfaceDefinition> getMappedInterfaceData(final String inputJson,
-                                                                 final User user,
-                                                                 final ComponentTypeEnum componentTypeEnum) {
-        final Either<UiComponentDataTransfer, ResponseFormat> uiComponentEither =
-            getComponentsUtils().convertJsonToObjectUsingObjectMapper(inputJson, user,
-                UiComponentDataTransfer.class, AuditingActionEnum.UPDATE_RESOURCE_METADATA, componentTypeEnum);
+    private Optional<InterfaceDefinition> getMappedInterfaceData(final String inputJson, final User user, final ComponentTypeEnum componentTypeEnum) {
+        final Either<UiComponentDataTransfer, ResponseFormat> uiComponentEither = getComponentsUtils()
+            .convertJsonToObjectUsingObjectMapper(inputJson, user, UiComponentDataTransfer.class, AuditingActionEnum.UPDATE_RESOURCE_METADATA,
+                componentTypeEnum);
         return uiComponentEither.left().value().getInterfaces().values().stream().findFirst();
     }
-
 }
index 68d8380..0e2b285 100644 (file)
@@ -16,7 +16,6 @@
  *  SPDX-License-Identifier: Apache-2.0
  *  ============LICENSE_END=========================================================
  */
-
 package org.openecomp.sdc.be.servlets;
 
 import io.swagger.v3.oas.annotations.Operation;
@@ -72,30 +71,22 @@ public class ComponentNodeFilterServlet extends AbstractValidationsServlet {
     private static final Logger LOGGER = LoggerFactory.getLogger(ComponentNodeFilterServlet.class);
     private static final String START_HANDLE_REQUEST_OF = "Start handle {} request of {}";
     private static final String MODIFIER_ID_IS = "modifier id is {}";
-
     private static final String FAILED_TO_PARSE_COMPONENT = "failed to parse component";
-
     private static final String FAILED_TO_CREATE_NODE_FILTER = "failed to create node filter";
     private static final String NODE_FILTER_CREATION = "Node Filter Creation";
     private static final String CREATE_NODE_FILTER_WITH_AN_ERROR = "create node filter with an error";
-
     private static final String FAILED_TO_UPDATE_NODE_FILTER = "failed to update node filter";
     private static final String NODE_FILTER_UPDATE = "Node Filter Update";
     private static final String UPDATE_NODE_FILTER_WITH_AN_ERROR = "update node filter with an error";
-
     private static final String FAILED_TO_DELETE_NODE_FILTER = "failed to delete node filter";
     private static final String NODE_FILTER_DELETE = "Node Filter Delete";
     private static final String DELETE_NODE_FILTER_WITH_AN_ERROR = "delete node filter with an error";
-
-    private static  final String INVALID_NODE_FILTER_CONSTRAINT_TYPE = "Invalid value for NodeFilterConstraintType enum {}";
-
+    private static final String INVALID_NODE_FILTER_CONSTRAINT_TYPE = "Invalid value for NodeFilterConstraintType enum {}";
     private final ComponentNodeFilterBusinessLogic componentNodeFilterBusinessLogic;
 
     @Inject
-    public ComponentNodeFilterServlet(final UserBusinessLogic userBusinessLogic,
-                                      final ComponentInstanceBusinessLogic componentInstanceBL,
-                                      final ComponentsUtils componentsUtils,
-                                      final ServletUtils servletUtils,
+    public ComponentNodeFilterServlet(final UserBusinessLogic userBusinessLogic, final ComponentInstanceBusinessLogic componentInstanceBL,
+                                      final ComponentsUtils componentsUtils, final ServletUtils servletUtils,
                                       final ResourceImportManager resourceImportManager,
                                       final ComponentNodeFilterBusinessLogic componentNodeFilterBusinessLogic) {
         super(userBusinessLogic, componentInstanceBL, componentsUtils, servletUtils, resourceImportManager);
@@ -106,62 +97,50 @@ public class ComponentNodeFilterServlet extends AbstractValidationsServlet {
     @Consumes(MediaType.APPLICATION_JSON)
     @Produces(MediaType.APPLICATION_JSON)
     @Path("/nodeFilter")
-    @Operation(description = "Add Component Filter Constraint", method = "POST",
-        summary = "Add Component Filter Constraint", responses = {
+    @Operation(description = "Add Component Filter Constraint", method = "POST", summary = "Add Component Filter Constraint", responses = {
         @ApiResponse(content = @Content(array = @ArraySchema(schema = @Schema(implementation = Response.class)))),
         @ApiResponse(responseCode = "201", description = "Create Component Filter"),
         @ApiResponse(responseCode = "403", description = "Restricted operation"),
         @ApiResponse(responseCode = "400", description = "Invalid content / Missing content")})
     @PermissionAllowed(AafPermission.PermNames.INTERNAL_ALL_VALUE)
-    public Response addComponentFilterConstraint(
-        @Parameter(description = "UIConstraint data", required = true) String constraintData,
-        @Parameter(description = "Component Id") @PathParam("componentId") String componentId,
-        @Parameter(description = "Component Instance Id") @PathParam("componentInstanceId") String componentInstanceId,
-        @Parameter(description = "valid values: resources / services",
-            schema = @Schema(allowableValues = {
-                ComponentTypeEnum.RESOURCE_PARAM_NAME,
-                ComponentTypeEnum.SERVICE_PARAM_NAME})) @PathParam("componentType") final String componentType,
-        @Parameter(description = "Constraint type. Valid values: properties / capabilities",
-            schema = @Schema(allowableValues = {NodeFilterConstraintType.PROPERTIES_PARAM_NAME,
-                NodeFilterConstraintType.CAPABILITIES_PARAM_NAME}))
-        @PathParam("constraintType") final String constraintType,
-        @Context final HttpServletRequest request,
-        @HeaderParam(value = Constants.USER_ID_HEADER) String userId) {
-
+    public Response addComponentFilterConstraint(@Parameter(description = "UIConstraint data", required = true) String constraintData,
+                                                 @Parameter(description = "Component Id") @PathParam("componentId") String componentId,
+                                                 @Parameter(description = "Component Instance Id") @PathParam("componentInstanceId") String componentInstanceId,
+                                                 @Parameter(description = "valid values: resources / services", schema = @Schema(allowableValues = {
+                                                     ComponentTypeEnum.RESOURCE_PARAM_NAME,
+                                                     ComponentTypeEnum.SERVICE_PARAM_NAME})) @PathParam("componentType") final String componentType,
+                                                 @Parameter(description = "Constraint type. Valid values: properties / capabilities", schema = @Schema(allowableValues = {
+                                                     NodeFilterConstraintType.PROPERTIES_PARAM_NAME,
+                                                     NodeFilterConstraintType.CAPABILITIES_PARAM_NAME})) @PathParam("constraintType") final String constraintType,
+                                                 @Context final HttpServletRequest request,
+                                                 @HeaderParam(value = Constants.USER_ID_HEADER) String userId) {
         LOGGER.debug(START_HANDLE_REQUEST_OF, request.getMethod(), request.getRequestURI());
         LOGGER.debug(MODIFIER_ID_IS, userId);
         final User userModifier = componentNodeFilterBusinessLogic.validateUser(userId);
-
         final ComponentTypeEnum componentTypeEnum = ComponentTypeEnum.findByParamName(componentType);
         try {
-            final Optional<UIConstraint> convertResponse = componentsUtils
-                .parseToConstraint(constraintData, userModifier, componentTypeEnum);
+            final Optional<UIConstraint> convertResponse = componentsUtils.parseToConstraint(constraintData, userModifier, componentTypeEnum);
             if (convertResponse.isEmpty()) {
                 LOGGER.error(FAILED_TO_PARSE_COMPONENT);
                 return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR));
             }
-            final Optional<NodeFilterConstraintType> nodeFilterConstraintType =
-                NodeFilterConstraintType.parse(constraintType);
+            final Optional<NodeFilterConstraintType> nodeFilterConstraintType = NodeFilterConstraintType.parse(constraintType);
             if (nodeFilterConstraintType.isEmpty()) {
-                return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.INVALID_CONTENT_PARAM,
-                    INVALID_NODE_FILTER_CONSTRAINT_TYPE, constraintType));
+                return buildErrorResponse(
+                    getComponentsUtils().getResponseFormat(ActionStatus.INVALID_CONTENT_PARAM, INVALID_NODE_FILTER_CONSTRAINT_TYPE, constraintType));
             }
             final UIConstraint uiConstraint = convertResponse.get();
             final String constraint = new ConstraintConvertor().convert(uiConstraint);
             final Optional<CINodeFilterDataDefinition> actionResponse = componentNodeFilterBusinessLogic
-                .addNodeFilter(componentId.toLowerCase(), componentInstanceId, NodeFilterConstraintAction.ADD,
-                    uiConstraint.getServicePropertyName(), constraint, true, componentTypeEnum,
-                    nodeFilterConstraintType.get(),
+                .addNodeFilter(componentId.toLowerCase(), componentInstanceId, NodeFilterConstraintAction.ADD, uiConstraint.getServicePropertyName(),
+                    constraint, true, componentTypeEnum, nodeFilterConstraintType.get(),
                     StringUtils.isEmpty(uiConstraint.getCapabilityName()) ? "" : uiConstraint.getCapabilityName());
-
             if (actionResponse.isEmpty()) {
                 LOGGER.error(FAILED_TO_CREATE_NODE_FILTER);
                 return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR));
             }
-
             return buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK),
                 new NodeFilterConverter().convertToUi(actionResponse.get()));
-
         } catch (final Exception e) {
             BeEcompErrorManager.getInstance().logBeRestApiGeneralError(NODE_FILTER_CREATION);
             LOGGER.error(CREATE_NODE_FILTER_WITH_AN_ERROR, e);
@@ -173,60 +152,49 @@ public class ComponentNodeFilterServlet extends AbstractValidationsServlet {
     @Consumes(MediaType.APPLICATION_JSON)
     @Produces(MediaType.APPLICATION_JSON)
     @Path("/{constraintIndex}/nodeFilter")
-    @Operation(description = "Update Component Filter Constraint", method = "PUT",
-        summary = "Update Component Filter Constraint", responses = {
+    @Operation(description = "Update Component Filter Constraint", method = "PUT", summary = "Update Component Filter Constraint", responses = {
         @ApiResponse(content = @Content(array = @ArraySchema(schema = @Schema(implementation = Response.class)))),
         @ApiResponse(responseCode = "201", description = "Create Component Filter"),
         @ApiResponse(responseCode = "403", description = "Restricted operation"),
         @ApiResponse(responseCode = "400", description = "Invalid content / Missing content")})
     @PermissionAllowed(AafPermission.PermNames.INTERNAL_ALL_VALUE)
-    public Response updateComponentFilterConstraint(
-        @Parameter(description = "UIConstraint data", required = true) String constraintData,
-        @Parameter(description = "Component Id") @PathParam("componentId") String componentId,
-        @Parameter(description = "Component Instance Id") @PathParam("componentInstanceId") String componentInstanceId,
-        @Parameter(description = "valid values: resources / services",
-            schema = @Schema(allowableValues = {
-                ComponentTypeEnum.RESOURCE_PARAM_NAME,
-                ComponentTypeEnum.SERVICE_PARAM_NAME})) @PathParam("componentType") final String componentType,
-        @Parameter(description = "Constraint type. Valid values: properties / capabilities",
-            schema = @Schema(allowableValues = {NodeFilterConstraintType.PROPERTIES_PARAM_NAME,
-                NodeFilterConstraintType.CAPABILITIES_PARAM_NAME}))
-        @PathParam("constraintType") final String constraintType,
-        @Parameter(description = "Constraint Index") @PathParam("constraintIndex") int index,
-        @Context final HttpServletRequest request, @HeaderParam(value = Constants.USER_ID_HEADER) String userId) {
-
+    public Response updateComponentFilterConstraint(@Parameter(description = "UIConstraint data", required = true) String constraintData,
+                                                    @Parameter(description = "Component Id") @PathParam("componentId") String componentId,
+                                                    @Parameter(description = "Component Instance Id") @PathParam("componentInstanceId") String componentInstanceId,
+                                                    @Parameter(description = "valid values: resources / services", schema = @Schema(allowableValues = {
+                                                        ComponentTypeEnum.RESOURCE_PARAM_NAME,
+                                                        ComponentTypeEnum.SERVICE_PARAM_NAME})) @PathParam("componentType") final String componentType,
+                                                    @Parameter(description = "Constraint type. Valid values: properties / capabilities", schema = @Schema(allowableValues = {
+                                                        NodeFilterConstraintType.PROPERTIES_PARAM_NAME,
+                                                        NodeFilterConstraintType.CAPABILITIES_PARAM_NAME})) @PathParam("constraintType") final String constraintType,
+                                                    @Parameter(description = "Constraint Index") @PathParam("constraintIndex") int index,
+                                                    @Context final HttpServletRequest request,
+                                                    @HeaderParam(value = Constants.USER_ID_HEADER) String userId) {
         LOGGER.debug(START_HANDLE_REQUEST_OF, request.getMethod(), request.getRequestURI());
         LOGGER.debug(MODIFIER_ID_IS, userId);
         final User userModifier = componentNodeFilterBusinessLogic.validateUser(userId);
-
         try {
-            final Optional<NodeFilterConstraintType> nodeFilterConstraintTypeOptional =
-                NodeFilterConstraintType.parse(constraintType);
+            final Optional<NodeFilterConstraintType> nodeFilterConstraintTypeOptional = NodeFilterConstraintType.parse(constraintType);
             if (nodeFilterConstraintTypeOptional.isEmpty()) {
-                return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.INVALID_CONTENT_PARAM,
-                    INVALID_NODE_FILTER_CONSTRAINT_TYPE, constraintType));
+                return buildErrorResponse(
+                    getComponentsUtils().getResponseFormat(ActionStatus.INVALID_CONTENT_PARAM, INVALID_NODE_FILTER_CONSTRAINT_TYPE, constraintType));
             }
-
             final ComponentTypeEnum componentTypeEnum = ComponentTypeEnum.findByParamName(componentType);
-            final Optional<UIConstraint> convertResponse = componentsUtils
-                .parseToConstraint(constraintData, userModifier, componentTypeEnum);
+            final Optional<UIConstraint> convertResponse = componentsUtils.parseToConstraint(constraintData, userModifier, componentTypeEnum);
             if (convertResponse.isEmpty()) {
                 LOGGER.error(FAILED_TO_PARSE_COMPONENT);
                 return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR));
             }
             final NodeFilterConstraintType nodeFilterConstraintType = nodeFilterConstraintTypeOptional.get();
             final Optional<CINodeFilterDataDefinition> actionResponse = componentNodeFilterBusinessLogic
-                .updateNodeFilter(componentId.toLowerCase(), componentInstanceId, convertResponse.get(),
-                    componentTypeEnum, nodeFilterConstraintType, index);
-
+                .updateNodeFilter(componentId.toLowerCase(), componentInstanceId, convertResponse.get(), componentTypeEnum, nodeFilterConstraintType,
+                    index);
             if (actionResponse.isEmpty()) {
                 LOGGER.error(FAILED_TO_UPDATE_NODE_FILTER);
                 return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR));
             }
-
             return buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK),
                 new NodeFilterConverter().convertToUi(actionResponse.get()));
-
         } catch (final Exception e) {
             BeEcompErrorManager.getInstance().logBeRestApiGeneralError(NODE_FILTER_UPDATE);
             LOGGER.error(UPDATE_NODE_FILTER_WITH_AN_ERROR, e);
@@ -238,56 +206,45 @@ public class ComponentNodeFilterServlet extends AbstractValidationsServlet {
     @Consumes(MediaType.APPLICATION_JSON)
     @Produces(MediaType.APPLICATION_JSON)
     @Path("{constraintIndex}/nodeFilter")
-    @Operation(description = "Delete Component Filter Constraint", method = "Delete",
-        summary = "Delete Component Filter Constraint", responses = {
+    @Operation(description = "Delete Component Filter Constraint", method = "Delete", summary = "Delete Component Filter Constraint", responses = {
         @ApiResponse(content = @Content(array = @ArraySchema(schema = @Schema(implementation = Response.class)))),
         @ApiResponse(responseCode = "201", description = "Delete Component Filter Constraint"),
         @ApiResponse(responseCode = "403", description = "Restricted operation"),
         @ApiResponse(responseCode = "400", description = "Invalid content / Missing content")})
     @PermissionAllowed(AafPermission.PermNames.INTERNAL_ALL_VALUE)
-    public Response deleteComponentFilterConstraint(
-        @Parameter(description = "Component Id") @PathParam("componentId") String componentId,
-        @Parameter(description = "Component Instance Id") @PathParam("componentInstanceId") String componentInstanceId,
-        @Parameter(description = "Constraint Index") @PathParam("constraintIndex") int index,
-        @Parameter(description = "valid values: resources / services",
-            schema = @Schema(allowableValues = {
-                ComponentTypeEnum.RESOURCE_PARAM_NAME,
-                ComponentTypeEnum.SERVICE_PARAM_NAME})) @PathParam("componentType") final String componentType,
-        @Parameter(description = "Constraint type. Valid values: properties / capabilities",
-            schema = @Schema(allowableValues = {NodeFilterConstraintType.PROPERTIES_PARAM_NAME,
-                NodeFilterConstraintType.CAPABILITIES_PARAM_NAME}))
-        @PathParam("constraintType") final String constraintType,
-        @Context final HttpServletRequest request, @HeaderParam(value = Constants.USER_ID_HEADER) String userId) {
-
+    public Response deleteComponentFilterConstraint(@Parameter(description = "Component Id") @PathParam("componentId") String componentId,
+                                                    @Parameter(description = "Component Instance Id") @PathParam("componentInstanceId") String componentInstanceId,
+                                                    @Parameter(description = "Constraint Index") @PathParam("constraintIndex") int index,
+                                                    @Parameter(description = "valid values: resources / services", schema = @Schema(allowableValues = {
+                                                        ComponentTypeEnum.RESOURCE_PARAM_NAME,
+                                                        ComponentTypeEnum.SERVICE_PARAM_NAME})) @PathParam("componentType") final String componentType,
+                                                    @Parameter(description = "Constraint type. Valid values: properties / capabilities", schema = @Schema(allowableValues = {
+                                                        NodeFilterConstraintType.PROPERTIES_PARAM_NAME,
+                                                        NodeFilterConstraintType.CAPABILITIES_PARAM_NAME})) @PathParam("constraintType") final String constraintType,
+                                                    @Context final HttpServletRequest request,
+                                                    @HeaderParam(value = Constants.USER_ID_HEADER) String userId) {
         LOGGER.debug(START_HANDLE_REQUEST_OF, request.getMethod(), request.getRequestURI());
         LOGGER.debug(MODIFIER_ID_IS, userId);
         componentNodeFilterBusinessLogic.validateUser(userId);
-
         try {
-            final Optional<NodeFilterConstraintType> nodeFilterConstraintType =
-                NodeFilterConstraintType.parse(constraintType);
+            final Optional<NodeFilterConstraintType> nodeFilterConstraintType = NodeFilterConstraintType.parse(constraintType);
             if (nodeFilterConstraintType.isEmpty()) {
-                return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.INVALID_CONTENT_PARAM,
-                    INVALID_NODE_FILTER_CONSTRAINT_TYPE, constraintType));
+                return buildErrorResponse(
+                    getComponentsUtils().getResponseFormat(ActionStatus.INVALID_CONTENT_PARAM, INVALID_NODE_FILTER_CONSTRAINT_TYPE, constraintType));
             }
             final Optional<CINodeFilterDataDefinition> actionResponse = componentNodeFilterBusinessLogic
-                .deleteNodeFilter(componentId.toLowerCase(), componentInstanceId, NodeFilterConstraintAction.DELETE,
-                    null, index, true, ComponentTypeEnum.findByParamName(componentType),
-                    nodeFilterConstraintType.get());
-
+                .deleteNodeFilter(componentId.toLowerCase(), componentInstanceId, NodeFilterConstraintAction.DELETE, null, index, true,
+                    ComponentTypeEnum.findByParamName(componentType), nodeFilterConstraintType.get());
             if (actionResponse.isEmpty()) {
                 LOGGER.debug(FAILED_TO_DELETE_NODE_FILTER);
                 return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR));
             }
-
             return buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK),
                 new NodeFilterConverter().convertToUi(actionResponse.get()));
-
         } catch (final Exception e) {
             BeEcompErrorManager.getInstance().logBeRestApiGeneralError(NODE_FILTER_DELETE);
             LOGGER.debug(DELETE_NODE_FILTER_WITH_AN_ERROR, e);
             return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR));
         }
     }
-
 }
index fcca339..9ff155f 100644 (file)
@@ -13,7 +13,6 @@
  * See the License for the specific language governing permissions and
  * limitations under the License.
  */
-
 package org.openecomp.sdc.be.servlets;
 
 import com.jcabi.aspects.Loggable;
@@ -28,6 +27,23 @@ import io.swagger.v3.oas.annotations.servers.Server;
 import io.swagger.v3.oas.annotations.servers.Servers;
 import io.swagger.v3.oas.annotations.tags.Tag;
 import io.swagger.v3.oas.annotations.tags.Tags;
+import java.util.List;
+import java.util.Map;
+import javax.inject.Inject;
+import javax.inject.Singleton;
+import javax.servlet.http.HttpServletRequest;
+import javax.ws.rs.Consumes;
+import javax.ws.rs.DELETE;
+import javax.ws.rs.GET;
+import javax.ws.rs.HeaderParam;
+import javax.ws.rs.POST;
+import javax.ws.rs.PUT;
+import javax.ws.rs.Path;
+import javax.ws.rs.PathParam;
+import javax.ws.rs.Produces;
+import javax.ws.rs.core.Context;
+import javax.ws.rs.core.MediaType;
+import javax.ws.rs.core.Response;
 import org.openecomp.sdc.be.components.impl.PropertyBusinessLogic;
 import org.openecomp.sdc.be.components.impl.aaf.AafPermission;
 import org.openecomp.sdc.be.components.impl.aaf.PermissionAllowed;
@@ -48,24 +64,6 @@ import org.openecomp.sdc.exception.ResponseFormat;
 import org.slf4j.Logger;
 import org.slf4j.LoggerFactory;
 
-import javax.inject.Inject;
-import javax.inject.Singleton;
-import javax.servlet.http.HttpServletRequest;
-import javax.ws.rs.Consumes;
-import javax.ws.rs.DELETE;
-import javax.ws.rs.GET;
-import javax.ws.rs.HeaderParam;
-import javax.ws.rs.POST;
-import javax.ws.rs.PUT;
-import javax.ws.rs.Path;
-import javax.ws.rs.PathParam;
-import javax.ws.rs.Produces;
-import javax.ws.rs.core.Context;
-import javax.ws.rs.core.MediaType;
-import javax.ws.rs.core.Response;
-import java.util.List;
-import java.util.Map;
-
 @Loggable(prepend = true, value = Loggable.DEBUG, trim = false)
 @Path("/v1/catalog")
 @Tags({@Tag(name = "SDC Internal APIs")})
@@ -73,43 +71,36 @@ import java.util.Map;
 @Singleton
 public class ComponentPropertyServlet extends BeGenericServlet {
 
-  private final PropertyBusinessLogic propertyBusinessLogic;
-  private final ApplicationDataTypeCache applicationDataTypeCache;
-
-       @Inject
-  public ComponentPropertyServlet(UserBusinessLogic userBusinessLogic,
-      ComponentsUtils componentsUtils,
-      ApplicationDataTypeCache applicationDataTypeCache,
-      PropertyBusinessLogic propertyBusinessLogic) {
-    super(userBusinessLogic, componentsUtils);
-    this.applicationDataTypeCache = applicationDataTypeCache;
-    this.propertyBusinessLogic = propertyBusinessLogic;
-  }
-
-  private static final Logger log = LoggerFactory.getLogger(ComponentPropertyServlet.class);
-  private static final String CREATE_PROPERTY = "Create Property";
-  private static final String DEBUG_MESSAGE = "Start handle request of {} modifier id is {}";
-  private static final LoggerSupportability loggerSupportability = LoggerSupportability.getLogger(ComponentPropertyServlet.class.getName());
-
+    private static final Logger log = LoggerFactory.getLogger(ComponentPropertyServlet.class);
+    private static final String CREATE_PROPERTY = "Create Property";
+    private static final String DEBUG_MESSAGE = "Start handle request of {} modifier id is {}";
+    private static final LoggerSupportability loggerSupportability = LoggerSupportability.getLogger(ComponentPropertyServlet.class.getName());
+    private final PropertyBusinessLogic propertyBusinessLogic;
+    private final ApplicationDataTypeCache applicationDataTypeCache;
+
+    @Inject
+    public ComponentPropertyServlet(UserBusinessLogic userBusinessLogic, ComponentsUtils componentsUtils,
+                                    ApplicationDataTypeCache applicationDataTypeCache, PropertyBusinessLogic propertyBusinessLogic) {
+        super(userBusinessLogic, componentsUtils);
+        this.applicationDataTypeCache = applicationDataTypeCache;
+        this.propertyBusinessLogic = propertyBusinessLogic;
+    }
 
     @POST
     @Path("services/{serviceId}/properties")
     @Consumes(MediaType.APPLICATION_JSON)
     @Produces(MediaType.APPLICATION_JSON)
-    @Operation(description = "Create Service Property", method = "POST", summary = "Returns created service property",
-            responses = {@ApiResponse(
-                    content = @Content(array = @ArraySchema(schema = @Schema(implementation = Response.class)))),
-                    @ApiResponse(responseCode = "201", description = "Service property created"),
-                    @ApiResponse(responseCode = "403", description = "Restricted operation"),
-                    @ApiResponse(responseCode = "400", description = "Invalid content / Missing content"),
-                    @ApiResponse(responseCode = "409", description = "Service property already exist")})
+    @Operation(description = "Create Service Property", method = "POST", summary = "Returns created service property", responses = {
+        @ApiResponse(content = @Content(array = @ArraySchema(schema = @Schema(implementation = Response.class)))),
+        @ApiResponse(responseCode = "201", description = "Service property created"),
+        @ApiResponse(responseCode = "403", description = "Restricted operation"),
+        @ApiResponse(responseCode = "400", description = "Invalid content / Missing content"),
+        @ApiResponse(responseCode = "409", description = "Service property already exist")})
     @PermissionAllowed(AafPermission.PermNames.INTERNAL_ALL_VALUE)
     public Response createPropertyInService(
-            @Parameter(description = "service id to update with new property",
-                    required = true) @PathParam("serviceId") final String serviceId,
-            @Parameter(description = "Service property to be created", required = true) String data,
-            @Context final HttpServletRequest request, @HeaderParam(value = Constants.USER_ID_HEADER) String userId) {
-
+        @Parameter(description = "service id to update with new property", required = true) @PathParam("serviceId") final String serviceId,
+        @Parameter(description = "Service property to be created", required = true) String data, @Context final HttpServletRequest request,
+        @HeaderParam(value = Constants.USER_ID_HEADER) String userId) {
         return createProperty(serviceId, data, request, userId);
     }
 
@@ -117,41 +108,34 @@ public class ComponentPropertyServlet extends BeGenericServlet {
     @Path("resources/{resourceId}/properties")
     @Consumes(MediaType.APPLICATION_JSON)
     @Produces(MediaType.APPLICATION_JSON)
-    @Operation(description = "Create Resource Property", method = "POST", summary = "Returns created service property",
-            responses = {@ApiResponse(
-                    content = @Content(array = @ArraySchema(schema = @Schema(implementation = Response.class)))),
-                    @ApiResponse(responseCode = "201", description = "Resource property created"),
-                    @ApiResponse(responseCode = "403", description = "Restricted operation"),
-                    @ApiResponse(responseCode = "400", description = "Invalid content / Missing content"),
-                    @ApiResponse(responseCode = "409", description = "Resource property already exist")})
+    @Operation(description = "Create Resource Property", method = "POST", summary = "Returns created service property", responses = {
+        @ApiResponse(content = @Content(array = @ArraySchema(schema = @Schema(implementation = Response.class)))),
+        @ApiResponse(responseCode = "201", description = "Resource property created"),
+        @ApiResponse(responseCode = "403", description = "Restricted operation"),
+        @ApiResponse(responseCode = "400", description = "Invalid content / Missing content"),
+        @ApiResponse(responseCode = "409", description = "Resource property already exist")})
     @PermissionAllowed(AafPermission.PermNames.INTERNAL_ALL_VALUE)
     public Response createPropertyInResource(
-            @Parameter(description = "Resource id to update with new property",
-                    required = true) @PathParam("resourceId") final String resourceId,
-            @Parameter(description = "Resource property to be created", required = true) String data,
-            @Context final HttpServletRequest request, @HeaderParam(value = Constants.USER_ID_HEADER) String userId) {
-
+        @Parameter(description = "Resource id to update with new property", required = true) @PathParam("resourceId") final String resourceId,
+        @Parameter(description = "Resource property to be created", required = true) String data, @Context final HttpServletRequest request,
+        @HeaderParam(value = Constants.USER_ID_HEADER) String userId) {
         return createProperty(resourceId, data, request, userId);
     }
 
-
     @GET
     @Path("services/{serviceId}/properties/{propertyId}")
     @Consumes(MediaType.APPLICATION_JSON)
     @Produces(MediaType.APPLICATION_JSON)
-    @Operation(description = "Get Service Property", method = "GET", summary = "Returns property of service",
-            responses = {@ApiResponse(
-                    content = @Content(array = @ArraySchema(schema = @Schema(implementation = Response.class)))),
-                    @ApiResponse(responseCode = "200", description = "property"),
-                    @ApiResponse(responseCode = "403", description = "Restricted operation"),
-                    @ApiResponse(responseCode = "400", description = "Invalid content / Missing content"),
-                    @ApiResponse(responseCode = "404", description = "Service property not found")})
+    @Operation(description = "Get Service Property", method = "GET", summary = "Returns property of service", responses = {
+        @ApiResponse(content = @Content(array = @ArraySchema(schema = @Schema(implementation = Response.class)))),
+        @ApiResponse(responseCode = "200", description = "property"), @ApiResponse(responseCode = "403", description = "Restricted operation"),
+        @ApiResponse(responseCode = "400", description = "Invalid content / Missing content"),
+        @ApiResponse(responseCode = "404", description = "Service property not found")})
     @PermissionAllowed(AafPermission.PermNames.INTERNAL_ALL_VALUE)
     public Response getPropertyInService(
-            @Parameter(description = "service id of property", required = true) @PathParam("serviceId") final String serviceId,
-            @Parameter(description = "property id to get", required = true) @PathParam("propertyId") final String propertyId,
-            @Context final HttpServletRequest request, @HeaderParam(value = Constants.USER_ID_HEADER) String userId) {
-
+        @Parameter(description = "service id of property", required = true) @PathParam("serviceId") final String serviceId,
+        @Parameter(description = "property id to get", required = true) @PathParam("propertyId") final String propertyId,
+        @Context final HttpServletRequest request, @HeaderParam(value = Constants.USER_ID_HEADER) String userId) {
         return getProperty(serviceId, propertyId, request, userId);
     }
 
@@ -159,20 +143,16 @@ public class ComponentPropertyServlet extends BeGenericServlet {
     @Path("resources/{resourceId}/properties/{propertyId}")
     @Consumes(MediaType.APPLICATION_JSON)
     @Produces(MediaType.APPLICATION_JSON)
-    @Operation(description = "Get Resource Property", method = "GET", summary = "Returns property of resource",
-            responses = {@ApiResponse(
-                    content = @Content(array = @ArraySchema(schema = @Schema(implementation = Response.class)))),
-                    @ApiResponse(responseCode = "200", description = "property"),
-                    @ApiResponse(responseCode = "403", description = "Restricted operation"),
-                    @ApiResponse(responseCode = "400", description = "Invalid content / Missing content"),
-                    @ApiResponse(responseCode = "404", description = "Resource property not found")})
+    @Operation(description = "Get Resource Property", method = "GET", summary = "Returns property of resource", responses = {
+        @ApiResponse(content = @Content(array = @ArraySchema(schema = @Schema(implementation = Response.class)))),
+        @ApiResponse(responseCode = "200", description = "property"), @ApiResponse(responseCode = "403", description = "Restricted operation"),
+        @ApiResponse(responseCode = "400", description = "Invalid content / Missing content"),
+        @ApiResponse(responseCode = "404", description = "Resource property not found")})
     @PermissionAllowed(AafPermission.PermNames.INTERNAL_ALL_VALUE)
     public Response getPropertyInResource(
-            @Parameter(description = "resource id of property",
-                    required = true) @PathParam("resourceId") final String resourceId,
-            @Parameter(description = "property id to get", required = true) @PathParam("propertyId") final String propertyId,
-            @Context final HttpServletRequest request, @HeaderParam(value = Constants.USER_ID_HEADER) String userId) {
-
+        @Parameter(description = "resource id of property", required = true) @PathParam("resourceId") final String resourceId,
+        @Parameter(description = "property id to get", required = true) @PathParam("propertyId") final String propertyId,
+        @Context final HttpServletRequest request, @HeaderParam(value = Constants.USER_ID_HEADER) String userId) {
         return getProperty(resourceId, propertyId, request, userId);
     }
 
@@ -180,19 +160,15 @@ public class ComponentPropertyServlet extends BeGenericServlet {
     @Path("services/{serviceId}/properties")
     @Consumes(MediaType.APPLICATION_JSON)
     @Produces(MediaType.APPLICATION_JSON)
-    @Operation(description = "Get Service Property", method = "GET", summary = "Returns property list of service",
-            responses = {@ApiResponse(
-                    content = @Content(array = @ArraySchema(schema = @Schema(implementation = Response.class)))),
-                    @ApiResponse(responseCode = "200", description = "property"),
-                    @ApiResponse(responseCode = "403", description = "Restricted operation"),
-                    @ApiResponse(responseCode = "400", description = "Invalid content / Missing content"),
-                    @ApiResponse(responseCode = "404", description = "Service property not found")})
+    @Operation(description = "Get Service Property", method = "GET", summary = "Returns property list of service", responses = {
+        @ApiResponse(content = @Content(array = @ArraySchema(schema = @Schema(implementation = Response.class)))),
+        @ApiResponse(responseCode = "200", description = "property"), @ApiResponse(responseCode = "403", description = "Restricted operation"),
+        @ApiResponse(responseCode = "400", description = "Invalid content / Missing content"),
+        @ApiResponse(responseCode = "404", description = "Service property not found")})
     @PermissionAllowed(AafPermission.PermNames.INTERNAL_ALL_VALUE)
     public Response getPropertyListInService(
-            @Parameter(description = "service id of property",
-                    required = true) @PathParam("serviceId") final String serviceId,
-            @Context final HttpServletRequest request, @HeaderParam(value = Constants.USER_ID_HEADER) String userId) {
-
+        @Parameter(description = "service id of property", required = true) @PathParam("serviceId") final String serviceId,
+        @Context final HttpServletRequest request, @HeaderParam(value = Constants.USER_ID_HEADER) String userId) {
         return getPropertyList(serviceId, request, userId);
     }
 
@@ -200,19 +176,15 @@ public class ComponentPropertyServlet extends BeGenericServlet {
     @Path("resources/{resourceId}/properties")
     @Consumes(MediaType.APPLICATION_JSON)
     @Produces(MediaType.APPLICATION_JSON)
-    @Operation(description = "Get Resource Property", method = "GET", summary = "Returns property list of resource",
-            responses = {@ApiResponse(
-                    content = @Content(array = @ArraySchema(schema = @Schema(implementation = Response.class)))),
-                    @ApiResponse(responseCode = "200", description = "property"),
-                    @ApiResponse(responseCode = "403", description = "Restricted operation"),
-                    @ApiResponse(responseCode = "400", description = "Invalid content / Missing content"),
-                    @ApiResponse(responseCode = "404", description = "Resource property not found")})
+    @Operation(description = "Get Resource Property", method = "GET", summary = "Returns property list of resource", responses = {
+        @ApiResponse(content = @Content(array = @ArraySchema(schema = @Schema(implementation = Response.class)))),
+        @ApiResponse(responseCode = "200", description = "property"), @ApiResponse(responseCode = "403", description = "Restricted operation"),
+        @ApiResponse(responseCode = "400", description = "Invalid content / Missing content"),
+        @ApiResponse(responseCode = "404", description = "Resource property not found")})
     @PermissionAllowed(AafPermission.PermNames.INTERNAL_ALL_VALUE)
     public Response getPropertyListInResource(
-            @Parameter(description = "resource id of property",
-                    required = true) @PathParam("resourceId") final String resourceId,
-            @Context final HttpServletRequest request, @HeaderParam(value = Constants.USER_ID_HEADER) String userId) {
-
+        @Parameter(description = "resource id of property", required = true) @PathParam("resourceId") final String resourceId,
+        @Context final HttpServletRequest request, @HeaderParam(value = Constants.USER_ID_HEADER) String userId) {
         return getPropertyList(resourceId, request, userId);
     }
 
@@ -220,21 +192,17 @@ public class ComponentPropertyServlet extends BeGenericServlet {
     @Path("services/{serviceId}/properties/{propertyId}")
     @Consumes(MediaType.APPLICATION_JSON)
     @Produces(MediaType.APPLICATION_JSON)
-    @Operation(description = "Delete Service Property", method = "DELETE", summary = "Returns deleted property",
-            responses = {@ApiResponse(
-                    content = @Content(array = @ArraySchema(schema = @Schema(implementation = Response.class)))),
-                    @ApiResponse(responseCode = "204", description = "deleted property"),
-                    @ApiResponse(responseCode = "403", description = "Restricted operation"),
-                    @ApiResponse(responseCode = "400", description = "Invalid content / Missing content"),
-                    @ApiResponse(responseCode = "404", description = "Service property not found")})
+    @Operation(description = "Delete Service Property", method = "DELETE", summary = "Returns deleted property", responses = {
+        @ApiResponse(content = @Content(array = @ArraySchema(schema = @Schema(implementation = Response.class)))),
+        @ApiResponse(responseCode = "204", description = "deleted property"),
+        @ApiResponse(responseCode = "403", description = "Restricted operation"),
+        @ApiResponse(responseCode = "400", description = "Invalid content / Missing content"),
+        @ApiResponse(responseCode = "404", description = "Service property not found")})
     @PermissionAllowed(AafPermission.PermNames.INTERNAL_ALL_VALUE)
     public Response deletePropertyInService(
-            @Parameter(description = "service id of property",
-                    required = true) @PathParam("serviceId") final String serviceId,
-            @Parameter(description = "Property id to delete",
-                    required = true) @PathParam("propertyId") final String propertyId,
-            @Context final HttpServletRequest request, @HeaderParam(value = Constants.USER_ID_HEADER) String userId) {
-
+        @Parameter(description = "service id of property", required = true) @PathParam("serviceId") final String serviceId,
+        @Parameter(description = "Property id to delete", required = true) @PathParam("propertyId") final String propertyId,
+        @Context final HttpServletRequest request, @HeaderParam(value = Constants.USER_ID_HEADER) String userId) {
         return deleteProperty(serviceId, propertyId, request, userId);
     }
 
@@ -242,21 +210,17 @@ public class ComponentPropertyServlet extends BeGenericServlet {
     @Path("resources/{resourceId}/properties/{propertyId}")
     @Consumes(MediaType.APPLICATION_JSON)
     @Produces(MediaType.APPLICATION_JSON)
-    @Operation(description = "Delete Resource Property", method = "DELETE", summary = "Returns deleted property",
-            responses = {@ApiResponse(
-                    content = @Content(array = @ArraySchema(schema = @Schema(implementation = Response.class)))),
-                    @ApiResponse(responseCode = "204", description = "deleted property"),
-                    @ApiResponse(responseCode = "403", description = "Restricted operation"),
-                    @ApiResponse(responseCode = "400", description = "Invalid content / Missing content"),
-                    @ApiResponse(responseCode = "404", description = "Resource property not found")})
+    @Operation(description = "Delete Resource Property", method = "DELETE", summary = "Returns deleted property", responses = {
+        @ApiResponse(content = @Content(array = @ArraySchema(schema = @Schema(implementation = Response.class)))),
+        @ApiResponse(responseCode = "204", description = "deleted property"),
+        @ApiResponse(responseCode = "403", description = "Restricted operation"),
+        @ApiResponse(responseCode = "400", description = "Invalid content / Missing content"),
+        @ApiResponse(responseCode = "404", description = "Resource property not found")})
     @PermissionAllowed(AafPermission.PermNames.INTERNAL_ALL_VALUE)
     public Response deletePropertyInResource(
-            @Parameter(description = "resource id of property",
-                    required = true) @PathParam("resourceId") final String resourceId,
-            @Parameter(description = "Property id to delete",
-                    required = true) @PathParam("propertyId") final String propertyId,
-            @Context final HttpServletRequest request, @HeaderParam(value = Constants.USER_ID_HEADER) String userId) {
-
+        @Parameter(description = "resource id of property", required = true) @PathParam("resourceId") final String resourceId,
+        @Parameter(description = "Property id to delete", required = true) @PathParam("propertyId") final String propertyId,
+        @Context final HttpServletRequest request, @HeaderParam(value = Constants.USER_ID_HEADER) String userId) {
         return deleteProperty(resourceId, propertyId, request, userId);
     }
 
@@ -264,19 +228,16 @@ public class ComponentPropertyServlet extends BeGenericServlet {
     @Path("services/{serviceId}/properties")
     @Consumes(MediaType.APPLICATION_JSON)
     @Produces(MediaType.APPLICATION_JSON)
-    @Operation(description = "Update Service Property", method = "PUT", summary = "Returns updated property",
-            responses = {@ApiResponse(
-                    content = @Content(array = @ArraySchema(schema = @Schema(implementation = Response.class)))),
-                    @ApiResponse(responseCode = "200", description = "Service property updated"),
-                    @ApiResponse(responseCode = "403", description = "Restricted operation"),
-                    @ApiResponse(responseCode = "400", description = "Invalid content / Missing content")})
+    @Operation(description = "Update Service Property", method = "PUT", summary = "Returns updated property", responses = {
+        @ApiResponse(content = @Content(array = @ArraySchema(schema = @Schema(implementation = Response.class)))),
+        @ApiResponse(responseCode = "200", description = "Service property updated"),
+        @ApiResponse(responseCode = "403", description = "Restricted operation"),
+        @ApiResponse(responseCode = "400", description = "Invalid content / Missing content")})
     @PermissionAllowed(AafPermission.PermNames.INTERNAL_ALL_VALUE)
     public Response updatePropertyInService(
-            @Parameter(description = "service id to update with new property",
-                    required = true) @PathParam("serviceId") final String serviceId,
-            @Parameter(description = "Service property to update", required = true) String data,
-            @Context final HttpServletRequest request, @HeaderParam(value = Constants.USER_ID_HEADER) String userId) {
-
+        @Parameter(description = "service id to update with new property", required = true) @PathParam("serviceId") final String serviceId,
+        @Parameter(description = "Service property to update", required = true) String data, @Context final HttpServletRequest request,
+        @HeaderParam(value = Constants.USER_ID_HEADER) String userId) {
         return updateProperty(serviceId, data, request, userId);
     }
 
@@ -284,208 +245,163 @@ public class ComponentPropertyServlet extends BeGenericServlet {
     @Path("resources/{resourceId}/properties")
     @Consumes(MediaType.APPLICATION_JSON)
     @Produces(MediaType.APPLICATION_JSON)
-    @Operation(description = "Update Resource Property", method = "PUT", summary = "Returns updated property",
-            responses = {@ApiResponse(
-                    content = @Content(array = @ArraySchema(schema = @Schema(implementation = Response.class)))),
-                    @ApiResponse(responseCode = "200", description = "Resource property updated"),
-                    @ApiResponse(responseCode = "403", description = "Restricted operation"),
-                    @ApiResponse(responseCode = "400", description = "Invalid content / Missing content")})
+    @Operation(description = "Update Resource Property", method = "PUT", summary = "Returns updated property", responses = {
+        @ApiResponse(content = @Content(array = @ArraySchema(schema = @Schema(implementation = Response.class)))),
+        @ApiResponse(responseCode = "200", description = "Resource property updated"),
+        @ApiResponse(responseCode = "403", description = "Restricted operation"),
+        @ApiResponse(responseCode = "400", description = "Invalid content / Missing content")})
     @PermissionAllowed(AafPermission.PermNames.INTERNAL_ALL_VALUE)
     public Response updatePropertyInResource(
-            @Parameter(description = "resource id to update with new property",
-                    required = true) @PathParam("resourceId") final String resourceId,
-            @Parameter(description = "Resource property to update", required = true) String data,
-            @Context final HttpServletRequest request, @HeaderParam(value = Constants.USER_ID_HEADER) String userId) {
-
-    return updateProperty(resourceId, data, request, userId);
-  }
-
-  private Response createProperty(String componentId, String data,  HttpServletRequest request,String userId) {
-    String url = request.getMethod() + " " + request.getRequestURI();
-    log.debug("Start handle request of {} modifier id is {} data is {}", url, userId, data);
-    loggerSupportability.log(LoggerSupportabilityActions.CREATE_PROPERTIES, StatusCode.STARTED,"CREATE_PROPERTIES by user {} ", userId);
-
-    try{
-      Either<Map<String, PropertyDefinition>, ActionStatus> propertyDefinition =
-              getPropertyModel(componentId, data);
-      if (propertyDefinition.isRight()) {
-        ResponseFormat responseFormat = getComponentsUtils().getResponseFormat(propertyDefinition.right().value());
-        return buildErrorResponse(responseFormat);
-      }
-
-      Map<String, PropertyDefinition> properties = propertyDefinition.left().value();
-      if (properties == null || properties.size() != 1) {
-        log.info("Property content is invalid - {}", data);
-        ResponseFormat responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.INVALID_CONTENT);
-        return buildErrorResponse(responseFormat);
-      }
-
-      Map.Entry<String, PropertyDefinition> entry = properties.entrySet().iterator().next();
-      PropertyDefinition newPropertyDefinition = entry.getValue();
-      newPropertyDefinition.setParentUniqueId(componentId);
-      String propertyName = newPropertyDefinition.getName();
-
-      Either<EntryData<String, PropertyDefinition>, ResponseFormat> addPropertyEither =
-              propertyBusinessLogic.addPropertyToComponent(componentId, propertyName, newPropertyDefinition, userId);
-
-      if(addPropertyEither.isRight()) {
-        return buildErrorResponse(addPropertyEither.right().value());
-      }
-
-      loggerSupportability.log(LoggerSupportabilityActions.CREATE_PROPERTIES, StatusCode.COMPLETE,"CREATE_PROPERTIES by user {} ", userId);
-      return buildOkResponse(newPropertyDefinition);
-
-    } catch (Exception e) {
-      BeEcompErrorManager.getInstance().logBeRestApiGeneralError(CREATE_PROPERTY);
-      log.debug("create property failed with exception", e);
-      ResponseFormat responseFormat =
-              getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR);
-      return buildErrorResponse(responseFormat);
+        @Parameter(description = "resource id to update with new property", required = true) @PathParam("resourceId") final String resourceId,
+        @Parameter(description = "Resource property to update", required = true) String data, @Context final HttpServletRequest request,
+        @HeaderParam(value = Constants.USER_ID_HEADER) String userId) {
+        return updateProperty(resourceId, data, request, userId);
     }
-  }
-
 
-  private Response updateProperty(String componentId, String data, HttpServletRequest request, String userId) {
-    String url = request.getMethod() + " " + request.getRequestURI();
-    log.debug("Start handle request of {}", url);
-    loggerSupportability.log(LoggerSupportabilityActions.UPDATE_PROPERTIES, StatusCode.STARTED,"UPDATE_PROPERTIES by user {} ", userId);
+    private Response createProperty(String componentId, String data, HttpServletRequest request, String userId) {
+        String url = request.getMethod() + " " + request.getRequestURI();
+        log.debug("Start handle request of {} modifier id is {} data is {}", url, userId, data);
+        loggerSupportability.log(LoggerSupportabilityActions.CREATE_PROPERTIES, StatusCode.STARTED, "CREATE_PROPERTIES by user {} ", userId);
+        try {
+            Either<Map<String, PropertyDefinition>, ActionStatus> propertyDefinition = getPropertyModel(componentId, data);
+            if (propertyDefinition.isRight()) {
+                ResponseFormat responseFormat = getComponentsUtils().getResponseFormat(propertyDefinition.right().value());
+                return buildErrorResponse(responseFormat);
+            }
+            Map<String, PropertyDefinition> properties = propertyDefinition.left().value();
+            if (properties == null || properties.size() != 1) {
+                log.info("Property content is invalid - {}", data);
+                ResponseFormat responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.INVALID_CONTENT);
+                return buildErrorResponse(responseFormat);
+            }
+            Map.Entry<String, PropertyDefinition> entry = properties.entrySet().iterator().next();
+            PropertyDefinition newPropertyDefinition = entry.getValue();
+            newPropertyDefinition.setParentUniqueId(componentId);
+            String propertyName = newPropertyDefinition.getName();
+            Either<EntryData<String, PropertyDefinition>, ResponseFormat> addPropertyEither = propertyBusinessLogic
+                .addPropertyToComponent(componentId, propertyName, newPropertyDefinition, userId);
+            if (addPropertyEither.isRight()) {
+                return buildErrorResponse(addPropertyEither.right().value());
+            }
+            loggerSupportability.log(LoggerSupportabilityActions.CREATE_PROPERTIES, StatusCode.COMPLETE, "CREATE_PROPERTIES by user {} ", userId);
+            return buildOkResponse(newPropertyDefinition);
+        } catch (Exception e) {
+            BeEcompErrorManager.getInstance().logBeRestApiGeneralError(CREATE_PROPERTY);
+            log.debug("create property failed with exception", e);
+            ResponseFormat responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR);
+            return buildErrorResponse(responseFormat);
+        }
+    }
 
-    // get modifier id
-    User modifier = new User();
-    modifier.setUserId(userId);
-    log.debug("modifier id is {}", userId);
+    private Response updateProperty(String componentId, String data, HttpServletRequest request, String userId) {
+        String url = request.getMethod() + " " + request.getRequestURI();
+        log.debug("Start handle request of {}", url);
+        loggerSupportability.log(LoggerSupportabilityActions.UPDATE_PROPERTIES, StatusCode.STARTED, "UPDATE_PROPERTIES by user {} ", userId);
+        // get modifier id
+        User modifier = new User();
+        modifier.setUserId(userId);
+        log.debug("modifier id is {}", userId);
 //
-    try {
-      // convert json to PropertyDefinition
-
-      Either<Map<String, PropertyDefinition>, ActionStatus> propertiesListEither =
-          getPropertiesListForUpdate(data);
-      if (propertiesListEither.isRight()) {
-        ResponseFormat responseFormat =
-            getComponentsUtils().getResponseFormat(propertiesListEither.right().value());
-        return buildErrorResponse(responseFormat);
-      }
-      Map<String, PropertyDefinition> properties = propertiesListEither.left().value();
-      if (properties == null) {
-        log.info("Property content is invalid - {}", data);
-        ResponseFormat responseFormat =
-            getComponentsUtils().getResponseFormat(ActionStatus.INVALID_CONTENT);
-        return buildErrorResponse(responseFormat);
-      }
-
-               //Validate value and Constraint of property
-               Either<Boolean, ResponseFormat> constraintValidatorResponse =
-                               PropertyValueConstraintValidationUtil.getInstance().
-                                               validatePropertyConstraints(properties.values(), applicationDataTypeCache);
-               if (constraintValidatorResponse.isRight()) {
-                       log.error("Failed validation value and constraint of property: {}",
-                                       constraintValidatorResponse.right().value());
-                       return buildErrorResponse(constraintValidatorResponse.right().value());
-               }
-
-      // update property
-
-      for(PropertyDefinition propertyDefinition : properties.values()) {
-        Either<EntryData<String, PropertyDefinition>, ResponseFormat> status =
-            propertyBusinessLogic.updateComponentProperty(
-                componentId, propertyDefinition.getUniqueId(), propertyDefinition, userId);
-        if (status.isRight()) {
-          log.info("Failed to update Property. Reason - ", status.right().value());
-          return buildErrorResponse(status.right().value());
+        try {
+            // convert json to PropertyDefinition
+            Either<Map<String, PropertyDefinition>, ActionStatus> propertiesListEither = getPropertiesListForUpdate(data);
+            if (propertiesListEither.isRight()) {
+                ResponseFormat responseFormat = getComponentsUtils().getResponseFormat(propertiesListEither.right().value());
+                return buildErrorResponse(responseFormat);
+            }
+            Map<String, PropertyDefinition> properties = propertiesListEither.left().value();
+            if (properties == null) {
+                log.info("Property content is invalid - {}", data);
+                ResponseFormat responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.INVALID_CONTENT);
+                return buildErrorResponse(responseFormat);
+            }
+            //Validate value and Constraint of property
+            Either<Boolean, ResponseFormat> constraintValidatorResponse = PropertyValueConstraintValidationUtil.getInstance()
+                .validatePropertyConstraints(properties.values(), applicationDataTypeCache);
+            if (constraintValidatorResponse.isRight()) {
+                log.error("Failed validation value and constraint of property: {}", constraintValidatorResponse.right().value());
+                return buildErrorResponse(constraintValidatorResponse.right().value());
+            }
+            // update property
+            for (PropertyDefinition propertyDefinition : properties.values()) {
+                Either<EntryData<String, PropertyDefinition>, ResponseFormat> status = propertyBusinessLogic
+                    .updateComponentProperty(componentId, propertyDefinition.getUniqueId(), propertyDefinition, userId);
+                if (status.isRight()) {
+                    log.info("Failed to update Property. Reason - ", status.right().value());
+                    return buildErrorResponse(status.right().value());
+                }
+                EntryData<String, PropertyDefinition> property = status.left().value();
+                PropertyDefinition updatedPropertyDefinition = property.getValue();
+                log.debug("Property id {} updated successfully ", updatedPropertyDefinition.getUniqueId());
+            }
+            ResponseFormat responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.OK);
+            loggerSupportability.log(LoggerSupportabilityActions.UPDATE_PROPERTIES, StatusCode.COMPLETE, "UPDATE_PROPERTIES by user {} ", userId);
+            return buildOkResponse(responseFormat, properties);
+        } catch (Exception e) {
+            BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Update Property");
+            log.debug("update property failed with exception", e);
+            ResponseFormat responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR);
+            return buildErrorResponse(responseFormat);
         }
-        EntryData<String, PropertyDefinition> property = status.left().value();
-        PropertyDefinition updatedPropertyDefinition = property.getValue();
-
-        log.debug("Property id {} updated successfully ", updatedPropertyDefinition.getUniqueId());
-      }
-
-      ResponseFormat responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.OK);
-      loggerSupportability.log(LoggerSupportabilityActions.UPDATE_PROPERTIES, StatusCode.COMPLETE,"UPDATE_PROPERTIES by user {} ", userId);
-      return buildOkResponse(responseFormat, properties);
-
-    } catch (Exception e) {
-      BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Update Property");
-      log.debug("update property failed with exception", e);
-      ResponseFormat responseFormat =
-          getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR);
-      return buildErrorResponse(responseFormat);
-
     }
-  }
-
-  private Response getProperty(String componentId, String propertyId, HttpServletRequest request, String userId) {
-    String url = request.getMethod() + " " + request.getRequestURI();
-    log.debug(DEBUG_MESSAGE, url, userId);
 
-    try {
-      Either<Map.Entry<String, PropertyDefinition>, ResponseFormat> retrievedPropertyEither =
-              propertyBusinessLogic.getComponentProperty(componentId, propertyId, userId);
-
-      if(retrievedPropertyEither.isRight()) {
-        return buildErrorResponse(retrievedPropertyEither.right().value());
-      }
-
-      return buildOkResponse(retrievedPropertyEither.left().value());
-
-    } catch (Exception e) {
-      BeEcompErrorManager.getInstance().logBeRestApiGeneralError(CREATE_PROPERTY);
-      log.debug("get property failed with exception", e);
-      ResponseFormat responseFormat =
-              getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR);
-      return buildErrorResponse(responseFormat);
+    private Response getProperty(String componentId, String propertyId, HttpServletRequest request, String userId) {
+        String url = request.getMethod() + " " + request.getRequestURI();
+        log.debug(DEBUG_MESSAGE, url, userId);
+        try {
+            Either<Map.Entry<String, PropertyDefinition>, ResponseFormat> retrievedPropertyEither = propertyBusinessLogic
+                .getComponentProperty(componentId, propertyId, userId);
+            if (retrievedPropertyEither.isRight()) {
+                return buildErrorResponse(retrievedPropertyEither.right().value());
+            }
+            return buildOkResponse(retrievedPropertyEither.left().value());
+        } catch (Exception e) {
+            BeEcompErrorManager.getInstance().logBeRestApiGeneralError(CREATE_PROPERTY);
+            log.debug("get property failed with exception", e);
+            ResponseFormat responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR);
+            return buildErrorResponse(responseFormat);
+        }
     }
-  }
-  private Response getPropertyList(String componentId, HttpServletRequest request, String userId) {
-
-    String url = request.getMethod() + " " + request.getRequestURI();
-    log.debug(DEBUG_MESSAGE, url, userId);
 
-    try {
-      Either<List<PropertyDefinition>, ResponseFormat> propertiesListEither =
-              propertyBusinessLogic.getPropertiesList(componentId, userId);
-
-      if(propertiesListEither.isRight()) {
-        return buildErrorResponse(propertiesListEither.right().value());
-      }
-
-      return buildOkResponse(propertiesListEither.left().value());
-
-    } catch (Exception e) {
-      BeEcompErrorManager.getInstance().logBeRestApiGeneralError(CREATE_PROPERTY);
-      log.debug("get property failed with exception", e);
-      ResponseFormat responseFormat =
-              getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR);
-      return buildErrorResponse(responseFormat);
+    private Response getPropertyList(String componentId, HttpServletRequest request, String userId) {
+        String url = request.getMethod() + " " + request.getRequestURI();
+        log.debug(DEBUG_MESSAGE, url, userId);
+        try {
+            Either<List<PropertyDefinition>, ResponseFormat> propertiesListEither = propertyBusinessLogic.getPropertiesList(componentId, userId);
+            if (propertiesListEither.isRight()) {
+                return buildErrorResponse(propertiesListEither.right().value());
+            }
+            return buildOkResponse(propertiesListEither.left().value());
+        } catch (Exception e) {
+            BeEcompErrorManager.getInstance().logBeRestApiGeneralError(CREATE_PROPERTY);
+            log.debug("get property failed with exception", e);
+            ResponseFormat responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR);
+            return buildErrorResponse(responseFormat);
+        }
     }
-  }
-  private Response deleteProperty(String componentId, String propertyId, HttpServletRequest request, String userId) {
-    String url = request.getMethod() + " " + request.getRequestURI();
-    log.debug(DEBUG_MESSAGE, url, userId);
-
-    try {
-
-      // delete the property
-      Either<Map.Entry<String, PropertyDefinition>, ResponseFormat> status =
-              propertyBusinessLogic.deletePropertyFromComponent(componentId, propertyId, userId);
-      if (status.isRight()) {
-        log.debug("Failed to delete Property. Reason - ", status.right().value());
-        return buildErrorResponse(status.right().value());
-      }
-      Map.Entry<String, PropertyDefinition> property = status.left().value();
-      String name = property.getKey();
-      PropertyDefinition propertyDefinition = property.getValue();
-
-      log.debug("Property {} deleted successfully with id {}", name, propertyDefinition.getUniqueId());
-      ResponseFormat responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.NO_CONTENT);
-      return buildOkResponse(responseFormat, propertyToJson(property));
-
-    } catch (Exception e) {
-      BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Delete Property");
-      log.debug("delete property failed with exception", e);
-      ResponseFormat responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR);
-      return buildErrorResponse(responseFormat);
 
+    private Response deleteProperty(String componentId, String propertyId, HttpServletRequest request, String userId) {
+        String url = request.getMethod() + " " + request.getRequestURI();
+        log.debug(DEBUG_MESSAGE, url, userId);
+        try {
+            // delete the property
+            Either<Map.Entry<String, PropertyDefinition>, ResponseFormat> status = propertyBusinessLogic
+                .deletePropertyFromComponent(componentId, propertyId, userId);
+            if (status.isRight()) {
+                log.debug("Failed to delete Property. Reason - ", status.right().value());
+                return buildErrorResponse(status.right().value());
+            }
+            Map.Entry<String, PropertyDefinition> property = status.left().value();
+            String name = property.getKey();
+            PropertyDefinition propertyDefinition = property.getValue();
+            log.debug("Property {} deleted successfully with id {}", name, propertyDefinition.getUniqueId());
+            ResponseFormat responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.NO_CONTENT);
+            return buildOkResponse(responseFormat, propertyToJson(property));
+        } catch (Exception e) {
+            BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Delete Property");
+            log.debug("delete property failed with exception", e);
+            ResponseFormat responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR);
+            return buildErrorResponse(responseFormat);
+        }
     }
-  }
-
 }
index 6c5d603..28ebfd4 100644 (file)
@@ -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.
  * limitations under the License.
  * ============LICENSE_END=========================================================
  */
-
 package org.openecomp.sdc.be.servlets;
 
+import static org.openecomp.sdc.common.util.GeneralUtility.getCategorizedComponents;
+
 import com.jcabi.aspects.Loggable;
 import fj.data.Either;
 import io.swagger.v3.oas.annotations.Operation;
@@ -32,6 +33,24 @@ import io.swagger.v3.oas.annotations.servers.Server;
 import io.swagger.v3.oas.annotations.servers.Servers;
 import io.swagger.v3.oas.annotations.tags.Tag;
 import io.swagger.v3.oas.annotations.tags.Tags;
+import java.io.IOException;
+import java.util.ArrayList;
+import java.util.EnumMap;
+import java.util.List;
+import java.util.Map;
+import javax.inject.Inject;
+import javax.servlet.http.HttpServletRequest;
+import javax.ws.rs.Consumes;
+import javax.ws.rs.GET;
+import javax.ws.rs.HeaderParam;
+import javax.ws.rs.POST;
+import javax.ws.rs.Path;
+import javax.ws.rs.PathParam;
+import javax.ws.rs.Produces;
+import javax.ws.rs.QueryParam;
+import javax.ws.rs.core.Context;
+import javax.ws.rs.core.MediaType;
+import javax.ws.rs.core.Response;
 import org.apache.commons.collections.CollectionUtils;
 import org.openecomp.sdc.be.components.impl.ComponentBusinessLogic;
 import org.openecomp.sdc.be.components.impl.ComponentBusinessLogicProvider;
@@ -59,49 +78,23 @@ import org.openecomp.sdc.common.log.wrappers.Logger;
 import org.openecomp.sdc.exception.ResponseFormat;
 import org.springframework.stereotype.Controller;
 
-import javax.inject.Inject;
-import javax.servlet.http.HttpServletRequest;
-import javax.ws.rs.Consumes;
-import javax.ws.rs.GET;
-import javax.ws.rs.HeaderParam;
-import javax.ws.rs.POST;
-import javax.ws.rs.Path;
-import javax.ws.rs.PathParam;
-import javax.ws.rs.Produces;
-import javax.ws.rs.QueryParam;
-import javax.ws.rs.core.Context;
-import javax.ws.rs.core.MediaType;
-import javax.ws.rs.core.Response;
-import java.io.IOException;
-import java.util.ArrayList;
-import java.util.EnumMap;
-import java.util.List;
-import java.util.Map;
-
-import static org.openecomp.sdc.common.util.GeneralUtility.getCategorizedComponents;
-
 @Loggable(prepend = true, value = Loggable.DEBUG, trim = false)
 @Path("/v1/catalog")
 @Tags({@Tag(name = "SDC Internal APIs")})
 @Servers({@Server(url = "/sdc2/rest")})
 @Controller
 public class ComponentServlet extends BeGenericServlet {
-    private static final String GET_CERTIFIED_NOT_ABSTRACT_COMPONENTS_FAILED_WITH_EXCEPTION = "getCertifiedNotAbstractComponents failed with exception";
-
-       private static final String GET_CERTIFIED_NON_ABSTRACT = "Get Certified Non Abstract";
-
-       private static final String FAILED_TO_GET_ALL_NON_ABSTRACT = "failed to get all non abstract {}";
-
-       private static final String START_HANDLE_REQUEST_OF = "Start handle request of {}";
-
-       private static final Logger log = Logger.getLogger(ComponentServlet.class);
 
+    private static final String GET_CERTIFIED_NOT_ABSTRACT_COMPONENTS_FAILED_WITH_EXCEPTION = "getCertifiedNotAbstractComponents failed with exception";
+    private static final String GET_CERTIFIED_NON_ABSTRACT = "Get Certified Non Abstract";
+    private static final String FAILED_TO_GET_ALL_NON_ABSTRACT = "failed to get all non abstract {}";
+    private static final String START_HANDLE_REQUEST_OF = "Start handle request of {}";
+    private static final Logger log = Logger.getLogger(ComponentServlet.class);
     private final ComponentBusinessLogicProvider componentBusinessLogicProvider;
 
     @Inject
-    public ComponentServlet(UserBusinessLogic userBusinessLogic,
-        ComponentsUtils componentsUtils,
-        ComponentBusinessLogicProvider componentBusinessLogicProvider) {
+    public ComponentServlet(UserBusinessLogic userBusinessLogic, ComponentsUtils componentsUtils,
+                            ComponentBusinessLogicProvider componentBusinessLogicProvider) {
         super(userBusinessLogic, componentsUtils);
         this.componentBusinessLogicProvider = componentBusinessLogicProvider;
     }
@@ -110,21 +103,17 @@ public class ComponentServlet extends BeGenericServlet {
     @Path("/{componentType}/{componentUuid}/conformanceLevelValidation")
     @Consumes(MediaType.APPLICATION_JSON)
     @Produces(MediaType.APPLICATION_JSON)
-    @Operation(description = "Validate Component Conformance Level", method = "GET",
-            summary = "Returns the result according to conformance level in BE config", responses = {
-            @ApiResponse(content = @Content(array = @ArraySchema(schema = @Schema(implementation = Resource.class)))),
-            @ApiResponse(responseCode = "200", description = "Component found"),
-            @ApiResponse(responseCode = "403", description = "Restricted operation"),
-            @ApiResponse(responseCode = "404", description = "Component not found")})
+    @Operation(description = "Validate Component Conformance Level", method = "GET", summary = "Returns the result according to conformance level in BE config", responses = {
+        @ApiResponse(content = @Content(array = @ArraySchema(schema = @Schema(implementation = Resource.class)))),
+        @ApiResponse(responseCode = "200", description = "Component found"), @ApiResponse(responseCode = "403", description = "Restricted operation"),
+        @ApiResponse(responseCode = "404", description = "Component not found")})
     @PermissionAllowed(AafPermission.PermNames.INTERNAL_ALL_VALUE)
     public Response conformanceLevelValidation(@PathParam("componentType") final String componentType,
-            @PathParam("componentUuid") final String componentUuid, @Context final HttpServletRequest request,
-            @HeaderParam(value = Constants.USER_ID_HEADER) String userId) {
+                                               @PathParam("componentUuid") final String componentUuid, @Context final HttpServletRequest request,
+                                               @HeaderParam(value = Constants.USER_ID_HEADER) String userId) {
         Response response;
-
         String url = request.getMethod() + " " + request.getRequestURI();
         log.debug(START_HANDLE_REQUEST_OF, url);
-
         ComponentTypeEnum componentTypeEnum = ComponentTypeEnum.findByParamName(componentType);
         if (componentTypeEnum != null) {
             ComponentBusinessLogic compBL = componentBusinessLogicProvider.getInstance(componentTypeEnum);
@@ -132,12 +121,12 @@ public class ComponentServlet extends BeGenericServlet {
             if (eitherConformanceLevel.isRight()) {
                 response = buildErrorResponse(eitherConformanceLevel.right().value());
             } else {
-                response = buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), gson.toJson(eitherConformanceLevel.left().value()));
+                response = buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK),
+                    gson.toJson(eitherConformanceLevel.left().value()));
             }
         } else {
             response = buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.INVALID_CONTENT));
         }
-
         return response;
     }
 
@@ -145,27 +134,23 @@ public class ComponentServlet extends BeGenericServlet {
     @Path("/{componentType}/{componentId}/requirmentsCapabilities")
     @Consumes(MediaType.APPLICATION_JSON)
     @Produces(MediaType.APPLICATION_JSON)
-    @Operation(description = "Get Component Requirments And Capabilities", method = "GET",
-            summary = "Returns Requirements And Capabilities according to componentId", responses = {
-            @ApiResponse(content = @Content(array = @ArraySchema(schema = @Schema(implementation = Resource.class)))),
-            @ApiResponse(responseCode = "200", description = "Component found"),
-            @ApiResponse(responseCode = "403", description = "Restricted operation"),
-            @ApiResponse(responseCode = "404", description = "Component not found")})
+    @Operation(description = "Get Component Requirments And Capabilities", method = "GET", summary = "Returns Requirements And Capabilities according to componentId", responses = {
+        @ApiResponse(content = @Content(array = @ArraySchema(schema = @Schema(implementation = Resource.class)))),
+        @ApiResponse(responseCode = "200", description = "Component found"), @ApiResponse(responseCode = "403", description = "Restricted operation"),
+        @ApiResponse(responseCode = "404", description = "Component not found")})
     @PermissionAllowed(AafPermission.PermNames.INTERNAL_ALL_VALUE)
     public Response getRequirementAndCapabilities(@PathParam("componentType") final String componentType,
-            @PathParam("componentId") final String componentId, @Context final HttpServletRequest request,
-            @HeaderParam(value = Constants.USER_ID_HEADER) String userId) throws IOException {
+                                                  @PathParam("componentId") final String componentId, @Context final HttpServletRequest request,
+                                                  @HeaderParam(value = Constants.USER_ID_HEADER) String userId) throws IOException {
         Response response;
-
         String url = request.getMethod() + " " + request.getRequestURI();
         log.debug(START_HANDLE_REQUEST_OF, url);
-
         ComponentTypeEnum componentTypeEnum = ComponentTypeEnum.findByParamName(componentType);
         if (componentTypeEnum != null) {
             try {
                 ComponentBusinessLogic compBL = componentBusinessLogicProvider.getInstance(componentTypeEnum);
                 response = buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK),
-                        RepresentationUtils.toRepresentation(compBL.getRequirementsAndCapabilities(componentId, componentTypeEnum, userId)));
+                    RepresentationUtils.toRepresentation(compBL.getRequirementsAndCapabilities(componentId, componentTypeEnum, userId)));
             } catch (IOException e) {
                 BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Get Capabilities and requirements for " + componentId);
                 log.debug("getRequirementAndCapabilities failed with exception", e);
@@ -174,7 +159,6 @@ public class ComponentServlet extends BeGenericServlet {
         } else {
             response = buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.INVALID_CONTENT));
         }
-
         return response;
     }
 
@@ -182,43 +166,34 @@ public class ComponentServlet extends BeGenericServlet {
     @Path("/{componentType}/latestversion/notabstract")
     @Consumes(MediaType.APPLICATION_JSON)
     @Produces(MediaType.APPLICATION_JSON)
-    @Operation(description = "Get Component Requirments And Capabilities", method = "GET",
-            summary = "Returns Requirments And Capabilities according to componentId", responses = {
-            @ApiResponse(content = @Content(array = @ArraySchema(schema = @Schema(implementation = Resource.class)))),
-            @ApiResponse(responseCode = "200", description = "Component found"),
-            @ApiResponse(responseCode = "403", description = "Restricted operation"),
-            @ApiResponse(responseCode = "404", description = "Component not found")})
+    @Operation(description = "Get Component Requirments And Capabilities", method = "GET", summary = "Returns Requirments And Capabilities according to componentId", responses = {
+        @ApiResponse(content = @Content(array = @ArraySchema(schema = @Schema(implementation = Resource.class)))),
+        @ApiResponse(responseCode = "200", description = "Component found"), @ApiResponse(responseCode = "403", description = "Restricted operation"),
+        @ApiResponse(responseCode = "404", description = "Component not found")})
     @PermissionAllowed(AafPermission.PermNames.INTERNAL_ALL_VALUE)
-    public Response getLatestVersionNotAbstractCheckoutComponents(
-            @PathParam("componentType") final String componentType, @Context final HttpServletRequest request,
-            @QueryParam("internalComponentType") String internalComponentType,
-            @QueryParam("componentUids") List<String> componentUids,
-            @HeaderParam(value = Constants.USER_ID_HEADER) String userId) throws IOException {
-
+    public Response getLatestVersionNotAbstractCheckoutComponents(@PathParam("componentType") final String componentType,
+                                                                  @Context final HttpServletRequest request,
+                                                                  @QueryParam("internalComponentType") String internalComponentType,
+                                                                  @QueryParam("componentUids") List<String> componentUids,
+                                                                  @HeaderParam(value = Constants.USER_ID_HEADER) String userId) throws IOException {
         String url = request.getMethod() + " " + request.getRequestURI();
         log.debug("(get) Start handle request of {}", url);
-
         try {
-
             ComponentTypeEnum componentTypeEnum = ComponentTypeEnum.findByParamName(componentType);
             ComponentBusinessLogic businessLogic = componentBusinessLogicProvider.getInstance(componentTypeEnum);
-
             log.debug("Received componentUids size is {}", componentUids == null ? 0 : componentUids.size());
-
-            Either<List<Component>, ResponseFormat> actionResponse = businessLogic.getLatestVersionNotAbstractComponents(false, componentTypeEnum, internalComponentType, componentUids, userId);
-
+            Either<List<Component>, ResponseFormat> actionResponse = businessLogic
+                .getLatestVersionNotAbstractComponents(false, componentTypeEnum, internalComponentType, componentUids, userId);
             if (actionResponse.isRight()) {
                 log.debug(FAILED_TO_GET_ALL_NON_ABSTRACT, componentType);
                 return buildErrorResponse(actionResponse.right().value());
             }
             Object components = RepresentationUtils.toRepresentation(actionResponse.left().value());
             return buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), components);
-
         } catch (Exception e) {
             BeEcompErrorManager.getInstance().logBeRestApiGeneralError(GET_CERTIFIED_NON_ABSTRACT + componentType);
             log.debug(GET_CERTIFIED_NOT_ABSTRACT_COMPONENTS_FAILED_WITH_EXCEPTION, e);
             throw e;
-
         }
     }
 
@@ -226,49 +201,39 @@ public class ComponentServlet extends BeGenericServlet {
     @Path("/{componentType}/latestversion/notabstract")
     @Consumes(MediaType.APPLICATION_JSON)
     @Produces(MediaType.APPLICATION_JSON)
-    @Operation(description = "Get Component Requirments And Capabilities", method = "GET",
-            summary = "Returns Requirments And Capabilities according to componentId", responses = {
-            @ApiResponse(content = @Content(array = @ArraySchema(schema = @Schema(implementation = Resource.class)))),
-            @ApiResponse(responseCode = "200", description = "Component found"),
-            @ApiResponse(responseCode = "403", description = "Restricted operation"),
-            @ApiResponse(responseCode = "404", description = "Component not found")})
+    @Operation(description = "Get Component Requirments And Capabilities", method = "GET", summary = "Returns Requirments And Capabilities according to componentId", responses = {
+        @ApiResponse(content = @Content(array = @ArraySchema(schema = @Schema(implementation = Resource.class)))),
+        @ApiResponse(responseCode = "200", description = "Component found"), @ApiResponse(responseCode = "403", description = "Restricted operation"),
+        @ApiResponse(responseCode = "404", description = "Component not found")})
     @PermissionAllowed(AafPermission.PermNames.INTERNAL_ALL_VALUE)
-    public Response getLatestVersionNotAbstractCheckoutComponentsByBody(
-            @PathParam("componentType") final String componentType, @Context final HttpServletRequest request,
-            @QueryParam("internalComponentType") String internalComponentType,
-            @HeaderParam(value = Constants.USER_ID_HEADER) String userId,
-            @Parameter(description = "Consumer Object to be created", required = true) List<String> data) throws IOException {
-
+    public Response getLatestVersionNotAbstractCheckoutComponentsByBody(@PathParam("componentType") final String componentType,
+                                                                        @Context final HttpServletRequest request,
+                                                                        @QueryParam("internalComponentType") String internalComponentType,
+                                                                        @HeaderParam(value = Constants.USER_ID_HEADER) String userId,
+                                                                        @Parameter(description = "Consumer Object to be created", required = true) List<String> data)
+        throws IOException {
         String url = request.getMethod() + " " + request.getRequestURI();
         log.debug("(GET) Start handle request of {}", url);
         Response response;
-
         try {
-
             ComponentTypeEnum componentTypeEnum = ComponentTypeEnum.findByParamName(componentType);
             ComponentBusinessLogic businessLogic = componentBusinessLogicProvider.getInstance(componentTypeEnum);
             if (log.isDebugEnabled()) {
                 log.debug("Received componentUids size is {}", data == null ? 0 : data.size());
             }
-
-            Either<List<Component>, ResponseFormat> actionResponse = businessLogic.getLatestVersionNotAbstractComponents(false, componentTypeEnum, internalComponentType, data, userId);
-
+            Either<List<Component>, ResponseFormat> actionResponse = businessLogic
+                .getLatestVersionNotAbstractComponents(false, componentTypeEnum, internalComponentType, data, userId);
             if (actionResponse.isRight()) {
                 log.debug(FAILED_TO_GET_ALL_NON_ABSTRACT, componentType);
                 return buildErrorResponse(actionResponse.right().value());
-
             }
             Object components = RepresentationUtils.toRepresentation(actionResponse.left().value());
-            return  buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), components);
-
-
-
+            return buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), components);
         } catch (Exception e) {
             BeEcompErrorManager.getInstance().logBeRestApiGeneralError(GET_CERTIFIED_NON_ABSTRACT + componentType);
             log.debug(GET_CERTIFIED_NOT_ABSTRACT_COMPONENTS_FAILED_WITH_EXCEPTION, e);
             throw e;
         }
-
     }
 
     @GET
@@ -276,72 +241,69 @@ public class ComponentServlet extends BeGenericServlet {
     @Consumes(MediaType.APPLICATION_JSON)
     @Produces(MediaType.APPLICATION_JSON)
     @Operation(description = "Get Component uid only", method = "GET", summary = "Returns componentId", responses = {
-            @ApiResponse(content = @Content(array = @ArraySchema(schema = @Schema(implementation = Resource.class)))),
-            @ApiResponse(responseCode = "200", description = "Component found"),
-            @ApiResponse(responseCode = "403", description = "Restricted operation"),
-            @ApiResponse(responseCode = "404", description = "Component not found")})
+        @ApiResponse(content = @Content(array = @ArraySchema(schema = @Schema(implementation = Resource.class)))),
+        @ApiResponse(responseCode = "200", description = "Component found"), @ApiResponse(responseCode = "403", description = "Restricted operation"),
+        @ApiResponse(responseCode = "404", description = "Component not found")})
     @PermissionAllowed(AafPermission.PermNames.INTERNAL_ALL_VALUE)
-    public Response getLatestVersionNotAbstractCheckoutComponentsIdesOnly(
-            @PathParam("componentType") final String componentType, @Context final HttpServletRequest request,
-            @QueryParam("internalComponentType") String internalComponentType,
-            @HeaderParam(value = Constants.USER_ID_HEADER) String userId,
-            @Parameter(description = "uid list", required = true) String data) throws IOException {
-
+    public Response getLatestVersionNotAbstractCheckoutComponentsIdesOnly(@PathParam("componentType") final String componentType,
+                                                                          @Context final HttpServletRequest request,
+                                                                          @QueryParam("internalComponentType") String internalComponentType,
+                                                                          @HeaderParam(value = Constants.USER_ID_HEADER) String userId,
+                                                                          @Parameter(description = "uid list", required = true) String data)
+        throws IOException {
         String url = request.getMethod() + " " + request.getRequestURI();
         log.debug("(get) Start handle request of {}", url);
         try {
             ComponentTypeEnum componentTypeEnum = ComponentTypeEnum.findByParamName(componentType);
             ComponentBusinessLogic businessLogic = componentBusinessLogicProvider.getInstance(componentTypeEnum);
-
-            Either<List<Component>, ResponseFormat> actionResponse = businessLogic.getLatestVersionNotAbstractComponentsMetadata(false, HighestFilterEnum.HIGHEST_ONLY, componentTypeEnum, internalComponentType, userId);
+            Either<List<Component>, ResponseFormat> actionResponse = businessLogic
+                .getLatestVersionNotAbstractComponentsMetadata(false, HighestFilterEnum.HIGHEST_ONLY, componentTypeEnum, internalComponentType,
+                    userId);
             if (actionResponse.isRight()) {
                 log.debug(FAILED_TO_GET_ALL_NON_ABSTRACT, componentType);
                 return buildErrorResponse(actionResponse.right().value());
             }
-            List<UiLeftPaletteComponent> uiLeftPaletteComponents = getComponentsUtils().convertComponentToUiLeftPaletteComponentObject(actionResponse.left().value());
+            List<UiLeftPaletteComponent> uiLeftPaletteComponents = getComponentsUtils()
+                .convertComponentToUiLeftPaletteComponentObject(actionResponse.left().value());
             Map<String, Map<String, List<UiLeftPaletteComponent>>> categorizedComponents = getCategorizedComponents(uiLeftPaletteComponents);
             Object components = RepresentationUtils.toRepresentation(categorizedComponents);
             return buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), components);
-
         } catch (Exception e) {
             BeEcompErrorManager.getInstance().logBeRestApiGeneralError(GET_CERTIFIED_NON_ABSTRACT + componentType);
             log.debug(GET_CERTIFIED_NOT_ABSTRACT_COMPONENTS_FAILED_WITH_EXCEPTION, e);
             throw e;
         }
-
     }
 
     @GET
     @Path("/{componentType}/{componentId}/componentInstances")
     @Consumes(MediaType.APPLICATION_JSON)
     @Produces(MediaType.APPLICATION_JSON)
-    @Operation(description = "Get Component instances", method = "GET", summary = "Returns component instances",
-            responses = {@ApiResponse(
-                    content = @Content(array = @ArraySchema(schema = @Schema(implementation = Resource.class)))),
-                    @ApiResponse(responseCode = "200", description = "Component found"),
-                    @ApiResponse(responseCode = "403", description = "Restricted operation"),
-                    @ApiResponse(responseCode = "404", description = "Component not found")})
+    @Operation(description = "Get Component instances", method = "GET", summary = "Returns component instances", responses = {
+        @ApiResponse(content = @Content(array = @ArraySchema(schema = @Schema(implementation = Resource.class)))),
+        @ApiResponse(responseCode = "200", description = "Component found"), @ApiResponse(responseCode = "403", description = "Restricted operation"),
+        @ApiResponse(responseCode = "404", description = "Component not found")})
     @PermissionAllowed(AafPermission.PermNames.INTERNAL_ALL_VALUE)
-    public Response getComponentInstancesFilteredByPropertiesAndInputs(
-            @PathParam("componentType") final String componentType, @PathParam("componentId") final String componentId,
-            @Context final HttpServletRequest request, @QueryParam("searchText") String searchText,
-            @HeaderParam(value = Constants.USER_ID_HEADER) String userId,
-            @Parameter(description = "uid" + " " + "list", required = true) String data) throws IOException {
-
+    public Response getComponentInstancesFilteredByPropertiesAndInputs(@PathParam("componentType") final String componentType,
+                                                                       @PathParam("componentId") final String componentId,
+                                                                       @Context final HttpServletRequest request,
+                                                                       @QueryParam("searchText") String searchText,
+                                                                       @HeaderParam(value = Constants.USER_ID_HEADER) String userId,
+                                                                       @Parameter(description = "uid" + " " + "list", required = true) String data)
+        throws IOException {
         String url = request.getMethod() + " " + request.getRequestURI();
         log.debug("(GET) Start handle request of {}", url);
         try {
             ComponentTypeEnum componentTypeEnum = ComponentTypeEnum.findByParamName(componentType);
             ComponentBusinessLogic businessLogic = componentBusinessLogicProvider.getInstance(componentTypeEnum);
-
-            Either<List<ComponentInstance>, ResponseFormat> actionResponse = businessLogic.getComponentInstancesFilteredByPropertiesAndInputs(componentId, userId);
+            Either<List<ComponentInstance>, ResponseFormat> actionResponse = businessLogic
+                .getComponentInstancesFilteredByPropertiesAndInputs(componentId, userId);
             if (actionResponse.isRight()) {
                 log.debug("failed to get all component instances filtered by properties and inputs", componentType);
                 return buildErrorResponse(actionResponse.right().value());
             }
             Object components = RepresentationUtils.toRepresentation(actionResponse.left().value());
             return buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), components);
-
         } catch (Exception e) {
             BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Get Component Instances filtered by properties & inputs" + componentType);
             log.debug("getComponentInstancesFilteredByPropertiesAndInputs failed with exception", e);
@@ -349,11 +311,9 @@ public class ComponentServlet extends BeGenericServlet {
         }
     }
 
-
-
     /**
-     * This API is a generic api for ui - the api get a list of strings and return the data on the component according to to list.
-     * for example: list of the string "properties, inputs" will return component with the list of properties and inputs.
+     * This API is a generic api for ui - the api get a list of strings and return the data on the component according to to list. for example: list
+     * of the string "properties, inputs" will return component with the list of properties and inputs.
      *
      * @param componentType
      * @param componentId
@@ -362,48 +322,40 @@ public class ComponentServlet extends BeGenericServlet {
      * @param userId
      * @return
      */
-
-
     @GET
     @Path("/{componentType}/{componentId}/filteredDataByParams")
     @Consumes(MediaType.APPLICATION_JSON)
     @Produces(MediaType.APPLICATION_JSON)
-    @Operation(description = "Retrieve Resource", method = "GET", summary = "Returns resource according to resourceId",
-            responses = {@ApiResponse(
-                    content = @Content(array = @ArraySchema(schema = @Schema(implementation = Resource.class)))),
-                    @ApiResponse(responseCode = "200", description = "Resource found"),
-                    @ApiResponse(responseCode = "403", description = "Restricted operation"),
-                    @ApiResponse(responseCode = "404", description = "Resource not found")})
+    @Operation(description = "Retrieve Resource", method = "GET", summary = "Returns resource according to resourceId", responses = {
+        @ApiResponse(content = @Content(array = @ArraySchema(schema = @Schema(implementation = Resource.class)))),
+        @ApiResponse(responseCode = "200", description = "Resource found"), @ApiResponse(responseCode = "403", description = "Restricted operation"),
+        @ApiResponse(responseCode = "404", description = "Resource not found")})
     @ResponseView(mixin = {GroupCompositionMixin.class, PolicyCompositionMixin.class})
     @PermissionAllowed(AafPermission.PermNames.INTERNAL_ALL_VALUE)
     public Response getComponentDataFilteredByParams(@PathParam("componentType") final String componentType,
-            @PathParam("componentId") final String componentId,
-            @QueryParam("include") final List<String> dataParamsToReturn, @Context final HttpServletRequest request,
-            @HeaderParam(value = Constants.USER_ID_HEADER) String userId) throws IOException {
-
+                                                     @PathParam("componentId") final String componentId,
+                                                     @QueryParam("include") final List<String> dataParamsToReturn,
+                                                     @Context final HttpServletRequest request,
+                                                     @HeaderParam(value = Constants.USER_ID_HEADER) String userId) throws IOException {
         String url = request.getMethod() + " " + request.getRequestURI();
-        log.debug(START_HANDLE_REQUEST_OF , url);
-
+        log.debug(START_HANDLE_REQUEST_OF, url);
         // get modifier id
         User modifier = new User();
         modifier.setUserId(userId);
-        log.debug("modifier id is {}" , userId);
-
+        log.debug("modifier id is {}", userId);
         try {
             String resourceIdLower = componentId.toLowerCase();
             ComponentTypeEnum componentTypeEnum = ComponentTypeEnum.findByParamName(componentType);
             ComponentBusinessLogic businessLogic = componentBusinessLogicProvider.getInstance(componentTypeEnum);
-
             log.trace("get component with id {} filtered by ui params", componentId);
-            Either<UiComponentDataTransfer, ResponseFormat> actionResponse = businessLogic.getComponentDataFilteredByParams(resourceIdLower, modifier, dataParamsToReturn);
-
+            Either<UiComponentDataTransfer, ResponseFormat> actionResponse = businessLogic
+                .getComponentDataFilteredByParams(resourceIdLower, modifier, dataParamsToReturn);
             if (actionResponse.isRight()) {
                 log.debug("failed to get component data filtered by ui params");
                 return buildErrorResponse(actionResponse.right().value());
             }
             RepresentationUtils.toRepresentation(actionResponse.left().value());
             return buildOkResponse(actionResponse.left().value());
-
         } catch (Exception e) {
             BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Get component filtered by ui params");
             log.debug("get resource failed with exception", e);
@@ -411,32 +363,24 @@ public class ComponentServlet extends BeGenericServlet {
         }
     }
 
-
     @GET
     @Path("/{componentType}/{componentId}/filteredproperties/{propertyNameFragment}")
     @Consumes(MediaType.APPLICATION_JSON)
     @Produces(MediaType.APPLICATION_JSON)
-    @Operation(
-            description = "Retrieve properties belonging to component instances of specific component by name and optionally resource type",
-            method = "GET",
-            summary = "Returns properties belonging to component instances of specific component by name and optionally resource type",
-            responses = {@ApiResponse(
-                    content = @Content(array = @ArraySchema(schema = @Schema(implementation = Map.class)))),
-                    @ApiResponse(responseCode = "200", description = "Component found"),
-                    @ApiResponse(responseCode = "403", description = "Restricted operation"),
-                    @ApiResponse(responseCode = "404", description = "Component not found")})
+    @Operation(description = "Retrieve properties belonging to component instances of specific component by name and optionally resource type", method = "GET", summary = "Returns properties belonging to component instances of specific component by name and optionally resource type", responses = {
+        @ApiResponse(content = @Content(array = @ArraySchema(schema = @Schema(implementation = Map.class)))),
+        @ApiResponse(responseCode = "200", description = "Component found"), @ApiResponse(responseCode = "403", description = "Restricted operation"),
+        @ApiResponse(responseCode = "404", description = "Component not found")})
     @PermissionAllowed(AafPermission.PermNames.INTERNAL_ALL_VALUE)
-    public Response getFilteredComponentInstanceProperties(
-            @PathParam("componentType") final String componentType,
-            @PathParam("componentId") final String componentId,
-            @PathParam("propertyNameFragment") final String propertyNameFragment,
-            @QueryParam("resourceType") List<String> resourceTypes,
-            @Context final HttpServletRequest request,
-            @HeaderParam(value = Constants.USER_ID_HEADER) String userId) throws IOException {
-
+    public Response getFilteredComponentInstanceProperties(@PathParam("componentType") final String componentType,
+                                                           @PathParam("componentId") final String componentId,
+                                                           @PathParam("propertyNameFragment") final String propertyNameFragment,
+                                                           @QueryParam("resourceType") List<String> resourceTypes,
+                                                           @Context final HttpServletRequest request,
+                                                           @HeaderParam(value = Constants.USER_ID_HEADER) String userId) throws IOException {
         User user = new User();
         user.setUserId(userId);
-        log.debug("User Id is {}" , userId);
+        log.debug("User Id is {}", userId);
         Response response;
         try {
             ComponentTypeEnum componentTypeEnum = ComponentTypeEnum.findByParamName(componentType);
@@ -445,17 +389,17 @@ public class ComponentServlet extends BeGenericServlet {
             List<String> propertyNameFragments = new ArrayList<>();
             propertyNameFragments.add(propertyNameFragment);
             filters.put(FilterKeyEnum.NAME_FRAGMENT, propertyNameFragments);
-            if(CollectionUtils.isNotEmpty(resourceTypes)){
+            if (CollectionUtils.isNotEmpty(resourceTypes)) {
                 filters.put(FilterKeyEnum.RESOURCE_TYPE, resourceTypes);
             }
-            Either<Map<String, List<IComponentInstanceConnectedElement>>, ResponseFormat> actionResponse = businessLogic.getFilteredComponentInstanceProperties(componentId, filters, userId);
+            Either<Map<String, List<IComponentInstanceConnectedElement>>, ResponseFormat> actionResponse = businessLogic
+                .getFilteredComponentInstanceProperties(componentId, filters, userId);
             if (actionResponse.isRight()) {
                 response = buildErrorResponse(actionResponse.right().value());
                 return response;
             }
             Object resource = RepresentationUtils.toRepresentation(actionResponse.left().value());
             return buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), resource);
-
         } catch (Exception e) {
             BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Get Filtered Component Instance Properties");
             log.debug("Getting of filtered component instance properties failed with exception", e);
index 4a44c20..f12fbd7 100644 (file)
@@ -16,7 +16,6 @@
  *  SPDX-License-Identifier: Apache-2.0
  *  ============LICENSE_END=========================================================
  */
-
 package org.openecomp.sdc.be.servlets;
 
 import io.swagger.v3.oas.annotations.Operation;
@@ -75,26 +74,20 @@ public class ComponentSubstitutionFilterServlet extends AbstractValidationsServl
     private static final String MODIFIER_ID_IS = "Modifier id is {}";
     private static final String FAILED_TO_PARSE_COMPONENT = "Failed to parse component";
     private static final String INVALID_CONSTRAINTYPE_ENUM = "Invalid value for NodeFilterConstraintType enum %s";
-
     private static final String FAILED_TO_ADD_SUBSTITUTION_FILTER = "Failed to add substitution filter";
     private static final String ADD_SUBSTITUTION_FILTER = "Add Substitution Filter";
     private static final String ADD_SUBSTITUTION_FILTER_WITH_AN_ERROR = "Add substitution filter with an error";
-
     private static final String FAILED_TO_UPDATE_SUBSTITUTION_FILTER = "Failed to update substitution filter";
     private static final String SUBSTITUTION_FILTER_UPDATE = "Substitution Filter Update";
     private static final String UPDATE_SUBSTITUTION_FILTER_WITH_AN_ERROR = "Update substitution filter with an error {}";
-
     private static final String FAILED_TO_DELETE_SUBSTITUTION_FILTER = "Failed to delete substitution filter";
     private static final String SUBSTITUTION_FILTER_DELETE = "Substitution Filter Delete";
     private static final String DELETE_SUBSTITUTION_FILTER_WITH_AN_ERROR = "Delete substitution filter with an error";
-
     private final ComponentSubstitutionFilterBusinessLogic componentSubstitutionFilterBusinessLogic;
 
     @Inject
-    public ComponentSubstitutionFilterServlet(final UserBusinessLogic userBusinessLogic,
-                                              final ComponentInstanceBusinessLogic componentInstanceBL,
-                                              final ComponentsUtils componentsUtils,
-                                              final ServletUtils servletUtils,
+    public ComponentSubstitutionFilterServlet(final UserBusinessLogic userBusinessLogic, final ComponentInstanceBusinessLogic componentInstanceBL,
+                                              final ComponentsUtils componentsUtils, final ServletUtils servletUtils,
                                               final ResourceImportManager resourceImportManager,
                                               final ComponentSubstitutionFilterBusinessLogic componentSubstitutionFilterBusinessLogic) {
         super(userBusinessLogic, componentInstanceBL, componentsUtils, servletUtils, resourceImportManager);
@@ -104,62 +97,46 @@ public class ComponentSubstitutionFilterServlet extends AbstractValidationsServl
     @POST
     @Consumes(MediaType.APPLICATION_JSON)
     @Produces(MediaType.APPLICATION_JSON)
-    @Operation(description = "Add Component Substitution Filter Constraint", method = "POST",
-        summary = "Add Component Substitution Filter Constraint", responses = {
+    @Operation(description = "Add Component Substitution Filter Constraint", method = "POST", summary = "Add Component Substitution Filter Constraint", responses = {
         @ApiResponse(content = @Content(array = @ArraySchema(schema = @Schema(implementation = Response.class)))),
         @ApiResponse(responseCode = "201", description = "Add Substitution Filter Constraint"),
         @ApiResponse(responseCode = "403", description = "Restricted operation"),
         @ApiResponse(responseCode = "400", description = "Invalid content / Missing content")})
     @PermissionAllowed(AafPermission.PermNames.INTERNAL_ALL_VALUE)
-    public Response addSubstitutionFilter(
-        @Parameter(description = "UIConstraint data", required = true) String constraintData,
-        @Parameter(description = "Component Id") @PathParam("componentId") String componentId,
-        @Parameter(description = "valid value: resources / services",
-            schema = @Schema(allowableValues = {
-                ComponentTypeEnum.SERVICE_PARAM_NAME,
-                ComponentTypeEnum.SERVICE_PARAM_NAME})) @PathParam("componentType") final String componentType,
-        @Parameter(description = "Constraint type. Valid values: properties / capabilities",
-            schema = @Schema(allowableValues = {NodeFilterConstraintType.PROPERTIES_PARAM_NAME,
-                NodeFilterConstraintType.CAPABILITIES_PARAM_NAME}))
-        @PathParam("constraintType") final String constraintType,
-        @Context final HttpServletRequest request,
-        @HeaderParam(value = Constants.USER_ID_HEADER) String userId) {
-
+    public Response addSubstitutionFilter(@Parameter(description = "UIConstraint data", required = true) String constraintData,
+                                          @Parameter(description = "Component Id") @PathParam("componentId") String componentId,
+                                          @Parameter(description = "valid value: resources / services", schema = @Schema(allowableValues = {
+                                              ComponentTypeEnum.SERVICE_PARAM_NAME,
+                                              ComponentTypeEnum.SERVICE_PARAM_NAME})) @PathParam("componentType") final String componentType,
+                                          @Parameter(description = "Constraint type. Valid values: properties / capabilities", schema = @Schema(allowableValues = {
+                                              NodeFilterConstraintType.PROPERTIES_PARAM_NAME,
+                                              NodeFilterConstraintType.CAPABILITIES_PARAM_NAME})) @PathParam("constraintType") final String constraintType,
+                                          @Context final HttpServletRequest request, @HeaderParam(value = Constants.USER_ID_HEADER) String userId) {
         LOGGER.debug(START_HANDLE_REQUEST_OF, request.getMethod(), request.getRequestURI());
         LOGGER.debug(MODIFIER_ID_IS, userId);
         final User userModifier = componentSubstitutionFilterBusinessLogic.validateUser(userId);
-
         final ComponentTypeEnum componentTypeEnum = ComponentTypeEnum.findByParamName(componentType);
         try {
-            final Optional<UIConstraint> convertResponse = componentsUtils
-                .parseToConstraint(constraintData, userModifier, componentTypeEnum);
+            final Optional<UIConstraint> convertResponse = componentsUtils.parseToConstraint(constraintData, userModifier, componentTypeEnum);
             if (convertResponse.isEmpty()) {
                 LOGGER.error(FAILED_TO_PARSE_COMPONENT);
                 return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR));
             }
-
             final UIConstraint uiConstraint = convertResponse.get();
             final String constraint = new ConstraintConvertor().convert(uiConstraint);
-
-            final Optional<NodeFilterConstraintType> nodeFilterConstraintType =
-                NodeFilterConstraintType.parse(constraintType);
+            final Optional<NodeFilterConstraintType> nodeFilterConstraintType = NodeFilterConstraintType.parse(constraintType);
             if (nodeFilterConstraintType.isEmpty()) {
-                return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.INVALID_CONTENT_PARAM,
-                        INVALID_CONSTRAINTYPE_ENUM, constraintType));
+                return buildErrorResponse(
+                    getComponentsUtils().getResponseFormat(ActionStatus.INVALID_CONTENT_PARAM, INVALID_CONSTRAINTYPE_ENUM, constraintType));
             }
-
             final Optional<SubstitutionFilterDataDefinition> actionResponse = componentSubstitutionFilterBusinessLogic
-                .addSubstitutionFilter(componentId.toLowerCase(),
-                    uiConstraint.getServicePropertyName(), constraint, true, componentTypeEnum);
-
+                .addSubstitutionFilter(componentId.toLowerCase(), uiConstraint.getServicePropertyName(), constraint, true, componentTypeEnum);
             if (actionResponse.isEmpty()) {
                 LOGGER.error(FAILED_TO_ADD_SUBSTITUTION_FILTER);
                 return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR));
             }
             final UINodeFilter uiFilter = new SubstitutionFilterConverter().convertToUi(actionResponse.get());
-
             return buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), uiFilter);
-
         } catch (final Exception e) {
             BeEcompErrorManager.getInstance().logBeRestApiGeneralError(ADD_SUBSTITUTION_FILTER);
             LOGGER.error(ADD_SUBSTITUTION_FILTER_WITH_AN_ERROR, e);
@@ -170,60 +147,46 @@ public class ComponentSubstitutionFilterServlet extends AbstractValidationsServl
     @PUT
     @Consumes(MediaType.APPLICATION_JSON)
     @Produces(MediaType.APPLICATION_JSON)
-    @Operation(description = "Update Component Substitution Filter Constraint", method = "PUT",
-        summary = "Update Component Substitution Filter Constraint", responses = {
+    @Operation(description = "Update Component Substitution Filter Constraint", method = "PUT", summary = "Update Component Substitution Filter Constraint", responses = {
         @ApiResponse(content = @Content(array = @ArraySchema(schema = @Schema(implementation = Response.class)))),
         @ApiResponse(responseCode = "201", description = "Update Substitution Filter Constraint"),
         @ApiResponse(responseCode = "403", description = "Restricted operation"),
         @ApiResponse(responseCode = "400", description = "Invalid content / Missing content")})
     @PermissionAllowed(AafPermission.PermNames.INTERNAL_ALL_VALUE)
-    public Response updateSubstitutionFilter(
-        @Parameter(description = "UIConstraint data", required = true) String constraintData,
-        @Parameter(description = "Component Id") @PathParam("componentId") String componentId,
-        @Parameter(description = "valid value: resources / services",
-            schema = @Schema(allowableValues = {
-                ComponentTypeEnum.SERVICE_PARAM_NAME,
-                ComponentTypeEnum.SERVICE_PARAM_NAME})) @PathParam("componentType") final String componentType,
-        @Parameter(description = "Constraint type. Valid values: properties / capabilities",
-            schema = @Schema(allowableValues = {NodeFilterConstraintType.PROPERTIES_PARAM_NAME,
-                NodeFilterConstraintType.CAPABILITIES_PARAM_NAME}))
-        @PathParam("constraintType") final String constraintType,
-        @Context final HttpServletRequest request, @HeaderParam(value = Constants.USER_ID_HEADER) String userId) {
-
+    public Response updateSubstitutionFilter(@Parameter(description = "UIConstraint data", required = true) String constraintData,
+                                             @Parameter(description = "Component Id") @PathParam("componentId") String componentId,
+                                             @Parameter(description = "valid value: resources / services", schema = @Schema(allowableValues = {
+                                                 ComponentTypeEnum.SERVICE_PARAM_NAME,
+                                                 ComponentTypeEnum.SERVICE_PARAM_NAME})) @PathParam("componentType") final String componentType,
+                                             @Parameter(description = "Constraint type. Valid values: properties / capabilities", schema = @Schema(allowableValues = {
+                                                 NodeFilterConstraintType.PROPERTIES_PARAM_NAME,
+                                                 NodeFilterConstraintType.CAPABILITIES_PARAM_NAME})) @PathParam("constraintType") final String constraintType,
+                                             @Context final HttpServletRequest request,
+                                             @HeaderParam(value = Constants.USER_ID_HEADER) String userId) {
         LOGGER.debug(START_HANDLE_REQUEST_OF, request.getMethod(), request.getRequestURI());
         LOGGER.debug(MODIFIER_ID_IS, userId);
         final User userModifier = componentSubstitutionFilterBusinessLogic.validateUser(userId);
-
         try {
             final ComponentTypeEnum componentTypeEnum = ComponentTypeEnum.findByParamName(componentType);
-            final List<UIConstraint>  uiConstraints = componentsUtils
-                .validateAndParseConstraint(componentTypeEnum, constraintData, userModifier);
+            final List<UIConstraint> uiConstraints = componentsUtils.validateAndParseConstraint(componentTypeEnum, constraintData, userModifier);
             if (CollectionUtils.isEmpty(uiConstraints)) {
-                LOGGER.error("Failed to Parse Constraint data {} when executing {} ",
-                    constraintData, SUBSTITUTION_FILTER_UPDATE);
-                return buildErrorResponse(componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR,
-                    "Failed to parse constraint data"));
+                LOGGER.error("Failed to Parse Constraint data {} when executing {} ", constraintData, SUBSTITUTION_FILTER_UPDATE);
+                return buildErrorResponse(componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR, "Failed to parse constraint data"));
             }
-
             final List<String> constraints = new ConstraintConvertor().convertToList(uiConstraints);
-            final Optional<NodeFilterConstraintType> nodeFilterConstraintType =
-                NodeFilterConstraintType.parse(constraintType);
+            final Optional<NodeFilterConstraintType> nodeFilterConstraintType = NodeFilterConstraintType.parse(constraintType);
             if (!nodeFilterConstraintType.isPresent()) {
-                return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.INVALID_CONTENT_PARAM,
-                        INVALID_CONSTRAINTYPE_ENUM, constraintType));
+                return buildErrorResponse(
+                    getComponentsUtils().getResponseFormat(ActionStatus.INVALID_CONTENT_PARAM, INVALID_CONSTRAINTYPE_ENUM, constraintType));
             }
             final Optional<SubstitutionFilterDataDefinition> actionResponse = componentSubstitutionFilterBusinessLogic
-                .updateSubstitutionFilter(componentId.toLowerCase(), constraints,
-                    true, componentTypeEnum);
-
+                .updateSubstitutionFilter(componentId.toLowerCase(), constraints, true, componentTypeEnum);
             if (!actionResponse.isPresent()) {
                 LOGGER.error(FAILED_TO_UPDATE_SUBSTITUTION_FILTER);
                 return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR));
             }
-
             return buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK),
                 new SubstitutionFilterConverter().convertToUi(actionResponse.get()));
-
         } catch (final Exception e) {
             BeEcompErrorManager.getInstance().logBeRestApiGeneralError(SUBSTITUTION_FILTER_UPDATE);
             LOGGER.error(UPDATE_SUBSTITUTION_FILTER_WITH_AN_ERROR, e.getMessage(), e);
@@ -235,55 +198,43 @@ public class ComponentSubstitutionFilterServlet extends AbstractValidationsServl
     @Consumes(MediaType.APPLICATION_JSON)
     @Produces(MediaType.APPLICATION_JSON)
     @Path("/{constraintIndex}")
-    @Operation(description = "Delete Component Substitution Filter Constraint", method = "Delete",
-        summary = "Delete Component Substitution Filter Constraint", responses = {
+    @Operation(description = "Delete Component Substitution Filter Constraint", method = "Delete", summary = "Delete Component Substitution Filter Constraint", responses = {
         @ApiResponse(content = @Content(array = @ArraySchema(schema = @Schema(implementation = Response.class)))),
         @ApiResponse(responseCode = "201", description = "Delete Substitution Filter Constraint"),
         @ApiResponse(responseCode = "403", description = "Restricted operation"),
         @ApiResponse(responseCode = "400", description = "Invalid content / Missing content")})
     @PermissionAllowed(AafPermission.PermNames.INTERNAL_ALL_VALUE)
-    public Response deleteSubstitutionFilterConstraint(
-        @Parameter(description = "Component Id") @PathParam("componentId") String componentId,
-        @Parameter(description = "Constraint Index") @PathParam("constraintIndex") int index,
-        @Parameter(description = "valid value: resources / services",
-            schema = @Schema(allowableValues = {
-                ComponentTypeEnum.SERVICE_PARAM_NAME,
-                ComponentTypeEnum.SERVICE_PARAM_NAME})) @PathParam("componentType") final String componentType,
-        @Parameter(description = "Constraint type. Valid values: properties / capabilities",
-            schema = @Schema(allowableValues = {NodeFilterConstraintType.PROPERTIES_PARAM_NAME,
-                NodeFilterConstraintType.CAPABILITIES_PARAM_NAME}))
-        @PathParam("constraintType") final String constraintType,
-        @Context final HttpServletRequest request, @HeaderParam(value = Constants.USER_ID_HEADER) String userId) {
-
+    public Response deleteSubstitutionFilterConstraint(@Parameter(description = "Component Id") @PathParam("componentId") String componentId,
+                                                       @Parameter(description = "Constraint Index") @PathParam("constraintIndex") int index,
+                                                       @Parameter(description = "valid value: resources / services", schema = @Schema(allowableValues = {
+                                                           ComponentTypeEnum.SERVICE_PARAM_NAME,
+                                                           ComponentTypeEnum.SERVICE_PARAM_NAME})) @PathParam("componentType") final String componentType,
+                                                       @Parameter(description = "Constraint type. Valid values: properties / capabilities", schema = @Schema(allowableValues = {
+                                                           NodeFilterConstraintType.PROPERTIES_PARAM_NAME,
+                                                           NodeFilterConstraintType.CAPABILITIES_PARAM_NAME})) @PathParam("constraintType") final String constraintType,
+                                                       @Context final HttpServletRequest request,
+                                                       @HeaderParam(value = Constants.USER_ID_HEADER) String userId) {
         LOGGER.debug(START_HANDLE_REQUEST_OF, request.getMethod(), request.getRequestURI());
         LOGGER.debug(MODIFIER_ID_IS, userId);
         componentSubstitutionFilterBusinessLogic.validateUser(userId);
-
-            final Optional<NodeFilterConstraintType> nodeFilterConstraintType =
-                NodeFilterConstraintType.parse(constraintType);
-            if (!nodeFilterConstraintType.isPresent()) {
-                return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.INVALID_CONTENT_PARAM,
-                        INVALID_CONSTRAINTYPE_ENUM, constraintType));
-            }
-
+        final Optional<NodeFilterConstraintType> nodeFilterConstraintType = NodeFilterConstraintType.parse(constraintType);
+        if (!nodeFilterConstraintType.isPresent()) {
+            return buildErrorResponse(
+                getComponentsUtils().getResponseFormat(ActionStatus.INVALID_CONTENT_PARAM, INVALID_CONSTRAINTYPE_ENUM, constraintType));
+        }
         try {
             final Optional<SubstitutionFilterDataDefinition> actionResponse = componentSubstitutionFilterBusinessLogic
                 .deleteSubstitutionFilter(componentId.toLowerCase(), index, true, ComponentTypeEnum.findByParamName(componentType));
-
             if (!actionResponse.isPresent()) {
                 LOGGER.debug(FAILED_TO_DELETE_SUBSTITUTION_FILTER);
                 return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR));
             }
-
             return buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK),
                 new SubstitutionFilterConverter().convertToUi(actionResponse.get()));
-
         } catch (final Exception e) {
             BeEcompErrorManager.getInstance().logBeRestApiGeneralError(SUBSTITUTION_FILTER_DELETE);
             LOGGER.debug(DELETE_SUBSTITUTION_FILTER_WITH_AN_ERROR, e);
             return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR));
-
         }
     }
-
 }
index 24eb531..9249d21 100644 (file)
@@ -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.
@@ -17,7 +17,6 @@
  * limitations under the License.
  * ============LICENSE_END=========================================================
  */
-
 package org.openecomp.sdc.be.servlets;
 
 import com.jcabi.aspects.Loggable;
@@ -25,14 +24,6 @@ import io.swagger.v3.oas.annotations.servers.Server;
 import io.swagger.v3.oas.annotations.servers.Servers;
 import io.swagger.v3.oas.annotations.tags.Tag;
 import io.swagger.v3.oas.annotations.tags.Tags;
-import org.openecomp.sdc.be.components.impl.aaf.AafPermission;
-import org.openecomp.sdc.be.components.impl.aaf.PermissionAllowed;
-import org.openecomp.sdc.be.config.Configuration;
-import org.openecomp.sdc.be.config.ConfigurationManager;
-import org.openecomp.sdc.common.api.Constants;
-import org.openecomp.sdc.common.log.wrappers.Logger;
-import org.openecomp.sdc.common.servlets.BasicServlet;
-
 import javax.servlet.ServletContext;
 import javax.servlet.http.HttpServletRequest;
 import javax.ws.rs.Consumes;
@@ -44,6 +35,13 @@ import javax.ws.rs.Produces;
 import javax.ws.rs.QueryParam;
 import javax.ws.rs.core.Context;
 import javax.ws.rs.core.MediaType;
+import org.openecomp.sdc.be.components.impl.aaf.AafPermission;
+import org.openecomp.sdc.be.components.impl.aaf.PermissionAllowed;
+import org.openecomp.sdc.be.config.Configuration;
+import org.openecomp.sdc.be.config.ConfigurationManager;
+import org.openecomp.sdc.common.api.Constants;
+import org.openecomp.sdc.common.log.wrappers.Logger;
+import org.openecomp.sdc.common.servlets.BasicServlet;
 
 /**
  * Root resource (exposed at "/" path)
@@ -61,28 +59,19 @@ public class ConfigMgrServlet extends BasicServlet {
     @Produces(MediaType.APPLICATION_JSON)
     @PermissionAllowed(AafPermission.PermNames.INTERNAL_ALL_VALUE)
     public String getConfig(@Context final HttpServletRequest request, @QueryParam("type") String type) {
-
         String result = null;
-
         ServletContext context = request.getSession().getServletContext();
-
         ConfigurationManager configurationManager = (ConfigurationManager) context.getAttribute(Constants.CONFIGURATION_MANAGER_ATTR);
-
         if (type == null || type.equals("configuration")) {
-
             Configuration configuration = configurationManager.getConfiguration();
             if (configuration == null) {
                 log.warn("Configuration of type {} was not found", Configuration.class);
             } else {
                 log.info("The value returned from getConfig is {}", configuration);
-
                 result = gson.toJson(configuration);
-
             }
         }
-
         return result;
-
     }
 
     @POST
@@ -91,11 +80,8 @@ public class ConfigMgrServlet extends BasicServlet {
     @Consumes(MediaType.APPLICATION_JSON)
     @PermissionAllowed(AafPermission.PermNames.INTERNAL_ALL_VALUE)
     public String setConfig1(@Context final HttpServletRequest request, Configuration configuration) {
-
         log.debug("{}", configuration);
-
         return "ok";
-
     }
 
     @POST
@@ -104,9 +90,7 @@ public class ConfigMgrServlet extends BasicServlet {
     @Consumes(MediaType.APPLICATION_JSON)
     @PermissionAllowed(AafPermission.PermNames.INTERNAL_ALL_VALUE)
     public void setConfig2(@Context final HttpServletRequest request, Configuration configuration) {
-
         log.debug("{}", configuration);
-
     }
 
     @PUT
@@ -115,11 +99,8 @@ public class ConfigMgrServlet extends BasicServlet {
     @Consumes(MediaType.APPLICATION_JSON)
     @PermissionAllowed(AafPermission.PermNames.INTERNAL_ALL_VALUE)
     public String setConfig3(@Context final HttpServletRequest request, Configuration configuration) {
-
         log.debug("{}", configuration);
-
         return "ok";
-
     }
 
     @PUT
@@ -128,9 +109,6 @@ public class ConfigMgrServlet extends BasicServlet {
     @Consumes(MediaType.APPLICATION_JSON)
     @PermissionAllowed(AafPermission.PermNames.INTERNAL_ALL_VALUE)
     public void setConfig4(@Context final HttpServletRequest request, Configuration configuration) {
-
         log.debug("{}", configuration);
-
     }
-
 }
index 86a8a2d..1c90ea0 100644 (file)
@@ -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.
@@ -17,7 +17,6 @@
  * limitations under the License.
  * ============LICENSE_END=========================================================
  */
-
 package org.openecomp.sdc.be.servlets;
 
 import com.jcabi.aspects.Loggable;
@@ -29,14 +28,6 @@ import io.swagger.v3.oas.annotations.servers.Server;
 import io.swagger.v3.oas.annotations.servers.Servers;
 import io.swagger.v3.oas.annotations.tags.Tag;
 import io.swagger.v3.oas.annotations.tags.Tags;
-import org.openecomp.sdc.be.components.impl.aaf.AafPermission;
-import org.openecomp.sdc.be.components.impl.aaf.PermissionAllowed;
-import org.openecomp.sdc.be.config.Configuration;
-import org.openecomp.sdc.common.api.ConfigurationSource;
-import org.openecomp.sdc.common.api.Constants;
-import org.openecomp.sdc.common.log.wrappers.Logger;
-import org.openecomp.sdc.common.servlets.BasicServlet;
-
 import javax.servlet.ServletContext;
 import javax.servlet.http.HttpServletRequest;
 import javax.ws.rs.GET;
@@ -44,6 +35,13 @@ import javax.ws.rs.Path;
 import javax.ws.rs.Produces;
 import javax.ws.rs.core.Context;
 import javax.ws.rs.core.MediaType;
+import org.openecomp.sdc.be.components.impl.aaf.AafPermission;
+import org.openecomp.sdc.be.components.impl.aaf.PermissionAllowed;
+import org.openecomp.sdc.be.config.Configuration;
+import org.openecomp.sdc.common.api.ConfigurationSource;
+import org.openecomp.sdc.common.api.Constants;
+import org.openecomp.sdc.common.log.wrappers.Logger;
+import org.openecomp.sdc.common.servlets.BasicServlet;
 
 /**
  * Root resource (exposed at "/" path)
@@ -61,33 +59,23 @@ public class ConfigServlet extends BasicServlet {
     @Produces(MediaType.APPLICATION_JSON)
     @PermissionAllowed(AafPermission.PermNames.INTERNAL_ALL_VALUE)
     @Operation(description = "Retrieve configuration", method = "GET", responses = {
-            @ApiResponse(responseCode = "200", description = "OK", content = @Content(schema = @Schema(implementation = String.class)))
-    })
+        @ApiResponse(responseCode = "200", description = "OK", content = @Content(schema = @Schema(implementation = String.class)))})
     public String getConfig(@Context final HttpServletRequest request) {
-
         String result = null;
-
         ServletContext context = request.getSession().getServletContext();
-
         ConfigurationSource configurationSource = (ConfigurationSource) context.getAttribute(Constants.CONFIGURATION_SOURCE_ATTR);
         if (configurationSource != null) {
             Configuration configuration = configurationSource.getAndWatchConfiguration(Configuration.class, null);
-
             if (configuration == null) {
                 log.warn("Configuration of type {} was not found", Configuration.class);
             }
             log.debug("{}", configuration);
             log.info("Info level ENABLED...");
             log.info("The value returned from getConfig is {}", configuration);
-
             result = gson.toJson(configuration);
-
         } else {
             log.warn("Source Configuration object was not initialized in the context.");
         }
-
         return result;
-
     }
-
 }
index f3d1860..4b31cb1 100644 (file)
@@ -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.
@@ -17,7 +17,6 @@
  * limitations under the License.
  * ============LICENSE_END=========================================================
  */
-
 package org.openecomp.sdc.be.servlets;
 
 import com.google.gson.Gson;
@@ -33,18 +32,6 @@ import io.swagger.v3.oas.annotations.servers.Server;
 import io.swagger.v3.oas.annotations.servers.Servers;
 import io.swagger.v3.oas.annotations.tags.Tag;
 import io.swagger.v3.oas.annotations.tags.Tags;
-import org.openecomp.sdc.be.components.impl.ConsumerBusinessLogic;
-import org.openecomp.sdc.be.config.BeEcompErrorManager;
-import org.openecomp.sdc.be.dao.api.ActionStatus;
-import org.openecomp.sdc.be.impl.ComponentsUtils;
-import org.openecomp.sdc.be.model.ConsumerDefinition;
-import org.openecomp.sdc.be.model.User;
-import org.openecomp.sdc.be.resources.data.auditing.AuditingActionEnum;
-import org.openecomp.sdc.be.user.UserBusinessLogic;
-import org.openecomp.sdc.common.api.Constants;
-import org.openecomp.sdc.common.log.wrappers.Logger;
-import org.openecomp.sdc.exception.ResponseFormat;
-
 import javax.inject.Inject;
 import javax.inject.Singleton;
 import javax.servlet.ServletContext;
@@ -60,6 +47,17 @@ import javax.ws.rs.Produces;
 import javax.ws.rs.core.Context;
 import javax.ws.rs.core.MediaType;
 import javax.ws.rs.core.Response;
+import org.openecomp.sdc.be.components.impl.ConsumerBusinessLogic;
+import org.openecomp.sdc.be.config.BeEcompErrorManager;
+import org.openecomp.sdc.be.dao.api.ActionStatus;
+import org.openecomp.sdc.be.impl.ComponentsUtils;
+import org.openecomp.sdc.be.model.ConsumerDefinition;
+import org.openecomp.sdc.be.model.User;
+import org.openecomp.sdc.be.resources.data.auditing.AuditingActionEnum;
+import org.openecomp.sdc.be.user.UserBusinessLogic;
+import org.openecomp.sdc.common.api.Constants;
+import org.openecomp.sdc.common.log.wrappers.Logger;
+import org.openecomp.sdc.exception.ResponseFormat;
 
 @Loggable(prepend = true, value = Loggable.DEBUG, trim = false)
 @Path("/v1/consumers")
@@ -69,14 +67,12 @@ import javax.ws.rs.core.Response;
 public class ConsumerServlet extends BeGenericServlet {
 
     private static final String MODIFIER_ID_IS = "modifier id is {}";
-       private static final String START_HANDLE_REQUEST_OF = "Start handle request of {}";
-       private static final Logger log = Logger.getLogger(ConsumerServlet.class);
+    private static final String START_HANDLE_REQUEST_OF = "Start handle request of {}";
+    private static final Logger log = Logger.getLogger(ConsumerServlet.class);
     private final ConsumerBusinessLogic businessLogic;
 
-         @Inject
-    public ConsumerServlet(UserBusinessLogic userBusinessLogic,
-        ComponentsUtils componentsUtils,
-        ConsumerBusinessLogic businessLogic) {
+    @Inject
+    public ConsumerServlet(UserBusinessLogic userBusinessLogic, ComponentsUtils componentsUtils, ConsumerBusinessLogic businessLogic) {
         super(userBusinessLogic, componentsUtils);
         this.businessLogic = businessLogic;
     }
@@ -84,49 +80,38 @@ public class ConsumerServlet extends BeGenericServlet {
     @POST
     @Consumes(MediaType.APPLICATION_JSON)
     @Produces(MediaType.APPLICATION_JSON)
-    @Operation(description = "Consumer credentials", method = "POST",
-            summary = "Returns created ECOMP consumer credentials", responses = {
-            @ApiResponse(content = @Content(array = @ArraySchema(schema = @Schema(implementation = Response.class)))),
-            @ApiResponse(responseCode = "201", description = "Consumer credentials created"),
-            @ApiResponse(responseCode = "403", description = "Restricted operation"),
-            @ApiResponse(responseCode = "400", description = "Invalid content / Missing content")})
+    @Operation(description = "Consumer credentials", method = "POST", summary = "Returns created ECOMP consumer credentials", responses = {
+        @ApiResponse(content = @Content(array = @ArraySchema(schema = @Schema(implementation = Response.class)))),
+        @ApiResponse(responseCode = "201", description = "Consumer credentials created"),
+        @ApiResponse(responseCode = "403", description = "Restricted operation"),
+        @ApiResponse(responseCode = "400", description = "Invalid content / Missing content")})
     public Response createConsumer(@Parameter(description = "Consumer Object to be created", required = true) String data,
-            @Context final HttpServletRequest request, @HeaderParam(value = Constants.USER_ID_HEADER) String userId) {
-
+                                   @Context final HttpServletRequest request, @HeaderParam(value = Constants.USER_ID_HEADER) String userId) {
         ServletContext context = request.getSession().getServletContext();
-
         String url = request.getMethod() + " " + request.getRequestURI();
         log.debug(START_HANDLE_REQUEST_OF, url);
-
         User modifier = new User();
         modifier.setUserId(userId);
         log.debug(MODIFIER_ID_IS, userId);
-
         try {
-            Either<ConsumerDefinition, ResponseFormat> convertionResponse = convertJsonToObject(data, modifier, AuditingActionEnum.ADD_ECOMP_USER_CREDENTIALS);
-
+            Either<ConsumerDefinition, ResponseFormat> convertionResponse = convertJsonToObject(data, modifier,
+                AuditingActionEnum.ADD_ECOMP_USER_CREDENTIALS);
             if (convertionResponse.isRight()) {
                 log.debug("failed to create Consumer");
                 return buildErrorResponse(convertionResponse.right().value());
             }
-
             ConsumerDefinition consumer = convertionResponse.left().value();
-
             Either<ConsumerDefinition, ResponseFormat> actionResult = businessLogic.createConsumer(modifier, consumer);
-
             if (actionResult.isRight()) {
                 log.debug("failed to create Consumer");
                 return buildErrorResponse(actionResult.right().value());
             }
-
             return buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.CREATED), actionResult.left().value());
-
         } catch (Exception e) {
             BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Create consumer");
             log.debug("create consumer failed with exception", e);
             ResponseFormat responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR);
             return buildErrorResponse(responseFormat);
-
         }
     }
 
@@ -134,33 +119,25 @@ public class ConsumerServlet extends BeGenericServlet {
     @Path("/{consumerId}")
     @Consumes(MediaType.APPLICATION_JSON)
     @Produces(MediaType.APPLICATION_JSON)
-    @Operation(description = "Retrieve Consumer", method = "GET", summary = "Returns consumer according to ConsumerID",
-            responses = {@ApiResponse(content = @Content(
-                    array = @ArraySchema(schema = @Schema(implementation = ConsumerDefinition.class)))),
-                    @ApiResponse(responseCode = "200", description = "Consumer found"),
-                    @ApiResponse(responseCode = "403", description = "Restricted operation"),
-                    @ApiResponse(responseCode = "404", description = "Consumer not found")})
-    public Response getConsumer(@PathParam("consumerId") final String consumerId,
-            @Context final HttpServletRequest request, @HeaderParam(value = Constants.USER_ID_HEADER) String userId) {
-
+    @Operation(description = "Retrieve Consumer", method = "GET", summary = "Returns consumer according to ConsumerID", responses = {
+        @ApiResponse(content = @Content(array = @ArraySchema(schema = @Schema(implementation = ConsumerDefinition.class)))),
+        @ApiResponse(responseCode = "200", description = "Consumer found"), @ApiResponse(responseCode = "403", description = "Restricted operation"),
+        @ApiResponse(responseCode = "404", description = "Consumer not found")})
+    public Response getConsumer(@PathParam("consumerId") final String consumerId, @Context final HttpServletRequest request,
+                                @HeaderParam(value = Constants.USER_ID_HEADER) String userId) {
         ServletContext context = request.getSession().getServletContext();
-
         String url = request.getMethod() + " " + request.getRequestURI();
         log.debug(START_HANDLE_REQUEST_OF, url);
-
         User modifier = new User();
         modifier.setUserId(userId);
         log.debug(MODIFIER_ID_IS, userId);
-
         try {
             Either<ConsumerDefinition, ResponseFormat> actionResponse = businessLogic.getConsumer(consumerId, modifier);
-
             if (actionResponse.isRight()) {
                 log.debug("failed to get consumer");
                 return buildErrorResponse(actionResponse.right().value());
             }
             return buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), actionResponse.left().value());
-
         } catch (Exception e) {
             BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Get Consumer");
             log.debug("get consumer failed with exception", e);
@@ -172,31 +149,25 @@ public class ConsumerServlet extends BeGenericServlet {
     @Path("/{consumerId}")
     @Consumes(MediaType.APPLICATION_JSON)
     @Produces(MediaType.APPLICATION_JSON)
-    @Operation(description = "Deletes Consumer", method = "DELETE",
-            summary = "Returns deleted consumer according to ConsumerID", responses = {@ApiResponse(
-            content = @Content(array = @ArraySchema(schema = @Schema(implementation = ConsumerDefinition.class)))),
-            @ApiResponse(responseCode = "204", description = "Consumer deleted"),
-            @ApiResponse(responseCode = "403", description = "Restricted operation"),
-            @ApiResponse(responseCode = "404", description = "Consumer not found")})
-    public Response deleteConsumer(@PathParam("consumerId") final String consumerId,
-            @Context final HttpServletRequest request, @HeaderParam(value = Constants.USER_ID_HEADER) String userId) {
-
+    @Operation(description = "Deletes Consumer", method = "DELETE", summary = "Returns deleted consumer according to ConsumerID", responses = {
+        @ApiResponse(content = @Content(array = @ArraySchema(schema = @Schema(implementation = ConsumerDefinition.class)))),
+        @ApiResponse(responseCode = "204", description = "Consumer deleted"),
+        @ApiResponse(responseCode = "403", description = "Restricted operation"),
+        @ApiResponse(responseCode = "404", description = "Consumer not found")})
+    public Response deleteConsumer(@PathParam("consumerId") final String consumerId, @Context final HttpServletRequest request,
+                                   @HeaderParam(value = Constants.USER_ID_HEADER) String userId) {
         String url = request.getMethod() + " " + request.getRequestURI();
         log.debug(START_HANDLE_REQUEST_OF, url);
-
         User modifier = new User();
         modifier.setUserId(userId);
         log.debug(MODIFIER_ID_IS, userId);
-
         try {
             Either<ConsumerDefinition, ResponseFormat> actionResponse = businessLogic.deleteConsumer(consumerId, modifier);
-
             if (actionResponse.isRight()) {
                 log.debug("failed to delete consumer");
                 return buildErrorResponse(actionResponse.right().value());
             }
             return buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), actionResponse.left().value());
-
         } catch (Exception e) {
             BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Get Consumer");
             log.debug("delete consumer failed with exception", e);
@@ -225,5 +196,4 @@ public class ConsumerServlet extends BeGenericServlet {
         }
         return Either.left(consumer);
     }
-
 }
index adffdaf..d1cee1b 100644 (file)
@@ -16,7 +16,6 @@
  *  SPDX-License-Identifier: Apache-2.0
  *  ============LICENSE_END=========================================================
  */
-
 package org.openecomp.sdc.be.servlets;
 
 import io.swagger.v3.oas.annotations.Operation;
@@ -57,29 +56,23 @@ public class DirectiveServlet extends BeGenericServlet {
     private static final Logger LOGGER = LoggerFactory.getLogger(DirectiveServlet.class);
 
     @Inject
-    public DirectiveServlet(final UserBusinessLogic userAdminManager,
-                            final ComponentsUtils componentsUtils) {
+    public DirectiveServlet(final UserBusinessLogic userAdminManager, final ComponentsUtils componentsUtils) {
         super(userAdminManager, componentsUtils);
     }
 
     @GET
     @Path("/")
     @Produces(MediaType.APPLICATION_JSON)
-    @Operation(description = "Retrieve all Directives values from configuration file", method = "GET",
-        summary = "Retrieve all Directives", responses = {
+    @Operation(description = "Retrieve all Directives values from configuration file", method = "GET", summary = "Retrieve all Directives", responses = {
         @ApiResponse(content = @Content(array = @ArraySchema(schema = @Schema(implementation = User.class)))),
-        @ApiResponse(responseCode = "200",
-            description = "Returns Directive values from configuration file Ok"),
-        @ApiResponse(responseCode = "404",
-            description = "Directive not found"),
+        @ApiResponse(responseCode = "200", description = "Returns Directive values from configuration file Ok"),
+        @ApiResponse(responseCode = "404", description = "Directive not found"),
         @ApiResponse(responseCode = "500", description = "Internal Server Error")})
     @PermissionAllowed(AafPermission.PermNames.INTERNAL_ALL_VALUE)
     public Response getConfCategoriesAndVersion(@Context final HttpServletRequest request,
                                                 @HeaderParam(value = Constants.USER_ID_HEADER) String userId) {
-
         final String url = request.getMethod() + " " + request.getRequestURI();
         LOGGER.debug("Start handle request of {}", url);
-
         final Map<String, Object> directivesMap = new HashMap<>();
         try {
             final List<String> directives = getDirectiveValues();
@@ -87,18 +80,15 @@ public class DirectiveServlet extends BeGenericServlet {
                 return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.NO_CONTENT));
             }
             directivesMap.put("directives", directives);
-
         } catch (final Exception e) {
             BeEcompErrorManager.getInstance().logBeRestApiGeneralError("SDC Failed to retrieve all Directives");
             LOGGER.debug("Method getDirectiveValues failed with unexpected exception", e);
             return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR));
         }
-
         return buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), directivesMap);
     }
 
     private List<String> getDirectiveValues() {
         return ConfigurationManager.getConfigurationManager().getConfiguration().getDirectives();
     }
-
 }
index 46338c2..20a1df2 100644 (file)
@@ -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.
@@ -17,7 +17,6 @@
  * limitations under the License.
  * ============LICENSE_END=========================================================
  */
-
 package org.openecomp.sdc.be.servlets;
 
 import com.jcabi.aspects.Loggable;
@@ -31,6 +30,17 @@ import io.swagger.v3.oas.annotations.servers.Server;
 import io.swagger.v3.oas.annotations.servers.Servers;
 import io.swagger.v3.oas.annotations.tags.Tag;
 import io.swagger.v3.oas.annotations.tags.Tags;
+import javax.inject.Inject;
+import javax.servlet.http.HttpServletRequest;
+import javax.ws.rs.Consumes;
+import javax.ws.rs.GET;
+import javax.ws.rs.HeaderParam;
+import javax.ws.rs.Path;
+import javax.ws.rs.PathParam;
+import javax.ws.rs.Produces;
+import javax.ws.rs.core.Context;
+import javax.ws.rs.core.MediaType;
+import javax.ws.rs.core.Response;
 import org.openecomp.sdc.be.components.impl.DistributionMonitoringBusinessLogic;
 import org.openecomp.sdc.be.components.impl.aaf.AafPermission;
 import org.openecomp.sdc.be.components.impl.aaf.PermissionAllowed;
@@ -45,18 +55,6 @@ import org.openecomp.sdc.common.log.wrappers.Logger;
 import org.openecomp.sdc.exception.ResponseFormat;
 import org.springframework.stereotype.Controller;
 
-import javax.inject.Inject;
-import javax.servlet.http.HttpServletRequest;
-import javax.ws.rs.Consumes;
-import javax.ws.rs.GET;
-import javax.ws.rs.HeaderParam;
-import javax.ws.rs.Path;
-import javax.ws.rs.PathParam;
-import javax.ws.rs.Produces;
-import javax.ws.rs.core.Context;
-import javax.ws.rs.core.MediaType;
-import javax.ws.rs.core.Response;
-
 /**
  * Root resource (exposed at "/" path)
  */
@@ -66,72 +64,61 @@ import javax.ws.rs.core.Response;
 @Servers({@Server(url = "/sdc2/rest")})
 @Controller
 public class DistributionServiceServlet extends BeGenericServlet {
+
     private static final Logger log = Logger.getLogger(DistributionServiceServlet.class);
+    private DistributionMonitoringBusinessLogic distributionMonitoringLogic;
 
     @Inject
-    public DistributionServiceServlet(UserBusinessLogic userBusinessLogic,
-        ComponentsUtils componentsUtils,
-        DistributionMonitoringBusinessLogic distributionMonitoringLogic) {
+    public DistributionServiceServlet(UserBusinessLogic userBusinessLogic, ComponentsUtils componentsUtils,
+                                      DistributionMonitoringBusinessLogic distributionMonitoringLogic) {
         super(userBusinessLogic, componentsUtils);
         this.distributionMonitoringLogic = distributionMonitoringLogic;
     }
 
-    private DistributionMonitoringBusinessLogic distributionMonitoringLogic;
-
     @GET
     @Path("/services/{serviceUUID}/distribution")
     @Consumes(MediaType.APPLICATION_JSON)
     @Produces(MediaType.APPLICATION_JSON)
-    @Operation(description = "Retrieve Distributions", method = "GET",
-            summary = "Returns list  bases on the  information extracted from  Auditing Records according to service uuid",
-            responses = {@ApiResponse(content = @Content(
-                    array = @ArraySchema(schema = @Schema(implementation = DistributionStatusListResponse.class)))),
-                    @ApiResponse(responseCode = "200", description = "Service found"),
-                    @ApiResponse(responseCode = "403", description = "Restricted operation"),
-                    @ApiResponse(responseCode = "404", description = "Service not found")})
+    @Operation(description = "Retrieve Distributions", method = "GET", summary = "Returns list  bases on the  information extracted from  Auditing Records according to service uuid", responses = {
+        @ApiResponse(content = @Content(array = @ArraySchema(schema = @Schema(implementation = DistributionStatusListResponse.class)))),
+        @ApiResponse(responseCode = "200", description = "Service found"), @ApiResponse(responseCode = "403", description = "Restricted operation"),
+        @ApiResponse(responseCode = "404", description = "Service not found")})
     @PermissionAllowed(AafPermission.PermNames.INTERNAL_ALL_VALUE)
-    public Response getServiceById(@PathParam("serviceUUID") final String serviceUUID,
-            @Context final HttpServletRequest request, @HeaderParam(value = Constants.USER_ID_HEADER) String userId) {
-
+    public Response getServiceById(@PathParam("serviceUUID") final String serviceUUID, @Context final HttpServletRequest request,
+                                   @HeaderParam(value = Constants.USER_ID_HEADER) String userId) {
         String url = request.getMethod() + " " + request.getRequestURI();
         log.debug("Start handle request of {}", url);
         try {
-            Either<DistributionStatusOfServiceListResponce, ResponseFormat> actionResponse = distributionMonitoringLogic.getListOfDistributionServiceStatus(serviceUUID, userId);
-
+            Either<DistributionStatusOfServiceListResponce, ResponseFormat> actionResponse = distributionMonitoringLogic
+                .getListOfDistributionServiceStatus(serviceUUID, userId);
             if (actionResponse.isRight()) {
                 return buildErrorResponse(actionResponse.right().value());
             } else {
                 return buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), actionResponse.left().value());
-
             }
         } catch (Exception e) {
             BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Get Distribution list for Service");
             log.debug("failed to get service distribution statuses", e);
             throw e;
         }
-
     }
 
     @GET
     @Path("/services/distribution/{did}")
     @Consumes(MediaType.APPLICATION_JSON)
     @Produces(MediaType.APPLICATION_JSON)
-    @Operation(description = "Retrieve Distributions", method = "GET",
-            summary = "Return  the  list  of  distribution status objects", responses = {@ApiResponse(
-            content = @Content(
-                    array = @ArraySchema(schema = @Schema(implementation = DistributionStatusListResponse.class)))),
-            @ApiResponse(responseCode = "200", description = "Service found"),
-            @ApiResponse(responseCode = "403", description = "Restricted operation"),
-            @ApiResponse(responseCode = "404", description = "Status not found")})
+    @Operation(description = "Retrieve Distributions", method = "GET", summary = "Return  the  list  of  distribution status objects", responses = {
+        @ApiResponse(content = @Content(array = @ArraySchema(schema = @Schema(implementation = DistributionStatusListResponse.class)))),
+        @ApiResponse(responseCode = "200", description = "Service found"), @ApiResponse(responseCode = "403", description = "Restricted operation"),
+        @ApiResponse(responseCode = "404", description = "Status not found")})
     @PermissionAllowed(AafPermission.PermNames.INTERNAL_ALL_VALUE)
-    public Response getListOfDistributionStatuses(@PathParam("did") final String did,
-            @Context final HttpServletRequest request, @HeaderParam(value = Constants.USER_ID_HEADER) String userId) {
-
+    public Response getListOfDistributionStatuses(@PathParam("did") final String did, @Context final HttpServletRequest request,
+                                                  @HeaderParam(value = Constants.USER_ID_HEADER) String userId) {
         String url = request.getMethod() + " " + request.getRequestURI();
         log.debug("Start handle request of {}", url);
         try {
-            Either<DistributionStatusListResponse, ResponseFormat> actionResponse = distributionMonitoringLogic.getListOfDistributionStatus(did, userId);
-
+            Either<DistributionStatusListResponse, ResponseFormat> actionResponse = distributionMonitoringLogic
+                .getListOfDistributionStatus(did, userId);
             if (actionResponse.isRight()) {
                 ResponseFormat responseFormat = actionResponse.right().value();
                 log.debug("failed to fount statuses for did {} {}", did, responseFormat);
@@ -146,7 +133,5 @@ public class DistributionServiceServlet extends BeGenericServlet {
             log.debug("failed to get distribution status ", e);
             throw e;
         }
-
     }
-
 }
index 9ea4a44..e0382c0 100644 (file)
@@ -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.
@@ -17,7 +17,6 @@
  * limitations under the License.
  * ============LICENSE_END=========================================================
  */
-
 package org.openecomp.sdc.be.servlets;
 
 import com.jcabi.aspects.Loggable;
@@ -31,6 +30,26 @@ import io.swagger.v3.oas.annotations.responses.ApiResponse;
 import io.swagger.v3.oas.annotations.servers.Server;
 import io.swagger.v3.oas.annotations.servers.Servers;
 import io.swagger.v3.oas.annotations.tags.Tags;
+import java.io.IOException;
+import java.util.ArrayList;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+import javax.inject.Inject;
+import javax.servlet.ServletContext;
+import javax.servlet.http.HttpServletRequest;
+import javax.ws.rs.Consumes;
+import javax.ws.rs.DELETE;
+import javax.ws.rs.GET;
+import javax.ws.rs.HeaderParam;
+import javax.ws.rs.POST;
+import javax.ws.rs.Path;
+import javax.ws.rs.PathParam;
+import javax.ws.rs.Produces;
+import javax.ws.rs.QueryParam;
+import javax.ws.rs.core.Context;
+import javax.ws.rs.core.MediaType;
+import javax.ws.rs.core.Response;
 import org.openecomp.sdc.be.components.impl.ArtifactsBusinessLogic;
 import org.openecomp.sdc.be.components.impl.ElementBusinessLogic;
 import org.openecomp.sdc.be.components.impl.aaf.AafPermission;
@@ -63,29 +82,7 @@ import org.openecomp.sdc.common.log.wrappers.Logger;
 import org.openecomp.sdc.exception.ResponseFormat;
 import org.springframework.stereotype.Controller;
 
-import javax.inject.Inject;
-import javax.servlet.ServletContext;
-import javax.servlet.http.HttpServletRequest;
-import javax.ws.rs.Consumes;
-import javax.ws.rs.DELETE;
-import javax.ws.rs.GET;
-import javax.ws.rs.HeaderParam;
-import javax.ws.rs.POST;
-import javax.ws.rs.Path;
-import javax.ws.rs.PathParam;
-import javax.ws.rs.Produces;
-import javax.ws.rs.QueryParam;
-import javax.ws.rs.core.Context;
-import javax.ws.rs.core.MediaType;
-import javax.ws.rs.core.Response;
-import java.io.IOException;
-import java.util.ArrayList;
-import java.util.HashMap;
-import java.util.List;
-import java.util.Map;
-
 @Path("/v1/")
-
 /**
  *
  * UI oriented servlet - to return elements in specific format UI needs
@@ -105,17 +102,14 @@ public class ElementServlet extends BeGenericServlet {
     private final ArtifactsBusinessLogic artifactsBusinessLogic;
 
     @Inject
-    public ElementServlet(final UserBusinessLogic userBusinessLogic,
-                          final ComponentsUtils componentsUtils,
-                          final ComponentsCleanBusinessLogic componentsCleanBusinessLogic,
-                          final ElementBusinessLogic elementBusinessLogic,
+    public ElementServlet(final UserBusinessLogic userBusinessLogic, final ComponentsUtils componentsUtils,
+                          final ComponentsCleanBusinessLogic componentsCleanBusinessLogic, final ElementBusinessLogic elementBusinessLogic,
                           final ArtifactsBusinessLogic artifactsBusinessLogic) {
         super(userBusinessLogic, componentsUtils);
         this.componentsCleanBusinessLogic = componentsCleanBusinessLogic;
         this.elementBusinessLogic = elementBusinessLogic;
         this.artifactsBusinessLogic = artifactsBusinessLogic;
     }
-
     /*
      ******************************************************************************
      * NEW CATEGORIES category / \ subcategory subcategory / grouping
@@ -126,29 +120,27 @@ public class ElementServlet extends BeGenericServlet {
      *
      * CATEGORIES
      */
+
     /////////////////////////////////////////////////////////////////////////////////////////////////////
+
     // retrieve all component categories
     @GET
     @Path("/categories/{componentType}")
     @Consumes(MediaType.APPLICATION_JSON)
     @Produces(MediaType.APPLICATION_JSON)
-    @Operation(description = "Retrieve the list of all resource/service/product categories/sub-categories/groupings",
-            method = "GET",
-            summary = "Retrieve the list of all resource/service/product categories/sub-categories/groupings.",
-            responses = {@ApiResponse(
-                    content = @Content(array = @ArraySchema(schema = @Schema(implementation = Response.class)))),
-                    @ApiResponse(responseCode = "200", description = "Returns categories Ok"),
-                    @ApiResponse(responseCode = "403", description = "Missing information"),
-                    @ApiResponse(responseCode = "400", description = "Invalid component type"),
-                    @ApiResponse(responseCode = "409", description = "Restricted operation"),
-                    @ApiResponse(responseCode = "500", description = "Internal Server Error")})
+    @Operation(description = "Retrieve the list of all resource/service/product categories/sub-categories/groupings", method = "GET", summary = "Retrieve the list of all resource/service/product categories/sub-categories/groupings.", responses = {
+        @ApiResponse(content = @Content(array = @ArraySchema(schema = @Schema(implementation = Response.class)))),
+        @ApiResponse(responseCode = "200", description = "Returns categories Ok"),
+        @ApiResponse(responseCode = "403", description = "Missing information"),
+        @ApiResponse(responseCode = "400", description = "Invalid component type"),
+        @ApiResponse(responseCode = "409", description = "Restricted operation"),
+        @ApiResponse(responseCode = "500", description = "Internal Server Error")})
     @PermissionAllowed(AafPermission.PermNames.INTERNAL_ALL_VALUE)
     public Response getComponentCategories(
-            @Parameter(description = "allowed values are resources / services/ products", schema = @Schema(allowableValues = {ComponentTypeEnum.RESOURCE_PARAM_NAME ,
-                    ComponentTypeEnum.SERVICE_PARAM_NAME,ComponentTypeEnum.PRODUCT_PARAM_NAME}),required = true)
-                     @PathParam(value = "componentType") final String componentType,
-            @HeaderParam(value = Constants.USER_ID_HEADER) String userId, @Context final HttpServletRequest request) {
-
+        @Parameter(description = "allowed values are resources / services/ products", schema = @Schema(allowableValues = {
+            ComponentTypeEnum.RESOURCE_PARAM_NAME, ComponentTypeEnum.SERVICE_PARAM_NAME,
+            ComponentTypeEnum.PRODUCT_PARAM_NAME}), required = true) @PathParam(value = "componentType") final String componentType,
+        @HeaderParam(value = Constants.USER_ID_HEADER) String userId, @Context final HttpServletRequest request) {
         try {
             ElementBusinessLogic elementBL = getElementBL(request.getSession().getServletContext());
             Either<List<CategoryDefinition>, ResponseFormat> either = elementBL.getAllCategories(componentType, userId);
@@ -169,34 +161,28 @@ public class ElementServlet extends BeGenericServlet {
     @Path("/category/{componentType}")
     @Consumes(MediaType.APPLICATION_JSON)
     @Produces(MediaType.APPLICATION_JSON)
-    @Operation(description = "Create new component category", method = "POST",
-            summary = "Create new component category",
-            responses = {@ApiResponse(responseCode = "201", description = "Category created"),
-                    @ApiResponse(responseCode = "400", description = "Invalid category data"),
-                    @ApiResponse(responseCode = "403", description = "USER_ID header is missing"),
-                    @ApiResponse(responseCode = "409",
-                            description = "Category already exists / User not permitted to perform the action"),
-                    @ApiResponse(responseCode = "500", description = "General Error")})
+    @Operation(description = "Create new component category", method = "POST", summary = "Create new component category", responses = {
+        @ApiResponse(responseCode = "201", description = "Category created"),
+        @ApiResponse(responseCode = "400", description = "Invalid category data"),
+        @ApiResponse(responseCode = "403", description = "USER_ID header is missing"),
+        @ApiResponse(responseCode = "409", description = "Category already exists / User not permitted to perform the action"),
+        @ApiResponse(responseCode = "500", description = "General Error")})
     @PermissionAllowed(AafPermission.PermNames.INTERNAL_ALL_VALUE)
     public Response createComponentCategory(
-            @Parameter(description = "allowed values are resources /services / products",
-                    schema = @Schema(allowableValues = {ComponentTypeEnum.RESOURCE_PARAM_NAME ,
-                            ComponentTypeEnum.SERVICE_PARAM_NAME,ComponentTypeEnum.PRODUCT_PARAM_NAME}),
-                    required = true) @PathParam(value = "componentType") final String componentType,
-            @Parameter(description = "Category to be created", required = true) String data,
-            @Context final HttpServletRequest request, @HeaderParam(value = Constants.USER_ID_HEADER) String userId) {
+        @Parameter(description = "allowed values are resources /services / products", schema = @Schema(allowableValues = {
+            ComponentTypeEnum.RESOURCE_PARAM_NAME, ComponentTypeEnum.SERVICE_PARAM_NAME,
+            ComponentTypeEnum.PRODUCT_PARAM_NAME}), required = true) @PathParam(value = "componentType") final String componentType,
+        @Parameter(description = "Category to be created", required = true) String data, @Context final HttpServletRequest request,
+        @HeaderParam(value = Constants.USER_ID_HEADER) String userId) {
         try {
             ElementBusinessLogic elementBL = getElementBL(request.getSession().getServletContext());
             CategoryDefinition category = RepresentationUtils.fromRepresentation(data, CategoryDefinition.class);
-
             Either<CategoryDefinition, ResponseFormat> createResourceCategory = elementBL.createCategory(category, componentType, userId);
             if (createResourceCategory.isRight()) {
                 return buildErrorResponse(createResourceCategory.right().value());
             }
-
             ResponseFormat responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.CREATED);
             return buildOkResponse(responseFormat, createResourceCategory.left().value());
-
         } catch (Exception e) {
             BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Create resource category");
             log.debug("createResourceCategory failed with exception", e);
@@ -208,29 +194,24 @@ public class ElementServlet extends BeGenericServlet {
     @Path("/category/{componentType}/{categoryUniqueId}")
     @Consumes(MediaType.APPLICATION_JSON)
     @Produces(MediaType.APPLICATION_JSON)
-    @Operation(description = "Delete component category", method = "DELETE", summary = "Delete component category",
-            responses = {@ApiResponse(
-                    content = @Content(array = @ArraySchema(schema = @Schema(implementation = Category.class)))),
-                    @ApiResponse(responseCode = "204", description = "Category deleted"),
-                    @ApiResponse(responseCode = "403", description = "USER_ID header is missing"),
-                    @ApiResponse(responseCode = "409", description = "User not permitted to perform the action"),
-                    @ApiResponse(responseCode = "404", description = "Category not found"),
-                    @ApiResponse(responseCode = "500", description = "General Error")})
+    @Operation(description = "Delete component category", method = "DELETE", summary = "Delete component category", responses = {
+        @ApiResponse(content = @Content(array = @ArraySchema(schema = @Schema(implementation = Category.class)))),
+        @ApiResponse(responseCode = "204", description = "Category deleted"),
+        @ApiResponse(responseCode = "403", description = "USER_ID header is missing"),
+        @ApiResponse(responseCode = "409", description = "User not permitted to perform the action"),
+        @ApiResponse(responseCode = "404", description = "Category not found"), @ApiResponse(responseCode = "500", description = "General Error")})
     @PermissionAllowed(AafPermission.PermNames.INTERNAL_ALL_VALUE)
     public Response deleteComponentCategory(@PathParam(value = "categoryUniqueId") final String categoryUniqueId,
-            @PathParam(value = "componentType") final String componentType, @Context final HttpServletRequest request,
-            @HeaderParam(value = Constants.USER_ID_HEADER) String userId) {
-
+                                            @PathParam(value = "componentType") final String componentType, @Context final HttpServletRequest request,
+                                            @HeaderParam(value = Constants.USER_ID_HEADER) String userId) {
         try {
             ElementBusinessLogic elementBL = getElementBL(request.getSession().getServletContext());
             Either<CategoryDefinition, ResponseFormat> createResourceCategory = elementBL.deleteCategory(categoryUniqueId, componentType, userId);
-
             if (createResourceCategory.isRight()) {
                 return buildErrorResponse(createResourceCategory.right().value());
             }
             ResponseFormat responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.NO_CONTENT);
             return buildOkResponse(responseFormat, null);
-
         } catch (Exception e) {
             BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Create resource category");
             log.debug("createResourceCategory failed with exception", e);
@@ -244,43 +225,34 @@ public class ElementServlet extends BeGenericServlet {
      * SUBCATEGORIES
      *
      */
-
     @POST
     @Path("/category/{componentType}/{categoryId}/subCategory")
     @Consumes(MediaType.APPLICATION_JSON)
     @Produces(MediaType.APPLICATION_JSON)
-    @Operation(description = "Create new component sub-category", method = "POST",
-            summary = "Create new component sub-category for existing category",
-            responses = {@ApiResponse(responseCode = "201", description = "Subcategory created"),
-                    @ApiResponse(responseCode = "400", description = "Invalid subcategory data"),
-                    @ApiResponse(responseCode = "403", description = "USER_ID header is missing"),
-                    @ApiResponse(responseCode = "404", description = "Parent category wasn't found"),
-                    @ApiResponse(responseCode = "409",
-                            description = "Subcategory already exists / User not permitted to perform the action"),
-                    @ApiResponse(responseCode = "500", description = "General Error")})
+    @Operation(description = "Create new component sub-category", method = "POST", summary = "Create new component sub-category for existing category", responses = {
+        @ApiResponse(responseCode = "201", description = "Subcategory created"),
+        @ApiResponse(responseCode = "400", description = "Invalid subcategory data"),
+        @ApiResponse(responseCode = "403", description = "USER_ID header is missing"),
+        @ApiResponse(responseCode = "404", description = "Parent category wasn't found"),
+        @ApiResponse(responseCode = "409", description = "Subcategory already exists / User not permitted to perform the action"),
+        @ApiResponse(responseCode = "500", description = "General Error")})
     @PermissionAllowed(AafPermission.PermNames.INTERNAL_ALL_VALUE)
     public Response createComponentSubCategory(
-            @Parameter(description = "allowed values are resources / products",
-                    schema = @Schema(allowableValues = {ComponentTypeEnum.RESOURCE_PARAM_NAME ,
-                            ComponentTypeEnum.PRODUCT_PARAM_NAME}),
-                    required = true) @PathParam(value = "componentType") final String componentType,
-            @Parameter(description = "Parent category unique ID",
-                    required = true) @PathParam(value = "categoryId") final String categoryId,
-            @Parameter(description = "Subcategory to be created. \ne.g. {\"name\":\"Resource-subcat\"}",
-                    required = true) String data,
-            @Context final HttpServletRequest request, @HeaderParam(value = Constants.USER_ID_HEADER) String userId) {
-
+        @Parameter(description = "allowed values are resources / products", schema = @Schema(allowableValues = {ComponentTypeEnum.RESOURCE_PARAM_NAME,
+            ComponentTypeEnum.PRODUCT_PARAM_NAME}), required = true) @PathParam(value = "componentType") final String componentType,
+        @Parameter(description = "Parent category unique ID", required = true) @PathParam(value = "categoryId") final String categoryId,
+        @Parameter(description = "Subcategory to be created. \ne.g. {\"name\":\"Resource-subcat\"}", required = true) String data,
+        @Context final HttpServletRequest request, @HeaderParam(value = Constants.USER_ID_HEADER) String userId) {
         try {
             ElementBusinessLogic elementBL = getElementBL(request.getSession().getServletContext());
             SubCategoryDefinition subCategory = RepresentationUtils.fromRepresentation(data, SubCategoryDefinition.class);
-
-            Either<SubCategoryDefinition, ResponseFormat> createSubcategory = elementBL.createSubCategory(subCategory, componentType, categoryId, userId);
+            Either<SubCategoryDefinition, ResponseFormat> createSubcategory = elementBL
+                .createSubCategory(subCategory, componentType, categoryId, userId);
             if (createSubcategory.isRight()) {
                 return buildErrorResponse(createSubcategory.right().value());
             }
             ResponseFormat responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.CREATED);
             return buildOkResponse(responseFormat, createSubcategory.left().value());
-
         } catch (Exception e) {
             BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Create sub-category");
             log.debug("createComponentSubCategory failed with exception", e);
@@ -292,29 +264,27 @@ public class ElementServlet extends BeGenericServlet {
     @Path("/category/{componentType}/{categoryUniqueId}/subCategory/{subCategoryUniqueId}")
     @Consumes(MediaType.APPLICATION_JSON)
     @Produces(MediaType.APPLICATION_JSON)
-    @Operation(description = "Delete component category", method = "DELETE", summary = "Delete component category",
-            responses = {@ApiResponse(
-                    content = @Content(array = @ArraySchema(schema = @Schema(implementation = Category.class)))),
-                    @ApiResponse(responseCode = "204", description = "Category deleted"),
-                    @ApiResponse(responseCode = "403", description = "USER_ID header is missing"),
-                    @ApiResponse(responseCode = "409", description = "User not permitted to perform the action"),
-                    @ApiResponse(responseCode = "404", description = "Category not found"),
-                    @ApiResponse(responseCode = "500", description = "General Error")})
+    @Operation(description = "Delete component category", method = "DELETE", summary = "Delete component category", responses = {
+        @ApiResponse(content = @Content(array = @ArraySchema(schema = @Schema(implementation = Category.class)))),
+        @ApiResponse(responseCode = "204", description = "Category deleted"),
+        @ApiResponse(responseCode = "403", description = "USER_ID header is missing"),
+        @ApiResponse(responseCode = "409", description = "User not permitted to perform the action"),
+        @ApiResponse(responseCode = "404", description = "Category not found"), @ApiResponse(responseCode = "500", description = "General Error")})
     @PermissionAllowed(AafPermission.PermNames.INTERNAL_ALL_VALUE)
     public Response deleteComponentSubCategory(@PathParam(value = "categoryUniqueId") final String categoryUniqueId,
-            @PathParam(value = "subCategoryUniqueId") final String subCategoryUniqueId,
-            @PathParam(value = "componentType") final String componentType, @Context final HttpServletRequest request,
-            @HeaderParam(value = Constants.USER_ID_HEADER) String userId) {
-
+                                               @PathParam(value = "subCategoryUniqueId") final String subCategoryUniqueId,
+                                               @PathParam(value = "componentType") final String componentType,
+                                               @Context final HttpServletRequest request,
+                                               @HeaderParam(value = Constants.USER_ID_HEADER) String userId) {
         try {
             ElementBusinessLogic elementBL = getElementBL(request.getSession().getServletContext());
-            Either<SubCategoryDefinition, ResponseFormat> deleteSubResourceCategory = elementBL.deleteSubCategory(subCategoryUniqueId, componentType, userId);
+            Either<SubCategoryDefinition, ResponseFormat> deleteSubResourceCategory = elementBL
+                .deleteSubCategory(subCategoryUniqueId, componentType, userId);
             if (deleteSubResourceCategory.isRight()) {
                 return buildErrorResponse(deleteSubResourceCategory.right().value());
             }
             ResponseFormat responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.NO_CONTENT);
             return buildOkResponse(responseFormat, null);
-
         } catch (Exception e) {
             BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Delete component subcategory");
             log.debug("deleteComponentSubCategory failed with exception", e);
@@ -329,37 +299,30 @@ public class ElementServlet extends BeGenericServlet {
     @Path("/category/{componentType}/{categoryId}/subCategory/{subCategoryId}/grouping")
     @Consumes(MediaType.APPLICATION_JSON)
     @Produces(MediaType.APPLICATION_JSON)
-    @Operation(description = "Create new component grouping", method = "POST",
-            summary = "Create new component grouping for existing sub-category",
-            responses = {@ApiResponse(responseCode = "201", description = "Grouping created"),
-                    @ApiResponse(responseCode = "400", description = "Invalid grouping data"),
-                    @ApiResponse(responseCode = "403", description = "USER_ID header is missing"),
-                    @ApiResponse(responseCode = "404", description = "Parent category or subcategory were not found"),
-                    @ApiResponse(responseCode = "409",
-                            description = "Grouping already exists / User not permitted to perform the action"),
-                    @ApiResponse(responseCode = "500", description = "General Error")})
+    @Operation(description = "Create new component grouping", method = "POST", summary = "Create new component grouping for existing sub-category", responses = {
+        @ApiResponse(responseCode = "201", description = "Grouping created"),
+        @ApiResponse(responseCode = "400", description = "Invalid grouping data"),
+        @ApiResponse(responseCode = "403", description = "USER_ID header is missing"),
+        @ApiResponse(responseCode = "404", description = "Parent category or subcategory were not found"),
+        @ApiResponse(responseCode = "409", description = "Grouping already exists / User not permitted to perform the action"),
+        @ApiResponse(responseCode = "500", description = "General Error")})
     @PermissionAllowed(AafPermission.PermNames.INTERNAL_ALL_VALUE)
-    public Response createComponentGrouping(
-            @Parameter(description = "allowed values are products",
-                    schema = @Schema(allowableValues = {ComponentTypeEnum.PRODUCT_PARAM_NAME}),
-                    required = true) @PathParam(value = "componentType") final String componentType,
-            @Parameter(description = "Parent category unique ID",
-                    required = true) @PathParam(value = "categoryId") final String grandParentCategoryId,
-            @Parameter(description = "Parent sub-category unique ID",
-                    required = true) @PathParam(value = "subCategoryId") final String parentSubCategoryId,
-            @Parameter(description = "Subcategory to be created", required = true) String data,
-            @Context final HttpServletRequest request, @HeaderParam(value = Constants.USER_ID_HEADER) String userId) {
+    public Response createComponentGrouping(@Parameter(description = "allowed values are products", schema = @Schema(allowableValues = {
+        ComponentTypeEnum.PRODUCT_PARAM_NAME}), required = true) @PathParam(value = "componentType") final String componentType,
+                                            @Parameter(description = "Parent category unique ID", required = true) @PathParam(value = "categoryId") final String grandParentCategoryId,
+                                            @Parameter(description = "Parent sub-category unique ID", required = true) @PathParam(value = "subCategoryId") final String parentSubCategoryId,
+                                            @Parameter(description = "Subcategory to be created", required = true) String data,
+                                            @Context final HttpServletRequest request, @HeaderParam(value = Constants.USER_ID_HEADER) String userId) {
         try {
             ElementBusinessLogic elementBL = getElementBL(request.getSession().getServletContext());
             GroupingDefinition grouping = RepresentationUtils.fromRepresentation(data, GroupingDefinition.class);
-
-            Either<GroupingDefinition, ResponseFormat> createGrouping = elementBL.createGrouping(grouping, componentType, grandParentCategoryId, parentSubCategoryId, userId);
+            Either<GroupingDefinition, ResponseFormat> createGrouping = elementBL
+                .createGrouping(grouping, componentType, grandParentCategoryId, parentSubCategoryId, userId);
             if (createGrouping.isRight()) {
                 return buildErrorResponse(createGrouping.right().value());
             }
             ResponseFormat responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.CREATED);
             return buildOkResponse(responseFormat, createGrouping.left().value());
-
         } catch (Exception e) {
             BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Create grouping");
             log.debug("createComponentGrouping failed with exception", e);
@@ -371,22 +334,18 @@ public class ElementServlet extends BeGenericServlet {
     @Path("/category/{componentType}/{categoryUniqueId}/subCategory/{subCategoryUniqueId}/grouping/{groupingUniqueId}")
     @Consumes(MediaType.APPLICATION_JSON)
     @Produces(MediaType.APPLICATION_JSON)
-    @Operation(description = "Delete component category", method = "DELETE", summary = "Delete component category",
-            responses = {@ApiResponse(
-                    content = @Content(array = @ArraySchema(schema = @Schema(implementation = Category.class)))),
-                    @ApiResponse(responseCode = "204", description = "Category deleted"),
-                    @ApiResponse(responseCode = "403", description = "USER_ID header is missing"),
-                    @ApiResponse(responseCode = "409", description = "User not permitted to perform the action"),
-                    @ApiResponse(responseCode = "404", description = "Category not found"),
-                    @ApiResponse(responseCode = "500", description = "General Error")})
+    @Operation(description = "Delete component category", method = "DELETE", summary = "Delete component category", responses = {
+        @ApiResponse(content = @Content(array = @ArraySchema(schema = @Schema(implementation = Category.class)))),
+        @ApiResponse(responseCode = "204", description = "Category deleted"),
+        @ApiResponse(responseCode = "403", description = "USER_ID header is missing"),
+        @ApiResponse(responseCode = "409", description = "User not permitted to perform the action"),
+        @ApiResponse(responseCode = "404", description = "Category not found"), @ApiResponse(responseCode = "500", description = "General Error")})
     @PermissionAllowed(AafPermission.PermNames.INTERNAL_ALL_VALUE)
-    public Response deleteComponentGrouping(
-            @PathParam(value = "categoryUniqueId") final String grandParentCategoryUniqueId,
-            @PathParam(value = "subCategoryUniqueId") final String parentSubCategoryUniqueId,
-            @PathParam(value = "groupingUniqueId") final String groupingUniqueId,
-            @PathParam(value = "componentType") final String componentType, @Context final HttpServletRequest request,
-            @HeaderParam(value = Constants.USER_ID_HEADER) String userId) {
-
+    public Response deleteComponentGrouping(@PathParam(value = "categoryUniqueId") final String grandParentCategoryUniqueId,
+                                            @PathParam(value = "subCategoryUniqueId") final String parentSubCategoryUniqueId,
+                                            @PathParam(value = "groupingUniqueId") final String groupingUniqueId,
+                                            @PathParam(value = "componentType") final String componentType, @Context final HttpServletRequest request,
+                                            @HeaderParam(value = Constants.USER_ID_HEADER) String userId) {
         try {
             ElementBusinessLogic elementBL = getElementBL(request.getSession().getServletContext());
             Either<GroupingDefinition, ResponseFormat> deleteGrouping = elementBL.deleteGrouping(groupingUniqueId, componentType, userId);
@@ -395,31 +354,27 @@ public class ElementServlet extends BeGenericServlet {
             }
             ResponseFormat responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.NO_CONTENT);
             return buildOkResponse(responseFormat, null);
-
         } catch (Exception e) {
             BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Delete component grouping");
             log.debug("deleteGrouping failed with exception", e);
             throw e;
         }
     }
-
     /////////////////////////////////////////////////////////////////////////////////////////////////////
+
     // retrieve all tags
     @GET
     @Path("/tags")
     @Consumes(MediaType.APPLICATION_JSON)
     @Produces(MediaType.APPLICATION_JSON)
     @Operation(description = "Retrieve all tags", method = "GET", summary = "Retrieve all tags", responses = {
-            @ApiResponse(content = @Content(array = @ArraySchema(schema = @Schema(implementation = User.class)))),
-            @ApiResponse(responseCode = "200", description = "Returns tags Ok"),
-            @ApiResponse(responseCode = "404", description = "No tags were found"),
-            @ApiResponse(responseCode = "500", description = "Internal Server Error")})
+        @ApiResponse(content = @Content(array = @ArraySchema(schema = @Schema(implementation = User.class)))),
+        @ApiResponse(responseCode = "200", description = "Returns tags Ok"), @ApiResponse(responseCode = "404", description = "No tags were found"),
+        @ApiResponse(responseCode = "500", description = "Internal Server Error")})
     @PermissionAllowed(AafPermission.PermNames.INTERNAL_ALL_VALUE)
-    public Response getTags(@Context final HttpServletRequest request,
-            @HeaderParam(value = Constants.USER_ID_HEADER) String userId) {
+    public Response getTags(@Context final HttpServletRequest request, @HeaderParam(value = Constants.USER_ID_HEADER) String userId) {
         String url = request.getMethod() + " " + request.getRequestURI();
         log.debug("(getTags) Start handle request of {}", url);
-
         try {
             ElementBusinessLogic elementBL = getElementBL(request.getSession().getServletContext());
             Either<List<Tag>, ActionStatus> either = elementBL.getAllTags(userId);
@@ -435,25 +390,22 @@ public class ElementServlet extends BeGenericServlet {
             throw e;
         }
     }
-
     /////////////////////////////////////////////////////////////////////////////////////////////////////
+
     // retrieve all property scopes
     @GET
     @Path("/propertyScopes")
     @Consumes(MediaType.APPLICATION_JSON)
     @Produces(MediaType.APPLICATION_JSON)
-    @Operation(description = "Retrieve all propertyScopes", method = "GET", summary = "Retrieve all propertyScopes",
-            responses = {@ApiResponse(
-                    content = @Content(array = @ArraySchema(schema = @Schema(implementation = User.class)))),
-                    @ApiResponse(responseCode = "200", description = "Returns propertyScopes Ok"),
-                    @ApiResponse(responseCode = "404", description = "No propertyScopes were found"),
-                    @ApiResponse(responseCode = "500", description = "Internal Server Error")})
+    @Operation(description = "Retrieve all propertyScopes", method = "GET", summary = "Retrieve all propertyScopes", responses = {
+        @ApiResponse(content = @Content(array = @ArraySchema(schema = @Schema(implementation = User.class)))),
+        @ApiResponse(responseCode = "200", description = "Returns propertyScopes Ok"),
+        @ApiResponse(responseCode = "404", description = "No propertyScopes were found"),
+        @ApiResponse(responseCode = "500", description = "Internal Server Error")})
     @PermissionAllowed(AafPermission.PermNames.INTERNAL_ALL_VALUE)
-    public Response getPropertyScopes(@Context final HttpServletRequest request,
-            @HeaderParam(value = Constants.USER_ID_HEADER) String userId) {
+    public Response getPropertyScopes(@Context final HttpServletRequest request, @HeaderParam(value = Constants.USER_ID_HEADER) String userId) {
         String url = request.getMethod() + " " + request.getRequestURI();
         log.debug("(getPropertyScopes) Start handle request of {}", url);
-
         try {
             ElementBusinessLogic elementBL = getElementBL(request.getSession().getServletContext());
             Either<List<PropertyScope>, ActionStatus> either = elementBL.getAllPropertyScopes(userId);
@@ -469,25 +421,22 @@ public class ElementServlet extends BeGenericServlet {
             throw e;
         }
     }
-
     /////////////////////////////////////////////////////////////////////////////////////////////////////
+
     // retrieve all artifact types
     @GET
     @Path("/artifactTypes")
     @Consumes(MediaType.APPLICATION_JSON)
     @Produces(MediaType.APPLICATION_JSON)
-    @Operation(description = "Retrieve all artifactTypes", method = "GET", summary = "Retrieve all artifactTypes",
-            responses = {@ApiResponse(
-                    content = @Content(array = @ArraySchema(schema = @Schema(implementation = User.class)))),
-                    @ApiResponse(responseCode = "200", description = "Returns artifactTypes Ok"),
-                    @ApiResponse(responseCode = "404", description = "No artifactTypes were found"),
-                    @ApiResponse(responseCode = "500", description = "Internal Server Error")})
+    @Operation(description = "Retrieve all artifactTypes", method = "GET", summary = "Retrieve all artifactTypes", responses = {
+        @ApiResponse(content = @Content(array = @ArraySchema(schema = @Schema(implementation = User.class)))),
+        @ApiResponse(responseCode = "200", description = "Returns artifactTypes Ok"),
+        @ApiResponse(responseCode = "404", description = "No artifactTypes were found"),
+        @ApiResponse(responseCode = "500", description = "Internal Server Error")})
     @PermissionAllowed(AafPermission.PermNames.INTERNAL_ALL_VALUE)
-    public Response getArtifactTypes(@Context final HttpServletRequest request,
-            @HeaderParam(value = Constants.USER_ID_HEADER) String userId) {
+    public Response getArtifactTypes(@Context final HttpServletRequest request, @HeaderParam(value = Constants.USER_ID_HEADER) String userId) {
         String url = request.getMethod() + " " + request.getRequestURI();
         log.debug("(GET - getArtifactTypes) Start handle request of {}", url);
-
         try {
             ElementBusinessLogic elementBL = getElementBL(request.getSession().getServletContext());
             Either<List<ArtifactType>, ActionStatus> either = elementBL.getAllArtifactTypes(userId);
@@ -495,12 +444,11 @@ public class ElementServlet extends BeGenericServlet {
                 log.debug("No artifact types were found");
                 return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.NO_CONTENT));
             } else {
-
-                Integer defaultHeatTimeout = ConfigurationManager.getConfigurationManager().getConfiguration().getHeatArtifactDeploymentTimeout().getDefaultMinutes();
+                Integer defaultHeatTimeout = ConfigurationManager.getConfigurationManager().getConfiguration().getHeatArtifactDeploymentTimeout()
+                    .getDefaultMinutes();
                 ArtifactTypesInfo typesResponse = new ArtifactTypesInfo();
                 typesResponse.setArtifactTypes(either.left().value());
                 typesResponse.setHeatDefaultTimeout(defaultHeatTimeout);
-
                 return buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), typesResponse);
             }
         } catch (Exception e) {
@@ -509,30 +457,29 @@ public class ElementServlet extends BeGenericServlet {
             throw e;
         }
     }
-
-
     /////////////////////////////////////////////////////////////////////////////////////////////////////
+
     // retrieve all followed resources and services
     @GET
     @Path("/followed")
     @Consumes(MediaType.APPLICATION_JSON)
     @Produces(MediaType.APPLICATION_JSON)
     @Operation(description = "Retrieve all followed", method = "GET", summary = "Retrieve all followed", responses = {
-            @ApiResponse(content = @Content(array = @ArraySchema(schema = @Schema(implementation = User.class)))),
-            @ApiResponse(responseCode = "200", description = "Returns followed Ok"),
-            @ApiResponse(responseCode = "404", description = "No followed were found"),
-            @ApiResponse(responseCode = "404", description = "User not found"),
-            @ApiResponse(responseCode = "500", description = "Internal Server Error")})
+        @ApiResponse(content = @Content(array = @ArraySchema(schema = @Schema(implementation = User.class)))),
+        @ApiResponse(responseCode = "200", description = "Returns followed Ok"),
+        @ApiResponse(responseCode = "404", description = "No followed were found"),
+        @ApiResponse(responseCode = "404", description = "User not found"),
+        @ApiResponse(responseCode = "500", description = "Internal Server Error")})
     @PermissionAllowed(AafPermission.PermNames.INTERNAL_ALL_VALUE)
     public Response getFollowedResourcesServices(@Context final HttpServletRequest request,
-            @HeaderParam(value = Constants.USER_ID_HEADER) String userId) throws IOException {
-
+                                                 @HeaderParam(value = Constants.USER_ID_HEADER) String userId) throws IOException {
         try {
             String url = request.getMethod() + " " + request.getRequestURI();
             log.debug(START_HANDLE_REQUEST_OF, url);
             UserBusinessLogic userAdminManager = getUserAdminManager(request.getSession().getServletContext());
             User userData = userAdminManager.getUser(userId, false);
-            Either<Map<String, List<? extends Component>>, ResponseFormat> followedResourcesServices = getElementBL(request.getSession().getServletContext()).getFollowed(userData);
+            Either<Map<String, List<? extends Component>>, ResponseFormat> followedResourcesServices = getElementBL(
+                request.getSession().getServletContext()).getFollowed(userData);
             if (followedResourcesServices.isRight()) {
                 log.debug("failed to get followed resources services ");
                 return buildErrorResponse(followedResourcesServices.right().value());
@@ -545,38 +492,33 @@ public class ElementServlet extends BeGenericServlet {
             throw e;
         }
     }
-
     /////////////////////////////////////////////////////////////////////////////////////////////////////
+
     // retrieve all certified resources and services and their last version
     @GET
     @Path("/screen")
     @Consumes(MediaType.APPLICATION_JSON)
     @Produces(MediaType.APPLICATION_JSON)
-    @Operation(description = "Retrieve catalog resources and services", method = "GET",
-            summary = "Retrieve catalog resources and services", responses = {
-            @ApiResponse(content = @Content(array = @ArraySchema(schema = @Schema(implementation = User.class)))),
-            @ApiResponse(responseCode = "200", description = "Returns resources and services Ok"),
-            @ApiResponse(responseCode = "404", description = "No resources and services were found"),
-            @ApiResponse(responseCode = "404", description = "User not found"),
-            @ApiResponse(responseCode = "500", description = "Internal Server Error")})
+    @Operation(description = "Retrieve catalog resources and services", method = "GET", summary = "Retrieve catalog resources and services", responses = {
+        @ApiResponse(content = @Content(array = @ArraySchema(schema = @Schema(implementation = User.class)))),
+        @ApiResponse(responseCode = "200", description = "Returns resources and services Ok"),
+        @ApiResponse(responseCode = "404", description = "No resources and services were found"),
+        @ApiResponse(responseCode = "404", description = "User not found"),
+        @ApiResponse(responseCode = "500", description = "Internal Server Error")})
     @PermissionAllowed(AafPermission.PermNames.INTERNAL_ALL_VALUE)
-    public Response getCatalogComponents(@Context final HttpServletRequest request,
-            @HeaderParam(value = Constants.USER_ID_HEADER) String userId,
-            @QueryParam("excludeTypes") List<OriginTypeEnum> excludeTypes) throws IOException {
-
+    public Response getCatalogComponents(@Context final HttpServletRequest request, @HeaderParam(value = Constants.USER_ID_HEADER) String userId,
+                                         @QueryParam("excludeTypes") List<OriginTypeEnum> excludeTypes) throws IOException {
         try {
             String url = request.getMethod() + " " + request.getRequestURI();
             log.debug(START_HANDLE_REQUEST_OF, url);
-
-            Either<Map<String, List<CatalogComponent>>, ResponseFormat> catalogData = getElementBL(request.getSession().getServletContext()).getCatalogComponents(userId, excludeTypes);
-
+            Either<Map<String, List<CatalogComponent>>, ResponseFormat> catalogData = getElementBL(request.getSession().getServletContext())
+                .getCatalogComponents(userId, excludeTypes);
             if (catalogData.isRight()) {
                 log.debug("failed to get catalog data");
                 return buildErrorResponse(catalogData.right().value());
             }
             Object data = RepresentationUtils.toRepresentation(catalogData.left().value());
             return buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), data);
-
         } catch (Exception e) {
             BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Get Catalog Components");
             log.debug("Getting catalog components failed with exception", e);
@@ -590,31 +532,27 @@ public class ElementServlet extends BeGenericServlet {
     public Response deleteMarkedResources(@PathParam("componentType") final String componentType, @Context final HttpServletRequest request) {
         String url = request.getMethod() + " " + request.getRequestURI();
         log.debug(START_HANDLE_REQUEST_OF, url);
-
         // get modifier id
         String userId = request.getHeader(Constants.USER_ID_HEADER);
         User modifier = new User();
         modifier.setUserId(userId);
         log.debug("modifier id is {}", userId);
-
         NodeTypeEnum nodeType = NodeTypeEnum.getByNameIgnoreCase(componentType);
         if (nodeType == null) {
             log.info("componentType is not valid: {}", componentType);
             return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.INVALID_CONTENT));
         }
-
         List<NodeTypeEnum> componentsList = new ArrayList<>();
         componentsList.add(nodeType);
         try {
-            Map<NodeTypeEnum, Either<List<String>, ResponseFormat>> cleanComponentsResult = componentsCleanBusinessLogic.cleanComponents(componentsList);
+            Map<NodeTypeEnum, Either<List<String>, ResponseFormat>> cleanComponentsResult = componentsCleanBusinessLogic
+                .cleanComponents(componentsList);
             Either<List<String>, ResponseFormat> cleanResult = cleanComponentsResult.get(nodeType);
-
             if (cleanResult.isRight()) {
                 log.debug("failed to delete marked components of type {}", nodeType);
                 return buildErrorResponse(cleanResult.right().value());
             }
             return buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), cleanResult.left().value());
-
         } catch (Exception e) {
             BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Delete Marked Components");
             log.debug("delete marked components failed with exception", e);
@@ -626,57 +564,46 @@ public class ElementServlet extends BeGenericServlet {
     @Path("/ecompPortalMenu")
     @Consumes(MediaType.APPLICATION_JSON)
     @Produces(MediaType.APPLICATION_JSON)
-    @Operation(description = "Retrieve ecomp portal menu - MOC", method = "GET", summary = "Retrieve ecomp portal menu",
-            responses = {@ApiResponse(
-                    content = @Content(array = @ArraySchema(schema = @Schema(implementation = User.class)))),
-                    @ApiResponse(responseCode = "200", description = "Retrieve ecomp portal menu")})
+    @Operation(description = "Retrieve ecomp portal menu - MOC", method = "GET", summary = "Retrieve ecomp portal menu", responses = {
+        @ApiResponse(content = @Content(array = @ArraySchema(schema = @Schema(implementation = User.class)))),
+        @ApiResponse(responseCode = "200", description = "Retrieve ecomp portal menu")})
     @PermissionAllowed(AafPermission.PermNames.INTERNAL_ALL_VALUE)
     public Response getListOfCsars(@Context final HttpServletRequest request) {
         return buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK),
-                "[{\"menuId\":1,\"column\":2,\"text\":\"Design\",\"parentMenuId\":null,\"url\":\"\",\"appid\":null,\"roles\":null,\"children\":[{\"menuId\":11,\"column\":1,\"text\":\"ProductDesign\",\"parentMenuId\":1,\"url\":\"\",\"appid\":null,\"roles\":null},{\"menuId\":12,\"column\":2,\"text\":\"Service\",\"parentMenuId\":1,\"url\":\"\",\"appid\":null,\"roles\":null,\"children\":[{\"menuId\":21,\"column\":1,\"text\":\"ViewPolicies\",\"parentMenuId\":12,\"url\":\"\",\"appid\":null,\"roles\":null,\"children\":[{\"menuId\":90,\"column\":1,\"text\":\"4thLevelApp1aR16\",\"parentMenuId\":21,\"url\":\"http://google.com\",\"appid\":null,\"roles\":null}]},{\"menuId\":22,\"column\":2,\"text\":\"UpdatePolicies\",\"parentMenuId\":12,\"url\":\"\",\"appid\":null,\"roles\":null,\"children\":[{\"menuId\":91,\"column\":1,\"text\":\"4thLevelApp1bR16\",\"parentMenuId\":22,\"url\":\"http://jsonlint.com/\",\"appid\":null,\"roles\":null}]},{\"menuId\":23,\"column\":3,\"text\":\"UpdateRules\",\"parentMenuId\":12,\"url\":\"\",\"appid\":null,\"roles\":null},{\"menuId\":24,\"column\":4,\"text\":\"CreateSignatures?\",\"parentMenuId\":12,\"url\":\"\",\"appid\":null,\"roles\":null},{\"menuId\":25,\"column\":5,\"text\":\"Definedata\",\"parentMenuId\":12,\"url\":\"\",\"appid\":null,\"roles\":null}]}]}]");
+            "[{\"menuId\":1,\"column\":2,\"text\":\"Design\",\"parentMenuId\":null,\"url\":\"\",\"appid\":null,\"roles\":null,\"children\":[{\"menuId\":11,\"column\":1,\"text\":\"ProductDesign\",\"parentMenuId\":1,\"url\":\"\",\"appid\":null,\"roles\":null},{\"menuId\":12,\"column\":2,\"text\":\"Service\",\"parentMenuId\":1,\"url\":\"\",\"appid\":null,\"roles\":null,\"children\":[{\"menuId\":21,\"column\":1,\"text\":\"ViewPolicies\",\"parentMenuId\":12,\"url\":\"\",\"appid\":null,\"roles\":null,\"children\":[{\"menuId\":90,\"column\":1,\"text\":\"4thLevelApp1aR16\",\"parentMenuId\":21,\"url\":\"http://google.com\",\"appid\":null,\"roles\":null}]},{\"menuId\":22,\"column\":2,\"text\":\"UpdatePolicies\",\"parentMenuId\":12,\"url\":\"\",\"appid\":null,\"roles\":null,\"children\":[{\"menuId\":91,\"column\":1,\"text\":\"4thLevelApp1bR16\",\"parentMenuId\":22,\"url\":\"http://jsonlint.com/\",\"appid\":null,\"roles\":null}]},{\"menuId\":23,\"column\":3,\"text\":\"UpdateRules\",\"parentMenuId\":12,\"url\":\"\",\"appid\":null,\"roles\":null},{\"menuId\":24,\"column\":4,\"text\":\"CreateSignatures?\",\"parentMenuId\":12,\"url\":\"\",\"appid\":null,\"roles\":null},{\"menuId\":25,\"column\":5,\"text\":\"Definedata\",\"parentMenuId\":12,\"url\":\"\",\"appid\":null,\"roles\":null}]}]}]");
     }
 
     @GET
     @Path("/catalogUpdateTime")
     @Consumes(MediaType.APPLICATION_JSON)
     @Produces(MediaType.APPLICATION_JSON)
-    @Operation(description = "Retrieve previus and current catalog update time", method = "GET",
-            summary = "Retrieve previus and current catalog update time", responses = {
-            @ApiResponse(content = @Content(array = @ArraySchema(schema = @Schema(implementation = Response.class)))),
-            @ApiResponse(responseCode = "200", description = "Retrieve previus and current catalog update time")})
+    @Operation(description = "Retrieve previus and current catalog update time", method = "GET", summary = "Retrieve previus and current catalog update time", responses = {
+        @ApiResponse(content = @Content(array = @ArraySchema(schema = @Schema(implementation = Response.class)))),
+        @ApiResponse(responseCode = "200", description = "Retrieve previus and current catalog update time")})
     @PermissionAllowed(AafPermission.PermNames.INTERNAL_ALL_VALUE)
     public Response getCatalogUpdateTime(@Context final HttpServletRequest request, @HeaderParam(value = Constants.USER_ID_HEADER) String userId) {
-
-
         String url = request.getMethod() + " " + request.getRequestURI();
         log.debug("(post) Start handle request of {}", url);
         CatalogUpdateTimestamp catalogUpdateTimestamp = getElementBL(request.getSession().getServletContext()).getCatalogUpdateTime(userId);
-
-        return buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK),
-                catalogUpdateTimestamp);
+        return buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), catalogUpdateTimestamp);
     }
 
-
     // retrieve all artifact types, ui configuration and sdc version
     @GET
     @Path("/setup/ui")
     @Consumes(MediaType.APPLICATION_JSON)
     @Produces(MediaType.APPLICATION_JSON)
-    @Operation(description = "Retrieve all artifactTypes, ui configuration and sdc version", method = "GET",
-            summary = "Retrieve all artifactTypes, ui configuration and sdc version", responses = {
-            @ApiResponse(content = @Content(array = @ArraySchema(schema = @Schema(implementation = User.class)))),
-            @ApiResponse(responseCode = "200",
-                    description = "Returns artifactTypes, ui configuration and sdc version Ok"),
-            @ApiResponse(responseCode = "404",
-                    description = "No artifactTypes were found/no ui configuration were found/no sdc version were found"),
-            @ApiResponse(responseCode = "500", description = "Internal Server Error")})
+    @Operation(description = "Retrieve all artifactTypes, ui configuration and sdc version", method = "GET", summary = "Retrieve all artifactTypes, ui configuration and sdc version", responses = {
+        @ApiResponse(content = @Content(array = @ArraySchema(schema = @Schema(implementation = User.class)))),
+        @ApiResponse(responseCode = "200", description = "Returns artifactTypes, ui configuration and sdc version Ok"),
+        @ApiResponse(responseCode = "404", description = "No artifactTypes were found/no ui configuration were found/no sdc version were found"),
+        @ApiResponse(responseCode = "500", description = "Internal Server Error")})
     @PermissionAllowed(AafPermission.PermNames.INTERNAL_ALL_VALUE)
-    public Response getConfCategoriesAndVersion(@Context final HttpServletRequest request, @HeaderParam(value = Constants.USER_ID_HEADER) String userId) {
+    public Response getConfCategoriesAndVersion(@Context final HttpServletRequest request,
+                                                @HeaderParam(value = Constants.USER_ID_HEADER) String userId) {
         String url = request.getMethod() + " " + request.getRequestURI();
         log.debug("(getConsolidated) Start handle request of {}", url);
-
         Map<String, Object> consolidatedObject = new HashMap<>();
-
         try {
             ServletContext servletContext = request.getSession().getServletContext();
             Map<String, Object> configuration = getConfigurationUi(elementBusinessLogic);
@@ -685,22 +612,18 @@ public class ElementServlet extends BeGenericServlet {
             } else {
                 return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.NO_CONTENT));
             }
-
             Either<UiCategories, ResponseFormat> either = elementBusinessLogic.getAllCategories(userId);
             if (either.isRight()) {
                 log.debug("No categories were found");
                 return buildErrorResponse(either.right().value());
             }
             consolidatedObject.put("categories", either.left().value());
-
             consolidatedObject.put("version", getVersion(servletContext));
-
         } catch (Exception e) {
             BeEcompErrorManager.getInstance().logBeRestApiGeneralError("getSDCVersion");
             log.debug("method getConfCategoriesAndVersion failed with unexpected exception", e);
             throw e;
         }
-
         return buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), consolidatedObject);
     }
 
@@ -713,9 +636,7 @@ public class ElementServlet extends BeGenericServlet {
     private Map<String, Object> getConfigurationUi(final ElementBusinessLogic elementBL) {
         Either<Configuration.HeatDeploymentArtifactTimeout, ActionStatus> defaultHeatTimeout = elementBL.getDefaultHeatTimeout();
         Either<Map<String, String>, ActionStatus> resourceTypesMap = elementBL.getResourceTypesMap();
-
         Map<String, Object> configuration = new HashMap<>();
-
         if (defaultHeatTimeout.isRight() || defaultHeatTimeout.left().value() == null) {
             log.debug("heat default timeout was not found");
             return configuration;
@@ -731,8 +652,6 @@ public class ElementServlet extends BeGenericServlet {
         configuration.put("resourceTypes", resourceTypesMap.left().value());
         configuration.put("environmentContext", ConfigurationManager.getConfigurationManager().getConfiguration().getEnvironmentContext());
         configuration.put("gab", ConfigurationManager.getConfigurationManager().getConfiguration().getGabConfig());
-
         return configuration;
     }
 }
-
index 7603d49..ff31aa5 100644 (file)
@@ -17,7 +17,6 @@
  * limitations under the License.
  * ============LICENSE_END=========================================================
  */
-
 package org.openecomp.sdc.be.servlets;
 
 import com.google.gson.Gson;
@@ -31,17 +30,16 @@ import io.swagger.v3.oas.annotations.servers.Server;
 import io.swagger.v3.oas.annotations.servers.Servers;
 import io.swagger.v3.oas.annotations.tags.Tag;
 import io.swagger.v3.oas.annotations.tags.Tags;
-import org.openecomp.sdc.be.dao.api.ActionStatus;
-import org.openecomp.sdc.be.impl.ComponentsUtils;
-import org.openecomp.sdc.common.log.wrappers.Logger;
-import org.openecomp.sdc.exception.ResponseFormat;
-import org.springframework.stereotype.Controller;
-
 import javax.ws.rs.GET;
 import javax.ws.rs.Path;
 import javax.ws.rs.Produces;
 import javax.ws.rs.core.MediaType;
 import javax.ws.rs.core.Response;
+import org.openecomp.sdc.be.dao.api.ActionStatus;
+import org.openecomp.sdc.be.impl.ComponentsUtils;
+import org.openecomp.sdc.common.log.wrappers.Logger;
+import org.openecomp.sdc.exception.ResponseFormat;
+import org.springframework.stereotype.Controller;
 
 @Loggable(prepend = true, value = Loggable.DEBUG, trim = false)
 @Path("/v1/catalog")
@@ -50,6 +48,7 @@ import javax.ws.rs.core.Response;
 @Produces(MediaType.APPLICATION_JSON)
 @Controller
 public class ExceptionHandlerEndpoint {
+
     private static final Logger log = Logger.getLogger(ExceptionHandlerEndpoint.class);
     private final Gson gson = new GsonBuilder().setPrettyPrinting().create();
     private final ComponentsUtils componentsUtils;
@@ -61,14 +60,10 @@ public class ExceptionHandlerEndpoint {
     @GET
     @Path("/handleException")
     @Operation(description = "Handle exception", method = "GET", responses = {
-            @ApiResponse(responseCode = "500", description = "Internal Error",
-                    content = @Content(schema = @Schema(implementation = Response.class)))})
+        @ApiResponse(responseCode = "500", description = "Internal Error", content = @Content(schema = @Schema(implementation = Response.class)))})
     public Response sendError() {
         log.debug("Request is received");
-
         ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR);
-        return Response.status(responseFormat.getStatus())
-                .entity(gson.toJson(responseFormat.getRequestError()))
-                .build();
+        return Response.status(responseFormat.getStatus()).entity(gson.toJson(responseFormat.getRequestError())).build();
     }
 }
index be106a1..df83035 100644 (file)
@@ -17,7 +17,6 @@
  * limitations under the License.
  * ============LICENSE_END=========================================================
  */
-
 package org.openecomp.sdc.be.servlets;
 
 import com.jcabi.aspects.Loggable;
@@ -31,6 +30,19 @@ import io.swagger.v3.oas.annotations.servers.Server;
 import io.swagger.v3.oas.annotations.servers.Servers;
 import io.swagger.v3.oas.annotations.tags.Tag;
 import io.swagger.v3.oas.annotations.tags.Tags;
+import java.io.IOException;
+import java.util.Set;
+import java.util.stream.Collectors;
+import javax.inject.Inject;
+import javax.servlet.ServletContext;
+import javax.servlet.http.HttpServletRequest;
+import javax.ws.rs.Consumes;
+import javax.ws.rs.POST;
+import javax.ws.rs.Path;
+import javax.ws.rs.Produces;
+import javax.ws.rs.core.Context;
+import javax.ws.rs.core.MediaType;
+import javax.ws.rs.core.Response;
 import org.apache.commons.lang3.tuple.ImmutablePair;
 import org.onap.sdc.gab.model.GABQuery;
 import org.onap.sdc.gab.model.GABQuery.GABQueryType;
@@ -43,20 +55,6 @@ import org.openecomp.sdc.common.log.wrappers.Logger;
 import org.owasp.esapi.ESAPI;
 import org.springframework.stereotype.Controller;
 
-import javax.inject.Inject;
-import javax.servlet.ServletContext;
-import javax.servlet.http.HttpServletRequest;
-import javax.ws.rs.Consumes;
-import javax.ws.rs.POST;
-import javax.ws.rs.Path;
-import javax.ws.rs.Produces;
-import javax.ws.rs.core.Context;
-import javax.ws.rs.core.MediaType;
-import javax.ws.rs.core.Response;
-import java.io.IOException;
-import java.util.Set;
-import java.util.stream.Collectors;
-
 @Loggable(prepend = true, value = Loggable.DEBUG, trim = false)
 @Path("/v1/catalog/gab")
 @Consumes(MediaType.APPLICATION_JSON)
@@ -71,10 +69,8 @@ public class GenericArtifactBrowserServlet extends BeGenericServlet {
     private final ArtifactsBusinessLogic artifactsBusinessLogic;
 
     @Inject
-    public GenericArtifactBrowserServlet(UserBusinessLogic userBusinessLogic,
-        ComponentsUtils componentsUtils,
-        ArtifactsBusinessLogic artifactsBusinessLogic,
-        GenericArtifactBrowserBusinessLogic gabLogic) {
+    public GenericArtifactBrowserServlet(UserBusinessLogic userBusinessLogic, ComponentsUtils componentsUtils,
+                                         ArtifactsBusinessLogic artifactsBusinessLogic, GenericArtifactBrowserBusinessLogic gabLogic) {
         super(userBusinessLogic, componentsUtils);
         this.artifactsBusinessLogic = artifactsBusinessLogic;
         this.gabLogic = gabLogic;
@@ -82,14 +78,12 @@ public class GenericArtifactBrowserServlet extends BeGenericServlet {
 
     @POST
     @Path("/searchFor")
-    @Operation(description = "Search json paths inside the yaml", method = "POST",
-            summary = "Returns found entries of json paths", responses = {
-            @ApiResponse(content = @Content(array = @ArraySchema(schema = @Schema(implementation = Response.class)))),
-            @ApiResponse(responseCode = "200", description = "Returned yaml entries"),
-            @ApiResponse(responseCode = "400", description = "Invalid content / Missing content")})
-    public Response searchFor(
-        @Parameter(description = "Generic Artifact search model", required = true) GenericArtifactQueryInfo query,
-        @Context final HttpServletRequest request) {
+    @Operation(description = "Search json paths inside the yaml", method = "POST", summary = "Returns found entries of json paths", responses = {
+        @ApiResponse(content = @Content(array = @ArraySchema(schema = @Schema(implementation = Response.class)))),
+        @ApiResponse(responseCode = "200", description = "Returned yaml entries"),
+        @ApiResponse(responseCode = "400", description = "Invalid content / Missing content")})
+    public Response searchFor(@Parameter(description = "Generic Artifact search model", required = true) GenericArtifactQueryInfo query,
+                              @Context final HttpServletRequest request) {
         try {
             ServletContext context = request.getSession().getServletContext();
             ImmutablePair<String, byte[]> immutablePairResponseFormatEither = getArtifactBL(context)
@@ -102,11 +96,9 @@ public class GenericArtifactBrowserServlet extends BeGenericServlet {
         }
     }
 
-    private GABQuery prepareGabQuery(GenericArtifactQueryInfo query,
-        ImmutablePair<String, byte[]> immutablePairResponseFormatEither) {
+    private GABQuery prepareGabQuery(GenericArtifactQueryInfo query, ImmutablePair<String, byte[]> immutablePairResponseFormatEither) {
         byte[] content = immutablePairResponseFormatEither.getRight();
         Set<String> queryFields = query.getFields().stream().map(ESAPI.encoder()::canonicalize).collect(Collectors.toSet());
         return new GABQuery(queryFields, new String(content), GABQueryType.CONTENT);
     }
-
 }
index a820125..7b2b22e 100644 (file)
@@ -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.
@@ -17,7 +17,6 @@
  * limitations under the License.
  * ============LICENSE_END=========================================================
  */
-
 package org.openecomp.sdc.be.servlets;
 
 import com.jcabi.aspects.Loggable;
@@ -66,70 +65,65 @@ import org.springframework.stereotype.Controller;
 @Controller
 @Consumes(MediaType.APPLICATION_JSON)
 @Produces(MediaType.APPLICATION_JSON)
-public class GroupEndpoint extends BeGenericServlet{
+public class GroupEndpoint extends BeGenericServlet {
 
-    private final GroupBusinessLogicNew groupBusinessLogic;
     private static final LoggerSupportability loggerSupportability = LoggerSupportability.getLogger(GroupEndpoint.class.getName());
+    private final GroupBusinessLogicNew groupBusinessLogic;
 
     @Inject
-    public GroupEndpoint(UserBusinessLogic userBusinessLogic,
-                         ComponentsUtils componentsUtils, GroupBusinessLogicNew groupBusinessLogic) {
+    public GroupEndpoint(UserBusinessLogic userBusinessLogic, ComponentsUtils componentsUtils, GroupBusinessLogicNew groupBusinessLogic) {
         super(userBusinessLogic, componentsUtils);
         this.groupBusinessLogic = groupBusinessLogic;
     }
 
     @POST
     @Path("/{containerComponentType}/{componentId}/groups/{groupUniqueId}/members")
-    @Operation(description = "Update group members ", method = "POST",
-            summary = "Updates list of members and returns it", responses = {
-            @ApiResponse(content = @Content(array = @ArraySchema(schema = @Schema(implementation = String.class)))),
-            @ApiResponse(responseCode = "200", description = "Group members updated"),
-            @ApiResponse(responseCode = "400",
-                    description = "field name invalid type/length, characters;  mandatory field is absent, already exists (name)"),
-            @ApiResponse(responseCode = "403", description = "Restricted operation"),
-            @ApiResponse(responseCode = "404", description = "Component not found"),
-            @ApiResponse(responseCode = "500", description = "Internal Error")})
+    @Operation(description = "Update group members ", method = "POST", summary = "Updates list of members and returns it", responses = {
+        @ApiResponse(content = @Content(array = @ArraySchema(schema = @Schema(implementation = String.class)))),
+        @ApiResponse(responseCode = "200", description = "Group members updated"),
+        @ApiResponse(responseCode = "400", description = "field name invalid type/length, characters;  mandatory field is absent, already exists (name)"),
+        @ApiResponse(responseCode = "403", description = "Restricted operation"),
+        @ApiResponse(responseCode = "404", description = "Component not found"), @ApiResponse(responseCode = "500", description = "Internal Error")})
     @PermissionAllowed(AafPermission.PermNames.INTERNAL_ALL_VALUE)
     public List<String> updateGroupMembers(@PathParam("containerComponentType") final String containerComponentType,
-            @PathParam("componentId") final String componentId, @PathParam("groupUniqueId") final String groupUniqueId,
-            @Parameter(description = "List of members unique ids", required = true) List<String> members,
-            @HeaderParam(value = Constants.USER_ID_HEADER) String userId) {
-        loggerSupportability.log(LoggerSupportabilityActions.UPDATE_GROUP_MEMBERS, StatusCode.STARTED," Starting to update Group Members for component {} " , componentId );
+                                           @PathParam("componentId") final String componentId, @PathParam("groupUniqueId") final String groupUniqueId,
+                                           @Parameter(description = "List of members unique ids", required = true) List<String> members,
+                                           @HeaderParam(value = Constants.USER_ID_HEADER) String userId) {
+        loggerSupportability
+            .log(LoggerSupportabilityActions.UPDATE_GROUP_MEMBERS, StatusCode.STARTED, " Starting to update Group Members for component {} ",
+                componentId);
         ComponentTypeEnum componentTypeEnum = ComponentTypeEnum.findByParamName(containerComponentType);
-        loggerSupportability.log(LoggerSupportabilityActions.UPDATE_GROUP_MEMBERS, StatusCode.COMPLETE," Ended update Group Members for component {} " , componentId );
+        loggerSupportability
+            .log(LoggerSupportabilityActions.UPDATE_GROUP_MEMBERS, StatusCode.COMPLETE, " Ended update Group Members for component {} ", componentId);
         return groupBusinessLogic.updateMembers(componentId, componentTypeEnum, userId, groupUniqueId, members);
     }
 
     @GET
     @Path("/{containerComponentType}/{componentId}/groups/{groupUniqueId}/properties")
-    @Operation(description = "Get List of properties on a group", method = "GET",
-            summary = "Returns list of properties", responses = {@ApiResponse(
-            content = @Content(array = @ArraySchema(schema = @Schema(implementation = GroupProperty.class)))),
-            @ApiResponse(responseCode = "200", description = "Group Updated"),
-            @ApiResponse(responseCode = "403", description = "Restricted operation"),
-            @ApiResponse(responseCode = "400", description = "Invalid content / Missing content")})
+    @Operation(description = "Get List of properties on a group", method = "GET", summary = "Returns list of properties", responses = {
+        @ApiResponse(content = @Content(array = @ArraySchema(schema = @Schema(implementation = GroupProperty.class)))),
+        @ApiResponse(responseCode = "200", description = "Group Updated"), @ApiResponse(responseCode = "403", description = "Restricted operation"),
+        @ApiResponse(responseCode = "400", description = "Invalid content / Missing content")})
     @PermissionAllowed(AafPermission.PermNames.INTERNAL_ALL_VALUE)
-    public List<PropertyDataDefinition> getGroupProperties(
-            @PathParam("containerComponentType") final String containerComponentType,
-            @PathParam("componentId") final String componentId, @PathParam("groupUniqueId") final String groupUniqueId,
-            @HeaderParam(value = Constants.USER_ID_HEADER) String userId) {
+    public List<PropertyDataDefinition> getGroupProperties(@PathParam("containerComponentType") final String containerComponentType,
+                                                           @PathParam("componentId") final String componentId,
+                                                           @PathParam("groupUniqueId") final String groupUniqueId,
+                                                           @HeaderParam(value = Constants.USER_ID_HEADER) String userId) {
         return groupBusinessLogic.getProperties(containerComponentType, userId, componentId, groupUniqueId);
     }
 
     @PUT
     @Path("/{containerComponentType}/{componentId}/groups/{groupUniqueId}/properties")
-    @Operation(description = "Updates List of properties on a group (only values)", method = "PUT",
-            summary = "Returns updated list of properties", responses = {@ApiResponse(
-            content = @Content(array = @ArraySchema(schema = @Schema(implementation = GroupProperty.class)))),
-            @ApiResponse(responseCode = "200", description = "Group Updated"),
-            @ApiResponse(responseCode = "403", description = "Restricted operation"),
-            @ApiResponse(responseCode = "400", description = "Invalid content / Missing content")})
+    @Operation(description = "Updates List of properties on a group (only values)", method = "PUT", summary = "Returns updated list of properties", responses = {
+        @ApiResponse(content = @Content(array = @ArraySchema(schema = @Schema(implementation = GroupProperty.class)))),
+        @ApiResponse(responseCode = "200", description = "Group Updated"), @ApiResponse(responseCode = "403", description = "Restricted operation"),
+        @ApiResponse(responseCode = "400", description = "Invalid content / Missing content")})
     @PermissionAllowed(AafPermission.PermNames.INTERNAL_ALL_VALUE)
-    public List<GroupProperty> updateGroupProperties(
-            @PathParam("containerComponentType") final String containerComponentType,
-            @PathParam("componentId") final String componentId, @PathParam("groupUniqueId") final String groupUniqueId,
-            @Parameter(description = "Group Properties to be Updated", required = true) List<GroupProperty> properties,
-            @HeaderParam(value = Constants.USER_ID_HEADER) String userId) {
+    public List<GroupProperty> updateGroupProperties(@PathParam("containerComponentType") final String containerComponentType,
+                                                     @PathParam("componentId") final String componentId,
+                                                     @PathParam("groupUniqueId") final String groupUniqueId,
+                                                     @Parameter(description = "Group Properties to be Updated", required = true) List<GroupProperty> properties,
+                                                     @HeaderParam(value = Constants.USER_ID_HEADER) String userId) {
         ComponentTypeEnum componentTypeEnum = ComponentTypeEnum.findByParamName(containerComponentType);
         return groupBusinessLogic.updateProperties(componentId, componentTypeEnum, userId, groupUniqueId, properties);
     }
index d1998d8..0dcbf8c 100644 (file)
@@ -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.
@@ -17,7 +17,6 @@
  * limitations under the License.
  * ============LICENSE_END=========================================================
  */
-
 package org.openecomp.sdc.be.servlets;
 
 import com.jcabi.aspects.Loggable;
@@ -79,117 +78,96 @@ import org.springframework.stereotype.Controller;
 @Controller
 public class GroupServlet extends AbstractValidationsServlet {
 
-    private static final Logger log = Logger.getLogger(GroupServlet.class);
     public static final String START_HANDLE_REQUEST = "Start handle request of {}";
+    private static final Logger log = Logger.getLogger(GroupServlet.class);
     private final GroupBusinessLogic groupBL;
 
     @Inject
-    public GroupServlet(UserBusinessLogic userBusinessLogic, GroupBusinessLogic groupBL,
-            ComponentInstanceBusinessLogic componentInstanceBL, ComponentsUtils componentsUtils,
-            ServletUtils servletUtils, ResourceImportManager resourceImportManager) {
+    public GroupServlet(UserBusinessLogic userBusinessLogic, GroupBusinessLogic groupBL, ComponentInstanceBusinessLogic componentInstanceBL,
+                        ComponentsUtils componentsUtils, ServletUtils servletUtils, ResourceImportManager resourceImportManager) {
         super(userBusinessLogic, componentInstanceBL, componentsUtils, servletUtils, resourceImportManager);
         this.groupBL = groupBL;
     }
 
     @POST
     @Path("/{containerComponentType}/{componentId}/groups/{groupType}")
-    @Operation(description = "Create group ", method = "POST",
-            summary = "Creates new group in component and returns it", responses = {@ApiResponse(
-            content = @Content(array = @ArraySchema(schema = @Schema(implementation = GroupDefinition.class)))),
-            @ApiResponse(responseCode = "201", description = "Group created"), @ApiResponse(responseCode = "400",
-            description = "field name invalid type/length, characters;  mandatory field is absent, already exists (name)"),
-            @ApiResponse(responseCode = "403", description = "Restricted operation"),
-            @ApiResponse(responseCode = "404", description = "Component not found"),
-            @ApiResponse(responseCode = "500", description = "Internal Error")})
+    @Operation(description = "Create group ", method = "POST", summary = "Creates new group in component and returns it", responses = {
+        @ApiResponse(content = @Content(array = @ArraySchema(schema = @Schema(implementation = GroupDefinition.class)))),
+        @ApiResponse(responseCode = "201", description = "Group created"),
+        @ApiResponse(responseCode = "400", description = "field name invalid type/length, characters;  mandatory field is absent, already exists (name)"),
+        @ApiResponse(responseCode = "403", description = "Restricted operation"),
+        @ApiResponse(responseCode = "404", description = "Component not found"), @ApiResponse(responseCode = "500", description = "Internal Error")})
     @PermissionAllowed(AafPermission.PermNames.INTERNAL_ALL_VALUE)
     public Response createGroup(@PathParam("containerComponentType") final String containerComponentType,
-            @PathParam("componentId") final String componentId, @PathParam("groupType") final String type,
-            @Context final HttpServletRequest request, @HeaderParam(value = Constants.USER_ID_HEADER) String userId) {
+                                @PathParam("componentId") final String componentId, @PathParam("groupType") final String type,
+                                @Context final HttpServletRequest request, @HeaderParam(value = Constants.USER_ID_HEADER) String userId) {
         String url = request.getMethod() + " " + request.getRequestURI();
         log.debug("(post) Start handle request of {}", url);
-
         ComponentTypeEnum componentTypeEnum = ComponentTypeEnum.findByParamName(containerComponentType);
-        GroupDefinition groupDefinition = groupBL
-                .createGroup(componentId, componentTypeEnum, type, userId);
-
-        return buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.CREATED),
-                groupDefinition);
+        GroupDefinition groupDefinition = groupBL.createGroup(componentId, componentTypeEnum, type, userId);
+        return buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.CREATED), groupDefinition);
     }
 
     @GET
     @Path("/{containerComponentType}/{componentId}/groups/{groupId}")
-    @Operation(description = "Get group artifacts ", method = "GET",
-            summary = "Returns artifacts metadata according to groupId", responses = {
-            @ApiResponse(content = @Content(array = @ArraySchema(schema = @Schema(implementation = Resource.class)))),
-            @ApiResponse(responseCode = "200", description = "group found"),
-            @ApiResponse(responseCode = "403", description = "Restricted operation"),
-            @ApiResponse(responseCode = "404", description = "Group not found")})
+    @Operation(description = "Get group artifacts ", method = "GET", summary = "Returns artifacts metadata according to groupId", responses = {
+        @ApiResponse(content = @Content(array = @ArraySchema(schema = @Schema(implementation = Resource.class)))),
+        @ApiResponse(responseCode = "200", description = "group found"), @ApiResponse(responseCode = "403", description = "Restricted operation"),
+        @ApiResponse(responseCode = "404", description = "Group not found")})
     @PermissionAllowed(AafPermission.PermNames.INTERNAL_ALL_VALUE)
     public Response getGroupById(@PathParam("containerComponentType") final String containerComponentType,
-            @PathParam("componentId") final String componentId, @PathParam("groupId") final String groupId,
-            @Context final HttpServletRequest request, @HeaderParam(value = Constants.USER_ID_HEADER) String userId) {
+                                 @PathParam("componentId") final String componentId, @PathParam("groupId") final String groupId,
+                                 @Context final HttpServletRequest request, @HeaderParam(value = Constants.USER_ID_HEADER) String userId) {
         String url = request.getMethod() + " " + request.getRequestURI();
         log.debug("(get) Start handle request of {}", url);
-
         try {
-
             ComponentTypeEnum componentTypeEnum = ComponentTypeEnum.findByParamName(containerComponentType);
-            Either<GroupDefinitionInfo, ResponseFormat> actionResponse =
-                    groupBL.getGroupWithArtifactsById(componentTypeEnum, componentId, groupId, userId, false);
-
+            Either<GroupDefinitionInfo, ResponseFormat> actionResponse = groupBL
+                .getGroupWithArtifactsById(componentTypeEnum, componentId, groupId, userId, false);
             if (actionResponse.isRight()) {
                 log.debug("failed to get all non abstract {}", containerComponentType);
                 return buildErrorResponse(actionResponse.right().value());
             }
-
-            return buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK),
-                    actionResponse.left().value());
-
+            return buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), actionResponse.left().value());
         } catch (Exception e) {
             BeEcompErrorManager.getInstance().logBeRestApiGeneralError("getGroupArtifactById");
             log.debug("getGroupArtifactById unexpected exception", e);
             throw e;
         }
-
     }
 
     @DELETE
     @Path("/{containerComponentType}/{componentId}/groups/{groupUniqueId}")
     @Operation(description = "Delete Group", method = "DELETE", summary = "Returns deleted group id", responses = {
-            @ApiResponse(content = @Content(array = @ArraySchema(schema = @Schema(implementation = Response.class)))),
-            @ApiResponse(responseCode = "201", description = "ResourceInstance deleted"),
-            @ApiResponse(responseCode = "400",
-                    description = "field name invalid type/length, characters;  mandatory field is absent, already exists (name)"),
-            @ApiResponse(responseCode = "403", description = "Restricted operation"),
-            @ApiResponse(responseCode = "404", description = "Component not found"),
-            @ApiResponse(responseCode = "500", description = "Internal Error")})
+        @ApiResponse(content = @Content(array = @ArraySchema(schema = @Schema(implementation = Response.class)))),
+        @ApiResponse(responseCode = "201", description = "ResourceInstance deleted"),
+        @ApiResponse(responseCode = "400", description = "field name invalid type/length, characters;  mandatory field is absent, already exists (name)"),
+        @ApiResponse(responseCode = "403", description = "Restricted operation"),
+        @ApiResponse(responseCode = "404", description = "Component not found"), @ApiResponse(responseCode = "500", description = "Internal Error")})
     @PermissionAllowed(AafPermission.PermNames.INTERNAL_ALL_VALUE)
     public Response deleteGroup(@PathParam("containerComponentType") final String containerComponentType,
-            @PathParam("componentId") final String componentId, @PathParam("groupUniqueId") final String groupId,
-            @Context final HttpServletRequest request, @HeaderParam(value = Constants.USER_ID_HEADER) String userId) {
+                                @PathParam("componentId") final String componentId, @PathParam("groupUniqueId") final String groupId,
+                                @Context final HttpServletRequest request, @HeaderParam(value = Constants.USER_ID_HEADER) String userId) {
         String url = request.getMethod() + " " + request.getRequestURI();
         log.debug(START_HANDLE_REQUEST, url);
         ComponentTypeEnum componentTypeEnum = ComponentTypeEnum.findByParamName(containerComponentType);
-        GroupDefinition groupDefinition = groupBL
-                .deleteGroup(componentId, componentTypeEnum, groupId, userId);
-
+        GroupDefinition groupDefinition = groupBL.deleteGroup(componentId, componentTypeEnum, groupId, userId);
         return buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.NO_CONTENT), groupDefinition.getUniqueId());
     }
 
     @PUT
     @Path("/{containerComponentType}/{componentId}/groups/{groupId}")
     @Operation(description = "Update Group metadata", method = "PUT", summary = "Returns updated Group", responses = {
-            @ApiResponse(content = @Content(array = @ArraySchema(schema = @Schema(implementation = Response.class)))),
-            @ApiResponse(responseCode = "200", description = "Group updated"),
-            @ApiResponse(responseCode = "403", description = "Restricted operation"),
-            @ApiResponse(responseCode = "400", description = "Invalid content / Missing content"),
-            @ApiResponse(responseCode = "404", description = "component / group Not found")})
+        @ApiResponse(content = @Content(array = @ArraySchema(schema = @Schema(implementation = Response.class)))),
+        @ApiResponse(responseCode = "200", description = "Group updated"), @ApiResponse(responseCode = "403", description = "Restricted operation"),
+        @ApiResponse(responseCode = "400", description = "Invalid content / Missing content"),
+        @ApiResponse(responseCode = "404", description = "component / group Not found")})
     @PermissionAllowed(AafPermission.PermNames.INTERNAL_ALL_VALUE)
     public Response updateGroup(@PathParam("containerComponentType") final String containerComponentType,
-            @PathParam("componentId") final String componentId, @PathParam("groupId") final String groupId,
-            @HeaderParam(value = Constants.USER_ID_HEADER) String userId,
-            @Parameter(description = "GroupDefinition", required = true) GroupDefinition groupData,
-            @Context final HttpServletRequest request) {
+                                @PathParam("componentId") final String componentId, @PathParam("groupId") final String groupId,
+                                @HeaderParam(value = Constants.USER_ID_HEADER) String userId,
+                                @Parameter(description = "GroupDefinition", required = true) GroupDefinition groupData,
+                                @Context final HttpServletRequest request) {
         ComponentTypeEnum componentTypeEnum = ComponentTypeEnum.findByParamName(containerComponentType);
         GroupDefinition updatedGroup = groupBL.updateGroup(componentId, componentTypeEnum, groupId, userId, groupData);
         return buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), updatedGroup);
@@ -199,25 +177,21 @@ public class GroupServlet extends AbstractValidationsServlet {
     @Path("/{containerComponentType}/{componentId}/groups/{groupUniqueId}/metadata")
     @Consumes(MediaType.APPLICATION_JSON)
     @Produces(MediaType.APPLICATION_JSON)
-    @Operation(description = "Update Group Metadata", method = "PUT", summary = "Returns updated group definition",
-            responses = {@ApiResponse(
-                    content = @Content(array = @ArraySchema(schema = @Schema(implementation = GroupDefinition.class)))),
-                    @ApiResponse(responseCode = "200", description = "Group Updated"),
-                    @ApiResponse(responseCode = "403", description = "Restricted operation"),
-                    @ApiResponse(responseCode = "400", description = "Invalid content / Missing content")})
+    @Operation(description = "Update Group Metadata", method = "PUT", summary = "Returns updated group definition", responses = {
+        @ApiResponse(content = @Content(array = @ArraySchema(schema = @Schema(implementation = GroupDefinition.class)))),
+        @ApiResponse(responseCode = "200", description = "Group Updated"), @ApiResponse(responseCode = "403", description = "Restricted operation"),
+        @ApiResponse(responseCode = "400", description = "Invalid content / Missing content")})
     @PermissionAllowed(AafPermission.PermNames.INTERNAL_ALL_VALUE)
     public Response updateGroupMetadata(@PathParam("containerComponentType") final String containerComponentType,
-            @PathParam("componentId") final String componentId, @PathParam("groupUniqueId") final String groupUniqueId,
-            @Parameter(description = "Service object to be Updated", required = true) String data,
-            @Context final HttpServletRequest request, @HeaderParam(value = Constants.USER_ID_HEADER) String userId) throws IOException {
-
+                                        @PathParam("componentId") final String componentId, @PathParam("groupUniqueId") final String groupUniqueId,
+                                        @Parameter(description = "Service object to be Updated", required = true) String data,
+                                        @Context final HttpServletRequest request, @HeaderParam(value = Constants.USER_ID_HEADER) String userId)
+        throws IOException {
         String url = request.getMethod() + " " + request.getRequestURI();
         log.debug(START_HANDLE_REQUEST, url);
-
         User user = new User();
         user.setUserId(userId);
         log.debug("modifier id is {}", userId);
-
         try {
             Either<GroupDefinition, ResponseFormat> convertResponse = parseToObject(data, () -> GroupDefinition.class);
             if (convertResponse.isRight()) {
@@ -225,26 +199,21 @@ public class GroupServlet extends AbstractValidationsServlet {
                 return buildErrorResponse(convertResponse.right().value());
             }
             GroupDefinition updatedGroup = convertResponse.left().value();
-
             // Update GroupDefinition
             ComponentTypeEnum componentTypeEnum = ComponentTypeEnum.findByParamName(containerComponentType);
             Either<GroupDefinition, ResponseFormat> actionResponse = groupBL
-                    .validateAndUpdateGroupMetadata(componentId, user, componentTypeEnum, updatedGroup, true ,true);
-
+                .validateAndUpdateGroupMetadata(componentId, user, componentTypeEnum, updatedGroup, true, true);
             if (actionResponse.isRight()) {
                 log.debug("failed to update GroupDefinition");
                 return buildErrorResponse(actionResponse.right().value());
             }
-
             GroupDefinition group = actionResponse.left().value();
             Object result = RepresentationUtils.toRepresentation(group);
             return buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), result);
-
         } catch (Exception e) {
             BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Update Group Metadata");
             log.debug("update group metadata failed with exception", e);
             throw e;
         }
     }
-
 }
index 69c51a6..afce970 100644 (file)
@@ -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.
@@ -17,7 +17,6 @@
  * limitations under the License.
  * ============LICENSE_END=========================================================
  */
-
 package org.openecomp.sdc.be.servlets;
 
 import com.jcabi.aspects.Loggable;
@@ -31,6 +30,14 @@ import io.swagger.v3.oas.annotations.servers.Server;
 import io.swagger.v3.oas.annotations.servers.Servers;
 import io.swagger.v3.oas.annotations.tags.Tag;
 import io.swagger.v3.oas.annotations.tags.Tags;
+import java.util.List;
+import javax.ws.rs.Consumes;
+import javax.ws.rs.GET;
+import javax.ws.rs.HeaderParam;
+import javax.ws.rs.Path;
+import javax.ws.rs.Produces;
+import javax.ws.rs.QueryParam;
+import javax.ws.rs.core.MediaType;
 import org.openecomp.sdc.be.components.impl.GroupTypeBusinessLogic;
 import org.openecomp.sdc.be.components.impl.aaf.AafPermission;
 import org.openecomp.sdc.be.components.impl.aaf.PermissionAllowed;
@@ -42,15 +49,6 @@ import org.openecomp.sdc.be.view.ResponseView;
 import org.openecomp.sdc.common.api.Constants;
 import org.springframework.stereotype.Controller;
 
-import javax.ws.rs.Consumes;
-import javax.ws.rs.GET;
-import javax.ws.rs.HeaderParam;
-import javax.ws.rs.Path;
-import javax.ws.rs.Produces;
-import javax.ws.rs.QueryParam;
-import javax.ws.rs.core.MediaType;
-import java.util.List;
-
 @Loggable(prepend = true, value = Loggable.DEBUG, trim = false)
 @Path("/v1/catalog")
 @Tags({@Tag(name = "SDC Internal APIs")})
@@ -58,12 +56,11 @@ import java.util.List;
 @Controller
 @Consumes(MediaType.APPLICATION_JSON)
 @Produces(MediaType.APPLICATION_JSON)
-public class GroupTypesEndpoint extends BeGenericServlet{
+public class GroupTypesEndpoint extends BeGenericServlet {
 
     private final GroupTypeBusinessLogic groupTypeBusinessLogic;
 
-    public GroupTypesEndpoint(UserBusinessLogic userBusinessLogic,
-        ComponentsUtils componentsUtils, GroupTypeBusinessLogic groupTypeBusinessLogic) {
+    public GroupTypesEndpoint(UserBusinessLogic userBusinessLogic, ComponentsUtils componentsUtils, GroupTypeBusinessLogic groupTypeBusinessLogic) {
         super(userBusinessLogic, componentsUtils);
         this.groupTypeBusinessLogic = groupTypeBusinessLogic;
     }
@@ -71,18 +68,14 @@ public class GroupTypesEndpoint extends BeGenericServlet{
     @GET
     @Path("/groupTypes")
     @Operation(description = "Get group types ", method = "GET", summary = "Returns group types", responses = {
-            @ApiResponse(content = @Content(
-                    array = @ArraySchema(schema = @Schema(implementation = GroupTypeDefinition.class)))),
-            @ApiResponse(responseCode = "200", description = "group types found"), @ApiResponse(responseCode = "400",
-            description = "field name invalid type/length, characters;  mandatory field is absent, already exists (name)"),
-            @ApiResponse(responseCode = "403", description = "Restricted operation"),
-            @ApiResponse(responseCode = "500", description = "Internal Error")})
+        @ApiResponse(content = @Content(array = @ArraySchema(schema = @Schema(implementation = GroupTypeDefinition.class)))),
+        @ApiResponse(responseCode = "200", description = "group types found"),
+        @ApiResponse(responseCode = "400", description = "field name invalid type/length, characters;  mandatory field is absent, already exists (name)"),
+        @ApiResponse(responseCode = "403", description = "Restricted operation"), @ApiResponse(responseCode = "500", description = "Internal Error")})
     @ResponseView(mixin = {GroupTypeMixin.class})
     @PermissionAllowed(AafPermission.PermNames.INTERNAL_ALL_VALUE)
     public List<GroupTypeDefinition> getGroupTypes(@HeaderParam(value = Constants.USER_ID_HEADER) String userId,
-            @Parameter(
-                    description = "An optional parameter to indicate the type of the container from where this call is executed") @QueryParam("internalComponentType") String internalComponentType) {
+                                                   @Parameter(description = "An optional parameter to indicate the type of the container from where this call is executed") @QueryParam("internalComponentType") String internalComponentType) {
         return groupTypeBusinessLogic.getAllGroupTypes(userId, internalComponentType);
     }
-
 }
index 0d073b5..96a8a70 100644 (file)
@@ -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.
@@ -17,7 +17,6 @@
  * limitations under the License.
  * ============LICENSE_END=========================================================
  */
-
 package org.openecomp.sdc.be.servlets;
 
 import com.fasterxml.jackson.core.JsonProcessingException;
@@ -32,6 +31,23 @@ import io.swagger.v3.oas.annotations.media.Schema;
 import io.swagger.v3.oas.annotations.responses.ApiResponse;
 import io.swagger.v3.oas.annotations.servers.Server;
 import io.swagger.v3.oas.annotations.tags.Tag;
+import java.io.IOException;
+import java.util.Arrays;
+import java.util.List;
+import java.util.Map;
+import javax.inject.Inject;
+import javax.servlet.http.HttpServletRequest;
+import javax.ws.rs.Consumes;
+import javax.ws.rs.DELETE;
+import javax.ws.rs.GET;
+import javax.ws.rs.HeaderParam;
+import javax.ws.rs.POST;
+import javax.ws.rs.Path;
+import javax.ws.rs.PathParam;
+import javax.ws.rs.Produces;
+import javax.ws.rs.core.Context;
+import javax.ws.rs.core.MediaType;
+import javax.ws.rs.core.Response;
 import org.apache.commons.lang3.builder.ReflectionToStringBuilder;
 import org.openecomp.sdc.be.components.impl.ComponentInstanceBusinessLogic;
 import org.openecomp.sdc.be.components.impl.DataTypeBusinessLogic;
@@ -65,24 +81,6 @@ import org.openecomp.sdc.common.log.wrappers.Logger;
 import org.openecomp.sdc.exception.ResponseFormat;
 import org.springframework.stereotype.Controller;
 
-import javax.inject.Inject;
-import javax.servlet.http.HttpServletRequest;
-import javax.ws.rs.Consumes;
-import javax.ws.rs.DELETE;
-import javax.ws.rs.GET;
-import javax.ws.rs.HeaderParam;
-import javax.ws.rs.POST;
-import javax.ws.rs.Path;
-import javax.ws.rs.PathParam;
-import javax.ws.rs.Produces;
-import javax.ws.rs.core.Context;
-import javax.ws.rs.core.MediaType;
-import javax.ws.rs.core.Response;
-import java.io.IOException;
-import java.util.Arrays;
-import java.util.List;
-import java.util.Map;
-
 @Loggable(prepend = true, value = Loggable.DEBUG, trim = false)
 @Tag(name = "SDC Internal APIs")
 @Server(url = "/sdc2/rest")
@@ -96,17 +94,13 @@ public class InputsServlet extends AbstractValidationsServlet {
     private static final LoggerSupportability loggerSupportability = LoggerSupportability.getLogger(InputsServlet.class.getName());
     private static final String START_HANDLE_REQUEST_OF = "(get) Start handle request of {}";
     private static final String CREATE_INPUT = "CreateInput";
-
     private final DataTypeBusinessLogic businessLogic;
     private final InputsBusinessLogic inputsBusinessLogic;
 
     @Inject
-    public InputsServlet(UserBusinessLogic userBusinessLogic,
-        InputsBusinessLogic inputsBusinessLogic,
-        ComponentInstanceBusinessLogic componentInstanceBL,
-        ComponentsUtils componentsUtils, ServletUtils servletUtils,
-        ResourceImportManager resourceImportManager,
-        DataTypeBusinessLogic dataTypeBusinessLogic) {
+    public InputsServlet(UserBusinessLogic userBusinessLogic, InputsBusinessLogic inputsBusinessLogic,
+                         ComponentInstanceBusinessLogic componentInstanceBL, ComponentsUtils componentsUtils, ServletUtils servletUtils,
+                         ResourceImportManager resourceImportManager, DataTypeBusinessLogic dataTypeBusinessLogic) {
         super(userBusinessLogic, componentInstanceBL, componentsUtils, servletUtils, resourceImportManager);
         this.inputsBusinessLogic = inputsBusinessLogic;
         this.businessLogic = dataTypeBusinessLogic;
@@ -114,59 +108,46 @@ public class InputsServlet extends AbstractValidationsServlet {
 
     @POST
     @Path("/{containerComponentType}/{componentId}/update/inputs")
-    @Operation(description = "Update resource  inputs", method = "POST", summary = "Returns updated input",
-            responses = {@ApiResponse(
-                    content = @Content(array = @ArraySchema(schema = @Schema(implementation = Response.class)))),
-                    @ApiResponse(responseCode = "200", description = "Input updated"),
-                    @ApiResponse(responseCode = "403", description = "Restricted operation"),
-                    @ApiResponse(responseCode = "400", description = "Invalid content / Missing content")})
-    public Response updateComponentInputs(@Parameter(description = "valid values: resources / services",
-            schema = @Schema(allowableValues = {ComponentTypeEnum.RESOURCE_PARAM_NAME ,
-                    ComponentTypeEnum.SERVICE_PARAM_NAME})) @PathParam("containerComponentType") final String containerComponentType,
-            @PathParam("componentId") final String componentId,
-            @Parameter(description = "json describe the input", required = true) String data,
-            @Context final HttpServletRequest request) throws JsonProcessingException {
-
+    @Operation(description = "Update resource  inputs", method = "POST", summary = "Returns updated input", responses = {
+        @ApiResponse(content = @Content(array = @ArraySchema(schema = @Schema(implementation = Response.class)))),
+        @ApiResponse(responseCode = "200", description = "Input updated"), @ApiResponse(responseCode = "403", description = "Restricted operation"),
+        @ApiResponse(responseCode = "400", description = "Invalid content / Missing content")})
+    public Response updateComponentInputs(
+        @Parameter(description = "valid values: resources / services", schema = @Schema(allowableValues = {ComponentTypeEnum.RESOURCE_PARAM_NAME,
+            ComponentTypeEnum.SERVICE_PARAM_NAME})) @PathParam("containerComponentType") final String containerComponentType,
+        @PathParam("componentId") final String componentId, @Parameter(description = "json describe the input", required = true) String data,
+        @Context final HttpServletRequest request) throws JsonProcessingException {
         String url = request.getMethod() + " " + request.getRequestURI();
         log.debug("Start handle request of {}", url);
         String userId = request.getHeader(Constants.USER_ID_HEADER);
-
         try {
             User modifier = new User();
             modifier.setUserId(userId);
             log.debug("modifier id is {}", userId);
-
             Either<InputDefinition[], ResponseFormat> inputsEither = getComponentsUtils()
-                    .convertJsonToObjectUsingObjectMapper(data, modifier, InputDefinition[].class,
-                            AuditingActionEnum.UPDATE_RESOURCE_METADATA, ComponentTypeEnum.SERVICE);
-            if(inputsEither.isRight()){
+                .convertJsonToObjectUsingObjectMapper(data, modifier, InputDefinition[].class, AuditingActionEnum.UPDATE_RESOURCE_METADATA,
+                    ComponentTypeEnum.SERVICE);
+            if (inputsEither.isRight()) {
                 log.debug("Failed to convert data to input definition. Status is {}", inputsEither.right().value());
                 return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.INVALID_CONTENT));
             }
             List<InputDefinition> inputsToUpdate = Arrays.asList(inputsEither.left().value());
-
             log.debug("Start handle request of updateComponentInputs. Received inputs are {}", inputsToUpdate);
-
             ComponentTypeEnum componentType = ComponentTypeEnum.findByParamName(containerComponentType);
-
             if (businessLogic == null) {
                 log.debug("Unsupported component type {}", containerComponentType);
                 return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.UNSUPPORTED_ERROR));
             }
-
-            Either<List<InputDefinition>, ResponseFormat> actionResponse = inputsBusinessLogic.updateInputsValue(componentType, componentId, inputsToUpdate, userId, true, false);
-
+            Either<List<InputDefinition>, ResponseFormat> actionResponse = inputsBusinessLogic
+                .updateInputsValue(componentType, componentId, inputsToUpdate, userId, true, false);
             if (actionResponse.isRight()) {
                 return buildErrorResponse(actionResponse.right().value());
             }
-
             List<InputDefinition> componentInputs = actionResponse.left().value();
             ObjectMapper mapper = new ObjectMapper();
             String result = mapper.writeValueAsString(componentInputs);
             return buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), result);
-
-        }
-        catch (Exception e) {
+        } catch (Exception e) {
             log.error("create and associate RI failed with exception: {}", e.getMessage(), e);
             throw e;
         }
@@ -175,27 +156,25 @@ public class InputsServlet extends AbstractValidationsServlet {
     @GET
     @Path("/{componentType}/{componentId}/componentInstances/{instanceId}/{originComponentUid}/inputs")
     @Operation(description = "Get Inputs only", method = "GET", summary = "Returns Inputs list", responses = {
-            @ApiResponse(content = @Content(array = @ArraySchema(schema = @Schema(implementation = Resource.class)))),
-            @ApiResponse(responseCode = "200", description = "Component found"),
-            @ApiResponse(responseCode = "403", description = "Restricted operation"),
-            @ApiResponse(responseCode = "404", description = "Component not found")})
+        @ApiResponse(content = @Content(array = @ArraySchema(schema = @Schema(implementation = Resource.class)))),
+        @ApiResponse(responseCode = "200", description = "Component found"), @ApiResponse(responseCode = "403", description = "Restricted operation"),
+        @ApiResponse(responseCode = "404", description = "Component not found")})
     public Response getComponentInstanceInputs(@PathParam("componentType") final String componentType,
-            @PathParam("componentId") final String componentId, @PathParam("instanceId") final String instanceId,
-            @PathParam("originComponentUid") final String originComponentUid, @Context final HttpServletRequest request,
-            @HeaderParam(value = Constants.USER_ID_HEADER) String userId) throws IOException {
-
+                                               @PathParam("componentId") final String componentId, @PathParam("instanceId") final String instanceId,
+                                               @PathParam("originComponentUid") final String originComponentUid,
+                                               @Context final HttpServletRequest request,
+                                               @HeaderParam(value = Constants.USER_ID_HEADER) String userId) throws IOException {
         String url = request.getMethod() + " " + request.getRequestURI();
         log.debug(START_HANDLE_REQUEST_OF, url);
-
         try {
-            Either<List<ComponentInstanceInput>, ResponseFormat> inputsResponse = inputsBusinessLogic.getComponentInstanceInputs(userId, componentId, instanceId);
+            Either<List<ComponentInstanceInput>, ResponseFormat> inputsResponse = inputsBusinessLogic
+                .getComponentInstanceInputs(userId, componentId, instanceId);
             if (inputsResponse.isRight()) {
                 log.debug("failed to get component instance inputs {}", componentType);
                 return buildErrorResponse(inputsResponse.right().value());
             }
             Object inputs = RepresentationUtils.toRepresentation(inputsResponse.left().value());
             return buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), inputs);
-
         } catch (Exception e) {
             BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Get Inputs " + componentType);
             log.debug("getInputs failed with exception", e);
@@ -206,30 +185,28 @@ public class InputsServlet extends AbstractValidationsServlet {
     @GET
     @Path("/{componentType}/{componentId}/componentInstances/{instanceId}/{inputId}/properties")
     @Operation(description = "Get properties", method = "GET", summary = "Returns properties list", responses = {
-            @ApiResponse(content = @Content(array = @ArraySchema(schema = @Schema(implementation = Resource.class)))),
-            @ApiResponse(responseCode = "200", description = "Component found"),
-            @ApiResponse(responseCode = "403", description = "Restricted operation"),
-            @ApiResponse(responseCode = "404", description = "Component not found")})
+        @ApiResponse(content = @Content(array = @ArraySchema(schema = @Schema(implementation = Resource.class)))),
+        @ApiResponse(responseCode = "200", description = "Component found"), @ApiResponse(responseCode = "403", description = "Restricted operation"),
+        @ApiResponse(responseCode = "404", description = "Component not found")})
     public Response getInputPropertiesForComponentInstance(@PathParam("componentType") final String componentType,
-            @PathParam("componentId") final String componentId, @PathParam("instanceId") final String instanceId,
-            @PathParam("inputId") final String inputId, @Context final HttpServletRequest request,
-            @HeaderParam(value = Constants.USER_ID_HEADER) String userId) throws IOException {
-
+                                                           @PathParam("componentId") final String componentId,
+                                                           @PathParam("instanceId") final String instanceId,
+                                                           @PathParam("inputId") final String inputId, @Context final HttpServletRequest request,
+                                                           @HeaderParam(value = Constants.USER_ID_HEADER) String userId) throws IOException {
         String url = request.getMethod() + " " + request.getRequestURI();
         log.debug(START_HANDLE_REQUEST_OF, url);
-
         try {
             Either<List<ComponentInstanceProperty>, ResponseFormat> inputPropertiesRes = inputsBusinessLogic
-                    .getComponentInstancePropertiesByInputId(userId, componentId, instanceId, inputId);
+                .getComponentInstancePropertiesByInputId(userId, componentId, instanceId, inputId);
             if (inputPropertiesRes.isRight()) {
                 log.debug("failed to get properties of input: {}, with instance id: {}", inputId, instanceId);
                 return buildErrorResponse(inputPropertiesRes.right().value());
             }
             Object properties = RepresentationUtils.toRepresentation(inputPropertiesRes.left().value());
             return buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), properties);
-
         } catch (Exception e) {
-            BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Get Properites by input id: " + inputId + " for instance with id: " + instanceId);
+            BeEcompErrorManager.getInstance()
+                .logBeRestApiGeneralError("Get Properites by input id: " + inputId + " for instance with id: " + instanceId);
             log.debug("getInputPropertiesForComponentInstance failed with exception", e);
             throw e;
         }
@@ -238,29 +215,27 @@ public class InputsServlet extends AbstractValidationsServlet {
     @GET
     @Path("/{componentType}/{componentId}/inputs/{inputId}/inputs")
     @Operation(description = "Get inputs", method = "GET", summary = "Returns inputs list", responses = {
-            @ApiResponse(content = @Content(array = @ArraySchema(schema = @Schema(implementation = Resource.class)))),
-            @ApiResponse(responseCode = "200", description = "Component found"),
-            @ApiResponse(responseCode = "403", description = "Restricted operation"),
-            @ApiResponse(responseCode = "404", description = "Component not found")})
+        @ApiResponse(content = @Content(array = @ArraySchema(schema = @Schema(implementation = Resource.class)))),
+        @ApiResponse(responseCode = "200", description = "Component found"), @ApiResponse(responseCode = "403", description = "Restricted operation"),
+        @ApiResponse(responseCode = "404", description = "Component not found")})
     public Response getInputsForComponentInput(@PathParam("componentType") final String componentType,
-            @PathParam("componentId") final String componentId, @PathParam("inputId") final String inputId,
-            @Context final HttpServletRequest request, @HeaderParam(value = Constants.USER_ID_HEADER) String userId) throws IOException {
-
+                                               @PathParam("componentId") final String componentId, @PathParam("inputId") final String inputId,
+                                               @Context final HttpServletRequest request,
+                                               @HeaderParam(value = Constants.USER_ID_HEADER) String userId) throws IOException {
         String url = request.getMethod() + " " + request.getRequestURI();
         log.debug(START_HANDLE_REQUEST_OF, url);
         try {
-            Either<List<ComponentInstanceInput>, ResponseFormat> inputsRes =
-                    inputsBusinessLogic.getInputsForComponentInput(userId, componentId, inputId);
-
+            Either<List<ComponentInstanceInput>, ResponseFormat> inputsRes = inputsBusinessLogic
+                .getInputsForComponentInput(userId, componentId, inputId);
             if (inputsRes.isRight()) {
                 log.debug("failed to get inputs of input: {}, with instance id: {}", inputId, componentId);
                 return buildErrorResponse(inputsRes.right().value());
             }
             Object properties = RepresentationUtils.toRepresentation(inputsRes.left().value());
             return buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), properties);
-
         } catch (Exception e) {
-            BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Get inputs by input id: " + inputId + " for component with id: " + componentId);
+            BeEcompErrorManager.getInstance()
+                .logBeRestApiGeneralError("Get inputs by input id: " + inputId + " for component with id: " + componentId);
             log.debug("getInputsForComponentInput failed with exception", e);
             throw e;
         }
@@ -269,98 +244,82 @@ public class InputsServlet extends AbstractValidationsServlet {
     @GET
     @Path("/{componentType}/{componentId}/inputs/{inputId}")
     @Operation(description = "Get inputs", method = "GET", summary = "Returns inputs list", responses = {
-            @ApiResponse(content = @Content(array = @ArraySchema(schema = @Schema(implementation = Resource.class)))),
-            @ApiResponse(responseCode = "200", description = "Component found"),
-            @ApiResponse(responseCode = "403", description = "Restricted operation"),
-            @ApiResponse(responseCode = "404", description = "Component not found")})
+        @ApiResponse(content = @Content(array = @ArraySchema(schema = @Schema(implementation = Resource.class)))),
+        @ApiResponse(responseCode = "200", description = "Component found"), @ApiResponse(responseCode = "403", description = "Restricted operation"),
+        @ApiResponse(responseCode = "404", description = "Component not found")})
     public Response getInputsAndPropertiesForComponentInput(@PathParam("componentType") final String componentType,
-            @PathParam("componentId") final String componentId, @PathParam("inputId") final String inputId,
-            @Context final HttpServletRequest request, @HeaderParam(value = Constants.USER_ID_HEADER) String userId) throws IOException {
-
+                                                            @PathParam("componentId") final String componentId,
+                                                            @PathParam("inputId") final String inputId, @Context final HttpServletRequest request,
+                                                            @HeaderParam(value = Constants.USER_ID_HEADER) String userId) throws IOException {
         String url = request.getMethod() + " " + request.getRequestURI();
         log.debug(START_HANDLE_REQUEST_OF, url);
-
         try {
-            Either<InputDefinition, ResponseFormat> inputsRes =
-                    inputsBusinessLogic.getInputsAndPropertiesForComponentInput(userId, componentId, inputId, false);
-
+            Either<InputDefinition, ResponseFormat> inputsRes = inputsBusinessLogic
+                .getInputsAndPropertiesForComponentInput(userId, componentId, inputId, false);
             if (inputsRes.isRight()) {
                 log.debug("failed to get inputs of input: {}, with instance id: {}", inputId, componentId);
                 return buildErrorResponse(inputsRes.right().value());
             }
             Object properties = RepresentationUtils.toRepresentation(inputsRes.left().value());
             return buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), properties);
-
         } catch (Exception e) {
-            BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Get inputs by input id: " + inputId + " for component with id: " + componentId);
+            BeEcompErrorManager.getInstance()
+                .logBeRestApiGeneralError("Get inputs by input id: " + inputId + " for component with id: " + componentId);
             log.debug("getInputsForComponentInput failed with exception", e);
             throw e;
         }
     }
 
     private Either<ComponentInstListInput, ResponseFormat> parseToComponentInstListInput(String json, User user) {
-        return getComponentsUtils().convertJsonToObjectUsingObjectMapper(json, user, ComponentInstListInput.class, AuditingActionEnum.CREATE_RESOURCE, ComponentTypeEnum.SERVICE);
+        return getComponentsUtils().convertJsonToObjectUsingObjectMapper(json, user, ComponentInstListInput.class, AuditingActionEnum.CREATE_RESOURCE,
+            ComponentTypeEnum.SERVICE);
     }
 
     @POST
     @Path("/{componentType}/{componentId}/create/inputs")
     @Operation(description = "Create inputs on service", method = "POST", summary = "Return inputs list", responses = {
-            @ApiResponse(content = @Content(array = @ArraySchema(schema = @Schema(implementation = Resource.class)))),
-            @ApiResponse(responseCode = "200", description = "Component found"),
-            @ApiResponse(responseCode = "403", description = "Restricted operation"),
-            @ApiResponse(responseCode = "404", description = "Component not found")})
-    public Response createMultipleInputs(@PathParam("componentType") final String componentType,
-            @PathParam("componentId") final String componentId, @Context final HttpServletRequest request,
-            @HeaderParam(value = Constants.USER_ID_HEADER) String userId,
-            @Parameter(description = "ComponentIns Inputs Object to be created",
-                    required = true) String componentInstInputsMapObj) {
-
-        return super.declareProperties(userId, componentId, componentType, componentInstInputsMapObj,
-                DeclarationTypeEnum.INPUT, request);
+        @ApiResponse(content = @Content(array = @ArraySchema(schema = @Schema(implementation = Resource.class)))),
+        @ApiResponse(responseCode = "200", description = "Component found"), @ApiResponse(responseCode = "403", description = "Restricted operation"),
+        @ApiResponse(responseCode = "404", description = "Component not found")})
+    public Response createMultipleInputs(@PathParam("componentType") final String componentType, @PathParam("componentId") final String componentId,
+                                         @Context final HttpServletRequest request, @HeaderParam(value = Constants.USER_ID_HEADER) String userId,
+                                         @Parameter(description = "ComponentIns Inputs Object to be created", required = true) String componentInstInputsMapObj) {
+        return super.declareProperties(userId, componentId, componentType, componentInstInputsMapObj, DeclarationTypeEnum.INPUT, request);
     }
 
     @POST
     @Path("/{componentType}/{componentId}/create/input")
     @Operation(description = "Create inputs on service", method = "POST", summary = "Return inputs list", responses = {
-            @ApiResponse(content = @Content(array = @ArraySchema(schema = @Schema(implementation = Resource.class)))),
-            @ApiResponse(responseCode = "200", description = "Component found"),
-            @ApiResponse(responseCode = "403", description = "Restricted operation"),
-            @ApiResponse(responseCode = "404", description = "Component not found")})
-    public Response createInput(@PathParam("componentType") final String componentType,
-                                         @PathParam("componentId") final String componentId, @Context final HttpServletRequest request,
-                                         @HeaderParam(value = Constants.USER_ID_HEADER) String userId,
-                                         @Parameter(description = "ComponentIns Inputs Object to be created",
-                                                 required = true) String componentInstInputsMapObj) {
-
+        @ApiResponse(content = @Content(array = @ArraySchema(schema = @Schema(implementation = Resource.class)))),
+        @ApiResponse(responseCode = "200", description = "Component found"), @ApiResponse(responseCode = "403", description = "Restricted operation"),
+        @ApiResponse(responseCode = "404", description = "Component not found")})
+    public Response createInput(@PathParam("componentType") final String componentType, @PathParam("componentId") final String componentId,
+                                @Context final HttpServletRequest request, @HeaderParam(value = Constants.USER_ID_HEADER) String userId,
+                                @Parameter(description = "ComponentIns Inputs Object to be created", required = true) String componentInstInputsMapObj) {
         return createInput(componentId, componentInstInputsMapObj, request, userId);
     }
 
     /**
-     * Creates a "list input" and updates given list of properties to get value from the input.
-     * also a data type which has same properties is created.
+     * Creates a "list input" and updates given list of properties to get value from the input. also a data type which has same properties is created.
      * the data type will be the entry_schema of the list input.
-     * @param componentType the container type (service, resource, ...)
-     * @param componentId the container ID
-     * @param request HttpServletRequest object
-     * @param userId the User ID
-     * @param componentInstInputsMapObj the list of properties to be declared and the "list input" to be created.
-     *                                  the type of the input must be "list".
-     *                                  schema.type of the input will be the name of new data type.
+     *
+     * @param componentType             the container type (service, resource, ...)
+     * @param componentId               the container ID
+     * @param request                   HttpServletRequest object
+     * @param userId                    the User ID
+     * @param componentInstInputsMapObj the list of properties to be declared and the "list input" to be created. the type of the input must be
+     *                                  "list". schema.type of the input will be the name of new data type.
      * @return the created input
      */
     @POST
     @Path("/{componentType}/{componentId}/create/listInput")
     @Operation(description = "Create a list input on service", method = "POST", summary = "Return input", responses = {
-            @ApiResponse(content = @Content(array = @ArraySchema(schema = @Schema(implementation = Resource.class)))),
-            @ApiResponse(responseCode = "200", description = "Component found"),
-            @ApiResponse(responseCode = "403", description = "Restricted operation"),
-            @ApiResponse(responseCode = "404", description = "Component not found")})
-    public Response createListInput(@PathParam("componentType") final String componentType,
-            @PathParam("componentId") final String componentId, @Context final HttpServletRequest request,
-            @HeaderParam(value = Constants.USER_ID_HEADER) String userId,
-            @Parameter(description = "ComponentIns Inputs Object to be created",
-                    required = true) String componentInstInputsMapObj) {
-
+        @ApiResponse(content = @Content(array = @ArraySchema(schema = @Schema(implementation = Resource.class)))),
+        @ApiResponse(responseCode = "200", description = "Component found"), @ApiResponse(responseCode = "403", description = "Restricted operation"),
+        @ApiResponse(responseCode = "404", description = "Component not found")})
+    public Response createListInput(@PathParam("componentType") final String componentType, @PathParam("componentId") final String componentId,
+                                    @Context final HttpServletRequest request, @HeaderParam(value = Constants.USER_ID_HEADER) String userId,
+                                    @Parameter(description = "ComponentIns Inputs Object to be created", required = true) String componentInstInputsMapObj) {
         String url = request.getMethod() + " " + request.getRequestURI();
         log.debug("#createListInput: Start handle request of {}", url);
         try {
@@ -368,62 +327,53 @@ public class InputsServlet extends AbstractValidationsServlet {
             User modifier = new User();
             modifier.setUserId(userId);
             log.debug("modifier id is {}", userId);
-
-            Either<ComponentInstListInput, ResponseFormat> componentInstInputsMapRes =
-                parseToComponentInstListInput(componentInstInputsMapObj, modifier);
+            Either<ComponentInstListInput, ResponseFormat> componentInstInputsMapRes = parseToComponentInstListInput(componentInstInputsMapObj,
+                modifier);
             if (componentInstInputsMapRes.isRight()) {
                 log.debug("failed to parse componentInstInputsMap");
                 return buildErrorResponse(componentInstInputsMapRes.right().value());
             }
-
             ComponentTypeEnum componentTypeEnum = ComponentTypeEnum.findByParamName(componentType);
             ComponentInstListInput componentInstInputsMap = componentInstInputsMapRes.left().value();
             if (log.isDebugEnabled()) {
                 // for inspection on debug
-                log.debug("parsed componentInstInputsMap={}",
-                        ReflectionToStringBuilder.toString(componentInstInputsMap));
+                log.debug("parsed componentInstInputsMap={}", ReflectionToStringBuilder.toString(componentInstInputsMap));
             }
-
             Either<List<InputDefinition>, ResponseFormat> inputPropertiesRes = inputsBusinessLogic
-                    .createListInput(userId, componentId, componentTypeEnum, componentInstInputsMap, true, false);
+                .createListInput(userId, componentId, componentTypeEnum, componentInstInputsMap, true, false);
             if (inputPropertiesRes.isRight()) {
                 log.debug("failed to create list input for service: {}", componentId);
                 return buildErrorResponse(inputPropertiesRes.right().value());
             }
             Object properties = RepresentationUtils.toRepresentation(inputPropertiesRes.left().value());
             return buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), properties);
-
         } catch (Exception e) {
-            BeEcompErrorManager.getInstance()
-                    .logBeRestApiGeneralError("Create list input for service with id: " + componentId);
+            BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Create list input for service with id: " + componentId);
             log.debug("createListInput failed with exception", e);
             return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR));
         }
     }
 
-
     @DELETE
     @Path("/{componentType}/{componentId}/delete/{inputId}/input")
-    @Operation(description = "Delete input from service", method = "DELETE", summary = "Delete service input",
-            responses = {@ApiResponse(
-                    content = @Content(array = @ArraySchema(schema = @Schema(implementation = Resource.class)))),
-                    @ApiResponse(responseCode = "200", description = "Input deleted"),
-                    @ApiResponse(responseCode = "403", description = "Restricted operation"),
-                    @ApiResponse(responseCode = "404", description = "Input not found")})
-    public Response deleteInput(@PathParam("componentType") final String componentType,
-            @PathParam("componentId") final String componentId, @PathParam("inputId") final String inputId,
-            @Context final HttpServletRequest request, @HeaderParam(value = Constants.USER_ID_HEADER) String userId,
-            @Parameter(description = "Service Input to be deleted", required = true) String componentInstInputsMapObj) {
-
+    @Operation(description = "Delete input from service", method = "DELETE", summary = "Delete service input", responses = {
+        @ApiResponse(content = @Content(array = @ArraySchema(schema = @Schema(implementation = Resource.class)))),
+        @ApiResponse(responseCode = "200", description = "Input deleted"), @ApiResponse(responseCode = "403", description = "Restricted operation"),
+        @ApiResponse(responseCode = "404", description = "Input not found")})
+    public Response deleteInput(@PathParam("componentType") final String componentType, @PathParam("componentId") final String componentId,
+                                @PathParam("inputId") final String inputId, @Context final HttpServletRequest request,
+                                @HeaderParam(value = Constants.USER_ID_HEADER) String userId,
+                                @Parameter(description = "Service Input to be deleted", required = true) String componentInstInputsMapObj) {
         String url = request.getMethod() + " " + request.getRequestURI();
         log.debug(START_HANDLE_REQUEST_OF, url);
-        loggerSupportability.log(LoggerSupportabilityActions.DELETE_INPUTS, StatusCode.STARTED,"Starting to delete Inputs for component {} ",componentId + " by " +  userId );
-
+        loggerSupportability.log(LoggerSupportabilityActions.DELETE_INPUTS, StatusCode.STARTED, "Starting to delete Inputs for component {} ",
+            componentId + " by " + userId);
         try {
             InputDefinition deleteInput = inputsBusinessLogic.deleteInput(componentId, userId, inputId);
-            loggerSupportability.log(LoggerSupportabilityActions.DELETE_INPUTS, StatusCode.COMPLETE,"Ended delete Inputs for component {} ",componentId + " by " +  userId );
+            loggerSupportability.log(LoggerSupportabilityActions.DELETE_INPUTS, StatusCode.COMPLETE, "Ended delete Inputs for component {} ",
+                componentId + " by " + userId);
             return buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), deleteInput);
-        } catch (ComponentException e){
+        } catch (ComponentException e) {
             BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Delete input for service + " + componentId + " + with id: " + inputId);
             log.debug("Delete input failed with exception", e);
             throw e;
@@ -432,31 +382,25 @@ public class InputsServlet extends AbstractValidationsServlet {
 
     /**
      * Gets a specific data type associated with a component.
+     *
      * @param componentType the container type (service, resource, ...)
-     * @param componentId the container ID
-     * @param dataTypeName the data type name
-     * @param request HttpServletRequest object
+     * @param componentId   the container ID
+     * @param dataTypeName  the data type name
+     * @param request       HttpServletRequest object
      * @return the data type info
      */
     @GET
     @Path("/{componentType}/{componentId}/dataType/{dataTypeName}")
-    @Operation(description = "Get data type in service", method = "GET", summary = "Get data type in service",
-            responses = {@ApiResponse(content = @Content(
-                    array = @ArraySchema(schema = @Schema(implementation = DataTypeDefinition.class)))),
-                    @ApiResponse(responseCode = "200", description = "Data type found"),
-                    @ApiResponse(responseCode = "403", description = "Restricted operation"),
-                    @ApiResponse(responseCode = "404", description = "Data type not found")})
+    @Operation(description = "Get data type in service", method = "GET", summary = "Get data type in service", responses = {
+        @ApiResponse(content = @Content(array = @ArraySchema(schema = @Schema(implementation = DataTypeDefinition.class)))),
+        @ApiResponse(responseCode = "200", description = "Data type found"), @ApiResponse(responseCode = "403", description = "Restricted operation"),
+        @ApiResponse(responseCode = "404", description = "Data type not found")})
     @PermissionAllowed(AafPermission.PermNames.INTERNAL_ALL_VALUE)
-    public Response getDataType(
-            @PathParam("componentType") final String componentType,
-            @PathParam("componentId") final String componentId,
-            @PathParam("dataTypeName") final String dataTypeName,
-            @Context final HttpServletRequest request
-    ) {
+    public Response getDataType(@PathParam("componentType") final String componentType, @PathParam("componentId") final String componentId,
+                                @PathParam("dataTypeName") final String dataTypeName, @Context final HttpServletRequest request) {
         String url = request.getMethod() + " " + request.getRequestURI();
         log.debug("(getDataType) Start handle request of {}", url);
         Response response;
-
         try {
             Either<DataTypeDefinition, StorageOperationStatus> getResult = businessLogic.getPrivateDataType(componentId, dataTypeName);
             if (getResult.isRight()) {
@@ -466,7 +410,8 @@ public class InputsServlet extends AbstractValidationsServlet {
             Object json = RepresentationUtils.toRepresentation(getResult.left().value());
             return buildOkResponse(componentsUtils.getResponseFormat(ActionStatus.OK), json);
         } catch (Exception e) {
-            BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Get data type from service + " + componentId + " + with name: " + dataTypeName);
+            BeEcompErrorManager.getInstance()
+                .logBeRestApiGeneralError("Get data type from service + " + componentId + " + with name: " + dataTypeName);
             log.debug("Get data type failed with exception", e);
             response = buildErrorResponse(componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR));
             return response;
@@ -475,30 +420,25 @@ public class InputsServlet extends AbstractValidationsServlet {
 
     /**
      * Gets a list of data types which a component has.
+     *
      * @param componentType the container type (service, resource, ...)
-     * @param componentId the container ID
-     * @param request HttpServletRequest object
+     * @param componentId   the container ID
+     * @param request       HttpServletRequest object
      * @return the list of data types in the component
      */
     @GET
     @Path("/{componentType}/{componentId}/dataTypes")
-    @Operation(description = "Get data types that service has", method = "GET", summary = "Get data types in service",
-            responses = {@ApiResponse(
-                    content = @Content(array = @ArraySchema(schema = @Schema(implementation = Resource.class)))),
-                    @ApiResponse(responseCode = "200", description = "Data type found"),
-                    @ApiResponse(responseCode = "403", description = "Restricted operation"),
-                    @ApiResponse(responseCode = "404", description = "Component not found")})
+    @Operation(description = "Get data types that service has", method = "GET", summary = "Get data types in service", responses = {
+        @ApiResponse(content = @Content(array = @ArraySchema(schema = @Schema(implementation = Resource.class)))),
+        @ApiResponse(responseCode = "200", description = "Data type found"), @ApiResponse(responseCode = "403", description = "Restricted operation"),
+        @ApiResponse(responseCode = "404", description = "Component not found")})
     @PermissionAllowed(AafPermission.PermNames.INTERNAL_ALL_VALUE)
-    public Response getDataTypes(
-            @PathParam("componentType") final String componentType,
-            @PathParam("componentId") final String componentId,
-            @Context final HttpServletRequest request
-    ) {
+    public Response getDataTypes(@PathParam("componentType") final String componentType, @PathParam("componentId") final String componentId,
+                                 @Context final HttpServletRequest request) {
         ComponentsUtils componentsUtils = getComponentsUtils();
         String url = request.getMethod() + " " + request.getRequestURI();
         log.debug("(getDataType) Start handle request of {}", url);
         Response response;
-
         try {
             Either<List<DataTypeDefinition>, StorageOperationStatus> getResult = businessLogic.getPrivateDataTypes(componentId);
             if (getResult.isRight()) {
@@ -517,32 +457,27 @@ public class InputsServlet extends AbstractValidationsServlet {
 
     /**
      * Deletes a data type from a component.
+     *
      * @param componentType the container type (service, resource, ...)
-     * @param componentId the container ID
-     * @param dataTypeName the data type name to be deleted
-     * @param request HttpServletRequest object
+     * @param componentId   the container ID
+     * @param dataTypeName  the data type name to be deleted
+     * @param request       HttpServletRequest object
      * @return operation result
      */
     @DELETE
     @Path("/{componentType}/{componentId}/dataType/{dataTypeName}")
-    @Operation(description = "Delete data type from service", method = "DELETE", summary = "Delete service input",
-            responses = {@ApiResponse(
-                    content = @Content(array = @ArraySchema(schema = @Schema(implementation = Resource.class)))),
-                    @ApiResponse(responseCode = "200", description = "Data type deleted"),
-                    @ApiResponse(responseCode = "403", description = "Restricted operation"),
-                    @ApiResponse(responseCode = "404", description = "Data type not found")})
+    @Operation(description = "Delete data type from service", method = "DELETE", summary = "Delete service input", responses = {
+        @ApiResponse(content = @Content(array = @ArraySchema(schema = @Schema(implementation = Resource.class)))),
+        @ApiResponse(responseCode = "200", description = "Data type deleted"),
+        @ApiResponse(responseCode = "403", description = "Restricted operation"),
+        @ApiResponse(responseCode = "404", description = "Data type not found")})
     @PermissionAllowed(AafPermission.PermNames.INTERNAL_ALL_VALUE)
-    public Response deleteDataType(
-            @PathParam("componentType") final String componentType,
-            @PathParam("componentId") final String componentId,
-            @PathParam("dataTypeName") final String dataTypeName,
-            @Context final HttpServletRequest request
-    ) {
+    public Response deleteDataType(@PathParam("componentType") final String componentType, @PathParam("componentId") final String componentId,
+                                   @PathParam("dataTypeName") final String dataTypeName, @Context final HttpServletRequest request) {
         ComponentsUtils componentsUtils = getComponentsUtils();
         String url = request.getMethod() + " " + request.getRequestURI();
         log.debug(START_HANDLE_REQUEST_OF, url);
         Response response;
-
         try {
             Either<DataTypeDefinition, StorageOperationStatus> deleteResult = businessLogic.deletePrivateDataType(componentId, dataTypeName);
             if (deleteResult.isRight()) {
@@ -552,53 +487,45 @@ public class InputsServlet extends AbstractValidationsServlet {
             Object json = RepresentationUtils.toRepresentation(deleteResult.left().value());
             return buildOkResponse(componentsUtils.getResponseFormat(ActionStatus.OK), json);
         } catch (Exception e) {
-            BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Delete data type for service + " + componentId + " + with name: " + dataTypeName);
+            BeEcompErrorManager.getInstance()
+                .logBeRestApiGeneralError("Delete data type for service + " + componentId + " + with name: " + dataTypeName);
             log.debug("Delete data type failed with exception", e);
             response = buildErrorResponse(componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR));
             return response;
         }
     }
 
-    private Response createInput(String componentId, String data,  HttpServletRequest request,String userId) {
+    private Response createInput(String componentId, String data, HttpServletRequest request, String userId) {
         String url = request.getMethod() + " " + request.getRequestURI();
         log.debug("Start handle request of {} modifier id is {} data is {}", url, userId, data);
-        loggerSupportability.log(LoggerSupportabilityActions.CREATE_INPUTS, StatusCode.STARTED,"CREATE_INPUTS by user {} ", userId);
-
-        try{
-            Either<Map<String, InputDefinition>, ActionStatus> inputDefinition =
-                    getInputModel(componentId, data);
+        loggerSupportability.log(LoggerSupportabilityActions.CREATE_INPUTS, StatusCode.STARTED, "CREATE_INPUTS by user {} ", userId);
+        try {
+            Either<Map<String, InputDefinition>, ActionStatus> inputDefinition = getInputModel(componentId, data);
             if (inputDefinition.isRight()) {
                 ResponseFormat responseFormat = getComponentsUtils().getResponseFormat(inputDefinition.right().value());
                 return buildErrorResponse(responseFormat);
             }
-
             Map<String, InputDefinition> inputs = inputDefinition.left().value();
             if (inputs == null || inputs.size() != 1) {
                 log.info("Input content is invalid - {}", data);
                 ResponseFormat responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.INVALID_CONTENT);
                 return buildErrorResponse(responseFormat);
             }
-
             Map.Entry<String, InputDefinition> entry = inputs.entrySet().iterator().next();
             InputDefinition newInputDefinition = entry.getValue();
             newInputDefinition.setParentUniqueId(componentId);
             String inputName = newInputDefinition.getName();
-
-            Either<EntryData<String, InputDefinition>, ResponseFormat> addInputEither =
-                    inputsBusinessLogic.addInputToComponent(componentId, inputName, newInputDefinition, userId);
-
-            if(addInputEither.isRight()) {
+            Either<EntryData<String, InputDefinition>, ResponseFormat> addInputEither = inputsBusinessLogic
+                .addInputToComponent(componentId, inputName, newInputDefinition, userId);
+            if (addInputEither.isRight()) {
                 return buildErrorResponse(addInputEither.right().value());
             }
-
-            loggerSupportability.log(LoggerSupportabilityActions.CREATE_INPUTS, StatusCode.COMPLETE,"CREATE_INPUTS by user {} ", userId);
+            loggerSupportability.log(LoggerSupportabilityActions.CREATE_INPUTS, StatusCode.COMPLETE, "CREATE_INPUTS by user {} ", userId);
             return buildOkResponse(newInputDefinition);
-
         } catch (Exception e) {
             BeEcompErrorManager.getInstance().logBeRestApiGeneralError(CREATE_INPUT);
             log.debug("create input failed with exception", e);
-            ResponseFormat responseFormat =
-                    getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR);
+            ResponseFormat responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR);
             return buildErrorResponse(responseFormat);
         }
     }
index 0f7664b..1fd31db 100644 (file)
@@ -13,7 +13,6 @@
  * See the License for the specific language governing permissions and
  * limitations under the License.
  */
-
 package org.openecomp.sdc.be.servlets;
 
 import com.google.common.collect.ImmutableMap;
@@ -29,6 +28,25 @@ import io.swagger.v3.oas.annotations.servers.Server;
 import io.swagger.v3.oas.annotations.servers.Servers;
 import io.swagger.v3.oas.annotations.tags.Tag;
 import io.swagger.v3.oas.annotations.tags.Tags;
+import java.io.IOException;
+import java.util.ArrayList;
+import java.util.Collections;
+import java.util.List;
+import java.util.Map;
+import javax.inject.Inject;
+import javax.servlet.http.HttpServletRequest;
+import javax.ws.rs.Consumes;
+import javax.ws.rs.DELETE;
+import javax.ws.rs.GET;
+import javax.ws.rs.HeaderParam;
+import javax.ws.rs.POST;
+import javax.ws.rs.PUT;
+import javax.ws.rs.Path;
+import javax.ws.rs.PathParam;
+import javax.ws.rs.Produces;
+import javax.ws.rs.core.Context;
+import javax.ws.rs.core.MediaType;
+import javax.ws.rs.core.Response;
 import org.openecomp.sdc.be.components.impl.ComponentInstanceBusinessLogic;
 import org.openecomp.sdc.be.components.impl.InterfaceOperationBusinessLogic;
 import org.openecomp.sdc.be.components.impl.ResourceImportManager;
@@ -51,26 +69,6 @@ import org.slf4j.Logger;
 import org.slf4j.LoggerFactory;
 import org.springframework.stereotype.Controller;
 
-import javax.inject.Inject;
-import javax.servlet.http.HttpServletRequest;
-import javax.ws.rs.Consumes;
-import javax.ws.rs.DELETE;
-import javax.ws.rs.GET;
-import javax.ws.rs.HeaderParam;
-import javax.ws.rs.POST;
-import javax.ws.rs.PUT;
-import javax.ws.rs.Path;
-import javax.ws.rs.PathParam;
-import javax.ws.rs.Produces;
-import javax.ws.rs.core.Context;
-import javax.ws.rs.core.MediaType;
-import javax.ws.rs.core.Response;
-import java.io.IOException;
-import java.util.ArrayList;
-import java.util.Collections;
-import java.util.List;
-import java.util.Map;
-
 @Loggable(prepend = true, value = Loggable.DEBUG, trim = false)
 @Path("/v1/catalog")
 @Consumes(MediaType.APPLICATION_JSON)
@@ -84,11 +82,9 @@ public class InterfaceOperationServlet extends AbstractValidationsServlet {
     private final InterfaceOperationBusinessLogic interfaceOperationBusinessLogic;
 
     @Inject
-    public InterfaceOperationServlet(UserBusinessLogic userBusinessLogic,
-        ComponentInstanceBusinessLogic componentInstanceBL,
-        ComponentsUtils componentsUtils, ServletUtils servletUtils,
-        ResourceImportManager resourceImportManager,
-        InterfaceOperationBusinessLogic interfaceOperationBusinessLogic) {
+    public InterfaceOperationServlet(UserBusinessLogic userBusinessLogic, ComponentInstanceBusinessLogic componentInstanceBL,
+                                     ComponentsUtils componentsUtils, ServletUtils servletUtils, ResourceImportManager resourceImportManager,
+                                     InterfaceOperationBusinessLogic interfaceOperationBusinessLogic) {
         super(userBusinessLogic, componentInstanceBL, componentsUtils, servletUtils, resourceImportManager);
         this.interfaceOperationBusinessLogic = interfaceOperationBusinessLogic;
     }
@@ -97,50 +93,41 @@ public class InterfaceOperationServlet extends AbstractValidationsServlet {
     @Consumes(MediaType.APPLICATION_JSON)
     @Produces(MediaType.APPLICATION_JSON)
     @Path("/resources/{resourceId}/interfaceOperations")
-    @Operation(description = "Create Interface Operations on Resource", method = "POST",
-            summary = "Create Interface Operations on Resource", responses = {@ApiResponse(
-            content = @Content(array = @ArraySchema(schema = @Schema(implementation = InterfaceDefinition.class)))),
-            @ApiResponse(responseCode = "201", description = "Create Interface Operations on Resource"),
-            @ApiResponse(responseCode = "400", description = "Invalid content / Missing content"),
-            @ApiResponse(responseCode = "403", description = "Restricted operation"),
-            @ApiResponse(responseCode = "404", description = "Resource not found"),
-            @ApiResponse(responseCode = "409", description = "Interface Operation already exist")})
+    @Operation(description = "Create Interface Operations on Resource", method = "POST", summary = "Create Interface Operations on Resource", responses = {
+        @ApiResponse(content = @Content(array = @ArraySchema(schema = @Schema(implementation = InterfaceDefinition.class)))),
+        @ApiResponse(responseCode = "201", description = "Create Interface Operations on Resource"),
+        @ApiResponse(responseCode = "400", description = "Invalid content / Missing content"),
+        @ApiResponse(responseCode = "403", description = "Restricted operation"),
+        @ApiResponse(responseCode = "404", description = "Resource not found"),
+        @ApiResponse(responseCode = "409", description = "Interface Operation already exist")})
     @PermissionAllowed(AafPermission.PermNames.INTERNAL_ALL_VALUE)
-    public Response createInterfaceOperationsOnResource(
-            @Parameter(description = "Interface Operations to create", required = true) String data,
-            @Parameter(description = "Resource Id") @PathParam("resourceId") String resourceId,
-            @HeaderParam(value = Constants.USER_ID_HEADER) String userId, @Context final HttpServletRequest request) {
+    public Response createInterfaceOperationsOnResource(@Parameter(description = "Interface Operations to create", required = true) String data,
+                                                        @Parameter(description = "Resource Id") @PathParam("resourceId") String resourceId,
+                                                        @HeaderParam(value = Constants.USER_ID_HEADER) String userId,
+                                                        @Context final HttpServletRequest request) {
         return createOrUpdate(data, ComponentTypeEnum.RESOURCE, resourceId, request, userId, false);
     }
 
-    private Response createOrUpdate(String data, ComponentTypeEnum componentType, String componentId,
-            HttpServletRequest request, String userId, boolean isUpdate) {
+    private Response createOrUpdate(String data, ComponentTypeEnum componentType, String componentId, HttpServletRequest request, String userId,
+                                    boolean isUpdate) {
         String url = request.getMethod() + " " + request.getRequestURI();
-
         User modifier = new User();
         modifier.setUserId(userId);
         log.debug("Start create or update request of {} with modifier id {}", url, userId);
-
         try {
             String componentIdLower = componentId.toLowerCase();
-
             List<InterfaceDefinition> mappedInterfaceData = getMappedInterfaceData(data, modifier, componentType);
             Either<List<InterfaceDefinition>, ResponseFormat> actionResponse;
             if (isUpdate) {
-                actionResponse =
-                        interfaceOperationBusinessLogic.updateInterfaceOperation(componentIdLower, mappedInterfaceData, modifier, true);
+                actionResponse = interfaceOperationBusinessLogic.updateInterfaceOperation(componentIdLower, mappedInterfaceData, modifier, true);
             } else {
-                actionResponse =
-                        interfaceOperationBusinessLogic.createInterfaceOperation(componentIdLower, mappedInterfaceData, modifier, true);
+                actionResponse = interfaceOperationBusinessLogic.createInterfaceOperation(componentIdLower, mappedInterfaceData, modifier, true);
             }
-
             if (actionResponse.isRight()) {
                 log.error("failed to create or update interface operation");
                 return buildErrorResponse(actionResponse.right().value());
             }
-
-            return buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK),
-                    getFormattedResponse(actionResponse.left().value()));
+            return buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), getFormattedResponse(actionResponse.left().value()));
         } catch (Exception e) {
             BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Interface Operation Creation or update");
             log.error("create or update interface Operation with an error", e);
@@ -148,17 +135,16 @@ public class InterfaceOperationServlet extends AbstractValidationsServlet {
         }
     }
 
-    private List<InterfaceDefinition> getMappedInterfaceData(String inputJson, User user,
-            ComponentTypeEnum componentTypeEnum) {
-        Either<UiComponentDataTransfer, ResponseFormat> uiComponentEither =
-                getComponentsUtils().convertJsonToObjectUsingObjectMapper(inputJson, user,
-                        UiComponentDataTransfer.class, AuditingActionEnum.CREATE_RESOURCE, componentTypeEnum);
+    private List<InterfaceDefinition> getMappedInterfaceData(String inputJson, User user, ComponentTypeEnum componentTypeEnum) {
+        Either<UiComponentDataTransfer, ResponseFormat> uiComponentEither = getComponentsUtils()
+            .convertJsonToObjectUsingObjectMapper(inputJson, user, UiComponentDataTransfer.class, AuditingActionEnum.CREATE_RESOURCE,
+                componentTypeEnum);
         return new ArrayList<>(uiComponentEither.left().value().getInterfaces().values());
     }
 
     private Object getFormattedResponse(List<InterfaceDefinition> interfaceDefinitions) throws IOException {
-        Map<String, List<InterfaceDefinition>> allInterfaces =
-                ImmutableMap.of(JsonPresentationFields.INTERFACES.getPresentation(), interfaceDefinitions);
+        Map<String, List<InterfaceDefinition>> allInterfaces = ImmutableMap
+            .of(JsonPresentationFields.INTERFACES.getPresentation(), interfaceDefinitions);
         return RepresentationUtils.toFilteredRepresentation(allInterfaces);
     }
 
@@ -166,18 +152,17 @@ public class InterfaceOperationServlet extends AbstractValidationsServlet {
     @Consumes(MediaType.APPLICATION_JSON)
     @Produces(MediaType.APPLICATION_JSON)
     @Path("/resources/{resourceId}/interfaceOperations")
-    @Operation(description = "Update Interface Operations on Resource", method = "PUT",
-            summary = "Update Interface Operations on Resource", responses = {@ApiResponse(
-            content = @Content(array = @ArraySchema(schema = @Schema(implementation = InterfaceDefinition.class)))),
-            @ApiResponse(responseCode = "201", description = "Update Interface Operations on Resource"),
-            @ApiResponse(responseCode = "400", description = "Invalid content / Missing content"),
-            @ApiResponse(responseCode = "403", description = "Restricted operation"),
-            @ApiResponse(responseCode = "404", description = "Resource not found")})
+    @Operation(description = "Update Interface Operations on Resource", method = "PUT", summary = "Update Interface Operations on Resource", responses = {
+        @ApiResponse(content = @Content(array = @ArraySchema(schema = @Schema(implementation = InterfaceDefinition.class)))),
+        @ApiResponse(responseCode = "201", description = "Update Interface Operations on Resource"),
+        @ApiResponse(responseCode = "400", description = "Invalid content / Missing content"),
+        @ApiResponse(responseCode = "403", description = "Restricted operation"),
+        @ApiResponse(responseCode = "404", description = "Resource not found")})
     @PermissionAllowed(AafPermission.PermNames.INTERNAL_ALL_VALUE)
-    public Response updateInterfaceOperationsOnResource(
-            @Parameter(description = "Interface Operations to update", required = true) String data,
-            @Parameter(description = "Resource Id") @PathParam("resourceId") String resourceId,
-            @HeaderParam(value = Constants.USER_ID_HEADER) String userId, @Context final HttpServletRequest request) {
+    public Response updateInterfaceOperationsOnResource(@Parameter(description = "Interface Operations to update", required = true) String data,
+                                                        @Parameter(description = "Resource Id") @PathParam("resourceId") String resourceId,
+                                                        @HeaderParam(value = Constants.USER_ID_HEADER) String userId,
+                                                        @Context final HttpServletRequest request) {
         return createOrUpdate(data, ComponentTypeEnum.RESOURCE, resourceId, request, userId, true);
     }
 
@@ -185,42 +170,35 @@ public class InterfaceOperationServlet extends AbstractValidationsServlet {
     @Consumes(MediaType.APPLICATION_JSON)
     @Produces(MediaType.APPLICATION_JSON)
     @Path("/resources/{resourceId}/interfaces/{interfaceId}/operations/{operationId}")
-    @Operation(description = "Delete Interface Operation from Resource", method = "DELETE",
-            summary = "Delete Interface Operation from Resource", responses = {@ApiResponse(
-            content = @Content(array = @ArraySchema(schema = @Schema(implementation = InterfaceDefinition.class)))),
-            @ApiResponse(responseCode = "201", description = "Delete Interface Operation from Resource"),
-            @ApiResponse(responseCode = "400", description = "Invalid content / Missing content"),
-            @ApiResponse(responseCode = "403", description = "Restricted operation"),
-            @ApiResponse(responseCode = "404", description = "Resource not found")})
+    @Operation(description = "Delete Interface Operation from Resource", method = "DELETE", summary = "Delete Interface Operation from Resource", responses = {
+        @ApiResponse(content = @Content(array = @ArraySchema(schema = @Schema(implementation = InterfaceDefinition.class)))),
+        @ApiResponse(responseCode = "201", description = "Delete Interface Operation from Resource"),
+        @ApiResponse(responseCode = "400", description = "Invalid content / Missing content"),
+        @ApiResponse(responseCode = "403", description = "Restricted operation"),
+        @ApiResponse(responseCode = "404", description = "Resource not found")})
     @PermissionAllowed(AafPermission.PermNames.INTERNAL_ALL_VALUE)
-    public Response deleteInterfaceOperationsFromResource(
-            @Parameter(description = "Resource Id") @PathParam("resourceId") String resourceId,
-            @Parameter(description = "Interface Id") @PathParam("interfaceId") String interfaceId,
-            @Parameter(description = "Operation Id") @PathParam("operationId") String operationId,
-            @HeaderParam(value = Constants.USER_ID_HEADER) String userId, @Context final HttpServletRequest request) {
+    public Response deleteInterfaceOperationsFromResource(@Parameter(description = "Resource Id") @PathParam("resourceId") String resourceId,
+                                                          @Parameter(description = "Interface Id") @PathParam("interfaceId") String interfaceId,
+                                                          @Parameter(description = "Operation Id") @PathParam("operationId") String operationId,
+                                                          @HeaderParam(value = Constants.USER_ID_HEADER) String userId,
+                                                          @Context final HttpServletRequest request) {
         return delete(interfaceId, operationId, resourceId, request, userId);
     }
 
-    private Response delete(String interfaceId, String operationId, String componentId, HttpServletRequest request,
-            String userId) {
-
+    private Response delete(String interfaceId, String operationId, String componentId, HttpServletRequest request, String userId) {
         String url = request.getMethod() + " " + request.getRequestURI();
-
         User modifier = new User();
         modifier.setUserId(userId);
         log.debug("Start delete request of {} with modifier id {}", url, userId);
-
         try {
             String componentIdLower = componentId.toLowerCase();
-            Either<List<InterfaceDefinition>, ResponseFormat> actionResponse = interfaceOperationBusinessLogic.deleteInterfaceOperation(
-                    componentIdLower, interfaceId, Collections.singletonList(operationId), modifier, true);
+            Either<List<InterfaceDefinition>, ResponseFormat> actionResponse = interfaceOperationBusinessLogic
+                .deleteInterfaceOperation(componentIdLower, interfaceId, Collections.singletonList(operationId), modifier, true);
             if (actionResponse.isRight()) {
                 log.error("failed to delete interface operation");
                 return buildErrorResponse(actionResponse.right().value());
             }
-
-            return buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK),
-                    getFormattedResponse(actionResponse.left().value()));
+            return buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), getFormattedResponse(actionResponse.left().value()));
         } catch (Exception e) {
             BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Delete Interface Operation");
             log.error("Delete interface operation with an error", e);
@@ -232,41 +210,35 @@ public class InterfaceOperationServlet extends AbstractValidationsServlet {
     @Consumes(MediaType.APPLICATION_JSON)
     @Produces(MediaType.APPLICATION_JSON)
     @Path("/resources/{resourceId}/interfaces/{interfaceId}/operations/{operationId}")
-    @Operation(description = "Get Interface Operation from Resource", method = "GET",
-            summary = "GET Interface Operation from Resource", responses = {@ApiResponse(
-            content = @Content(array = @ArraySchema(schema = @Schema(implementation = InterfaceDefinition.class)))),
-            @ApiResponse(responseCode = "201", description = "Delete Interface Operation from Resource"),
-            @ApiResponse(responseCode = "400", description = "Invalid content / Missing content"),
-            @ApiResponse(responseCode = "403", description = "Restricted operation"),
-            @ApiResponse(responseCode = "404", description = "Resource not found")})
+    @Operation(description = "Get Interface Operation from Resource", method = "GET", summary = "GET Interface Operation from Resource", responses = {
+        @ApiResponse(content = @Content(array = @ArraySchema(schema = @Schema(implementation = InterfaceDefinition.class)))),
+        @ApiResponse(responseCode = "201", description = "Delete Interface Operation from Resource"),
+        @ApiResponse(responseCode = "400", description = "Invalid content / Missing content"),
+        @ApiResponse(responseCode = "403", description = "Restricted operation"),
+        @ApiResponse(responseCode = "404", description = "Resource not found")})
     @PermissionAllowed(AafPermission.PermNames.INTERNAL_ALL_VALUE)
-    public Response getInterfaceOperationsFromResource(
-            @Parameter(description = "Resource Id") @PathParam("resourceId") String resourceId,
-            @Parameter(description = "Interface Id") @PathParam("interfaceId") String interfaceId,
-            @Parameter(description = "Operation Id") @PathParam("operationId") String operationId,
-            @HeaderParam(value = Constants.USER_ID_HEADER) String userId, @Context final HttpServletRequest request) {
+    public Response getInterfaceOperationsFromResource(@Parameter(description = "Resource Id") @PathParam("resourceId") String resourceId,
+                                                       @Parameter(description = "Interface Id") @PathParam("interfaceId") String interfaceId,
+                                                       @Parameter(description = "Operation Id") @PathParam("operationId") String operationId,
+                                                       @HeaderParam(value = Constants.USER_ID_HEADER) String userId,
+                                                       @Context final HttpServletRequest request) {
         return get(interfaceId, operationId, resourceId, request, userId);
     }
 
-    private Response get(String interfaceId, String operationId, String componentId, HttpServletRequest request,
-            String userId) {
+    private Response get(String interfaceId, String operationId, String componentId, HttpServletRequest request, String userId) {
         String url = request.getMethod() + " " + request.getRequestURI();
-
         User modifier = new User();
         modifier.setUserId(userId);
         log.debug("Start get request of {} with modifier id {}", url, userId);
-
         try {
             String componentIdLower = componentId.toLowerCase();
-            Either<List<InterfaceDefinition>, ResponseFormat> actionResponse = interfaceOperationBusinessLogic.getInterfaceOperation(
-                    componentIdLower, interfaceId, Collections.singletonList(operationId), modifier, true);
+            Either<List<InterfaceDefinition>, ResponseFormat> actionResponse = interfaceOperationBusinessLogic
+                .getInterfaceOperation(componentIdLower, interfaceId, Collections.singletonList(operationId), modifier, true);
             if (actionResponse.isRight()) {
                 log.error("failed to get interface operation");
                 return buildErrorResponse(actionResponse.right().value());
             }
-
-            return buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK),
-                    getFormattedResponse(actionResponse.left().value()));
+            return buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), getFormattedResponse(actionResponse.left().value()));
         } catch (Exception e) {
             BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Get Component interface operations");
             log.error("get component interface operations failed with exception", e);
@@ -278,19 +250,18 @@ public class InterfaceOperationServlet extends AbstractValidationsServlet {
     @Consumes(MediaType.APPLICATION_JSON)
     @Produces(MediaType.APPLICATION_JSON)
     @Path("/services/{serviceId}/interfaceOperations")
-    @Operation(description = "Create Interface Operations on Service", method = "POST",
-            summary = "Create Interface Operations on Service", responses = {@ApiResponse(
-            content = @Content(array = @ArraySchema(schema = @Schema(implementation = InterfaceDefinition.class)))),
-            @ApiResponse(responseCode = "201", description = "Create Interface Operations on Service"),
-            @ApiResponse(responseCode = "400", description = "Invalid content / Missing content"),
-            @ApiResponse(responseCode = "403", description = "Restricted operation"),
-            @ApiResponse(responseCode = "404", description = "Service not found"),
-            @ApiResponse(responseCode = "409", description = "Interface Operation already exist")})
+    @Operation(description = "Create Interface Operations on Service", method = "POST", summary = "Create Interface Operations on Service", responses = {
+        @ApiResponse(content = @Content(array = @ArraySchema(schema = @Schema(implementation = InterfaceDefinition.class)))),
+        @ApiResponse(responseCode = "201", description = "Create Interface Operations on Service"),
+        @ApiResponse(responseCode = "400", description = "Invalid content / Missing content"),
+        @ApiResponse(responseCode = "403", description = "Restricted operation"),
+        @ApiResponse(responseCode = "404", description = "Service not found"),
+        @ApiResponse(responseCode = "409", description = "Interface Operation already exist")})
     @PermissionAllowed(AafPermission.PermNames.INTERNAL_ALL_VALUE)
-    public Response createInterfaceOperationsOnService(
-            @Parameter(description = "Interface Operations to create", required = true) String data,
-            @Parameter(description = "Service Id") @PathParam("serviceId") String serviceId,
-            @HeaderParam(value = Constants.USER_ID_HEADER) String userId, @Context final HttpServletRequest request) {
+    public Response createInterfaceOperationsOnService(@Parameter(description = "Interface Operations to create", required = true) String data,
+                                                       @Parameter(description = "Service Id") @PathParam("serviceId") String serviceId,
+                                                       @HeaderParam(value = Constants.USER_ID_HEADER) String userId,
+                                                       @Context final HttpServletRequest request) {
         return createOrUpdate(data, ComponentTypeEnum.SERVICE, serviceId, request, userId, false);
     }
 
@@ -298,18 +269,17 @@ public class InterfaceOperationServlet extends AbstractValidationsServlet {
     @Consumes(MediaType.APPLICATION_JSON)
     @Produces(MediaType.APPLICATION_JSON)
     @Path("/services/{serviceId}/interfaceOperations")
-    @Operation(description = "Update Interface Operations on Service", method = "PUT",
-            summary = "Update Interface Operations on Service", responses = {@ApiResponse(
-            content = @Content(array = @ArraySchema(schema = @Schema(implementation = InterfaceDefinition.class)))),
-            @ApiResponse(responseCode = "201", description = "Update Interface Operations on Service"),
-            @ApiResponse(responseCode = "400", description = "Invalid content / Missing content"),
-            @ApiResponse(responseCode = "403", description = "Restricted operation"),
-            @ApiResponse(responseCode = "404", description = "Service not found")})
+    @Operation(description = "Update Interface Operations on Service", method = "PUT", summary = "Update Interface Operations on Service", responses = {
+        @ApiResponse(content = @Content(array = @ArraySchema(schema = @Schema(implementation = InterfaceDefinition.class)))),
+        @ApiResponse(responseCode = "201", description = "Update Interface Operations on Service"),
+        @ApiResponse(responseCode = "400", description = "Invalid content / Missing content"),
+        @ApiResponse(responseCode = "403", description = "Restricted operation"),
+        @ApiResponse(responseCode = "404", description = "Service not found")})
     @PermissionAllowed(AafPermission.PermNames.INTERNAL_ALL_VALUE)
-    public Response updateInterfaceOperationsOnService(
-            @Parameter(description = "Interface Operations to update", required = true) String data,
-            @Parameter(description = "Service Id") @PathParam("serviceId") String serviceId,
-            @HeaderParam(value = Constants.USER_ID_HEADER) String userId, @Context final HttpServletRequest request) {
+    public Response updateInterfaceOperationsOnService(@Parameter(description = "Interface Operations to update", required = true) String data,
+                                                       @Parameter(description = "Service Id") @PathParam("serviceId") String serviceId,
+                                                       @HeaderParam(value = Constants.USER_ID_HEADER) String userId,
+                                                       @Context final HttpServletRequest request) {
         return createOrUpdate(data, ComponentTypeEnum.SERVICE, serviceId, request, userId, true);
     }
 
@@ -317,19 +287,18 @@ public class InterfaceOperationServlet extends AbstractValidationsServlet {
     @Consumes(MediaType.APPLICATION_JSON)
     @Produces(MediaType.APPLICATION_JSON)
     @Path("/services/{serviceId}/interfaces/{interfaceId}/operations/{operationId}")
-    @Operation(description = "Delete Interface Operation from Service", method = "DELETE",
-            summary = "Delete Interface Operation from Service", responses = {@ApiResponse(
-            content = @Content(array = @ArraySchema(schema = @Schema(implementation = InterfaceDefinition.class)))),
-            @ApiResponse(responseCode = "201", description = "Delete Interface Operation from Service"),
-            @ApiResponse(responseCode = "400", description = "Invalid content / Missing content"),
-            @ApiResponse(responseCode = "403", description = "Restricted operation"),
-            @ApiResponse(responseCode = "404", description = "Service not found")})
+    @Operation(description = "Delete Interface Operation from Service", method = "DELETE", summary = "Delete Interface Operation from Service", responses = {
+        @ApiResponse(content = @Content(array = @ArraySchema(schema = @Schema(implementation = InterfaceDefinition.class)))),
+        @ApiResponse(responseCode = "201", description = "Delete Interface Operation from Service"),
+        @ApiResponse(responseCode = "400", description = "Invalid content / Missing content"),
+        @ApiResponse(responseCode = "403", description = "Restricted operation"),
+        @ApiResponse(responseCode = "404", description = "Service not found")})
     @PermissionAllowed(AafPermission.PermNames.INTERNAL_ALL_VALUE)
-    public Response deleteInterfaceOperationsFromService(
-            @Parameter(description = "Service Id") @PathParam("serviceId") String serviceId,
-            @Parameter(description = "Interface Id") @PathParam("interfaceId") String interfaceId,
-            @Parameter(description = "Operation Id") @PathParam("operationId") String operationId,
-            @HeaderParam(value = Constants.USER_ID_HEADER) String userId, @Context final HttpServletRequest request) {
+    public Response deleteInterfaceOperationsFromService(@Parameter(description = "Service Id") @PathParam("serviceId") String serviceId,
+                                                         @Parameter(description = "Interface Id") @PathParam("interfaceId") String interfaceId,
+                                                         @Parameter(description = "Operation Id") @PathParam("operationId") String operationId,
+                                                         @HeaderParam(value = Constants.USER_ID_HEADER) String userId,
+                                                         @Context final HttpServletRequest request) {
         return delete(interfaceId, operationId, serviceId, request, userId);
     }
 
@@ -337,20 +306,18 @@ public class InterfaceOperationServlet extends AbstractValidationsServlet {
     @Consumes(MediaType.APPLICATION_JSON)
     @Produces(MediaType.APPLICATION_JSON)
     @Path("/services/{serviceId}/interfaces/{interfaceId}/operations/{operationId}")
-    @Operation(description = "Get Interface Operation from Service", method = "GET",
-            summary = "GET Interface Operation from Service", responses = {@ApiResponse(
-            content = @Content(array = @ArraySchema(schema = @Schema(implementation = InterfaceDefinition.class)))),
-            @ApiResponse(responseCode = "201", description = "Get Interface Operation from Service"),
-            @ApiResponse(responseCode = "400", description = "Invalid content / Missing content"),
-            @ApiResponse(responseCode = "403", description = "Restricted operation"),
-            @ApiResponse(responseCode = "404", description = "Service not found")})
+    @Operation(description = "Get Interface Operation from Service", method = "GET", summary = "GET Interface Operation from Service", responses = {
+        @ApiResponse(content = @Content(array = @ArraySchema(schema = @Schema(implementation = InterfaceDefinition.class)))),
+        @ApiResponse(responseCode = "201", description = "Get Interface Operation from Service"),
+        @ApiResponse(responseCode = "400", description = "Invalid content / Missing content"),
+        @ApiResponse(responseCode = "403", description = "Restricted operation"),
+        @ApiResponse(responseCode = "404", description = "Service not found")})
     @PermissionAllowed(AafPermission.PermNames.INTERNAL_ALL_VALUE)
-    public Response getInterfaceOperationsFromService(
-            @Parameter(description = "Service Id") @PathParam("serviceId") String serviceId,
-            @Parameter(description = "Interface Id") @PathParam("interfaceId") String interfaceId,
-            @Parameter(description = "Operation Id") @PathParam("operationId") String operationId,
-            @HeaderParam(value = Constants.USER_ID_HEADER) String userId, @Context final HttpServletRequest request) {
+    public Response getInterfaceOperationsFromService(@Parameter(description = "Service Id") @PathParam("serviceId") String serviceId,
+                                                      @Parameter(description = "Interface Id") @PathParam("interfaceId") String interfaceId,
+                                                      @Parameter(description = "Operation Id") @PathParam("operationId") String operationId,
+                                                      @HeaderParam(value = Constants.USER_ID_HEADER) String userId,
+                                                      @Context final HttpServletRequest request) {
         return get(interfaceId, operationId, serviceId, request, userId);
     }
 }
-
index 87c890d..de66aa6 100644 (file)
@@ -17,7 +17,6 @@
  * limitations under the License.
  * ============LICENSE_END=========================================================
  */
-
 package org.openecomp.sdc.be.servlets;
 
 import com.fasterxml.jackson.databind.ObjectMapper;
@@ -82,45 +81,37 @@ public class LifecycleServlet extends BeGenericServlet {
     private LifecycleBusinessLogic lifecycleBusinessLogic;
 
     @Inject
-    public LifecycleServlet(UserBusinessLogic userBusinessLogic,
-        ComponentsUtils componentsUtils,
-        LifecycleBusinessLogic lifecycleBusinessLogic) {
+    public LifecycleServlet(UserBusinessLogic userBusinessLogic, ComponentsUtils componentsUtils, LifecycleBusinessLogic lifecycleBusinessLogic) {
         super(userBusinessLogic, componentsUtils);
         this.lifecycleBusinessLogic = lifecycleBusinessLogic;
     }
 
-
     @POST
     @Path("/{componentCollection}/{componentId}/lifecycleState/{lifecycleOperation}")
     @Consumes(MediaType.APPLICATION_JSON)
     @Produces(MediaType.APPLICATION_JSON)
     @Operation(description = "Change Resource lifecycle State", method = "POST", responses = {
-            @ApiResponse(content = @Content(array = @ArraySchema(schema = @Schema(implementation = Response.class)))),
-            @ApiResponse(responseCode = "200", description = "Resource state changed"),
-            @ApiResponse(responseCode = "403", description = "Restricted operation"),
-            @ApiResponse(responseCode = "409", description = "Resource already exist")})
+        @ApiResponse(content = @Content(array = @ArraySchema(schema = @Schema(implementation = Response.class)))),
+        @ApiResponse(responseCode = "200", description = "Resource state changed"),
+        @ApiResponse(responseCode = "403", description = "Restricted operation"),
+        @ApiResponse(responseCode = "409", description = "Resource already exist")})
     @PermissionAllowed(AafPermission.PermNames.INTERNAL_ALL_VALUE)
     public Response changeResourceState(
-            @Parameter(description = "LifecycleChangeInfo - relevant for checkin, failCertification, cancelCertification")
-                String jsonChangeInfo,
-            @Parameter(description = "validValues: resources / services / products",
-                    schema = @Schema(allowableValues = {ComponentTypeEnum.RESOURCE_PARAM_NAME,
-                            ComponentTypeEnum.SERVICE_PARAM_NAME, ComponentTypeEnum.PRODUCT_PARAM_NAME})) @PathParam(
-                                    value = "componentCollection") final String componentCollection,
-            @Parameter(schema = @Schema(allowableValues = {
-                    "checkout, undoCheckout, checkin, certificationRequest, startCertification, failCertification,  cancelCertification, certify"}),
-                    required = true) @PathParam(value = "lifecycleOperation") final String lifecycleTransition,
-            @Parameter(description = "id of component to be changed") @PathParam(
-                    value = "componentId") final String componentId,
-            @Context final HttpServletRequest request,
-            @Parameter(description = "id of user initiating the operation") @HeaderParam(
-                    value = Constants.USER_ID_HEADER) String userId) throws IOException {
+        @Parameter(description = "LifecycleChangeInfo - relevant for checkin, failCertification, cancelCertification") String jsonChangeInfo,
+        @Parameter(description = "validValues: resources / services / products", schema = @Schema(allowableValues = {
+            ComponentTypeEnum.RESOURCE_PARAM_NAME, ComponentTypeEnum.SERVICE_PARAM_NAME,
+            ComponentTypeEnum.PRODUCT_PARAM_NAME})) @PathParam(value = "componentCollection") final String componentCollection,
+        @Parameter(schema = @Schema(allowableValues = {
+            "checkout, undoCheckout, checkin, certificationRequest, startCertification, failCertification,  cancelCertification, certify"}), required = true) @PathParam(value = "lifecycleOperation") final String lifecycleTransition,
+        @Parameter(description = "id of component to be changed") @PathParam(value = "componentId") final String componentId,
+        @Context final HttpServletRequest request,
+        @Parameter(description = "id of user initiating the operation") @HeaderParam(value = Constants.USER_ID_HEADER) String userId)
+        throws IOException {
         String url = request.getMethod() + " " + request.getRequestURI();
         log.debug("Start handle request of {}", url);
-        loggerSupportability.log(LoggerSupportabilityActions.CHANGELIFECYCLESTATE, StatusCode.STARTED,"Starting to change lifecycle state to " + lifecycleTransition + " by user " + userId);
-
+        loggerSupportability.log(LoggerSupportabilityActions.CHANGELIFECYCLESTATE, StatusCode.STARTED,
+            "Starting to change lifecycle state to " + lifecycleTransition + " by user " + userId);
         Response response = null;
-
         // get modifier from graph
         log.debug("get modifier properties");
         Either<User, ResponseFormat> eitherGetUser = getUser(request, userId);
@@ -128,58 +119,54 @@ public class LifecycleServlet extends BeGenericServlet {
             return buildErrorResponse(eitherGetUser.right().value());
         }
         User user = eitherGetUser.left().value();
-
         String resourceIdLower = componentId.toLowerCase();
         log.debug("perform {} operation to resource with id {} ", lifecycleTransition, resourceIdLower);
         Either<LifeCycleTransitionEnum, Response> validateEnum = validateTransitionEnum(lifecycleTransition, user);
         if (validateEnum.isRight()) {
             return validateEnum.right().value();
         }
-
         LifecycleChangeInfoWithAction changeInfo = new LifecycleChangeInfoWithAction();
-
         try {
             if (jsonChangeInfo != null && !jsonChangeInfo.isEmpty()) {
                 ObjectMapper mapper = new ObjectMapper();
-                changeInfo = new LifecycleChangeInfoWithAction(mapper
-                    .readValue(ValidationUtils.sanitizeInputString(jsonChangeInfo), LifecycleChangeInfoBase.class)
-                    .getUserRemarks());
+                changeInfo = new LifecycleChangeInfoWithAction(
+                    mapper.readValue(ValidationUtils.sanitizeInputString(jsonChangeInfo), LifecycleChangeInfoBase.class).getUserRemarks());
             }
-        }
-
-        catch (Exception e) {
+        } catch (Exception e) {
             BeEcompErrorManager.getInstance().logBeInvalidJsonInput("convertJsonToObject");
             log.debug("failed to convert from json {}", jsonChangeInfo, e);
             getComponentsUtils().getInvalidContentErrorAndAudit(user, componentId, AuditingActionEnum.CHECKOUT_RESOURCE);
             throw e;
         }
-
         LifeCycleTransitionEnum transitionEnum = validateEnum.left().value();
         ComponentTypeEnum componentType = ComponentTypeEnum.findByParamName(componentCollection);
         if (componentType != null) {
-            Either<? extends Component, ResponseFormat> actionResponse = lifecycleBusinessLogic.changeComponentState(componentType, componentId, user, transitionEnum, changeInfo, false, true);
-
+            Either<? extends Component, ResponseFormat> actionResponse = lifecycleBusinessLogic
+                .changeComponentState(componentType, componentId, user, transitionEnum, changeInfo, false, true);
             if (actionResponse.isRight()) {
                 log.info("failed to change resource state");
-                loggerSupportability.log(LoggerSupportabilityActions.CHANGELIFECYCLESTATE, StatusCode.ERROR,"failed to change resource state " + lifecycleTransition + " with error " + actionResponse.isRight() +  " by user " + userId);
+                loggerSupportability.log(LoggerSupportabilityActions.CHANGELIFECYCLESTATE, StatusCode.ERROR,
+                    "failed to change resource state " + lifecycleTransition + " with error " + actionResponse.isRight() + " by user " + userId);
                 response = buildErrorResponse(actionResponse.right().value());
                 return response;
             }
-
             log.debug("change state successful !!!");
             UiComponentMetadata componentMetatdata = UiComponentDataConverter.convertToUiComponentMetadata(actionResponse.left().value());
             Object value = null;
             try {
-            value = RepresentationUtils.toRepresentation(componentMetatdata);
+                value = RepresentationUtils.toRepresentation(componentMetatdata);
             } catch (IOException e) {
                 e.printStackTrace();
             }
             response = buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), value);
-            loggerSupportability.log(LoggerSupportabilityActions.CHANGELIFECYCLESTATE,actionResponse.left().value().getComponentMetadataForSupportLog(),StatusCode.COMPLETE," change state to " + lifecycleTransition + " was successful by user" + userId);
+            loggerSupportability
+                .log(LoggerSupportabilityActions.CHANGELIFECYCLESTATE, actionResponse.left().value().getComponentMetadataForSupportLog(),
+                    StatusCode.COMPLETE, " change state to " + lifecycleTransition + " was successful by user" + userId);
             return response;
         } else {
-            log.info("componentCollection \"{}\" is not valid. Supported componentCollection values are \"{}\", \"{}\" or \"{}\"", componentCollection, ComponentTypeEnum.RESOURCE_PARAM_NAME, ComponentTypeEnum.SERVICE_PARAM_NAME,
-                    ComponentTypeEnum.PRODUCT_PARAM_NAME);
+            log.info("componentCollection \"{}\" is not valid. Supported componentCollection values are \"{}\", \"{}\" or \"{}\"",
+                componentCollection, ComponentTypeEnum.RESOURCE_PARAM_NAME, ComponentTypeEnum.SERVICE_PARAM_NAME,
+                ComponentTypeEnum.PRODUCT_PARAM_NAME);
             ResponseFormat error = getComponentsUtils().getInvalidContentErrorAndAudit(user, componentId, AuditingActionEnum.CHECKOUT_RESOURCE);
             return buildErrorResponse(error);
         }
@@ -196,5 +183,4 @@ public class LifecycleServlet extends BeGenericServlet {
         }
         return Either.left(transitionEnum);
     }
-
 }
index 8f00d17..eb75825 100644 (file)
@@ -17,7 +17,6 @@
  * limitations under the License.
  * ============LICENSE_END=========================================================
  */
-
 package org.openecomp.sdc.be.servlets;
 
 import com.jcabi.aspects.Loggable;
@@ -79,16 +78,12 @@ public class OutputsServlet extends AbstractValidationsServlet {
 
     private static final Logger log = Logger.getLogger(OutputsServlet.class);
     private static final String START_HANDLE_REQUEST_OF = "(get) Start handle request of {}";
-
     private final OutputsBusinessLogic outputsBusinessLogic;
 
     @Inject
-    public OutputsServlet(final UserBusinessLogic userBusinessLogic,
-                          final OutputsBusinessLogic outputsBusinessLogic,
-                          final ComponentInstanceBusinessLogic componentInstanceBL,
-                          final ComponentsUtils componentsUtils,
-                          final ServletUtils servletUtils,
-                          final ResourceImportManager resourceImportManager) {
+    public OutputsServlet(final UserBusinessLogic userBusinessLogic, final OutputsBusinessLogic outputsBusinessLogic,
+                          final ComponentInstanceBusinessLogic componentInstanceBL, final ComponentsUtils componentsUtils,
+                          final ServletUtils servletUtils, final ResourceImportManager resourceImportManager) {
         super(userBusinessLogic, componentInstanceBL, componentsUtils, servletUtils, resourceImportManager);
         this.outputsBusinessLogic = outputsBusinessLogic;
     }
@@ -97,29 +92,24 @@ public class OutputsServlet extends AbstractValidationsServlet {
     @Path("/{componentType}/{componentId}/componentInstances/{instanceId}/{originComponentUid}/outputs")
     @Operation(description = "Get Outputs only", method = "GET", summary = "Returns Outputs list", responses = {
         @ApiResponse(content = @Content(array = @ArraySchema(schema = @Schema(implementation = Resource.class)))),
-        @ApiResponse(responseCode = "200", description = "Component found"),
-        @ApiResponse(responseCode = "403", description = "Restricted operation"),
+        @ApiResponse(responseCode = "200", description = "Component found"), @ApiResponse(responseCode = "403", description = "Restricted operation"),
         @ApiResponse(responseCode = "404", description = "Component not found")})
     public Response getComponentInstanceOutputs(@PathParam("componentType") final String componentType,
-                                                @PathParam("componentId") final String componentId,
-                                                @PathParam("instanceId") final String instanceId,
+                                                @PathParam("componentId") final String componentId, @PathParam("instanceId") final String instanceId,
                                                 @PathParam("originComponentUid") final String originComponentUid,
                                                 @Context final HttpServletRequest request,
                                                 @HeaderParam(value = Constants.USER_ID_HEADER) final String userId) {
-
         final String url = request.getMethod() + " " + request.getRequestURI();
         log.debug(START_HANDLE_REQUEST_OF, url);
-
         try {
-            final Either<List<ComponentInstanceOutput>, ResponseFormat> outputsResponse =
-                outputsBusinessLogic.getComponentInstanceOutputs(userId, componentId, instanceId);
+            final Either<List<ComponentInstanceOutput>, ResponseFormat> outputsResponse = outputsBusinessLogic
+                .getComponentInstanceOutputs(userId, componentId, instanceId);
             if (outputsResponse.isRight()) {
                 log.debug("failed to get component instance outputs {}", componentType);
                 return buildErrorResponse(outputsResponse.right().value());
             }
             final Object outputs = RepresentationUtils.toRepresentation(outputsResponse.left().value());
             return buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), outputs);
-
         } catch (final Exception e) {
             BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Get Outputs " + componentType);
             log.debug("getOutputs failed with exception", e);
@@ -131,61 +121,49 @@ public class OutputsServlet extends AbstractValidationsServlet {
     @Path("/{componentType}/{componentId}/create/outputs")
     @Operation(description = "Create outputs on service", method = "POST", summary = "Return outputs list", responses = {
         @ApiResponse(content = @Content(array = @ArraySchema(schema = @Schema(implementation = Resource.class)))),
-        @ApiResponse(responseCode = "200", description = "Component found"),
-        @ApiResponse(responseCode = "403", description = "Restricted operation"),
+        @ApiResponse(responseCode = "200", description = "Component found"), @ApiResponse(responseCode = "403", description = "Restricted operation"),
         @ApiResponse(responseCode = "404", description = "Component not found")})
-    public Response createMultipleOutputs(@PathParam("componentType") final String componentType,
-                                          @PathParam("componentId") final String componentId,
+    public Response createMultipleOutputs(@PathParam("componentType") final String componentType, @PathParam("componentId") final String componentId,
                                           @Context final HttpServletRequest request,
                                           @HeaderParam(value = Constants.USER_ID_HEADER) final String userId,
                                           @Parameter(description = "ComponentIns Outputs Object to be created", required = true) final String componentInstOutputsMapObj) {
         final String url = request.getMethod() + " " + request.getRequestURI();
         log.debug(START_HANDLE_REQUEST_OF, url);
-
         try {
             return declareAttributes(userId, componentId, componentType, componentInstOutputsMapObj, DeclarationTypeEnum.OUTPUT, request);
-
         } catch (final Exception e) {
-            BeEcompErrorManager.getInstance()
-                .logBeRestApiGeneralError("Create outputs for service with id: " + componentId);
+            BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Create outputs for service with id: " + componentId);
             log.debug("Attributes declaration failed with exception", e);
             return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR));
         }
     }
 
-    private Response declareAttributes(final String userId,
-                                         final String componentId,
-                                         final String componentType,
-                                         final String componentInstOutputsMapObj,
-                                         final DeclarationTypeEnum typeEnum,
-                                         final HttpServletRequest request) {
+    private Response declareAttributes(final String userId, final String componentId, final String componentType,
+                                       final String componentInstOutputsMapObj, final DeclarationTypeEnum typeEnum,
+                                       final HttpServletRequest request) {
         final ServletContext context = request.getSession().getServletContext();
         final String url = request.getMethod() + " " + request.getRequestURI();
         log.debug(START_HANDLE_REQUEST_OF, url);
-
         try {
             final BaseBusinessLogic businessLogic = getBlForDeclaration(typeEnum, context);
-
             // get modifier id
             final User modifier = new User(userId);
             log.debug("modifier id is {}", userId);
             final ComponentTypeEnum componentTypeEnum = ComponentTypeEnum.findByParamName(componentType);
-            final Either<ComponentInstOutputsMap, ResponseFormat> componentInstOutputsMapRes = parseToComponentInstanceMap(
-                componentInstOutputsMapObj, modifier, componentTypeEnum, ComponentInstOutputsMap.class);
+            final Either<ComponentInstOutputsMap, ResponseFormat> componentInstOutputsMapRes = parseToComponentInstanceMap(componentInstOutputsMapObj,
+                modifier, componentTypeEnum, ComponentInstOutputsMap.class);
             if (componentInstOutputsMapRes.isRight()) {
                 log.debug("failed to parse componentInstOutMap");
                 return buildErrorResponse(componentInstOutputsMapRes.right().value());
             }
-
-            final Either<List<ToscaDataDefinition>, ResponseFormat> attributesAfterDeclaration =
-                businessLogic.declareAttributes(userId, componentId, componentTypeEnum, componentInstOutputsMapRes.left().value());
+            final Either<List<ToscaDataDefinition>, ResponseFormat> attributesAfterDeclaration = businessLogic
+                .declareAttributes(userId, componentId, componentTypeEnum, componentInstOutputsMapRes.left().value());
             if (attributesAfterDeclaration.isRight()) {
                 log.debug("failed to create outputs  for service: {}", componentId);
                 return buildErrorResponse(attributesAfterDeclaration.right().value());
             }
             final Object attributes = RepresentationUtils.toRepresentation(attributesAfterDeclaration.left().value());
             return buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), attributes);
-
         } catch (final Exception e) {
             BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Create outputs for service with id: " + componentId);
             log.debug("Attributes declaration failed with exception", e);
@@ -195,22 +173,16 @@ public class OutputsServlet extends AbstractValidationsServlet {
 
     @DELETE
     @Path("/{componentType}/{componentId}/delete/{outputId}/output")
-    @Operation(description = "Delete output from service", method = "DELETE", summary = "Delete service output",
-        responses = {@ApiResponse(
-            content = @Content(array = @ArraySchema(schema = @Schema(implementation = Resource.class)))),
-            @ApiResponse(responseCode = "200", description = "Output deleted"),
-            @ApiResponse(responseCode = "403", description = "Restricted operation"),
-            @ApiResponse(responseCode = "404", description = "Output not found")})
-    public Response deleteOutput(@PathParam("componentType") final String componentType,
-                                 @PathParam("componentId") final String componentId,
-                                 @PathParam("outputId") final String outputId,
-                                 @Context final HttpServletRequest request,
+    @Operation(description = "Delete output from service", method = "DELETE", summary = "Delete service output", responses = {
+        @ApiResponse(content = @Content(array = @ArraySchema(schema = @Schema(implementation = Resource.class)))),
+        @ApiResponse(responseCode = "200", description = "Output deleted"), @ApiResponse(responseCode = "403", description = "Restricted operation"),
+        @ApiResponse(responseCode = "404", description = "Output not found")})
+    public Response deleteOutput(@PathParam("componentType") final String componentType, @PathParam("componentId") final String componentId,
+                                 @PathParam("outputId") final String outputId, @Context final HttpServletRequest request,
                                  @HeaderParam(value = Constants.USER_ID_HEADER) final String userId,
                                  @Parameter(description = "Service Output to be deleted", required = true) final String componentInstOutputsMapObj) {
-
         String url = request.getMethod() + " " + request.getRequestURI();
         log.debug(START_HANDLE_REQUEST_OF, url);
-
         try {
             final OutputDefinition deleteOutput = outputsBusinessLogic.deleteOutput(componentId, userId, outputId);
             return buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), deleteOutput);
@@ -220,5 +192,4 @@ public class OutputsServlet extends AbstractValidationsServlet {
             return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR));
         }
     }
-
 }
index 141d4cb..eaa9af4 100644 (file)
@@ -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.
@@ -17,7 +17,6 @@
  * limitations under the License.
  * ============LICENSE_END=========================================================
  */
-
 package org.openecomp.sdc.be.servlets;
 
 import com.jcabi.aspects.Loggable;
@@ -32,6 +31,24 @@ import io.swagger.v3.oas.annotations.servers.Server;
 import io.swagger.v3.oas.annotations.servers.Servers;
 import io.swagger.v3.oas.annotations.tags.Tag;
 import io.swagger.v3.oas.annotations.tags.Tags;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+import java.util.stream.Collectors;
+import javax.inject.Inject;
+import javax.servlet.http.HttpServletRequest;
+import javax.ws.rs.Consumes;
+import javax.ws.rs.DELETE;
+import javax.ws.rs.GET;
+import javax.ws.rs.HeaderParam;
+import javax.ws.rs.POST;
+import javax.ws.rs.PUT;
+import javax.ws.rs.Path;
+import javax.ws.rs.PathParam;
+import javax.ws.rs.Produces;
+import javax.ws.rs.core.Context;
+import javax.ws.rs.core.MediaType;
+import javax.ws.rs.core.Response;
 import org.apache.commons.lang3.StringUtils;
 import org.openecomp.sdc.be.components.impl.ComponentInstanceBusinessLogic;
 import org.openecomp.sdc.be.components.impl.PolicyBusinessLogic;
@@ -59,24 +76,6 @@ import org.openecomp.sdc.common.log.wrappers.Logger;
 import org.openecomp.sdc.exception.ResponseFormat;
 import org.springframework.stereotype.Controller;
 
-import javax.inject.Inject;
-import javax.servlet.http.HttpServletRequest;
-import javax.ws.rs.Consumes;
-import javax.ws.rs.DELETE;
-import javax.ws.rs.GET;
-import javax.ws.rs.HeaderParam;
-import javax.ws.rs.POST;
-import javax.ws.rs.PUT;
-import javax.ws.rs.Path;
-import javax.ws.rs.PathParam;
-import javax.ws.rs.Produces;
-import javax.ws.rs.core.Context;
-import javax.ws.rs.core.MediaType;
-import javax.ws.rs.core.Response;
-import java.util.HashMap;
-import java.util.List;
-import java.util.Map;
-import java.util.stream.Collectors;
 /**
  * Provides REST API to create, retrieve, update, delete a policy
  */
@@ -90,15 +89,12 @@ import java.util.stream.Collectors;
 public class PolicyServlet extends AbstractValidationsServlet {
 
     private static final Logger log = Logger.getLogger(PolicyServlet.class);
-    private final PolicyBusinessLogic policyBusinessLogic;
     private static final LoggerSupportability loggerSupportability = LoggerSupportability.getLogger(ServiceServlet.class.getName());
+    private final PolicyBusinessLogic policyBusinessLogic;
 
     @Inject
-    public PolicyServlet(UserBusinessLogic userBusinessLogic,
-        ComponentInstanceBusinessLogic componentInstanceBL,
-        ComponentsUtils componentsUtils, ServletUtils servletUtils,
-        ResourceImportManager resourceImportManager,
-        PolicyBusinessLogic policyBusinessLogic) {
+    public PolicyServlet(UserBusinessLogic userBusinessLogic, ComponentInstanceBusinessLogic componentInstanceBL, ComponentsUtils componentsUtils,
+                         ServletUtils servletUtils, ResourceImportManager resourceImportManager, PolicyBusinessLogic policyBusinessLogic) {
         super(userBusinessLogic, componentInstanceBL, componentsUtils, servletUtils, resourceImportManager);
         this.policyBusinessLogic = policyBusinessLogic;
         this.servletUtils = servletUtils;
@@ -109,101 +105,100 @@ public class PolicyServlet extends AbstractValidationsServlet {
     @POST
     @Path("/{containerComponentType}/{componentId}/policies/{policyTypeName}")
     @Operation(description = "Create Policy", method = "POST", summary = "Returns created Policy", responses = {
-            @ApiResponse(content = @Content(array = @ArraySchema(schema = @Schema(implementation = Response.class)))),
-            @ApiResponse(responseCode = "201", description = "Policy created"),
-            @ApiResponse(responseCode = "403", description = "Restricted operation"),
-            @ApiResponse(responseCode = "400", description = "Invalid content / Missing content"),
-            @ApiResponse(responseCode = "409", description = "Policy already exist"),
-            @ApiResponse(responseCode = "404", description = "Component not found")})
+        @ApiResponse(content = @Content(array = @ArraySchema(schema = @Schema(implementation = Response.class)))),
+        @ApiResponse(responseCode = "201", description = "Policy created"), @ApiResponse(responseCode = "403", description = "Restricted operation"),
+        @ApiResponse(responseCode = "400", description = "Invalid content / Missing content"),
+        @ApiResponse(responseCode = "409", description = "Policy already exist"),
+        @ApiResponse(responseCode = "404", description = "Component not found")})
     @PermissionAllowed(AafPermission.PermNames.INTERNAL_ALL_VALUE)
-    public Response createPolicy(@PathParam("componentId") final String containerComponentId, @Parameter(description = "valid values: resources / services",
-            schema = @Schema(allowableValues = {ComponentTypeEnum.RESOURCE_PARAM_NAME ,
-                    ComponentTypeEnum.SERVICE_PARAM_NAME})) @PathParam("containerComponentType") final String containerComponentType,
-            @PathParam("policyTypeName") final String policyTypeName,
-            @HeaderParam(value = Constants.USER_ID_HEADER) @Parameter(description = "USER_ID of modifier user",
-                    required = true) String userId,
-            @Context final HttpServletRequest request) {
+    public Response createPolicy(@PathParam("componentId") final String containerComponentId,
+                                 @Parameter(description = "valid values: resources / services", schema = @Schema(allowableValues = {
+                                     ComponentTypeEnum.RESOURCE_PARAM_NAME,
+                                     ComponentTypeEnum.SERVICE_PARAM_NAME})) @PathParam("containerComponentType") final String containerComponentType,
+                                 @PathParam("policyTypeName") final String policyTypeName,
+                                 @HeaderParam(value = Constants.USER_ID_HEADER) @Parameter(description = "USER_ID of modifier user", required = true) String userId,
+                                 @Context final HttpServletRequest request) {
         init();
-
-        loggerSupportability.log(LoggerSupportabilityActions.CREATE_POLICIES, StatusCode.STARTED,"Starting to create Policy by user {} containerComponentId={}" , userId , containerComponentId );
+        loggerSupportability
+            .log(LoggerSupportabilityActions.CREATE_POLICIES, StatusCode.STARTED, "Starting to create Policy by user {} containerComponentId={}",
+                userId, containerComponentId);
         ComponentTypeEnum componentType = validateComponentTypeAndUserId(containerComponentType, userId);
         PolicyDefinition policy = policyBusinessLogic.createPolicy(componentType, containerComponentId, policyTypeName, userId, true);
-        loggerSupportability.log(LoggerSupportabilityActions.CREATE_POLICIES, StatusCode.COMPLETE,"Ended create Policy by user {} containerComponentId={}" , userId , containerComponentId);
+        loggerSupportability
+            .log(LoggerSupportabilityActions.CREATE_POLICIES, StatusCode.COMPLETE, "Ended create Policy by user {} containerComponentId={}", userId,
+                containerComponentId);
         return buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.CREATED), policy);
     }
 
     @PUT
     @Path("/{containerComponentType}/{componentId}/policies/{policyId}")
     @Operation(description = "Update Policy metadata", method = "PUT", summary = "Returns updated Policy", responses = {
-            @ApiResponse(content = @Content(array = @ArraySchema(schema = @Schema(implementation = Response.class)))),
-            @ApiResponse(responseCode = "200", description = "Policy updated"),
-            @ApiResponse(responseCode = "403", description = "Restricted operation"),
-            @ApiResponse(responseCode = "400", description = "Invalid content / Missing content"),
-            @ApiResponse(responseCode = "404", description = "component / policy Not found")})
+        @ApiResponse(content = @Content(array = @ArraySchema(schema = @Schema(implementation = Response.class)))),
+        @ApiResponse(responseCode = "200", description = "Policy updated"), @ApiResponse(responseCode = "403", description = "Restricted operation"),
+        @ApiResponse(responseCode = "400", description = "Invalid content / Missing content"),
+        @ApiResponse(responseCode = "404", description = "component / policy Not found")})
     @PermissionAllowed(AafPermission.PermNames.INTERNAL_ALL_VALUE)
-    public Response updatePolicy(@PathParam("componentId") final String containerComponentId, @Parameter(
-            description = "valid values: resources / services",
-                    schema = @Schema(allowableValues = {ComponentTypeEnum.RESOURCE_PARAM_NAME,
-                            ComponentTypeEnum.SERVICE_PARAM_NAME})) @PathParam("containerComponentType") final String containerComponentType,
-            @PathParam("policyId") final String policyId,
-            @HeaderParam(value = Constants.USER_ID_HEADER) @Parameter(description = "USER_ID of modifier user",
-                    required = true) String userId,
-            @Parameter(description = "PolicyDefinition", required = true) String policyData,
-            @Context final HttpServletRequest request) {
+    public Response updatePolicy(@PathParam("componentId") final String containerComponentId,
+                                 @Parameter(description = "valid values: resources / services", schema = @Schema(allowableValues = {
+                                     ComponentTypeEnum.RESOURCE_PARAM_NAME,
+                                     ComponentTypeEnum.SERVICE_PARAM_NAME})) @PathParam("containerComponentType") final String containerComponentType,
+                                 @PathParam("policyId") final String policyId,
+                                 @HeaderParam(value = Constants.USER_ID_HEADER) @Parameter(description = "USER_ID of modifier user", required = true) String userId,
+                                 @Parameter(description = "PolicyDefinition", required = true) String policyData,
+                                 @Context final HttpServletRequest request) {
         init();
-
-        loggerSupportability.log(LoggerSupportabilityActions.UPDATE_POLICY_TARGET, StatusCode.STARTED,"Starting to update Policy by user {} containerComponentId={}" , userId , containerComponentId);
+        loggerSupportability
+            .log(LoggerSupportabilityActions.UPDATE_POLICY_TARGET, StatusCode.STARTED, "Starting to update Policy by user {} containerComponentId={}",
+                userId, containerComponentId);
         PolicyDefinition policyDefinition = convertJsonToObjectOfClass(policyData, PolicyDefinition.class);
         policyDefinition.setUniqueId(policyId);
-        policyDefinition = policyBusinessLogic.updatePolicy(validateComponentTypeAndUserId(containerComponentType, userId), containerComponentId, policyDefinition, userId, true);
-        loggerSupportability.log(LoggerSupportabilityActions.UPDATE_POLICY_TARGET, StatusCode.COMPLETE,"Ended update Policy by user {} containerComponentId={}" , userId , containerComponentId);
+        policyDefinition = policyBusinessLogic
+            .updatePolicy(validateComponentTypeAndUserId(containerComponentType, userId), containerComponentId, policyDefinition, userId, true);
+        loggerSupportability
+            .log(LoggerSupportabilityActions.UPDATE_POLICY_TARGET, StatusCode.COMPLETE, "Ended update Policy by user {} containerComponentId={}",
+                userId, containerComponentId);
         return buildOkResponse(policyDefinition);
-
     }
 
     @GET
     @Path("/{containerComponentType}/{componentId}/policies/{policyId}")
     @Operation(description = "Get Policy", method = "GET", summary = "Returns Policy", responses = {
-            @ApiResponse(content = @Content(array = @ArraySchema(schema = @Schema(implementation = Response.class)))),
-            @ApiResponse(responseCode = "200", description = "Policy was found"),
-            @ApiResponse(responseCode = "403", description = "Restricted operation"),
-            @ApiResponse(responseCode = "400", description = "Invalid content / Missing content"),
-            @ApiResponse(responseCode = "404", description = "component / policy Not found")})
+        @ApiResponse(content = @Content(array = @ArraySchema(schema = @Schema(implementation = Response.class)))),
+        @ApiResponse(responseCode = "200", description = "Policy was found"),
+        @ApiResponse(responseCode = "403", description = "Restricted operation"),
+        @ApiResponse(responseCode = "400", description = "Invalid content / Missing content"),
+        @ApiResponse(responseCode = "404", description = "component / policy Not found")})
     @PermissionAllowed(AafPermission.PermNames.INTERNAL_ALL_VALUE)
-    public Response getPolicy(@PathParam("componentId") final String containerComponentId, @Parameter(
-            description = "valid values: resources / services",
-                    schema = @Schema(allowableValues = {ComponentTypeEnum.RESOURCE_PARAM_NAME ,
-                            ComponentTypeEnum.SERVICE_PARAM_NAME})) @PathParam("containerComponentType") final String containerComponentType,
-            @PathParam("policyId") final String policyId,
-            @HeaderParam(value = Constants.USER_ID_HEADER) @Parameter(description = "USER_ID of modifier user",
-                    required = true) String userId,
-            @Context final HttpServletRequest request) {
+    public Response getPolicy(@PathParam("componentId") final String containerComponentId,
+                              @Parameter(description = "valid values: resources / services", schema = @Schema(allowableValues = {
+                                  ComponentTypeEnum.RESOURCE_PARAM_NAME,
+                                  ComponentTypeEnum.SERVICE_PARAM_NAME})) @PathParam("containerComponentType") final String containerComponentType,
+                              @PathParam("policyId") final String policyId,
+                              @HeaderParam(value = Constants.USER_ID_HEADER) @Parameter(description = "USER_ID of modifier user", required = true) String userId,
+                              @Context final HttpServletRequest request) {
         init();
-
-        PolicyDefinition policy = policyBusinessLogic.getPolicy(validateComponentTypeAndUserId(containerComponentType,
-                userId), containerComponentId, policyId, userId);
+        PolicyDefinition policy = policyBusinessLogic
+            .getPolicy(validateComponentTypeAndUserId(containerComponentType, userId), containerComponentId, policyId, userId);
         return buildOkResponse(policy);
     }
 
     @DELETE
     @Path("/{containerComponentType}/{componentId}/policies/{policyId}")
     @Operation(description = "Delete Policy", method = "DELETE", summary = "No body", responses = {
-            @ApiResponse(content = @Content(array = @ArraySchema(schema = @Schema(implementation = Response.class)))),
-            @ApiResponse(responseCode = "204", description = "Policy was deleted"),
-            @ApiResponse(responseCode = "403", description = "Restricted operation"),
-            @ApiResponse(responseCode = "400", description = "Invalid content / Missing content"),
-            @ApiResponse(responseCode = "404", description = "component / policy Not found")})
+        @ApiResponse(content = @Content(array = @ArraySchema(schema = @Schema(implementation = Response.class)))),
+        @ApiResponse(responseCode = "204", description = "Policy was deleted"),
+        @ApiResponse(responseCode = "403", description = "Restricted operation"),
+        @ApiResponse(responseCode = "400", description = "Invalid content / Missing content"),
+        @ApiResponse(responseCode = "404", description = "component / policy Not found")})
     @PermissionAllowed(AafPermission.PermNames.INTERNAL_ALL_VALUE)
-    public Response deletePolicy(@PathParam("componentId") final String containerComponentId, @Parameter(
-            description = "valid values: resources / services",
-                    schema = @Schema(allowableValues = {ComponentTypeEnum.RESOURCE_PARAM_NAME ,
-                            ComponentTypeEnum.SERVICE_PARAM_NAME})) @PathParam("containerComponentType") final String containerComponentType,
-            @PathParam("policyId") final String policyId,
-            @HeaderParam(value = Constants.USER_ID_HEADER) @Parameter(description = "USER_ID of modifier user",
-                    required = true) String userId,
-            @Context final HttpServletRequest request) {
+    public Response deletePolicy(@PathParam("componentId") final String containerComponentId,
+                                 @Parameter(description = "valid values: resources / services", schema = @Schema(allowableValues = {
+                                     ComponentTypeEnum.RESOURCE_PARAM_NAME,
+                                     ComponentTypeEnum.SERVICE_PARAM_NAME})) @PathParam("containerComponentType") final String containerComponentType,
+                                 @PathParam("policyId") final String policyId,
+                                 @HeaderParam(value = Constants.USER_ID_HEADER) @Parameter(description = "USER_ID of modifier user", required = true) String userId,
+                                 @Context final HttpServletRequest request) {
         init();
-
         ComponentTypeEnum componentTypeEnum = validateComponentTypeAndUserId(containerComponentType, userId);
         PolicyDefinition policyDefinition = policyBusinessLogic.deletePolicy(componentTypeEnum, containerComponentId, policyId, userId, true);
         return buildOkResponse(policyDefinition);
@@ -212,28 +207,28 @@ public class PolicyServlet extends AbstractValidationsServlet {
     @PUT
     @Path("/{containerComponentType}/{componentId}/policies/{policyId}/undeclare")
     @Operation(description = "undeclare Policy", method = "PUT", summary = "No body", responses = {
-            @ApiResponse(content = @Content(array = @ArraySchema(schema = @Schema(implementation = Response.class)))),
-            @ApiResponse(responseCode = "204", description = "Policy was undeclared"),
-            @ApiResponse(responseCode = "403", description = "Restricted operation"),
-            @ApiResponse(responseCode = "400", description = "Invalid content / Missing content"),
-            @ApiResponse(responseCode = "404", description = "component / policy Not found")})
+        @ApiResponse(content = @Content(array = @ArraySchema(schema = @Schema(implementation = Response.class)))),
+        @ApiResponse(responseCode = "204", description = "Policy was undeclared"),
+        @ApiResponse(responseCode = "403", description = "Restricted operation"),
+        @ApiResponse(responseCode = "400", description = "Invalid content / Missing content"),
+        @ApiResponse(responseCode = "404", description = "component / policy Not found")})
     @PermissionAllowed(AafPermission.PermNames.INTERNAL_ALL_VALUE)
-    public Response undeclarePolicy(@PathParam("componentId") final String containerComponentId, @Parameter(
-            description = "valid values: resources / services",
-                    schema = @Schema(allowableValues = {ComponentTypeEnum.RESOURCE_PARAM_NAME ,
-                            ComponentTypeEnum.SERVICE_PARAM_NAME})) @PathParam("containerComponentType") final String containerComponentType,
-            @PathParam("policyId") final String policyId,
-            @HeaderParam(value = Constants.USER_ID_HEADER) @Parameter(description = "USER_ID of modifier user",
-                    required = true) String userId,
-            @Context final HttpServletRequest request) {
+    public Response undeclarePolicy(@PathParam("componentId") final String containerComponentId,
+                                    @Parameter(description = "valid values: resources / services", schema = @Schema(allowableValues = {
+                                        ComponentTypeEnum.RESOURCE_PARAM_NAME,
+                                        ComponentTypeEnum.SERVICE_PARAM_NAME})) @PathParam("containerComponentType") final String containerComponentType,
+                                    @PathParam("policyId") final String policyId,
+                                    @HeaderParam(value = Constants.USER_ID_HEADER) @Parameter(description = "USER_ID of modifier user", required = true) String userId,
+                                    @Context final HttpServletRequest request) {
         init();
         Response response = null;
         try {
             ComponentTypeEnum componentTypeEnum = validateComponentTypeAndUserId(containerComponentType, userId);
-            Either<PolicyDefinition, ResponseFormat> undeclarePolicy = policyBusinessLogic.undeclarePolicy(componentTypeEnum, containerComponentId, policyId, userId, true);
-            if (undeclarePolicy.isLeft()){
+            Either<PolicyDefinition, ResponseFormat> undeclarePolicy = policyBusinessLogic
+                .undeclarePolicy(componentTypeEnum, containerComponentId, policyId, userId, true);
+            if (undeclarePolicy.isLeft()) {
                 response = buildOkResponse(undeclarePolicy.left().value());
-            } else{
+            } else {
                 response = buildErrorResponse(undeclarePolicy.right().value());
             }
         } catch (Exception e) {
@@ -245,58 +240,53 @@ public class PolicyServlet extends AbstractValidationsServlet {
 
     @GET
     @Path("/{containerComponentType}/{componentId}/policies/{policyId}/properties")
-    @Operation(description = "Get component policy properties", method = "GET",
-            summary = "Returns component policy properties", responses = {@ApiResponse(
-            content = @Content(array = @ArraySchema(schema = @Schema(implementation = PropertyDataDefinition.class)))),
-            @ApiResponse(responseCode = "200", description = "Properties found"), @ApiResponse(responseCode = "400",
-            description = "invalid content - Error: containerComponentType is invalid"),
-            @ApiResponse(responseCode = "403", description = "Restricted operation"),
-            @ApiResponse(responseCode = "404", description = "Componentorpolicy  not found"),
-            @ApiResponse(responseCode = "500", description = "The GET request failed due to internal SDC problem.")})
+    @Operation(description = "Get component policy properties", method = "GET", summary = "Returns component policy properties", responses = {
+        @ApiResponse(content = @Content(array = @ArraySchema(schema = @Schema(implementation = PropertyDataDefinition.class)))),
+        @ApiResponse(responseCode = "200", description = "Properties found"),
+        @ApiResponse(responseCode = "400", description = "invalid content - Error: containerComponentType is invalid"),
+        @ApiResponse(responseCode = "403", description = "Restricted operation"),
+        @ApiResponse(responseCode = "404", description = "Componentorpolicy  not found"),
+        @ApiResponse(responseCode = "500", description = "The GET request failed due to internal SDC problem.")})
     @PermissionAllowed(AafPermission.PermNames.INTERNAL_ALL_VALUE)
-    public Response getPolicyProperties(@Parameter(
-            description = "the id of the component which is the container of the policy") @PathParam("componentId") final String containerComponentId,
-            @Parameter(description = "valid values: resources / services",
-                    schema = @Schema(allowableValues = {ComponentTypeEnum.RESOURCE_PARAM_NAME ,
-                            ComponentTypeEnum.SERVICE_PARAM_NAME})) @PathParam("containerComponentType") final String containerComponentType,
-            @Parameter(
-                    description = "the id of the policy which its properties are to return") @PathParam("policyId") final String policyId,
-            @Parameter(description = "the userid",
-                    required = true) @HeaderParam(value = Constants.USER_ID_HEADER) String userId,
-            @Context final HttpServletRequest request) {
+    public Response getPolicyProperties(
+        @Parameter(description = "the id of the component which is the container of the policy") @PathParam("componentId") final String containerComponentId,
+        @Parameter(description = "valid values: resources / services", schema = @Schema(allowableValues = {ComponentTypeEnum.RESOURCE_PARAM_NAME,
+            ComponentTypeEnum.SERVICE_PARAM_NAME})) @PathParam("containerComponentType") final String containerComponentType,
+        @Parameter(description = "the id of the policy which its properties are to return") @PathParam("policyId") final String policyId,
+        @Parameter(description = "the userid", required = true) @HeaderParam(value = Constants.USER_ID_HEADER) String userId,
+        @Context final HttpServletRequest request) {
         init();
-        List<PropertyDataDefinition> propertyDataDefinitionList = policyBusinessLogic.getPolicyProperties(
-                convertToComponentType(containerComponentType), containerComponentId, policyId, userId);
+        List<PropertyDataDefinition> propertyDataDefinitionList = policyBusinessLogic
+            .getPolicyProperties(convertToComponentType(containerComponentType), containerComponentId, policyId, userId);
         return buildOkResponse(propertyDataDefinitionList);
     }
 
     @PUT
     @Path("/{containerComponentType}/{componentId}/policies/{policyId}/properties")
-    @Operation(description = "Update Policy properties", method = "PUT", summary = "Returns updated Policy",
-            responses = {@ApiResponse(
-                    content = @Content(array = @ArraySchema(schema = @Schema(implementation = Response.class)))),
-                    @ApiResponse(responseCode = "200", description = "Policy properties updated"),
-                    @ApiResponse(responseCode = "403", description = "Restricted operation"),
-                    @ApiResponse(responseCode = "400", description = "Invalid content / Missing content"),
-                    @ApiResponse(responseCode = "404", description = "component / policy Not found")})
+    @Operation(description = "Update Policy properties", method = "PUT", summary = "Returns updated Policy", responses = {
+        @ApiResponse(content = @Content(array = @ArraySchema(schema = @Schema(implementation = Response.class)))),
+        @ApiResponse(responseCode = "200", description = "Policy properties updated"),
+        @ApiResponse(responseCode = "403", description = "Restricted operation"),
+        @ApiResponse(responseCode = "400", description = "Invalid content / Missing content"),
+        @ApiResponse(responseCode = "404", description = "component / policy Not found")})
     @PermissionAllowed(AafPermission.PermNames.INTERNAL_ALL_VALUE)
-    public Response updatePolicyProperties(@PathParam("componentId") final String containerComponentId, @Parameter(
-            description = "valid values: resources / services",
-                    schema = @Schema(allowableValues = {ComponentTypeEnum.RESOURCE_PARAM_NAME ,
-                            ComponentTypeEnum.SERVICE_PARAM_NAME})) @PathParam("containerComponentType") final String containerComponentType,
-            @PathParam("policyId") final String policyId,
-            @HeaderParam(value = Constants.USER_ID_HEADER) @Parameter(description = "USER_ID of modifier user",
-                    required = true) String userId,
-            @Parameter(description = "PolicyDefinition", required = true) String policyData,
-            @Context final HttpServletRequest request) {
+    public Response updatePolicyProperties(@PathParam("componentId") final String containerComponentId,
+                                           @Parameter(description = "valid values: resources / services", schema = @Schema(allowableValues = {
+                                               ComponentTypeEnum.RESOURCE_PARAM_NAME,
+                                               ComponentTypeEnum.SERVICE_PARAM_NAME})) @PathParam("containerComponentType") final String containerComponentType,
+                                           @PathParam("policyId") final String policyId,
+                                           @HeaderParam(value = Constants.USER_ID_HEADER) @Parameter(description = "USER_ID of modifier user", required = true) String userId,
+                                           @Parameter(description = "PolicyDefinition", required = true) String policyData,
+                                           @Context final HttpServletRequest request) {
         init();
-        loggerSupportability.log(LoggerSupportabilityActions.UPDATE_POLICIES_PROPERTIES, StatusCode.STARTED,"Starting to update Policy Properties by user {} containerComponentId={}" , userId , containerComponentId);
-
+        loggerSupportability.log(LoggerSupportabilityActions.UPDATE_POLICIES_PROPERTIES, StatusCode.STARTED,
+            "Starting to update Policy Properties by user {} containerComponentId={}", userId, containerComponentId);
         ComponentTypeEnum componentTypeEnum = validateComponentTypeAndUserId(containerComponentType, userId);
         PropertyDataDefinition[] propertyDataDefinitions = convertJsonToObjectOfClass(policyData, PropertyDataDefinition[].class);
-        List<PropertyDataDefinition> propertyDataDefinitionList = policyBusinessLogic.updatePolicyProperties(componentTypeEnum,
-                    containerComponentId, policyId, propertyDataDefinitions, userId, true);
-        loggerSupportability.log(LoggerSupportabilityActions.UPDATE_POLICIES_PROPERTIES, StatusCode.STARTED,"Starting to update Policy Properties by user {} containerComponentId={}" , userId , containerComponentId);
+        List<PropertyDataDefinition> propertyDataDefinitionList = policyBusinessLogic
+            .updatePolicyProperties(componentTypeEnum, containerComponentId, policyId, propertyDataDefinitions, userId, true);
+        loggerSupportability.log(LoggerSupportabilityActions.UPDATE_POLICIES_PROPERTIES, StatusCode.STARTED,
+            "Starting to update Policy Properties by user {} containerComponentId={}", userId, containerComponentId);
         return buildOkResponse(propertyDataDefinitionList);
     }
 
@@ -313,70 +303,61 @@ public class PolicyServlet extends AbstractValidationsServlet {
     @Consumes(MediaType.APPLICATION_JSON)
     @Produces(MediaType.APPLICATION_JSON)
     @Operation(description = "update policy targets", method = "POST", summary = "Returns updated Policy", responses = {
-            @ApiResponse(content = @Content(array = @ArraySchema(schema = @Schema(implementation = Response.class)))),
-            @ApiResponse(responseCode = "201", description = "Policy target updated"),
-            @ApiResponse(responseCode = "403", description = "Restricted operation"),
-            @ApiResponse(responseCode = "400", description = "Invalid content / Missing content")})
+        @ApiResponse(content = @Content(array = @ArraySchema(schema = @Schema(implementation = Response.class)))),
+        @ApiResponse(responseCode = "201", description = "Policy target updated"),
+        @ApiResponse(responseCode = "403", description = "Restricted operation"),
+        @ApiResponse(responseCode = "400", description = "Invalid content / Missing content")})
     @PermissionAllowed(AafPermission.PermNames.INTERNAL_ALL_VALUE)
-    public Response updatePolicyTargets(@PathParam("componentId") final String containerComponentId, @Parameter(
-            description = "valid values: resources / services",
-                    schema = @Schema(allowableValues = {ComponentTypeEnum.RESOURCE_PARAM_NAME ,
-                            ComponentTypeEnum.SERVICE_PARAM_NAME})) @PathParam("containerComponentType") final String containerComponentType,
-            @PathParam("policyId") final String policyId,
-            @HeaderParam(value = Constants.USER_ID_HEADER) @Parameter(description = "USER_ID of modifier user",
-                    required = true) String userId,
-            @Context final HttpServletRequest request, List<PolicyTargetDTO> requestJson) {
+    public Response updatePolicyTargets(@PathParam("componentId") final String containerComponentId,
+                                        @Parameter(description = "valid values: resources / services", schema = @Schema(allowableValues = {
+                                            ComponentTypeEnum.RESOURCE_PARAM_NAME,
+                                            ComponentTypeEnum.SERVICE_PARAM_NAME})) @PathParam("containerComponentType") final String containerComponentType,
+                                        @PathParam("policyId") final String policyId,
+                                        @HeaderParam(value = Constants.USER_ID_HEADER) @Parameter(description = "USER_ID of modifier user", required = true) String userId,
+                                        @Context final HttpServletRequest request, List<PolicyTargetDTO> requestJson) {
         Map<PolicyTargetType, List<String>> policyTargetTypeListMap = updatePolicyTargetsFromDTO(requestJson);
-        PolicyDefinition policyDefinition = updatePolicyTargetsFromMap(policyTargetTypeListMap, containerComponentType, containerComponentId, policyId, userId);
+        PolicyDefinition policyDefinition = updatePolicyTargetsFromMap(policyTargetTypeListMap, containerComponentType, containerComponentId,
+            policyId, userId);
         return buildOkResponse(policyDefinition);
-
     }
 
     @POST
     @Path("/{componentType}/{componentId}/create/policies")
-    @Operation(description = "Create policies on service", method = "POST", summary = "Return policies list",
-            responses = {@ApiResponse(
-                    content = @Content(array = @ArraySchema(schema = @Schema(implementation = Resource.class)))),
-                    @ApiResponse(responseCode = "200", description = "Component found"),
-                    @ApiResponse(responseCode = "403", description = "Restricted operation"),
-                    @ApiResponse(responseCode = "404", description = "Component not found")})
+    @Operation(description = "Create policies on service", method = "POST", summary = "Return policies list", responses = {
+        @ApiResponse(content = @Content(array = @ArraySchema(schema = @Schema(implementation = Resource.class)))),
+        @ApiResponse(responseCode = "200", description = "Component found"), @ApiResponse(responseCode = "403", description = "Restricted operation"),
+        @ApiResponse(responseCode = "404", description = "Component not found")})
     @PermissionAllowed(AafPermission.PermNames.INTERNAL_ALL_VALUE)
-    public Response declareProperties(@PathParam("componentType") final String componentType,
-            @PathParam("componentId") final String componentId, @Context final HttpServletRequest request,
-            @HeaderParam(value = Constants.USER_ID_HEADER) String userId,
-            @Parameter(description = "ComponentIns policies Object to be created",
-                    required = true) String componentInstPoliciesMapObj) {
-
-        return super.declareProperties(userId, componentId, componentType, componentInstPoliciesMapObj,
-                DeclarationTypeEnum.POLICY, request);
+    public Response declareProperties(@PathParam("componentType") final String componentType, @PathParam("componentId") final String componentId,
+                                      @Context final HttpServletRequest request, @HeaderParam(value = Constants.USER_ID_HEADER) String userId,
+                                      @Parameter(description = "ComponentIns policies Object to be created", required = true) String componentInstPoliciesMapObj) {
+        return super.declareProperties(userId, componentId, componentType, componentInstPoliciesMapObj, DeclarationTypeEnum.POLICY, request);
     }
 
-
-    private PolicyDefinition updatePolicyTargetsFromMap(Map<PolicyTargetType, List<String>> policyTarget, String containerComponentType, String containerComponentId, String policyId, String userId) {
+    private PolicyDefinition updatePolicyTargetsFromMap(Map<PolicyTargetType, List<String>> policyTarget, String containerComponentType,
+                                                        String containerComponentId, String policyId, String userId) {
         ComponentTypeEnum componentTypeEnum = convertToComponentType(containerComponentType);
         return policyBusinessLogic.updatePolicyTargets(componentTypeEnum, containerComponentId, policyId, policyTarget, userId);
     }
 
     private Map<PolicyTargetType, List<String>> updatePolicyTargetsFromDTO(List<PolicyTargetDTO> targetDTOList) {
-        loggerSupportability.log(LoggerSupportabilityActions.UPDATE_POLICY_TARGET, StatusCode.STARTED,"Starting to update Policy target");
+        loggerSupportability.log(LoggerSupportabilityActions.UPDATE_POLICY_TARGET, StatusCode.STARTED, "Starting to update Policy target");
         Map<PolicyTargetType, List<String>> policyTarget = new HashMap<>();
         for (PolicyTargetDTO currentTarget : targetDTOList) {
-            if(!addTargetsByType(policyTarget, currentTarget.getType(), currentTarget.getUniqueIds())){
+            if (!addTargetsByType(policyTarget, currentTarget.getType(), currentTarget.getUniqueIds())) {
                 throw new ByActionStatusComponentException(ActionStatus.POLICY_TARGET_TYPE_DOES_NOT_EXIST, currentTarget.getType());
             }
         }
-        loggerSupportability.log(LoggerSupportabilityActions.UPDATE_POLICY_TARGET, StatusCode.COMPLETE,"Ended update Policy target");
+        loggerSupportability.log(LoggerSupportabilityActions.UPDATE_POLICY_TARGET, StatusCode.COMPLETE, "Ended update Policy target");
         return policyTarget;
     }
 
-
     public boolean addTargetsByType(Map<PolicyTargetType, List<String>> policyTarget, String type, List<String> uniqueIds) {
         PolicyTargetType targetTypeEnum = PolicyTargetType.getByNameIgnoreCase(type);
-        if(targetTypeEnum != null){
+        if (targetTypeEnum != null) {
             policyTarget.put(targetTypeEnum, validateUniquenessOfIds(uniqueIds));
             return true;
-        }
-        else{
+        } else {
             return false;
         }
     }
index 6c7bf21..2dcbda4 100644 (file)
@@ -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.
@@ -17,7 +17,6 @@
  * limitations under the License.
  * ============LICENSE_END=========================================================
  */
-
 package org.openecomp.sdc.be.servlets;
 
 import com.jcabi.aspects.Loggable;
@@ -31,6 +30,14 @@ import io.swagger.v3.oas.annotations.servers.Server;
 import io.swagger.v3.oas.annotations.servers.Servers;
 import io.swagger.v3.oas.annotations.tags.Tag;
 import io.swagger.v3.oas.annotations.tags.Tags;
+import java.util.List;
+import javax.ws.rs.Consumes;
+import javax.ws.rs.GET;
+import javax.ws.rs.HeaderParam;
+import javax.ws.rs.Path;
+import javax.ws.rs.Produces;
+import javax.ws.rs.QueryParam;
+import javax.ws.rs.core.MediaType;
 import org.openecomp.sdc.be.components.impl.PolicyTypeBusinessLogic;
 import org.openecomp.sdc.be.components.impl.aaf.AafPermission;
 import org.openecomp.sdc.be.components.impl.aaf.PermissionAllowed;
@@ -43,15 +50,6 @@ import org.openecomp.sdc.common.api.Constants;
 import org.openecomp.sdc.common.log.wrappers.Logger;
 import org.springframework.stereotype.Controller;
 
-import javax.ws.rs.Consumes;
-import javax.ws.rs.GET;
-import javax.ws.rs.HeaderParam;
-import javax.ws.rs.Path;
-import javax.ws.rs.Produces;
-import javax.ws.rs.QueryParam;
-import javax.ws.rs.core.MediaType;
-import java.util.List;
-
 @Loggable(prepend = true, value = Loggable.DEBUG, trim = false)
 @Path("/v1/catalog")
 @Tags({@Tag(name = "SDC Internal APIs")})
@@ -59,14 +57,13 @@ import java.util.List;
 @Controller
 @Consumes(MediaType.APPLICATION_JSON)
 @Produces(MediaType.APPLICATION_JSON)
-public class PolicyTypesEndpoint extends BeGenericServlet{
+public class PolicyTypesEndpoint extends BeGenericServlet {
 
     private static final Logger log = Logger.getLogger(PolicyTypesEndpoint.class);
-
     private final PolicyTypeBusinessLogic policyTypeBusinessLogic;
 
-    public PolicyTypesEndpoint(UserBusinessLogic userBusinessLogic,
-        ComponentsUtils componentsUtils, PolicyTypeBusinessLogic policyTypeBusinessLogic) {
+    public PolicyTypesEndpoint(UserBusinessLogic userBusinessLogic, ComponentsUtils componentsUtils,
+                               PolicyTypeBusinessLogic policyTypeBusinessLogic) {
         super(userBusinessLogic, componentsUtils);
         this.policyTypeBusinessLogic = policyTypeBusinessLogic;
     }
@@ -74,16 +71,15 @@ public class PolicyTypesEndpoint extends BeGenericServlet{
     @GET
     @Path("/policyTypes")
     @Operation(description = "Get policy types ", method = "GET", summary = "Returns policy types", responses = {
-            @ApiResponse(content = @Content(
-                    array = @ArraySchema(schema = @Schema(implementation = PolicyTypeDefinition.class)))),
-            @ApiResponse(responseCode = "200", description = "policy types found"),
-            @ApiResponse(responseCode = "403", description = "Restricted operation"),
-            @ApiResponse(responseCode = "500", description = "The GET request failed due to internal SDC problem.")})
+        @ApiResponse(content = @Content(array = @ArraySchema(schema = @Schema(implementation = PolicyTypeDefinition.class)))),
+        @ApiResponse(responseCode = "200", description = "policy types found"),
+        @ApiResponse(responseCode = "403", description = "Restricted operation"),
+        @ApiResponse(responseCode = "500", description = "The GET request failed due to internal SDC problem.")})
     @ResponseView(mixin = {PolicyTypeMixin.class})
     @PermissionAllowed(AafPermission.PermNames.INTERNAL_ALL_VALUE)
-    public List<PolicyTypeDefinition> getPolicyTypes(@Parameter(description = "An optional parameter to indicate the type of the container from where this call is executed")
-                                   @QueryParam("internalComponentType") String internalComponentType,
-                                   @Parameter(description = "The user id", required = true) @HeaderParam(value = Constants.USER_ID_HEADER) String userId) {
+    public List<PolicyTypeDefinition> getPolicyTypes(
+        @Parameter(description = "An optional parameter to indicate the type of the container from where this call is executed") @QueryParam("internalComponentType") String internalComponentType,
+        @Parameter(description = "The user id", required = true) @HeaderParam(value = Constants.USER_ID_HEADER) String userId) {
         log.debug("(get) Start handle request of GET policyTypes");
         return policyTypeBusinessLogic.getAllPolicyTypes(userId, internalComponentType);
     }
index f115f77..4a0f6cb 100644 (file)
@@ -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.
@@ -17,7 +17,6 @@
  * limitations under the License.
  * ============LICENSE_END=========================================================
  */
-
 package org.openecomp.sdc.be.servlets;
 
 import com.fasterxml.jackson.annotation.JsonFilter;
@@ -31,6 +30,13 @@ import com.google.common.collect.ImmutableMap;
 import com.google.gson.Gson;
 import com.google.gson.JsonElement;
 import com.google.gson.JsonObject;
+import java.io.IOException;
+import java.util.ArrayList;
+import java.util.Collection;
+import java.util.HashMap;
+import java.util.HashSet;
+import java.util.List;
+import java.util.Set;
 import org.apache.commons.lang.StringUtils;
 import org.openecomp.sdc.be.components.impl.exceptions.ByActionStatusComponentException;
 import org.openecomp.sdc.be.components.impl.exceptions.ComponentException;
@@ -44,23 +50,20 @@ import org.openecomp.sdc.common.api.ArtifactGroupTypeEnum;
 import org.openecomp.sdc.common.api.Constants;
 import org.openecomp.sdc.common.log.wrappers.Logger;
 
-import java.io.IOException;
-import java.util.ArrayList;
-import java.util.Collection;
-import java.util.HashMap;
-import java.util.HashSet;
-import java.util.List;
-import java.util.Set;
-
 public class RepresentationUtils {
 
     private static final Logger log = Logger.getLogger(RepresentationUtils.class);
+    private static final String EMPTY = "empty";
+    private static final String REMOVE_IS_EMPTY_FROM_COLLECTIONS_FILTER = "removeIsEmptyFromCollections";
+    private static final ImmutableMap<Class<?>, Class<?>> IS_EMPTY_FILTER_MIXIN = ImmutableMap.<Class<?>, Class<?>>builder()
+        .put(Collection.class, IsEmptyFilterMixIn.class).put(List.class, IsEmptyFilterMixIn.class).put(Set.class, IsEmptyFilterMixIn.class)
+        .put(HashMap.class, IsEmptyFilterMixIn.class).put(ArrayList.class, IsEmptyFilterMixIn.class).put(HashSet.class, IsEmptyFilterMixIn.class)
+        .put(InterfaceDefinition.class, IsEmptyFilterMixIn.class).put(Resource.class, IsEmptyFilterMixIn.class)
+        .put(ToscaDataDefinition.class, IsEmptyFilterMixIn.class).build();
 
     public static ArtifactDefinition convertJsonToArtifactDefinitionForUpdate(String content, Class<ArtifactDefinition> clazz) {
-
         JsonObject jsonElement = new JsonObject();
         ArtifactDefinition resourceInfo = null;
-
         try {
             Gson gson = new Gson();
             jsonElement = gson.fromJson(content, jsonElement.getClass());
@@ -78,23 +81,15 @@ public class RepresentationUtils {
             mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
             mapper.configure(SerializationFeature.FAIL_ON_EMPTY_BEANS, false);
             mapper.setSerializationInclusion(JsonInclude.Include.NON_NULL);
-
             resourceInfo = mapper.readValue(json, clazz);
             resourceInfo.setPayloadData(payload);
-
         } catch (Exception e) {
             BeEcompErrorManager.getInstance().logBeArtifactInformationInvalidError("Artifact Upload / Update");
             log.debug("Failed to convert the content {} to object.", content.substring(0, Math.min(50, content.length())), e);
         }
-
         return resourceInfo;
     }
 
-
-    public static class ResourceRep {
-
-    }
-
     /**
      * Build Representation of given Object
      *
@@ -103,7 +98,6 @@ public class RepresentationUtils {
      * @throws IOException
      */
     public static <T> Object toRepresentation(T elementToRepresent) throws IOException {
-
         ObjectMapper mapper = new ObjectMapper();
         mapper.configure(SerializationFeature.FAIL_ON_EMPTY_BEANS, false);
         mapper.setSerializationInclusion(JsonInclude.Include.NON_NULL);
@@ -121,19 +115,15 @@ public class RepresentationUtils {
         } catch (Exception e) {
             log.error("Error when parsing JSON of object of type {}", clazz.getSimpleName(), e);
         } // return null in case of exception
-
         return object;
     }
 
     public static ArtifactDefinition convertJsonToArtifactDefinition(String content, Class<ArtifactDefinition> clazz, boolean validateTimeout) {
-
         JsonObject jsonElement = new JsonObject();
         ArtifactDefinition resourceInfo = null;
-
         if (StringUtils.isEmpty(content)) {
             throw new ByActionStatusComponentException(ActionStatus.MISSING_BODY);
         }
-
         try {
             Gson gson = new Gson();
             jsonElement = gson.fromJson(content, jsonElement.getClass());
@@ -146,7 +136,6 @@ public class RepresentationUtils {
                 elementsToValidate.put(Constants.ARTIFACT_TIMEOUT, jsonElement.get(Constants.ARTIFACT_TIMEOUT));
             }
             validateMandatoryProperties(elementsToValidate);
-
             if (artifactGroupValue != null && !artifactGroupValue.isJsonNull()) {
                 String groupValueUpper = artifactGroupValue.getAsString().toUpperCase();
                 if (!ArtifactGroupTypeEnum.getAllTypes().contains(groupValueUpper)) {
@@ -172,20 +161,16 @@ public class RepresentationUtils {
             mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
             mapper.configure(SerializationFeature.FAIL_ON_EMPTY_BEANS, false);
             mapper.setSerializationInclusion(JsonInclude.Include.NON_NULL);
-
             resourceInfo = mapper.readValue(json, clazz);
             resourceInfo.setPayloadData(payload);
-
         } catch (ComponentException ce) {
             BeEcompErrorManager.getInstance().logBeArtifactInformationInvalidError("Artifact Upload / Update");
             log.debug("Failed to convert the content {} to object.", content.substring(0, Math.min(50, content.length())), ce);
             throw ce;
-        }
-        catch (Exception e) {
+        } catch (Exception e) {
             BeEcompErrorManager.getInstance().logBeArtifactInformationInvalidError("Artifact Upload / Update");
             log.debug("Failed to convert the content {} to object.", content.substring(0, Math.min(50, content.length())), e);
         }
-
         return resourceInfo;
     }
 
@@ -205,26 +190,17 @@ public class RepresentationUtils {
         mapper.configure(SerializationFeature.FAIL_ON_EMPTY_BEANS, false);
         mapper.setSerializationInclusion(JsonInclude.Include.NON_NULL);
         mapper.setMixIns(IS_EMPTY_FILTER_MIXIN);
-        return mapper.writer(new SimpleFilterProvider().addFilter(REMOVE_IS_EMPTY_FROM_COLLECTIONS_FILTER,
-                SerializeExceptFilter.serializeAllExcept(EMPTY))).writeValueAsString(elementToRepresent);
+        return mapper
+            .writer(new SimpleFilterProvider().addFilter(REMOVE_IS_EMPTY_FROM_COLLECTIONS_FILTER, SerializeExceptFilter.serializeAllExcept(EMPTY)))
+            .writeValueAsString(elementToRepresent);
     }
 
-    @JsonFilter(REMOVE_IS_EMPTY_FROM_COLLECTIONS_FILTER)
-    private static class IsEmptyFilterMixIn {}
+    public static class ResourceRep {
 
-    private static final String EMPTY = "empty";
-    private static final String REMOVE_IS_EMPTY_FROM_COLLECTIONS_FILTER = "removeIsEmptyFromCollections";
-    private static final ImmutableMap<Class<?>,Class<?>> IS_EMPTY_FILTER_MIXIN =
-            ImmutableMap.<Class<?>,Class<?>>builder()
-                    .put(Collection.class,IsEmptyFilterMixIn.class)
-                    .put(List.class,IsEmptyFilterMixIn.class)
-                    .put(Set.class,IsEmptyFilterMixIn.class)
-                    .put(HashMap.class,IsEmptyFilterMixIn.class)
-                    .put(ArrayList.class,IsEmptyFilterMixIn.class)
-                    .put(HashSet.class,IsEmptyFilterMixIn.class)
-                    .put(InterfaceDefinition.class,IsEmptyFilterMixIn.class)
-                    .put(Resource.class,IsEmptyFilterMixIn.class)
-                    .put(ToscaDataDefinition.class,IsEmptyFilterMixIn.class)
-                    .build();
+    }
 
+    @JsonFilter(REMOVE_IS_EMPTY_FROM_COLLECTIONS_FILTER)
+    private static class IsEmptyFilterMixIn {
+
+    }
 }
index 2d2b21e..6164cd1 100644 (file)
@@ -13,7 +13,6 @@
  * See the License for the specific language governing permissions and
  * limitations under the License.
  */
-
 package org.openecomp.sdc.be.servlets;
 
 import com.jcabi.aspects.Loggable;
@@ -28,6 +27,22 @@ import io.swagger.v3.oas.annotations.servers.Server;
 import io.swagger.v3.oas.annotations.servers.Servers;
 import io.swagger.v3.oas.annotations.tags.Tag;
 import io.swagger.v3.oas.annotations.tags.Tags;
+import java.util.List;
+import java.util.Optional;
+import javax.inject.Inject;
+import javax.servlet.http.HttpServletRequest;
+import javax.ws.rs.Consumes;
+import javax.ws.rs.DELETE;
+import javax.ws.rs.GET;
+import javax.ws.rs.HeaderParam;
+import javax.ws.rs.POST;
+import javax.ws.rs.PUT;
+import javax.ws.rs.Path;
+import javax.ws.rs.PathParam;
+import javax.ws.rs.Produces;
+import javax.ws.rs.core.Context;
+import javax.ws.rs.core.MediaType;
+import javax.ws.rs.core.Response;
 import org.openecomp.sdc.be.components.impl.ComponentInstanceBusinessLogic;
 import org.openecomp.sdc.be.components.impl.RequirementBusinessLogic;
 import org.openecomp.sdc.be.components.impl.ResourceImportManager;
@@ -48,23 +63,6 @@ import org.openecomp.sdc.common.log.wrappers.Logger;
 import org.openecomp.sdc.exception.ResponseFormat;
 import org.springframework.stereotype.Controller;
 
-import javax.inject.Inject;
-import javax.servlet.http.HttpServletRequest;
-import javax.ws.rs.Consumes;
-import javax.ws.rs.DELETE;
-import javax.ws.rs.GET;
-import javax.ws.rs.HeaderParam;
-import javax.ws.rs.POST;
-import javax.ws.rs.PUT;
-import javax.ws.rs.Path;
-import javax.ws.rs.PathParam;
-import javax.ws.rs.Produces;
-import javax.ws.rs.core.Context;
-import javax.ws.rs.core.MediaType;
-import javax.ws.rs.core.Response;
-import java.util.List;
-import java.util.Optional;
-
 @Loggable(prepend = true, value = Loggable.DEBUG, trim = false)
 @Path("/v1/catalog")
 @Consumes(MediaType.APPLICATION_JSON)
@@ -73,15 +71,14 @@ import java.util.Optional;
 @Servers({@Server(url = "/sdc2/rest")})
 @Controller
 public class RequirementServlet extends AbstractValidationsServlet {
+
     private static final Logger LOGGER = Logger.getLogger(RequirementServlet.class);
     private final RequirementBusinessLogic requirementBusinessLogic;
 
     @Inject
-    public RequirementServlet(UserBusinessLogic userBusinessLogic,
-            ComponentInstanceBusinessLogic componentInstanceBL,
-            ComponentsUtils componentsUtils, ServletUtils servletUtils,
-            ResourceImportManager resourceImportManager,
-            RequirementBusinessLogic requirementBusinessLogic) {
+    public RequirementServlet(UserBusinessLogic userBusinessLogic, ComponentInstanceBusinessLogic componentInstanceBL,
+                              ComponentsUtils componentsUtils, ServletUtils servletUtils, ResourceImportManager resourceImportManager,
+                              RequirementBusinessLogic requirementBusinessLogic) {
         super(userBusinessLogic, componentInstanceBL, componentsUtils, servletUtils, resourceImportManager);
         this.requirementBusinessLogic = requirementBusinessLogic;
     }
@@ -90,61 +87,50 @@ public class RequirementServlet extends AbstractValidationsServlet {
     @Consumes(MediaType.APPLICATION_JSON)
     @Produces(MediaType.APPLICATION_JSON)
     @Path("/resources/{resourceId}/requirements")
-    @Operation(description = "Create requirements on resource", method = "POST",
-            summary = "Create requirements on resource", responses = {
-            @ApiResponse(content = @Content(array = @ArraySchema(schema = @Schema(implementation = Response.class)))),
-            @ApiResponse(responseCode = "201", description = "Create requirements"),
-            @ApiResponse(responseCode = "403", description = "Restricted operation"),
-            @ApiResponse(responseCode = "400", description = "Invalid content / Missing content"),
-            @ApiResponse(responseCode = "409", description = "requirement already exist")})
+    @Operation(description = "Create requirements on resource", method = "POST", summary = "Create requirements on resource", responses = {
+        @ApiResponse(content = @Content(array = @ArraySchema(schema = @Schema(implementation = Response.class)))),
+        @ApiResponse(responseCode = "201", description = "Create requirements"),
+        @ApiResponse(responseCode = "403", description = "Restricted operation"),
+        @ApiResponse(responseCode = "400", description = "Invalid content / Missing content"),
+        @ApiResponse(responseCode = "409", description = "requirement already exist")})
     @PermissionAllowed(AafPermission.PermNames.INTERNAL_ALL_VALUE)
-    public Response createRequirementsOnResource(
-            @Parameter(description = "Requirement to create", required = true) String data,
-            @Parameter(description = "Resource Id") @PathParam("resourceId") String resourceId,
-            @Context final HttpServletRequest request,
-            @HeaderParam(value = Constants.USER_ID_HEADER) String userId) {
-        return createOrUpdate(data, "resources" , resourceId, request,
-                userId, false, "createRequirements");
+    public Response createRequirementsOnResource(@Parameter(description = "Requirement to create", required = true) String data,
+                                                 @Parameter(description = "Resource Id") @PathParam("resourceId") String resourceId,
+                                                 @Context final HttpServletRequest request,
+                                                 @HeaderParam(value = Constants.USER_ID_HEADER) String userId) {
+        return createOrUpdate(data, "resources", resourceId, request, userId, false, "createRequirements");
     }
 
-
     @PUT
     @Consumes(MediaType.APPLICATION_JSON)
     @Produces(MediaType.APPLICATION_JSON)
     @Path("/resources/{resourceId}/requirements")
-    @Operation(description = "Update Requirements on resource", method = "PUT",
-            summary = "Update Requirements on resource", responses = {@ApiResponse(
-            content = @Content(array = @ArraySchema(schema = @Schema(implementation = RequirementDefinition.class)))),
-            @ApiResponse(responseCode = "201", description = "Update Requirements"),
-            @ApiResponse(responseCode = "403", description = "Restricted operation"),
-            @ApiResponse(responseCode = "400", description = "Invalid content / Missing content")})
+    @Operation(description = "Update Requirements on resource", method = "PUT", summary = "Update Requirements on resource", responses = {
+        @ApiResponse(content = @Content(array = @ArraySchema(schema = @Schema(implementation = RequirementDefinition.class)))),
+        @ApiResponse(responseCode = "201", description = "Update Requirements"),
+        @ApiResponse(responseCode = "403", description = "Restricted operation"),
+        @ApiResponse(responseCode = "400", description = "Invalid content / Missing content")})
     @PermissionAllowed(AafPermission.PermNames.INTERNAL_ALL_VALUE)
-    public Response updateRequirementsOnResource(
-            @Parameter(description = "Requirements to update", required = true) String data,
-            @Parameter(description = "Component Id") @PathParam("resourceId") String resourceId,
-            @Context final HttpServletRequest request,
-            @HeaderParam(value = Constants.USER_ID_HEADER) String userId) {
-        return createOrUpdate(data, "resources", resourceId, request,
-                userId, true, "updateRequirements");
+    public Response updateRequirementsOnResource(@Parameter(description = "Requirements to update", required = true) String data,
+                                                 @Parameter(description = "Component Id") @PathParam("resourceId") String resourceId,
+                                                 @Context final HttpServletRequest request,
+                                                 @HeaderParam(value = Constants.USER_ID_HEADER) String userId) {
+        return createOrUpdate(data, "resources", resourceId, request, userId, true, "updateRequirements");
     }
 
     @GET
     @Consumes(MediaType.APPLICATION_JSON)
     @Produces(MediaType.APPLICATION_JSON)
     @Path("/resources/{resourceId}/requirements/{requirementId}")
-    @Operation(description = "Get Requirement from resource", method = "GET", summary = "GET Requirement from resource",
-            responses = {@ApiResponse(content = @Content(
-                    array = @ArraySchema(schema = @Schema(implementation = RequirementDefinition.class)))),
-                    @ApiResponse(responseCode = "201", description = "GET requirement"),
-                    @ApiResponse(responseCode = "403", description = "Restricted operation"),
-                    @ApiResponse(responseCode = "400", description = "Invalid content / Missing content")})
+    @Operation(description = "Get Requirement from resource", method = "GET", summary = "GET Requirement from resource", responses = {
+        @ApiResponse(content = @Content(array = @ArraySchema(schema = @Schema(implementation = RequirementDefinition.class)))),
+        @ApiResponse(responseCode = "201", description = "GET requirement"), @ApiResponse(responseCode = "403", description = "Restricted operation"),
+        @ApiResponse(responseCode = "400", description = "Invalid content / Missing content")})
     @PermissionAllowed(AafPermission.PermNames.INTERNAL_ALL_VALUE)
-    public Response getRequirementsFromResource(
-            @Parameter(description = "Resource Id") @PathParam("resourceId") String resourceId,
-            @Parameter(description = "Requirement Id") @PathParam("requirementId") String requirementId,
-            @Context final HttpServletRequest request,
-            @HeaderParam(value = Constants.USER_ID_HEADER) String userId) {
-
+    public Response getRequirementsFromResource(@Parameter(description = "Resource Id") @PathParam("resourceId") String resourceId,
+                                                @Parameter(description = "Requirement Id") @PathParam("requirementId") String requirementId,
+                                                @Context final HttpServletRequest request,
+                                                @HeaderParam(value = Constants.USER_ID_HEADER) String userId) {
         return get(requirementId, resourceId, request, userId);
     }
 
@@ -152,18 +138,16 @@ public class RequirementServlet extends AbstractValidationsServlet {
     @Consumes(MediaType.APPLICATION_JSON)
     @Produces(MediaType.APPLICATION_JSON)
     @Path("/resources/{resourceId}/requirements/{requirementId}")
-    @Operation(description = "Delete requirements from resource", method = "DELETE",
-            summary = "Delete requirements from resource", responses = {@ApiResponse(
-            content = @Content(array = @ArraySchema(schema = @Schema(implementation = RequirementDefinition.class)))),
-            @ApiResponse(responseCode = "201", description = "Delete requirement"),
-            @ApiResponse(responseCode = "403", description = "Restricted operation"),
-            @ApiResponse(responseCode = "400", description = "Invalid content / Missing content")})
+    @Operation(description = "Delete requirements from resource", method = "DELETE", summary = "Delete requirements from resource", responses = {
+        @ApiResponse(content = @Content(array = @ArraySchema(schema = @Schema(implementation = RequirementDefinition.class)))),
+        @ApiResponse(responseCode = "201", description = "Delete requirement"),
+        @ApiResponse(responseCode = "403", description = "Restricted operation"),
+        @ApiResponse(responseCode = "400", description = "Invalid content / Missing content")})
     @PermissionAllowed(AafPermission.PermNames.INTERNAL_ALL_VALUE)
-    public Response deleteRequirementsFromResource(
-            @Parameter(description = "Resource Id") @PathParam("resourceId") String resourceId,
-            @Parameter(description = "requirement Id") @PathParam("requirementId") String requirementId,
-            @Context final HttpServletRequest request,
-            @HeaderParam(value = Constants.USER_ID_HEADER) String userId) {
+    public Response deleteRequirementsFromResource(@Parameter(description = "Resource Id") @PathParam("resourceId") String resourceId,
+                                                   @Parameter(description = "requirement Id") @PathParam("requirementId") String requirementId,
+                                                   @Context final HttpServletRequest request,
+                                                   @HeaderParam(value = Constants.USER_ID_HEADER) String userId) {
         return delete(requirementId, resourceId, request, userId);
     }
 
@@ -171,120 +155,97 @@ public class RequirementServlet extends AbstractValidationsServlet {
     @Consumes(MediaType.APPLICATION_JSON)
     @Produces(MediaType.APPLICATION_JSON)
     @Path("/services/{serviceId}/requirements")
-    @Operation(description = "Create requirements on service", method = "POST",
-            summary = "Create requirements on service", responses = {
-            @ApiResponse(content = @Content(array = @ArraySchema(schema = @Schema(implementation = Response.class)))),
-            @ApiResponse(responseCode = "201", description = "Create Requirements"),
-            @ApiResponse(responseCode = "403", description = "Restricted operation"),
-            @ApiResponse(responseCode = "400", description = "Invalid content / Missing content"),
-            @ApiResponse(responseCode = "409", description = "Requirement already exist")})
+    @Operation(description = "Create requirements on service", method = "POST", summary = "Create requirements on service", responses = {
+        @ApiResponse(content = @Content(array = @ArraySchema(schema = @Schema(implementation = Response.class)))),
+        @ApiResponse(responseCode = "201", description = "Create Requirements"),
+        @ApiResponse(responseCode = "403", description = "Restricted operation"),
+        @ApiResponse(responseCode = "400", description = "Invalid content / Missing content"),
+        @ApiResponse(responseCode = "409", description = "Requirement already exist")})
     @PermissionAllowed(AafPermission.PermNames.INTERNAL_ALL_VALUE)
-    public Response createRequirementsOnService(
-            @Parameter(description = "Requirements to create", required = true) String data,
-            @Parameter(description = "Service Id") @PathParam("serviceId") String serviceId,
-            @Context final HttpServletRequest request,
-            @HeaderParam(value = Constants.USER_ID_HEADER) String userId) {
-        return createOrUpdate(data, "services" , serviceId, request, userId,
-                false , "createRequirements");
+    public Response createRequirementsOnService(@Parameter(description = "Requirements to create", required = true) String data,
+                                                @Parameter(description = "Service Id") @PathParam("serviceId") String serviceId,
+                                                @Context final HttpServletRequest request,
+                                                @HeaderParam(value = Constants.USER_ID_HEADER) String userId) {
+        return createOrUpdate(data, "services", serviceId, request, userId, false, "createRequirements");
     }
 
-
     @PUT
     @Consumes(MediaType.APPLICATION_JSON)
     @Produces(MediaType.APPLICATION_JSON)
     @Path("/services/{serviceId}/requirements")
-    @Operation(description = "Update requirements on service", method = "PUT",
-            summary = "Update requirements on service", responses = {@ApiResponse(
-            content = @Content(array = @ArraySchema(schema = @Schema(implementation = RequirementDefinition.class)))),
-            @ApiResponse(responseCode = "201", description = "Update requirements"),
-            @ApiResponse(responseCode = "403", description = "Restricted operation"),
-            @ApiResponse(responseCode = "400", description = "Invalid content / Missing content")})
+    @Operation(description = "Update requirements on service", method = "PUT", summary = "Update requirements on service", responses = {
+        @ApiResponse(content = @Content(array = @ArraySchema(schema = @Schema(implementation = RequirementDefinition.class)))),
+        @ApiResponse(responseCode = "201", description = "Update requirements"),
+        @ApiResponse(responseCode = "403", description = "Restricted operation"),
+        @ApiResponse(responseCode = "400", description = "Invalid content / Missing content")})
     @PermissionAllowed(AafPermission.PermNames.INTERNAL_ALL_VALUE)
-    public Response updateRequirementsOnService(
-            @Parameter(description = "Requirements to update", required = true) String data,
-            @Parameter(description = "Component Id") @PathParam("serviceId") String serviceId,
-            @Context final HttpServletRequest request,
-            @HeaderParam(value = Constants.USER_ID_HEADER) String userId) {
-        return createOrUpdate(data, "services", serviceId, request, userId,
-                true, "updateRequirements");
+    public Response updateRequirementsOnService(@Parameter(description = "Requirements to update", required = true) String data,
+                                                @Parameter(description = "Component Id") @PathParam("serviceId") String serviceId,
+                                                @Context final HttpServletRequest request,
+                                                @HeaderParam(value = Constants.USER_ID_HEADER) String userId) {
+        return createOrUpdate(data, "services", serviceId, request, userId, true, "updateRequirements");
     }
 
     @GET
     @Consumes(MediaType.APPLICATION_JSON)
     @Produces(MediaType.APPLICATION_JSON)
     @Path("/services/{serviceId}/requirements/{requirementId}")
-    @Operation(description = "Get requirement from service", method = "GET", summary = "GET requirement from service",
-            responses = {@ApiResponse(content = @Content(
-                    array = @ArraySchema(schema = @Schema(implementation = RequirementDefinition.class)))),
-                    @ApiResponse(responseCode = "201", description = "GET Requirements"),
-                    @ApiResponse(responseCode = "403", description = "Restricted operation"),
-                    @ApiResponse(responseCode = "400", description = "Invalid content / Missing content")})
+    @Operation(description = "Get requirement from service", method = "GET", summary = "GET requirement from service", responses = {
+        @ApiResponse(content = @Content(array = @ArraySchema(schema = @Schema(implementation = RequirementDefinition.class)))),
+        @ApiResponse(responseCode = "201", description = "GET Requirements"),
+        @ApiResponse(responseCode = "403", description = "Restricted operation"),
+        @ApiResponse(responseCode = "400", description = "Invalid content / Missing content")})
     @PermissionAllowed(AafPermission.PermNames.INTERNAL_ALL_VALUE)
-    public Response getRequirementsOnService(
-            @Parameter(description = "Service Id") @PathParam("serviceId") String serviceId,
-            @Parameter(description = "Requirement Id") @PathParam("requirementId") String requirementId,
-            @Context final HttpServletRequest request,
-            @HeaderParam(value = Constants.USER_ID_HEADER) String userId) {
-
+    public Response getRequirementsOnService(@Parameter(description = "Service Id") @PathParam("serviceId") String serviceId,
+                                             @Parameter(description = "Requirement Id") @PathParam("requirementId") String requirementId,
+                                             @Context final HttpServletRequest request,
+                                             @HeaderParam(value = Constants.USER_ID_HEADER) String userId) {
         return get(requirementId, serviceId, request, userId);
     }
 
-
     @DELETE
     @Consumes(MediaType.APPLICATION_JSON)
     @Produces(MediaType.APPLICATION_JSON)
     @Path("/services/{serviceId}/requirements/{requirementId}")
-    @Operation(description = "Delete requirement from service", method = "DELETE",
-            summary = "Delete requirement from service", responses = {@ApiResponse(
-            content = @Content(array = @ArraySchema(schema = @Schema(implementation = RequirementDefinition.class)))),
-            @ApiResponse(responseCode = "201", description = "Delete Requirements"),
-            @ApiResponse(responseCode = "403", description = "Restricted operation"),
-            @ApiResponse(responseCode = "400", description = "Invalid content / Missing content")})
+    @Operation(description = "Delete requirement from service", method = "DELETE", summary = "Delete requirement from service", responses = {
+        @ApiResponse(content = @Content(array = @ArraySchema(schema = @Schema(implementation = RequirementDefinition.class)))),
+        @ApiResponse(responseCode = "201", description = "Delete Requirements"),
+        @ApiResponse(responseCode = "403", description = "Restricted operation"),
+        @ApiResponse(responseCode = "400", description = "Invalid content / Missing content")})
     @PermissionAllowed(AafPermission.PermNames.INTERNAL_ALL_VALUE)
-    public Response deleteRequirementsOnService(
-            @Parameter(description = "Service Id") @PathParam("serviceId") String serviceId,
-            @Parameter(description = "Requirement Id") @PathParam("requirementId") String requirementId,
-            @Context final HttpServletRequest request,
-            @HeaderParam(value = Constants.USER_ID_HEADER) String userId) {
+    public Response deleteRequirementsOnService(@Parameter(description = "Service Id") @PathParam("serviceId") String serviceId,
+                                                @Parameter(description = "Requirement Id") @PathParam("requirementId") String requirementId,
+                                                @Context final HttpServletRequest request,
+                                                @HeaderParam(value = Constants.USER_ID_HEADER) String userId) {
         return delete(requirementId, serviceId, request, userId);
     }
 
-
-    private Response createOrUpdate (String data, String componentType, String componentId,
-                                     HttpServletRequest request, String userId,
-                                     boolean isUpdate, String errorContext) {
+    private Response createOrUpdate(String data, String componentType, String componentId, HttpServletRequest request, String userId,
+                                    boolean isUpdate, String errorContext) {
         String url = request.getMethod() + " " + request.getRequestURI();
-
         User modifier = new User();
         modifier.setUserId(userId);
         LOGGER.debug("Start create or update request of {} with modifier id {}", url, userId);
-
         try {
             String componentIdLower = componentId.toLowerCase();
-
-            Either<List<RequirementDefinition>, ResponseFormat> mappedRequirementDataEither =
-                    getMappedRequirementData(data, modifier, ComponentTypeEnum.findByParamName(componentType));
-            if(mappedRequirementDataEither.isRight()) {
+            Either<List<RequirementDefinition>, ResponseFormat> mappedRequirementDataEither = getMappedRequirementData(data, modifier,
+                ComponentTypeEnum.findByParamName(componentType));
+            if (mappedRequirementDataEither.isRight()) {
                 LOGGER.error("Failed to create or update requirements");
                 return buildErrorResponse(mappedRequirementDataEither.right().value());
             }
             List<RequirementDefinition> mappedRequirementData = mappedRequirementDataEither.left().value();
             Either<List<RequirementDefinition>, ResponseFormat> actionResponse;
-            if(isUpdate) {
-                actionResponse = requirementBusinessLogic.updateRequirements(componentIdLower, mappedRequirementData, modifier,
-                        errorContext, true);
+            if (isUpdate) {
+                actionResponse = requirementBusinessLogic.updateRequirements(componentIdLower, mappedRequirementData, modifier, errorContext, true);
             } else {
-                actionResponse = requirementBusinessLogic.createRequirements(componentIdLower, mappedRequirementData, modifier,
-                        errorContext, true);
+                actionResponse = requirementBusinessLogic.createRequirements(componentIdLower, mappedRequirementData, modifier, errorContext, true);
             }
-
             if (actionResponse.isRight()) {
                 LOGGER.error("Failed to create or update requirements");
                 return buildErrorResponse(actionResponse.right().value());
             }
-
-            return buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK),
-                    actionResponse.left().value());
+            return buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), actionResponse.left().value());
         } catch (Exception e) {
             BeEcompErrorManager.getInstance().logBeRestApiGeneralError("requirements create or update");
             LOGGER.error("Failed to create or update requirements with an error", e);
@@ -292,19 +253,15 @@ public class RequirementServlet extends AbstractValidationsServlet {
         }
     }
 
-    private Response get (String requirementIdToGet,  String componentId,
-                          HttpServletRequest request, String userId){
+    private Response get(String requirementIdToGet, String componentId, HttpServletRequest request, String userId) {
         String url = request.getMethod() + " " + request.getRequestURI();
-
         User modifier = new User();
         modifier.setUserId(userId);
         LOGGER.debug("Start get request of {} with modifier id {}", url, userId);
-
         try {
             String componentIdLower = componentId.toLowerCase();
-
             Either<RequirementDefinition, ResponseFormat> actionResponse = requirementBusinessLogic
-                    .getRequirement(componentIdLower, requirementIdToGet, modifier, true);
+                .getRequirement(componentIdLower, requirementIdToGet, modifier, true);
             if (actionResponse.isRight()) {
                 LOGGER.error("failed to get requirements");
                 return buildErrorResponse(actionResponse.right().value());
@@ -318,19 +275,15 @@ public class RequirementServlet extends AbstractValidationsServlet {
         }
     }
 
-    private Response delete (String requirementId, String componentId, HttpServletRequest
-                                        request, String userId){
+    private Response delete(String requirementId, String componentId, HttpServletRequest request, String userId) {
         String url = request.getMethod() + " " + request.getRequestURI();
-
         User modifier = new User();
         modifier.setUserId(userId);
         LOGGER.debug("Start delete request of {} with modifier id {}", url, userId);
-
         try {
             String componentIdLower = componentId.toLowerCase();
-
             Either<RequirementDefinition, ResponseFormat> actionResponse = requirementBusinessLogic
-                    .deleteRequirement(componentIdLower, requirementId, modifier, true);
+                .deleteRequirement(componentIdLower, requirementId, modifier, true);
             if (actionResponse.isRight()) {
                 LOGGER.error("failed to delete requirements");
                 return buildErrorResponse(actionResponse.right().value());
@@ -345,14 +298,12 @@ public class RequirementServlet extends AbstractValidationsServlet {
     }
 
     private Either<List<RequirementDefinition>, ResponseFormat> getMappedRequirementData(String inputJson, User user,
-                                                                 ComponentTypeEnum componentTypeEnum){
+                                                                                         ComponentTypeEnum componentTypeEnum) {
         Either<UiComponentDataTransfer, ResponseFormat> mappedData = getComponentsUtils()
-                .convertJsonToObjectUsingObjectMapper(inputJson, user, UiComponentDataTransfer.class,
-                        AuditingActionEnum.CREATE_RESOURCE, componentTypeEnum);
-        Optional<List<RequirementDefinition>> requirementDefinitionList = mappedData.left().value()
-                .getRequirements().values().stream().findFirst();
-        return requirementDefinitionList.<Either<List<RequirementDefinition>, ResponseFormat>>
-                map(Either::left).orElseGet(() -> Either.right(getComponentsUtils()
-                .getResponseFormat(ActionStatus.GENERAL_ERROR)));
+            .convertJsonToObjectUsingObjectMapper(inputJson, user, UiComponentDataTransfer.class, AuditingActionEnum.CREATE_RESOURCE,
+                componentTypeEnum);
+        Optional<List<RequirementDefinition>> requirementDefinitionList = mappedData.left().value().getRequirements().values().stream().findFirst();
+        return requirementDefinitionList.<Either<List<RequirementDefinition>, ResponseFormat>>map(Either::left)
+            .orElseGet(() -> Either.right(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR)));
     }
 }
index 3a28206..ebe3472 100644 (file)
@@ -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.
@@ -17,7 +17,6 @@
  * limitations under the License.
  * ============LICENSE_END=========================================================
  */
-
 package org.openecomp.sdc.be.servlets;
 
 import com.jcabi.aspects.Loggable;
@@ -31,6 +30,21 @@ import io.swagger.v3.oas.annotations.servers.Server;
 import io.swagger.v3.oas.annotations.servers.Servers;
 import io.swagger.v3.oas.annotations.tags.Tag;
 import io.swagger.v3.oas.annotations.tags.Tags;
+import java.io.File;
+import java.io.FileNotFoundException;
+import javax.inject.Inject;
+import javax.servlet.http.HttpServletRequest;
+import javax.ws.rs.Consumes;
+import javax.ws.rs.DefaultValue;
+import javax.ws.rs.HeaderParam;
+import javax.ws.rs.POST;
+import javax.ws.rs.Path;
+import javax.ws.rs.PathParam;
+import javax.ws.rs.Produces;
+import javax.ws.rs.QueryParam;
+import javax.ws.rs.core.Context;
+import javax.ws.rs.core.MediaType;
+import javax.ws.rs.core.Response;
 import org.glassfish.jersey.media.multipart.FormDataContentDisposition;
 import org.glassfish.jersey.media.multipart.FormDataParam;
 import org.openecomp.sdc.be.components.impl.ComponentInstanceBusinessLogic;
@@ -49,22 +63,6 @@ import org.openecomp.sdc.common.log.wrappers.Logger;
 import org.openecomp.sdc.common.zip.exception.ZipException;
 import org.springframework.stereotype.Controller;
 
-import javax.inject.Inject;
-import javax.servlet.http.HttpServletRequest;
-import javax.ws.rs.Consumes;
-import javax.ws.rs.DefaultValue;
-import javax.ws.rs.HeaderParam;
-import javax.ws.rs.POST;
-import javax.ws.rs.Path;
-import javax.ws.rs.PathParam;
-import javax.ws.rs.Produces;
-import javax.ws.rs.QueryParam;
-import javax.ws.rs.core.Context;
-import javax.ws.rs.core.MediaType;
-import javax.ws.rs.core.Response;
-import java.io.File;
-import java.io.FileNotFoundException;
-
 /**
  * Root resource (exposed at "/" path)
  */
@@ -75,22 +73,79 @@ import java.io.FileNotFoundException;
 @Controller
 public class ResourceUploadServlet extends AbstractValidationsServlet {
 
-    private static final Logger log = Logger.getLogger(ResourceUploadServlet.class);
     public static final String NORMATIVE_TYPE_RESOURCE = "multipart";
     public static final String CSAR_TYPE_RESOURCE = "csar";
     public static final String USER_TYPE_RESOURCE = "user-resource";
     public static final String USER_TYPE_RESOURCE_UI_IMPORT = "user-resource-ui-import";
+    private static final Logger log = Logger.getLogger(ResourceUploadServlet.class);
 
     @Inject
-    public ResourceUploadServlet(UserBusinessLogic userBusinessLogic,
-        ComponentInstanceBusinessLogic componentInstanceBL,
-        ComponentsUtils componentsUtils, ServletUtils servletUtils,
-        ResourceImportManager resourceImportManager) {
+    public ResourceUploadServlet(UserBusinessLogic userBusinessLogic, ComponentInstanceBusinessLogic componentInstanceBL,
+                                 ComponentsUtils componentsUtils, ServletUtils servletUtils, ResourceImportManager resourceImportManager) {
         super(userBusinessLogic, componentInstanceBL, componentsUtils, servletUtils, resourceImportManager);
     }
 
+    @POST
+    @Path("/{resourceAuthority}")
+    @Consumes(MediaType.MULTIPART_FORM_DATA)
+    @Produces(MediaType.APPLICATION_JSON)
+    @Operation(description = "Create Resource from yaml", method = "POST", summary = "Returns created resource", responses = {
+        @ApiResponse(content = @Content(array = @ArraySchema(schema = @Schema(implementation = Response.class)))),
+        @ApiResponse(responseCode = "201", description = "Resource created"),
+        @ApiResponse(responseCode = "403", description = "Restricted operation"),
+        @ApiResponse(responseCode = "400", description = "Invalid content / Missing content"),
+        @ApiResponse(responseCode = "409", description = "Resource already exist")})
+    @PermissionAllowed(AafPermission.PermNames.INTERNAL_ALL_VALUE)
+    public Response uploadMultipart(
+        @Parameter(description = "validValues: normative-resource / user-resource", schema = @Schema(allowableValues = {NORMATIVE_TYPE_RESOURCE,
+            USER_TYPE_RESOURCE, USER_TYPE_RESOURCE_UI_IMPORT})) @PathParam(value = "resourceAuthority") final String resourceAuthority,
+        @Parameter(description = "FileInputStream") @FormDataParam("resourceZip") File file,
+        @Parameter(description = "ContentDisposition") @FormDataParam("resourceZip") FormDataContentDisposition contentDispositionHeader,
+        @Parameter(description = "resourceMetadata") @FormDataParam("resourceMetadata") String resourceInfoJsonString,
+        @Context final HttpServletRequest request, @HeaderParam(value = Constants.USER_ID_HEADER) String userId,
+        // updateResourse Query Parameter if false checks if already exist
+        @DefaultValue("true") @QueryParam("createNewVersion") boolean createNewVersion) throws FileNotFoundException, ZipException {
+        try {
+            Wrapper<Response> responseWrapper = new Wrapper<>();
+            Wrapper<User> userWrapper = new Wrapper<>();
+            Wrapper<UploadResourceInfo> uploadResourceInfoWrapper = new Wrapper<>();
+            Wrapper<String> yamlStringWrapper = new Wrapper<>();
+            String url = request.getMethod() + " " + request.getRequestURI();
+            log.debug("Start handle request of {}", url);
+            // When we get an errorResponse it will be filled into the
+
+            // responseWrapper
+            validateAuthorityType(responseWrapper, resourceAuthority);
+            ResourceAuthorityTypeEnum resourceAuthorityEnum = ResourceAuthorityTypeEnum.findByUrlPath(resourceAuthority);
+            commonGeneralValidations(responseWrapper, userWrapper, uploadResourceInfoWrapper, resourceAuthorityEnum, userId, resourceInfoJsonString);
+            fillPayload(responseWrapper, uploadResourceInfoWrapper, yamlStringWrapper, userWrapper.getInnerElement(), resourceInfoJsonString,
+                resourceAuthorityEnum, file);
+            // PayLoad Validations
+            if (resourceAuthorityEnum != ResourceAuthorityTypeEnum.CSAR_TYPE_BE) {
+                commonPayloadValidations(responseWrapper, yamlStringWrapper, userWrapper.getInnerElement(),
+                    uploadResourceInfoWrapper.getInnerElement());
+                specificResourceAuthorityValidations(responseWrapper, uploadResourceInfoWrapper, yamlStringWrapper, userWrapper.getInnerElement(),
+                    request, resourceInfoJsonString, resourceAuthorityEnum);
+            }
+            if (responseWrapper.isEmpty()) {
+                handleImport(responseWrapper, userWrapper.getInnerElement(), uploadResourceInfoWrapper.getInnerElement(),
+                    yamlStringWrapper.getInnerElement(), resourceAuthorityEnum, createNewVersion, null);
+            }
+            return responseWrapper.getInnerElement();
+        } catch (Exception e) {
+            BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Upload Resource");
+            log.debug("upload resource failed with exception", e);
+            throw e;
+        }
+    }
+
     public enum ResourceAuthorityTypeEnum {
-        NORMATIVE_TYPE_BE(NORMATIVE_TYPE_RESOURCE, true, false), USER_TYPE_BE(USER_TYPE_RESOURCE, true, true), USER_TYPE_UI(USER_TYPE_RESOURCE_UI_IMPORT, false, true), CSAR_TYPE_BE(CSAR_TYPE_RESOURCE, true, true);
+        // @formatter:off
+        NORMATIVE_TYPE_BE(NORMATIVE_TYPE_RESOURCE, true, false),
+        USER_TYPE_BE(USER_TYPE_RESOURCE, true, true),
+        USER_TYPE_UI(USER_TYPE_RESOURCE_UI_IMPORT, false, true),
+        CSAR_TYPE_BE(CSAR_TYPE_RESOURCE, true, true);
+        // @formatter:on
 
         private String urlPath;
         private boolean isBackEndImport, isUserTypeResource;
@@ -124,68 +179,4 @@ public class ResourceUploadServlet extends AbstractValidationsServlet {
             return isUserTypeResource;
         }
     }
-
-    @POST
-    @Path("/{resourceAuthority}")
-    @Consumes(MediaType.MULTIPART_FORM_DATA)
-    @Produces(MediaType.APPLICATION_JSON)
-    @Operation(description = "Create Resource from yaml", method = "POST", summary = "Returns created resource",
-            responses = {@ApiResponse(
-                    content = @Content(array = @ArraySchema(schema = @Schema(implementation = Response.class)))),
-                    @ApiResponse(responseCode = "201", description = "Resource created"),
-                    @ApiResponse(responseCode = "403", description = "Restricted operation"),
-                    @ApiResponse(responseCode = "400", description = "Invalid content / Missing content"),
-                    @ApiResponse(responseCode = "409", description = "Resource already exist")})
-    @PermissionAllowed(AafPermission.PermNames.INTERNAL_ALL_VALUE)
-    public Response uploadMultipart(
-            @Parameter(description = "validValues: normative-resource / user-resource",
-                    schema = @Schema(allowableValues = {NORMATIVE_TYPE_RESOURCE ,
-                            USER_TYPE_RESOURCE,USER_TYPE_RESOURCE_UI_IMPORT})) @PathParam(
-                                    value = "resourceAuthority") final String resourceAuthority,
-            @Parameter(description = "FileInputStream") @FormDataParam("resourceZip") File file,
-            @Parameter(description = "ContentDisposition") @FormDataParam("resourceZip") FormDataContentDisposition contentDispositionHeader,
-            @Parameter(description = "resourceMetadata") @FormDataParam("resourceMetadata") String resourceInfoJsonString,
-            @Context final HttpServletRequest request, @HeaderParam(value = Constants.USER_ID_HEADER) String userId,
-            // updateResourse Query Parameter if false checks if already exist
-            @DefaultValue("true") @QueryParam("createNewVersion") boolean createNewVersion) throws FileNotFoundException, ZipException {
-
-        try {
-
-            Wrapper<Response> responseWrapper = new Wrapper<>();
-            Wrapper<User> userWrapper = new Wrapper<>();
-            Wrapper<UploadResourceInfo> uploadResourceInfoWrapper = new Wrapper<>();
-            Wrapper<String> yamlStringWrapper = new Wrapper<>();
-
-            String url = request.getMethod() + " " + request.getRequestURI();
-            log.debug("Start handle request of {}", url);
-
-            // When we get an errorResponse it will be filled into the
-            // responseWrapper
-            validateAuthorityType(responseWrapper, resourceAuthority);
-
-            ResourceAuthorityTypeEnum resourceAuthorityEnum = ResourceAuthorityTypeEnum.findByUrlPath(resourceAuthority);
-
-            commonGeneralValidations(responseWrapper, userWrapper, uploadResourceInfoWrapper, resourceAuthorityEnum, userId, resourceInfoJsonString);
-
-            fillPayload(responseWrapper, uploadResourceInfoWrapper, yamlStringWrapper, userWrapper.getInnerElement(), resourceInfoJsonString, resourceAuthorityEnum, file);
-
-            // PayLoad Validations
-            if(resourceAuthorityEnum != ResourceAuthorityTypeEnum.CSAR_TYPE_BE){
-                commonPayloadValidations(responseWrapper, yamlStringWrapper, userWrapper.getInnerElement(), uploadResourceInfoWrapper.getInnerElement());
-
-                specificResourceAuthorityValidations(responseWrapper, uploadResourceInfoWrapper, yamlStringWrapper, userWrapper.getInnerElement(), request, resourceInfoJsonString, resourceAuthorityEnum);
-            }
-
-            if (responseWrapper.isEmpty()) {
-                handleImport(responseWrapper, userWrapper.getInnerElement(), uploadResourceInfoWrapper.getInnerElement(), yamlStringWrapper.getInnerElement(), resourceAuthorityEnum, createNewVersion, null);
-            }
-
-            return responseWrapper.getInnerElement();
-
-        } catch (Exception e) {
-            BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Upload Resource");
-            log.debug("upload resource failed with exception", e);
-            throw e;
-        }
-    }
 }
index 43fa378..9377820 100644 (file)
@@ -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.
@@ -17,7 +17,6 @@
  * limitations under the License.
  * ============LICENSE_END=========================================================
  */
-
 package org.openecomp.sdc.be.servlets;
 
 import com.jcabi.aspects.Loggable;
@@ -104,11 +103,9 @@ public class ResourcesServlet extends AbstractValidationsServlet {
     private final ResourceBusinessLogic resourceBusinessLogic;
 
     @Inject
-    public ResourcesServlet(UserBusinessLogic userBusinessLogic,
-        ComponentInstanceBusinessLogic componentInstanceBL,
-        ResourceBusinessLogic resourceBusinessLogic,
-        ComponentsUtils componentsUtils, ServletUtils servletUtils,
-        ResourceImportManager resourceImportManager) {
+    public ResourcesServlet(UserBusinessLogic userBusinessLogic, ComponentInstanceBusinessLogic componentInstanceBL,
+                            ResourceBusinessLogic resourceBusinessLogic, ComponentsUtils componentsUtils, ServletUtils servletUtils,
+                            ResourceImportManager resourceImportManager) {
         super(userBusinessLogic, componentInstanceBL, componentsUtils, servletUtils, resourceImportManager);
         this.resourceBusinessLogic = resourceBusinessLogic;
     }
@@ -118,28 +115,26 @@ public class ResourcesServlet extends AbstractValidationsServlet {
     @Consumes(MediaType.APPLICATION_JSON)
     @Produces(MediaType.APPLICATION_JSON)
     @Operation(description = "Create Resource", method = "POST", summary = "Returns created resource", responses = {
-            @ApiResponse(content = @Content(array = @ArraySchema(schema = @Schema(implementation = Resource.class)))),
-            @ApiResponse(responseCode = "201", description = "Resource created"),
-            @ApiResponse(responseCode = "403", description = "Restricted operation"),
-            @ApiResponse(responseCode = "400", description = "Invalid content / Missing content"),
-            @ApiResponse(responseCode = "409", description = "Resource already exist")})
+        @ApiResponse(content = @Content(array = @ArraySchema(schema = @Schema(implementation = Resource.class)))),
+        @ApiResponse(responseCode = "201", description = "Resource created"),
+        @ApiResponse(responseCode = "403", description = "Restricted operation"),
+        @ApiResponse(responseCode = "400", description = "Invalid content / Missing content"),
+        @ApiResponse(responseCode = "409", description = "Resource already exist")})
     @PermissionAllowed(AafPermission.PermNames.INTERNAL_ALL_VALUE)
     public Response createResource(@Parameter(description = "Resource object to be created", required = true) String data,
-            @Context final HttpServletRequest request, @HeaderParam(value = Constants.USER_ID_HEADER) String userId) throws IOException, ZipException {
-
+                                   @Context final HttpServletRequest request, @HeaderParam(value = Constants.USER_ID_HEADER) String userId)
+        throws IOException, ZipException {
         userId = (userId != null) ? userId : request.getHeader(Constants.USER_ID_HEADER);
         init();
-
         String url = request.getMethod() + " " + request.getRequestURI();
         log.debug(START_HANDLE_REQUEST_OF, url);
         // get modifier id
         User modifier = new User();
         modifier.setUserId(userId);
         log.debug(MODIFIER_ID_IS, userId);
-        loggerSupportability.log(LoggerSupportabilityActions.CREATE_RESOURCE, StatusCode.STARTED,"Starting to create Resource by user {}",userId);
+        loggerSupportability.log(LoggerSupportabilityActions.CREATE_RESOURCE, StatusCode.STARTED, "Starting to create Resource by user {}", userId);
         Response response;
         try {
-
             Wrapper<Response> responseWrapper = new Wrapper<>();
             // UI Import
             if (isUIImport(data)) {
@@ -147,20 +142,20 @@ public class ResourcesServlet extends AbstractValidationsServlet {
             }
             // UI Create
             else {
-
                 Either<Resource, ResponseFormat> convertResponse = parseToResource(data, modifier);
                 if (convertResponse.isRight()) {
                     log.debug("failed to parse resource");
                     response = buildErrorResponse(convertResponse.right().value());
                     return response;
                 }
-
                 Resource resource = convertResponse.left().value();
                 Resource createdResource = resourceBusinessLogic.createResource(resource, AuditingActionEnum.CREATE_RESOURCE, modifier, null, null);
                 Object representation = RepresentationUtils.toRepresentation(createdResource);
                 response = buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.CREATED), representation);
                 responseWrapper.setInnerElement(response);
-                loggerSupportability.log(LoggerSupportabilityActions.CREATE_RESOURCE,resource.getComponentMetadataForSupportLog() ,StatusCode.COMPLETE,"Resource successfully created user {}",userId);
+                loggerSupportability
+                    .log(LoggerSupportabilityActions.CREATE_RESOURCE, resource.getComponentMetadataForSupportLog(), StatusCode.COMPLETE,
+                        "Resource successfully created user {}", userId);
             }
             return responseWrapper.getInnerElement();
         } catch (final IOException | ZipException e) {
@@ -183,36 +178,36 @@ public class ResourcesServlet extends AbstractValidationsServlet {
         return isUIImport;
     }
 
-    private void performUIImport(final Wrapper<Response> responseWrapper, final String data,
-                                 final HttpServletRequest request, final String userId,
+    private void performUIImport(final Wrapper<Response> responseWrapper, final String data, final HttpServletRequest request, final String userId,
                                  final String resourceUniqueId) throws ZipException {
         Wrapper<User> userWrapper = new Wrapper<>();
         Wrapper<UploadResourceInfo> uploadResourceInfoWrapper = new Wrapper<>();
         Wrapper<String> yamlStringWrapper = new Wrapper<>();
-
         ResourceAuthorityTypeEnum resourceAuthorityEnum = ResourceAuthorityTypeEnum.USER_TYPE_UI;
-
         commonGeneralValidations(responseWrapper, userWrapper, uploadResourceInfoWrapper, resourceAuthorityEnum, userId, data);
-
         if (!CsarValidationUtils.isCsarPayloadName(uploadResourceInfoWrapper.getInnerElement().getPayloadName())) {
-            fillPayload(responseWrapper, uploadResourceInfoWrapper, yamlStringWrapper, userWrapper.getInnerElement(), data, resourceAuthorityEnum, null);
-
+            fillPayload(responseWrapper, uploadResourceInfoWrapper, yamlStringWrapper, userWrapper.getInnerElement(), data, resourceAuthorityEnum,
+                null);
             // PayLoad Validations
             commonPayloadValidations(responseWrapper, yamlStringWrapper, userWrapper.getInnerElement(), uploadResourceInfoWrapper.getInnerElement());
         }
-        specificResourceAuthorityValidations(responseWrapper, uploadResourceInfoWrapper, yamlStringWrapper, userWrapper.getInnerElement(), request, data, resourceAuthorityEnum);
-
+        specificResourceAuthorityValidations(responseWrapper, uploadResourceInfoWrapper, yamlStringWrapper, userWrapper.getInnerElement(), request,
+            data, resourceAuthorityEnum);
         if (responseWrapper.isEmpty()) {
-            handleImport(responseWrapper, userWrapper.getInnerElement(), uploadResourceInfoWrapper.getInnerElement(), yamlStringWrapper.getInnerElement(), resourceAuthorityEnum, true, resourceUniqueId);
+            handleImport(responseWrapper, userWrapper.getInnerElement(), uploadResourceInfoWrapper.getInnerElement(),
+                yamlStringWrapper.getInnerElement(), resourceAuthorityEnum, true, resourceUniqueId);
         }
     }
 
     private Either<Resource, ResponseFormat> parseToResource(String resourceJson, User user) {
-        return getComponentsUtils().convertJsonToObjectUsingObjectMapper(resourceJson, user, Resource.class, AuditingActionEnum.CREATE_RESOURCE, ComponentTypeEnum.RESOURCE);
+        return getComponentsUtils()
+            .convertJsonToObjectUsingObjectMapper(resourceJson, user, Resource.class, AuditingActionEnum.CREATE_RESOURCE, ComponentTypeEnum.RESOURCE);
     }
 
     private Either<Resource, ResponseFormat> parseToLightResource(String resourceJson, User user) {
-        Either<Resource, ResponseFormat> ret = getComponentsUtils().convertJsonToObjectUsingObjectMapper(resourceJson, user, Resource.class, AuditingActionEnum.UPDATE_RESOURCE_METADATA, ComponentTypeEnum.RESOURCE);
+        Either<Resource, ResponseFormat> ret = getComponentsUtils()
+            .convertJsonToObjectUsingObjectMapper(resourceJson, user, Resource.class, AuditingActionEnum.UPDATE_RESOURCE_METADATA,
+                ComponentTypeEnum.RESOURCE);
         if (ret.isLeft()) {// drop unwanted data (sent from UI in update flow)
             ret.left().value().setRequirements(null);
             ret.left().value().setCapabilities(null);
@@ -224,7 +219,6 @@ public class ResourcesServlet extends AbstractValidationsServlet {
     @Path("/resources/{resourceId}")
     @PermissionAllowed(AafPermission.PermNames.INTERNAL_ALL_VALUE)
     public Response deleteResource(@PathParam("resourceId") final String resourceId, @Context final HttpServletRequest request) {
-
         String url = request.getMethod() + " " + request.getRequestURI();
         log.debug(START_HANDLE_REQUEST_OF, url);
         // get modifier id
@@ -232,22 +226,19 @@ public class ResourcesServlet extends AbstractValidationsServlet {
         User modifier = new User();
         modifier.setUserId(userId);
         log.debug(MODIFIER_ID_IS, userId);
-        loggerSupportability.log(LoggerSupportabilityActions.DELETE_RESOURCE ,StatusCode.STARTED,"Starting to delete Resource by user {}",userId);
+        loggerSupportability.log(LoggerSupportabilityActions.DELETE_RESOURCE, StatusCode.STARTED, "Starting to delete Resource by user {}", userId);
         Response response;
-
         try {
             String resourceIdLower = resourceId.toLowerCase();
             ResponseFormat actionResponse = resourceBusinessLogic.deleteResource(resourceIdLower, modifier);
-
             if (actionResponse.getStatus() != HttpStatus.SC_NO_CONTENT) {
                 log.debug("failed to delete resource");
                 response = buildErrorResponse(actionResponse);
                 return response;
             }
             response = buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.NO_CONTENT), null);
-            loggerSupportability.log(LoggerSupportabilityActions.DELETE_RESOURCE ,StatusCode.COMPLETE,"Ended delete Resource by user {}",userId);
+            loggerSupportability.log(LoggerSupportabilityActions.DELETE_RESOURCE, StatusCode.COMPLETE, "Ended delete Resource by user {}", userId);
             return response;
-
         } catch (JSONException e) {
             BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Delete Resource");
             log.debug("delete resource failed with exception", e);
@@ -257,31 +248,26 @@ public class ResourcesServlet extends AbstractValidationsServlet {
 
     @DELETE
     @Path("/resources/{resourceName}/{version}")
-    @Operation(description = "Delete Resource By Name And Version", method = "DELETE", summary = "Returns no content",
-            responses = {@ApiResponse(
-                    content = @Content(array = @ArraySchema(schema = @Schema(implementation = Resource.class)))),
-                    @ApiResponse(responseCode = "204", description = "Resource deleted"),
-                    @ApiResponse(responseCode = "403", description = "Restricted operation"),
-                    @ApiResponse(responseCode = "400", description = "Invalid content / Missing content"),
-                    @ApiResponse(responseCode = "404", description = "Resource not found")})
+    @Operation(description = "Delete Resource By Name And Version", method = "DELETE", summary = "Returns no content", responses = {
+        @ApiResponse(content = @Content(array = @ArraySchema(schema = @Schema(implementation = Resource.class)))),
+        @ApiResponse(responseCode = "204", description = "Resource deleted"),
+        @ApiResponse(responseCode = "403", description = "Restricted operation"),
+        @ApiResponse(responseCode = "400", description = "Invalid content / Missing content"),
+        @ApiResponse(responseCode = "404", description = "Resource not found")})
     @PermissionAllowed(AafPermission.PermNames.INTERNAL_ALL_VALUE)
-    public Response deleteResourceByNameAndVersion(@PathParam("resourceName") final String resourceName, @PathParam("version") final String version, @Context final HttpServletRequest request) {
-
+    public Response deleteResourceByNameAndVersion(@PathParam("resourceName") final String resourceName, @PathParam("version") final String version,
+                                                   @Context final HttpServletRequest request) {
         ServletContext context = request.getSession().getServletContext();
-
         String url = request.getMethod() + " " + request.getRequestURI();
         log.debug(START_HANDLE_REQUEST_OF, url);
-
         // get modifier id
         String userId = request.getHeader(Constants.USER_ID_HEADER);
         User modifier = new User();
         modifier.setUserId(userId);
         log.debug(MODIFIER_ID_IS, userId);
-
         Response response;
         ResourceBusinessLogic businessLogic = getResourceBL(context);
         ResponseFormat actionResponse = businessLogic.deleteResourceByNameAndVersion(resourceName, version, modifier);
-
         if (actionResponse.getStatus() != HttpStatus.SC_NO_CONTENT) {
             log.debug("failed to delete resource");
             response = buildErrorResponse(actionResponse);
@@ -295,33 +281,25 @@ public class ResourcesServlet extends AbstractValidationsServlet {
     @Path("/resources/{resourceId}")
     @Consumes(MediaType.APPLICATION_JSON)
     @Produces(MediaType.APPLICATION_JSON)
-    @Operation(description = "Retrieve Resource", method = "GET", summary = "Returns resource according to resourceId",
-            responses = {@ApiResponse(
-                    content = @Content(array = @ArraySchema(schema = @Schema(implementation = Resource.class)))),
-                    @ApiResponse(responseCode = "200", description = "Resource found"),
-                    @ApiResponse(responseCode = "403", description = "Restricted operation"),
-                    @ApiResponse(responseCode = "404", description = "Resource not found")})
+    @Operation(description = "Retrieve Resource", method = "GET", summary = "Returns resource according to resourceId", responses = {
+        @ApiResponse(content = @Content(array = @ArraySchema(schema = @Schema(implementation = Resource.class)))),
+        @ApiResponse(responseCode = "200", description = "Resource found"), @ApiResponse(responseCode = "403", description = "Restricted operation"),
+        @ApiResponse(responseCode = "404", description = "Resource not found")})
     @PermissionAllowed(AafPermission.PermNames.INTERNAL_ALL_VALUE)
-    public Response getResourceById(@PathParam("resourceId") final String resourceId,
-            @Context final HttpServletRequest request, @HeaderParam(value = Constants.USER_ID_HEADER) String userId) throws IOException {
-
+    public Response getResourceById(@PathParam("resourceId") final String resourceId, @Context final HttpServletRequest request,
+                                    @HeaderParam(value = Constants.USER_ID_HEADER) String userId) throws IOException {
         ServletContext context = request.getSession().getServletContext();
-
         String url = request.getMethod() + " " + request.getRequestURI();
         log.debug(START_HANDLE_REQUEST_OF, url);
-
         // get modifier id
         User modifier = new User();
         modifier.setUserId(userId);
         log.debug(MODIFIER_ID_IS, userId);
-
         Response response;
-
         try {
             String resourceIdLower = resourceId.toLowerCase();
             log.trace("get resource with id {}", resourceId);
             Either<Resource, ResponseFormat> actionResponse = resourceBusinessLogic.getResource(resourceIdLower, modifier);
-
             if (actionResponse.isRight()) {
                 log.debug("failed to get resource");
                 response = buildErrorResponse(actionResponse.right().value());
@@ -329,7 +307,6 @@ public class ResourcesServlet extends AbstractValidationsServlet {
             }
             Object resource = RepresentationUtils.toRepresentation(actionResponse.left().value());
             return buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), resource);
-
         } catch (IOException e) {
             BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Get Resource");
             log.debug("get resource failed with exception", e);
@@ -341,31 +318,28 @@ public class ResourcesServlet extends AbstractValidationsServlet {
     @Path("/resources/resourceName/{resourceName}/resourceVersion/{resourceVersion}")
     @Consumes(MediaType.APPLICATION_JSON)
     @Produces(MediaType.APPLICATION_JSON)
-    @Operation(description = "Retrieve Resource by name and version", method = "GET",
-            summary = "Returns resource according to resourceId", responses = {
-            @ApiResponse(content = @Content(array = @ArraySchema(schema = @Schema(implementation = Resource.class)))),
-            @ApiResponse(responseCode = "200", description = "Resource found"),
-            @ApiResponse(responseCode = "403", description = "Restricted operation"),
-            @ApiResponse(responseCode = "404", description = "Resource not found")})
+    @Operation(description = "Retrieve Resource by name and version", method = "GET", summary = "Returns resource according to resourceId", responses = {
+        @ApiResponse(content = @Content(array = @ArraySchema(schema = @Schema(implementation = Resource.class)))),
+        @ApiResponse(responseCode = "200", description = "Resource found"), @ApiResponse(responseCode = "403", description = "Restricted operation"),
+        @ApiResponse(responseCode = "404", description = "Resource not found")})
     @PermissionAllowed(AafPermission.PermNames.INTERNAL_ALL_VALUE)
     public Response getResourceByNameAndVersion(@PathParam("resourceName") final String resourceName,
                                                 @PathParam("resourceVersion") final String resourceVersion, @Context final HttpServletRequest request,
                                                 @HeaderParam(value = Constants.USER_ID_HEADER) String userId) throws IOException {
-
         // get modifier id
         User modifier = new User();
         modifier.setUserId(userId);
         log.debug(MODIFIER_ID_IS, userId);
         Response response;
         try {
-            Either<Resource, ResponseFormat> actionResponse = resourceBusinessLogic.getResourceByNameAndVersion(resourceName, resourceVersion, userId);
+            Either<Resource, ResponseFormat> actionResponse = resourceBusinessLogic
+                .getResourceByNameAndVersion(resourceName, resourceVersion, userId);
             if (actionResponse.isRight()) {
                 response = buildErrorResponse(actionResponse.right().value());
                 return response;
             }
             Object resource = RepresentationUtils.toRepresentation(actionResponse.left().value());
             return buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), resource);
-
         } catch (IOException e) {
             BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Get Resource by name and version");
             log.debug("get resource failed with exception", e);
@@ -377,36 +351,30 @@ public class ResourcesServlet extends AbstractValidationsServlet {
     @Path("/resources/validate-name/{resourceName}")
     @Consumes(MediaType.APPLICATION_JSON)
     @Produces(MediaType.APPLICATION_JSON)
-    @Operation(description = "validate resource name", method = "GET",
-            summary = "checks if the chosen resource name is available ", responses = {
-            @ApiResponse(content = @Content(array = @ArraySchema(schema = @Schema(implementation = Resource.class)))),
-            @ApiResponse(responseCode = "200", description = "Resource found"),
-            @ApiResponse(responseCode = "403", description = "Restricted operation")})
+    @Operation(description = "validate resource name", method = "GET", summary = "checks if the chosen resource name is available ", responses = {
+        @ApiResponse(content = @Content(array = @ArraySchema(schema = @Schema(implementation = Resource.class)))),
+        @ApiResponse(responseCode = "200", description = "Resource found"), @ApiResponse(responseCode = "403", description = "Restricted operation")})
     @PermissionAllowed(AafPermission.PermNames.INTERNAL_ALL_VALUE)
-    public Response validateResourceName(@PathParam("resourceName") final String resourceName,
-            @QueryParam("subtype") String resourceType, @Context final HttpServletRequest request,
-            @HeaderParam(value = Constants.USER_ID_HEADER) String userId) {
+    public Response validateResourceName(@PathParam("resourceName") final String resourceName, @QueryParam("subtype") String resourceType,
+                                         @Context final HttpServletRequest request, @HeaderParam(value = Constants.USER_ID_HEADER) String userId) {
         String url = request.getMethod() + " " + request.getRequestURI();
         log.debug(START_HANDLE_REQUEST_OF, url);
-
         // get modifier id
         User modifier = new User();
         modifier.setUserId(userId);
         log.debug(MODIFIER_ID_IS, userId);
         Response response;
-
         if (resourceType != null && !ResourceTypeEnum.containsName(resourceType)) {
             log.debug("invalid resource type received");
             response = buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.INVALID_CONTENT));
             return response;
-
         }
         ResourceTypeEnum typeEnum = null;
         if (resourceType != null) {
             typeEnum = ResourceTypeEnum.valueOf(resourceType);
         }
-        Either<Map<String, Boolean>, ResponseFormat> actionResponse = resourceBusinessLogic.validateResourceNameExists(resourceName, typeEnum, userId);
-
+        Either<Map<String, Boolean>, ResponseFormat> actionResponse = resourceBusinessLogic
+            .validateResourceNameExists(resourceName, typeEnum, userId);
         if (actionResponse.isRight()) {
             log.debug("failed to validate resource name");
             response = buildErrorResponse(actionResponse.right().value());
@@ -420,14 +388,13 @@ public class ResourcesServlet extends AbstractValidationsServlet {
     @Consumes(MediaType.APPLICATION_JSON)
     @Produces(MediaType.APPLICATION_JSON)
     @PermissionAllowed(AafPermission.PermNames.INTERNAL_ALL_VALUE)
-    public Response getCertifiedAbstractResources(@Context final HttpServletRequest request, @HeaderParam(value = Constants.USER_ID_HEADER) String userId) throws IOException {
+    public Response getCertifiedAbstractResources(@Context final HttpServletRequest request,
+                                                  @HeaderParam(value = Constants.USER_ID_HEADER) String userId) throws IOException {
         String url = request.getMethod() + " " + request.getRequestURI();
-        log.debug("(get) Start handle request of {}" , url);
+        log.debug("(get) Start handle request of {}", url);
         try {
-            List<Resource> resources = resourceBusinessLogic
-                    .getAllCertifiedResources(true, HighestFilterEnum.HIGHEST_ONLY, userId);
+            List<Resource> resources = resourceBusinessLogic.getAllCertifiedResources(true, HighestFilterEnum.HIGHEST_ONLY, userId);
             return buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), RepresentationUtils.toRepresentation(resources));
-
         } catch (IOException e) {
             BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Get Certified Abstract Resources");
             log.debug("getCertifiedAbstractResources failed with exception", e);
@@ -440,39 +407,36 @@ public class ResourcesServlet extends AbstractValidationsServlet {
     @Consumes(MediaType.APPLICATION_JSON)
     @Produces(MediaType.APPLICATION_JSON)
     @PermissionAllowed(AafPermission.PermNames.INTERNAL_ALL_VALUE)
-    public Response getCertifiedNotAbstractResources(@Context final HttpServletRequest request, @HeaderParam(value = Constants.USER_ID_HEADER) String userId) throws IOException {
+    public Response getCertifiedNotAbstractResources(@Context final HttpServletRequest request,
+                                                     @HeaderParam(value = Constants.USER_ID_HEADER) String userId) throws IOException {
         String url = request.getMethod() + " " + request.getRequestURI();
-        log.debug("(get) Start handle request of {}" , url);
+        log.debug("(get) Start handle request of {}", url);
         try {
             List<Resource> resouces = resourceBusinessLogic.getAllCertifiedResources(false, HighestFilterEnum.ALL, userId);
             return buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), RepresentationUtils.toRepresentation(resouces));
-
         } catch (IOException e) {
             BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Get Certified Non Abstract Resources");
             log.debug("getCertifiedNotAbstractResources failed with exception", e);
             throw e;
         }
-
     }
 
     @PUT
     @Path("/resources/{resourceId}/metadata")
     @Consumes(MediaType.APPLICATION_JSON)
     @Produces(MediaType.APPLICATION_JSON)
-    @Operation(description = "Update Resource Metadata", method = "PUT", summary = "Returns updated resource metadata",
-            responses = {@ApiResponse(
-                    content = @Content(array = @ArraySchema(schema = @Schema(implementation = Resource.class)))),
-                    @ApiResponse(responseCode = "200", description = "Resource metadata updated"),
-                    @ApiResponse(responseCode = "403", description = "Restricted operation"),
-                    @ApiResponse(responseCode = "400", description = "Invalid content")})
+    @Operation(description = "Update Resource Metadata", method = "PUT", summary = "Returns updated resource metadata", responses = {
+        @ApiResponse(content = @Content(array = @ArraySchema(schema = @Schema(implementation = Resource.class)))),
+        @ApiResponse(responseCode = "200", description = "Resource metadata updated"),
+        @ApiResponse(responseCode = "403", description = "Restricted operation"),
+        @ApiResponse(responseCode = "400", description = "Invalid content")})
     @PermissionAllowed(AafPermission.PermNames.INTERNAL_ALL_VALUE)
     public Response updateResourceMetadata(@PathParam("resourceId") final String resourceId,
-            @Parameter(description = "Resource metadata to be updated", required = true) String data,
-            @Context final HttpServletRequest request,       @HeaderParam(value = Constants.USER_ID_HEADER) String userId) throws IOException {
-
+                                           @Parameter(description = "Resource metadata to be updated", required = true) String data,
+                                           @Context final HttpServletRequest request, @HeaderParam(value = Constants.USER_ID_HEADER) String userId)
+        throws IOException {
         String url = request.getMethod() + " " + request.getRequestURI();
         log.debug(START_HANDLE_REQUEST_OF, url);
-
         // get modifier id
         User modifier = new User();
         modifier.setUserId(userId);
@@ -480,13 +444,16 @@ public class ResourcesServlet extends AbstractValidationsServlet {
         Response response;
         try {
             String resourceIdLower = resourceId.toLowerCase();
-            Either<Resource, ResponseFormat> updateInfoResource = getComponentsUtils().convertJsonToObjectUsingObjectMapper(data, modifier, Resource.class, AuditingActionEnum.UPDATE_RESOURCE_METADATA, ComponentTypeEnum.RESOURCE);
+            Either<Resource, ResponseFormat> updateInfoResource = getComponentsUtils()
+                .convertJsonToObjectUsingObjectMapper(data, modifier, Resource.class, AuditingActionEnum.UPDATE_RESOURCE_METADATA,
+                    ComponentTypeEnum.RESOURCE);
             if (updateInfoResource.isRight()) {
                 log.debug("failed to parse resource metadata");
                 response = buildErrorResponse(updateInfoResource.right().value());
                 return response;
             }
-            Resource updatedResource = resourceBusinessLogic.updateResourceMetadata(resourceIdLower, updateInfoResource.left().value(), null, modifier, false);
+            Resource updatedResource = resourceBusinessLogic
+                .updateResourceMetadata(resourceIdLower, updateInfoResource.left().value(), null, modifier, false);
             Object resource = RepresentationUtils.toRepresentation(updatedResource);
             return buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), resource);
         } catch (IOException e) {
@@ -501,17 +468,15 @@ public class ResourcesServlet extends AbstractValidationsServlet {
     @Consumes(MediaType.APPLICATION_JSON)
     @Produces(MediaType.APPLICATION_JSON)
     @Operation(description = "Update Resource", method = "PUT", summary = "Returns updated resource", responses = {
-            @ApiResponse(content = @Content(array = @ArraySchema(schema = @Schema(implementation = Resource.class)))),
-            @ApiResponse(responseCode = "200", description = "Resource updated"),
-            @ApiResponse(responseCode = "403", description = "Restricted operation"),
-            @ApiResponse(responseCode = "400", description = "Invalid content / Missing content"),
-            @ApiResponse(responseCode = "409", description = "Resource already exist")})
+        @ApiResponse(content = @Content(array = @ArraySchema(schema = @Schema(implementation = Resource.class)))),
+        @ApiResponse(responseCode = "200", description = "Resource updated"),
+        @ApiResponse(responseCode = "403", description = "Restricted operation"),
+        @ApiResponse(responseCode = "400", description = "Invalid content / Missing content"),
+        @ApiResponse(responseCode = "409", description = "Resource already exist")})
     @PermissionAllowed(AafPermission.PermNames.INTERNAL_ALL_VALUE)
-    public Response updateResource(
-            @Parameter(description = "Resource object to be updated", required = true) String data,
-            @Context final HttpServletRequest request, @HeaderParam(value = Constants.USER_ID_HEADER) String userId,
-            @PathParam(value = "resourceId") String resourceId) throws IOException, ZipException {
-
+    public Response updateResource(@Parameter(description = "Resource object to be updated", required = true) String data,
+                                   @Context final HttpServletRequest request, @HeaderParam(value = Constants.USER_ID_HEADER) String userId,
+                                   @PathParam(value = "resourceId") String resourceId) throws IOException, ZipException {
         userId = (userId != null) ? userId : request.getHeader(Constants.USER_ID_HEADER);
         init();
         String url = request.getMethod() + " " + request.getRequestURI();
@@ -520,7 +485,7 @@ public class ResourcesServlet extends AbstractValidationsServlet {
         User modifier = new User();
         modifier.setUserId(userId);
         log.debug(MODIFIER_ID_IS, userId);
-        loggerSupportability.log(LoggerSupportabilityActions.UPDATE_RESOURCE,StatusCode.STARTED,"Starting to update a resource by user {}",userId);
+        loggerSupportability.log(LoggerSupportabilityActions.UPDATE_RESOURCE, StatusCode.STARTED, "Starting to update a resource by user {}", userId);
         Response response;
         try {
             Wrapper<Response> responseWrapper = new Wrapper<>();
@@ -534,12 +499,14 @@ public class ResourcesServlet extends AbstractValidationsServlet {
                     response = buildErrorResponse(convertResponse.right().value());
                     return response;
                 }
-                Resource updatedResource = resourceBusinessLogic.validateAndUpdateResourceFromCsar(convertResponse.left().value(), modifier, null, null, resourceId);
+                Resource updatedResource = resourceBusinessLogic
+                    .validateAndUpdateResourceFromCsar(convertResponse.left().value(), modifier, null, null, resourceId);
                 Object representation = RepresentationUtils.toRepresentation(updatedResource);
                 response = buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), representation);
                 responseWrapper.setInnerElement(response);
-                loggerSupportability.log(LoggerSupportabilityActions.UPDATE_RESOURCE,updatedResource.getComponentMetadataForSupportLog(),StatusCode.COMPLETE,"Ended update a resource by user {}",userId);
-
+                loggerSupportability
+                    .log(LoggerSupportabilityActions.UPDATE_RESOURCE, updatedResource.getComponentMetadataForSupportLog(), StatusCode.COMPLETE,
+                        "Ended update a resource by user {}", userId);
             }
             return responseWrapper.getInnerElement();
         } catch (final IOException | ZipException e) {
@@ -553,36 +520,26 @@ public class ResourcesServlet extends AbstractValidationsServlet {
     @Path("/resources/csar/{csaruuid}")
     @Consumes(MediaType.APPLICATION_JSON)
     @Produces(MediaType.APPLICATION_JSON)
-    @Operation(description = "Create Resource", method = "POST", summary = "Returns resource created from csar uuid",
-            responses = {@ApiResponse(
-                    content = @Content(array = @ArraySchema(schema = @Schema(implementation = Resource.class)))),
-                    @ApiResponse(responseCode = "201", description = "Resource retrieced"),
-                    @ApiResponse(responseCode = "403", description = "Restricted operation"),
-                    @ApiResponse(responseCode = "400", description = "Invalid content / Missing content")})
+    @Operation(description = "Create Resource", method = "POST", summary = "Returns resource created from csar uuid", responses = {
+        @ApiResponse(content = @Content(array = @ArraySchema(schema = @Schema(implementation = Resource.class)))),
+        @ApiResponse(responseCode = "201", description = "Resource retrieced"),
+        @ApiResponse(responseCode = "403", description = "Restricted operation"),
+        @ApiResponse(responseCode = "400", description = "Invalid content / Missing content")})
     @PermissionAllowed(AafPermission.PermNames.INTERNAL_ALL_VALUE)
-    public Response getResourceFromCsar(@Context final HttpServletRequest request,
-            @HeaderParam(value = Constants.USER_ID_HEADER) String userId,
-            @PathParam(value = "csaruuid") String csarUUID) throws IOException {
-
+    public Response getResourceFromCsar(@Context final HttpServletRequest request, @HeaderParam(value = Constants.USER_ID_HEADER) String userId,
+                                        @PathParam(value = "csaruuid") String csarUUID) throws IOException {
         init();
-
         String url = request.getMethod() + " " + request.getRequestURI();
         log.debug(START_HANDLE_REQUEST_OF, url);
-
         // retrieve user details
         userId = (userId != null) ? userId : request.getHeader(Constants.USER_ID_HEADER);
         User user = new User();
         user.setUserId(userId);
-
         log.debug("user id is {}", userId);
-
         Response response;
-
         try {
-
-            Either<Resource, ResponseFormat> eitherResource =
-                    resourceBusinessLogic.getLatestResourceFromCsarUuid(ValidationUtils.sanitizeInputString(csarUUID), user);
-
+            Either<Resource, ResponseFormat> eitherResource = resourceBusinessLogic
+                .getLatestResourceFromCsarUuid(ValidationUtils.sanitizeInputString(csarUUID), user);
             // validate response
             if (eitherResource.isRight()) {
                 log.debug("failed to get resource from csarUuid : {}", csarUUID);
@@ -591,9 +548,7 @@ public class ResourcesServlet extends AbstractValidationsServlet {
                 Object representation = RepresentationUtils.toRepresentation(eitherResource.left().value());
                 response = buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), representation);
             }
-
             return response;
-
         } catch (IOException e) {
             log.debug("get resource by csar failed with exception", e);
             throw e;
@@ -604,48 +559,33 @@ public class ResourcesServlet extends AbstractValidationsServlet {
     @Path("/resources/importReplaceResource")
     @Produces(MediaType.APPLICATION_JSON)
     @Operation(description = "Import Resource", method = "POST", summary = "Returns imported resource", responses = {
-            @ApiResponse(responseCode = "201", description = "Resource created"),
-            @ApiResponse(responseCode = "403", description = "Restricted operation"),
-            @ApiResponse(responseCode = "400", description = "Invalid content / Missing content"),
-            @ApiResponse(responseCode = "409", description = "Resource already exist")})
+        @ApiResponse(responseCode = "201", description = "Resource created"),
+        @ApiResponse(responseCode = "403", description = "Restricted operation"),
+        @ApiResponse(responseCode = "400", description = "Invalid content / Missing content"),
+        @ApiResponse(responseCode = "409", description = "Resource already exist")})
     @PermissionAllowed(AafPermission.PermNames.INTERNAL_ALL_VALUE)
     public Response importReplaceResource(
-            @Parameter(description = "The user id",
-                    required = true) @HeaderParam(value = Constants.USER_ID_HEADER) String userId,
-            @Parameter(description = "X-ECOMP-RequestID header",
-                    required = false) @HeaderParam(value = Constants.X_ECOMP_REQUEST_ID_HEADER) String requestId,
-            @Parameter(description = "X-ECOMP-InstanceID header", required = true) @HeaderParam(
-                    value = Constants.X_ECOMP_INSTANCE_ID_HEADER) final String instanceIdHeader,
-            @Parameter(description = "Determines the format of the body of the response",
-                    required = false) @HeaderParam(value = Constants.ACCEPT_HEADER) String accept,
-            @Parameter(description = "The username and password",
-                    required = true) @HeaderParam(value = Constants.AUTHORIZATION_HEADER) String authorization,
-            @Context final HttpServletRequest request,
-            @Parameter(description = "FileInputStream")
-            @FormDataParam("resourceZip") File file,
-            @Parameter(description = "ContentDisposition")
-            @FormDataParam("resourceZip") FormDataContentDisposition contentDispositionHeader,
-            @Parameter(description = "resourceMetadata")
-            @FormDataParam("resourceZipMetadata") String resourceInfoJsonString) {
-
+        @Parameter(description = "The user id", required = true) @HeaderParam(value = Constants.USER_ID_HEADER) String userId,
+        @Parameter(description = "X-ECOMP-RequestID header", required = false) @HeaderParam(value = Constants.X_ECOMP_REQUEST_ID_HEADER) String requestId,
+        @Parameter(description = "X-ECOMP-InstanceID header", required = true) @HeaderParam(value = Constants.X_ECOMP_INSTANCE_ID_HEADER) final String instanceIdHeader,
+        @Parameter(description = "Determines the format of the body of the response", required = false) @HeaderParam(value = Constants.ACCEPT_HEADER) String accept,
+        @Parameter(description = "The username and password", required = true) @HeaderParam(value = Constants.AUTHORIZATION_HEADER) String authorization,
+        @Context final HttpServletRequest request, @Parameter(description = "FileInputStream") @FormDataParam("resourceZip") File file,
+        @Parameter(description = "ContentDisposition") @FormDataParam("resourceZip") FormDataContentDisposition contentDispositionHeader,
+        @Parameter(description = "resourceMetadata") @FormDataParam("resourceZipMetadata") String resourceInfoJsonString) {
         init();
-
         String requestURI = request.getRequestURI();
         String url = request.getMethod() + " " + requestURI;
         log.debug("importReplaceResource,Start handle request of {}", url);
-
         // get modifier id
         User modifier = new User();
         modifier.setUserId(userId);
         log.debug("importReplaceResource,modifier id is {}", userId);
-
         log.debug("importReplaceResource,get file:{},fileName:{}", file, file.getName());
-
         Response response;
         ResponseFormat responseFormat = null;
         AuditingActionEnum auditingActionEnum = AuditingActionEnum.Import_Replace_Resource;
         String assetType = "resources";
-
         ComponentTypeEnum componentType = ComponentTypeEnum.findByParamName(assetType);
         ResourceCommonInfo resourceCommonInfo = new ResourceCommonInfo(componentType.getValue());
         DistributionData distributionData = new DistributionData(instanceIdHeader, requestURI);
@@ -653,37 +593,28 @@ public class ResourcesServlet extends AbstractValidationsServlet {
         if (instanceIdHeader == null || instanceIdHeader.isEmpty()) {
             log.debug("importReplaceResource: Missing X-ECOMP-InstanceID header");
             responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.MISSING_X_ECOMP_INSTANCE_ID);
-            getComponentsUtils().auditExternalGetAsset(responseFormat, auditingActionEnum, distributionData,
-                    resourceCommonInfo, requestId, null);
+            getComponentsUtils().auditExternalGetAsset(responseFormat, auditingActionEnum, distributionData, resourceCommonInfo, requestId, null);
             return buildErrorResponse(responseFormat);
         }
-
         try {
             Wrapper<Response> responseWrapper = new Wrapper<>();
             // file import
             Wrapper<User> userWrapper = new Wrapper<>();
             Wrapper<UploadResourceInfo> uploadResourceInfoWrapper = new Wrapper<>();
             Wrapper<String> yamlStringWrapper = new Wrapper<>();
-
             ResourceAuthorityTypeEnum serviceAuthorityEnum = ResourceAuthorityTypeEnum.CSAR_TYPE_BE;
-
             // PayLoad Validations
             commonGeneralValidations(responseWrapper, userWrapper, uploadResourceInfoWrapper, serviceAuthorityEnum, userId, resourceInfoJsonString);
-
             fillPayload(responseWrapper, uploadResourceInfoWrapper, yamlStringWrapper, modifier, resourceInfoJsonString, serviceAuthorityEnum, file);
-
-            specificResourceAuthorityValidations(responseWrapper, uploadResourceInfoWrapper, yamlStringWrapper, userWrapper.getInnerElement(), request, resourceInfoJsonString, serviceAuthorityEnum);
-
+            specificResourceAuthorityValidations(responseWrapper, uploadResourceInfoWrapper, yamlStringWrapper, userWrapper.getInnerElement(),
+                request, resourceInfoJsonString, serviceAuthorityEnum);
             log.debug("importReplaceResource:get payload:{}", uploadResourceInfoWrapper.getInnerElement().getPayloadData());
-
-            log.debug("importReplaceResource:get ResourceType:{}",
-                    uploadResourceInfoWrapper.getInnerElement().getResourceType());
-
+            log.debug("importReplaceResource:get ResourceType:{}", uploadResourceInfoWrapper.getInnerElement().getResourceType());
             if (responseWrapper.isEmpty()) {
                 log.debug("importReplaceService:start handleImport");
-                handleImport(responseWrapper, userWrapper.getInnerElement(), uploadResourceInfoWrapper.getInnerElement(), yamlStringWrapper.getInnerElement(), serviceAuthorityEnum, true, null);
+                handleImport(responseWrapper, userWrapper.getInnerElement(), uploadResourceInfoWrapper.getInnerElement(),
+                    yamlStringWrapper.getInnerElement(), serviceAuthorityEnum, true, null);
             }
-
             return responseWrapper.getInnerElement();
         } catch (ZipException e) {
             BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Import Resource");
index 359050c..27117fa 100644 (file)
  * See the License for the specific language governing permissions and
  * limitations under the License.
  */
-
 package org.openecomp.sdc.be.servlets;
 
+import static org.openecomp.sdc.be.tosca.InterfacesOperationsConverter.SELF;
+
 import com.google.gson.Gson;
 import com.google.gson.JsonParseException;
 import com.jcabi.aspects.Loggable;
@@ -29,6 +30,26 @@ import io.swagger.v3.oas.annotations.servers.Server;
 import io.swagger.v3.oas.annotations.servers.Servers;
 import io.swagger.v3.oas.annotations.tags.Tag;
 import io.swagger.v3.oas.annotations.tags.Tags;
+import java.util.ArrayList;
+import java.util.HashMap;
+import java.util.Iterator;
+import java.util.List;
+import java.util.Map;
+import java.util.Map.Entry;
+import java.util.stream.Collectors;
+import javax.inject.Inject;
+import javax.inject.Singleton;
+import javax.servlet.http.HttpServletRequest;
+import javax.ws.rs.Consumes;
+import javax.ws.rs.GET;
+import javax.ws.rs.HeaderParam;
+import javax.ws.rs.POST;
+import javax.ws.rs.Path;
+import javax.ws.rs.PathParam;
+import javax.ws.rs.Produces;
+import javax.ws.rs.core.Context;
+import javax.ws.rs.core.MediaType;
+import javax.ws.rs.core.Response;
 import org.apache.commons.lang3.StringUtils;
 import org.json.simple.JSONArray;
 import org.json.simple.parser.JSONParser;
@@ -45,39 +66,16 @@ import org.openecomp.sdc.be.impl.ComponentsUtils;
 import org.openecomp.sdc.be.model.Operation;
 import org.openecomp.sdc.be.model.OperationInput;
 import org.openecomp.sdc.be.model.User;
-import org.openecomp.sdc.tosca.datatypes.ToscaFunctions;
 import org.openecomp.sdc.be.resources.data.auditing.AuditingActionEnum;
 import org.openecomp.sdc.be.types.ServiceConsumptionData;
 import org.openecomp.sdc.be.types.ServiceConsumptionSource;
 import org.openecomp.sdc.be.user.UserBusinessLogic;
 import org.openecomp.sdc.common.api.Constants;
 import org.openecomp.sdc.exception.ResponseFormat;
+import org.openecomp.sdc.tosca.datatypes.ToscaFunctions;
 import org.slf4j.Logger;
 import org.slf4j.LoggerFactory;
 
-import javax.inject.Inject;
-import javax.inject.Singleton;
-import javax.servlet.http.HttpServletRequest;
-import javax.ws.rs.Consumes;
-import javax.ws.rs.GET;
-import javax.ws.rs.HeaderParam;
-import javax.ws.rs.POST;
-import javax.ws.rs.Path;
-import javax.ws.rs.PathParam;
-import javax.ws.rs.Produces;
-import javax.ws.rs.core.Context;
-import javax.ws.rs.core.MediaType;
-import javax.ws.rs.core.Response;
-import java.util.ArrayList;
-import java.util.HashMap;
-import java.util.Iterator;
-import java.util.List;
-import java.util.Map;
-import java.util.Map.Entry;
-import java.util.stream.Collectors;
-
-import static org.openecomp.sdc.be.tosca.InterfacesOperationsConverter.SELF;
-
 @Loggable(prepend = true, value = Loggable.DEBUG, trim = false)
 @Path("/v1/catalog")
 @Tags({@Tag(name = "SDC Internal APIs")})
@@ -91,8 +89,7 @@ public class ServiceConsumptionServlet extends BeGenericServlet {
 
     @Inject
     public ServiceConsumptionServlet(UserBusinessLogic userBusinessLogic, ComponentsUtils componentsUtils,
-            InterfaceOperationBusinessLogic interfaceOperationBusinessLogic,
-            ServiceBusinessLogic serviceBusinessLogic) {
+                                     InterfaceOperationBusinessLogic interfaceOperationBusinessLogic, ServiceBusinessLogic serviceBusinessLogic) {
         super(userBusinessLogic, componentsUtils);
         this.interfaceOperationBusinessLogic = interfaceOperationBusinessLogic;
         this.serviceBusinessLogic = serviceBusinessLogic;
@@ -102,55 +99,44 @@ public class ServiceConsumptionServlet extends BeGenericServlet {
     @Path("/services/{serviceId}/consumption/{serviceInstanceId}")
     @Consumes(MediaType.APPLICATION_JSON)
     @Produces(MediaType.APPLICATION_JSON)
-    @io.swagger.v3.oas.annotations.Operation(description = "Service consumption on operation", method = "POST",
-            summary = "Returns consumption data", responses = {
-            @ApiResponse(content = @Content(array = @ArraySchema(schema = @Schema(implementation = Response.class)))),
-            @ApiResponse(responseCode = "201", description = "Service property created"),
-            @ApiResponse(responseCode = "403", description = "Restricted operation"),
-            @ApiResponse(responseCode = "400", description = "Invalid content / Missing content"),
-            @ApiResponse(responseCode = "409", description = "Service property already exist")})
+    @io.swagger.v3.oas.annotations.Operation(description = "Service consumption on operation", method = "POST", summary = "Returns consumption data", responses = {
+        @ApiResponse(content = @Content(array = @ArraySchema(schema = @Schema(implementation = Response.class)))),
+        @ApiResponse(responseCode = "201", description = "Service property created"),
+        @ApiResponse(responseCode = "403", description = "Restricted operation"),
+        @ApiResponse(responseCode = "400", description = "Invalid content / Missing content"),
+        @ApiResponse(responseCode = "409", description = "Service property already exist")})
     @PermissionAllowed(AafPermission.PermNames.INTERNAL_ALL_VALUE)
     public Response addInputToServiceOperation(@PathParam("serviceId") final String serviceId,
-            @PathParam("serviceInstanceId") final String serviceInstanceId,
-            @Parameter(description = "Service Consumption Data", required = true) String data,
-            @Context final HttpServletRequest request, @HeaderParam(value = Constants.USER_ID_HEADER) String userId) {
-
-    String url = request.getMethod() + " " + request.getRequestURI();
-    log.debug("Start handle request of {} modifier id is {} data is {}", url, userId, data);
-    User modifier = new User();
-    modifier.setUserId(userId);
-
-    try {
-
-      Either<Map<String, List<ServiceConsumptionData>>, ResponseFormat> dataFromJson =
-          getServiceConsumptionData(data, modifier);
-      if(dataFromJson.isRight()) {
-        return buildErrorResponse(dataFromJson.right().value());
-      }
-
-      Map<String, List<ServiceConsumptionData>> serviceConsumptionDataMap = dataFromJson.left().value();
-
-      for(Entry<String, List<ServiceConsumptionData>> consumptionEntry : serviceConsumptionDataMap.entrySet()) {
-        List<ServiceConsumptionData> consumptionList = consumptionEntry.getValue();
-        Either<List<Operation>, ResponseFormat> operationEither =
-            serviceBusinessLogic.addServiceConsumptionData(serviceId, serviceInstanceId,
-                consumptionEntry.getKey(), consumptionList, userId);
-        if (operationEither.isRight()) {
-          return buildErrorResponse(operationEither.right().value());
+                                               @PathParam("serviceInstanceId") final String serviceInstanceId,
+                                               @Parameter(description = "Service Consumption Data", required = true) String data,
+                                               @Context final HttpServletRequest request,
+                                               @HeaderParam(value = Constants.USER_ID_HEADER) String userId) {
+        String url = request.getMethod() + " " + request.getRequestURI();
+        log.debug("Start handle request of {} modifier id is {} data is {}", url, userId, data);
+        User modifier = new User();
+        modifier.setUserId(userId);
+        try {
+            Either<Map<String, List<ServiceConsumptionData>>, ResponseFormat> dataFromJson = getServiceConsumptionData(data, modifier);
+            if (dataFromJson.isRight()) {
+                return buildErrorResponse(dataFromJson.right().value());
+            }
+            Map<String, List<ServiceConsumptionData>> serviceConsumptionDataMap = dataFromJson.left().value();
+            for (Entry<String, List<ServiceConsumptionData>> consumptionEntry : serviceConsumptionDataMap.entrySet()) {
+                List<ServiceConsumptionData> consumptionList = consumptionEntry.getValue();
+                Either<List<Operation>, ResponseFormat> operationEither = serviceBusinessLogic
+                    .addServiceConsumptionData(serviceId, serviceInstanceId, consumptionEntry.getKey(), consumptionList, userId);
+                if (operationEither.isRight()) {
+                    return buildErrorResponse(operationEither.right().value());
+                }
+            }
+            return buildOkResponse(serviceConsumptionDataMap);
+        } catch (Exception e) {
+            BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Create Operation Inputs");
+            log.debug("Create Operation Inputs failed with exception", e);
+            ResponseFormat responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR);
+            return buildErrorResponse(responseFormat);
         }
-      }
-
-      return buildOkResponse(serviceConsumptionDataMap);
-
     }
-    catch (Exception e) {
-      BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Create Operation Inputs");
-      log.debug("Create Operation Inputs failed with exception", e);
-      ResponseFormat responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR);
-      return buildErrorResponse(responseFormat);
-    }
-
-  }
 
     @GET
     @Path("/services/{serviceId}/consumption/{serviceInstanceId}/interfaces/{interfaceId}/operations/{operationId}/inputs")
@@ -158,118 +144,99 @@ public class ServiceConsumptionServlet extends BeGenericServlet {
     @Produces(MediaType.APPLICATION_JSON)
     @PermissionAllowed(AafPermission.PermNames.INTERNAL_ALL_VALUE)
     public Response getInputsListOfOperation(@PathParam("serviceId") final String serviceId,
-            @PathParam("serviceInstanceId") final String serviceInstanceId,
-            @PathParam("interfaceId") final String interfaceId, @PathParam("operationId") final String operationId,
-            @Context final HttpServletRequest request, @HeaderParam(value = Constants.USER_ID_HEADER) String userId) {
-
-    String url = request.getMethod() + " " + request.getRequestURI();
-    log.debug("Start handle request of {} modifier id is {}", url, userId);
-    User user = new User();
-    user.setUserId(userId);
-
-    try {
-      Either<List<OperationInputDefinition>, ResponseFormat> inputsEither =
-          interfaceOperationBusinessLogic.getInputsListForOperation(serviceId, serviceInstanceId, interfaceId, operationId, user);
-
-      if(inputsEither.isRight()) {
-        return buildErrorResponse(inputsEither.right().value());
-      }
-
-      List<OperationInputDefinition> inputs = inputsEither.left().value();
-               return buildOkResponse(updateOperationInputListForUi(inputs, interfaceOperationBusinessLogic));
-    }
-    catch (Exception e) {
-      BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Get Operation Inputs");
-      log.debug("Get Operation Inputs failed with exception", e);
-      ResponseFormat responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR);
-      return buildErrorResponse(responseFormat);
+                                             @PathParam("serviceInstanceId") final String serviceInstanceId,
+                                             @PathParam("interfaceId") final String interfaceId, @PathParam("operationId") final String operationId,
+                                             @Context final HttpServletRequest request,
+                                             @HeaderParam(value = Constants.USER_ID_HEADER) String userId) {
+        String url = request.getMethod() + " " + request.getRequestURI();
+        log.debug("Start handle request of {} modifier id is {}", url, userId);
+        User user = new User();
+        user.setUserId(userId);
+        try {
+            Either<List<OperationInputDefinition>, ResponseFormat> inputsEither = interfaceOperationBusinessLogic
+                .getInputsListForOperation(serviceId, serviceInstanceId, interfaceId, operationId, user);
+            if (inputsEither.isRight()) {
+                return buildErrorResponse(inputsEither.right().value());
+            }
+            List<OperationInputDefinition> inputs = inputsEither.left().value();
+            return buildOkResponse(updateOperationInputListForUi(inputs, interfaceOperationBusinessLogic));
+        } catch (Exception e) {
+            BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Get Operation Inputs");
+            log.debug("Get Operation Inputs failed with exception", e);
+            ResponseFormat responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR);
+            return buildErrorResponse(responseFormat);
+        }
     }
-  }
-
-       private List<OperationInput> updateOperationInputListForUi(List<OperationInputDefinition> inputsList,
-                                                                                                                          InterfaceOperationBusinessLogic interfaceOperationBL) {
-               List<OperationInput> operationInputs = new ArrayList<>();
-               for(OperationInputDefinition input : inputsList) {
-
-                       String value = input.getValue();
-
-                       // Additional UI mapping needed for other sources
-                       if (StringUtils.isNotBlank(value)
-                                       && !ServiceConsumptionSource.STATIC.getSource().equals(input.getSource())) {
-                               uiMappingForOtherSources(value, input);
-                       }
 
-                       // Add Constraint for UI
-                       OperationInput operationInput = new OperationInput(input);
-                       operationInput.setConstraints(interfaceOperationBL.setInputConstraint(input));
-                       operationInputs.add(operationInput);
-               }
-
-               return operationInputs;
-       }
-
-       private void uiMappingForOtherSources(String value, OperationInputDefinition input) {
-               try {
-                       Map<String, Object> valueAsMap = (new Gson()).fromJson(value, Map.class);
-                       String toscaFunction = valueAsMap.keySet().iterator().next();
-                       Object consumptionValueName = valueAsMap.values().iterator().next();
-                       if(consumptionValueName instanceof List) {
-                               List<Object> toscaFunctionList = (List<Object>) consumptionValueName;
-                               String consumptionInputValue = null;
-                               if (ToscaFunctions.GET_PROPERTY.getFunctionName().equals(toscaFunction)) {
-                                       String propertyValue = toscaFunctionList.stream()
-                                                       .map(Object::toString)
-                                                       .filter(val -> !val.equals(SELF))
-                                                       .collect(Collectors.joining("_"));
-                                       consumptionInputValue = String.valueOf(propertyValue);
-                               } else if (ToscaFunctions.GET_OPERATION_OUTPUT.getFunctionName().equals(toscaFunction)) {
-                                       //Return full output name
-                                       consumptionInputValue =
-                                                       toscaFunctionList.get(1) + "." + toscaFunctionList.get(2) + "." +toscaFunctionList.get(3);
-                               }
-                               input.setValue(consumptionInputValue);
-                       } else {
-                               input.setValue(String.valueOf(consumptionValueName));
-                       }
-               }
-               catch(JsonParseException ex){
-                       log.info("This means it is static value for which no changes are needed");
-               }
-       }
-
-  private Either<Map<String, List<ServiceConsumptionData>>, ResponseFormat> getServiceConsumptionData(String data,
-                                                                                                      User user) {
-    JSONParser parser = new JSONParser();
-    Map<String, List<ServiceConsumptionData>> serviceConsumptionDataMap = new HashMap<>();
-
-    try {
-      JSONArray operationsArray = (JSONArray) parser.parse(data);
-      Iterator iterator = operationsArray.iterator();
-      while (iterator.hasNext()) {
-        Map next = (Map) iterator.next();
-        Entry consumptionEntry = (Entry) next.entrySet().iterator().next();
-        String operationId = (String) consumptionEntry.getKey();
-        Object value = consumptionEntry.getValue();
-
-        JSONArray inputsArray = (JSONArray) parser.parse(value.toString());
-        serviceConsumptionDataMap.putIfAbsent(operationId, new ArrayList<>());
-        for(Object consumptionObject : inputsArray) {
-          Either<ServiceConsumptionData, ResponseFormat> serviceDataEither =
-              getComponentsUtils()
-                  .convertJsonToObjectUsingObjectMapper(consumptionObject.toString(), user, ServiceConsumptionData
-                      .class, AuditingActionEnum.CREATE_RESOURCE, ComponentTypeEnum.SERVICE);
-          if(serviceDataEither.isRight()) {
-            return Either.right(serviceDataEither.right().value());
-          }
+    private List<OperationInput> updateOperationInputListForUi(List<OperationInputDefinition> inputsList,
+                                                               InterfaceOperationBusinessLogic interfaceOperationBL) {
+        List<OperationInput> operationInputs = new ArrayList<>();
+        for (OperationInputDefinition input : inputsList) {
+            String value = input.getValue();
+            // Additional UI mapping needed for other sources
+            if (StringUtils.isNotBlank(value) && !ServiceConsumptionSource.STATIC.getSource().equals(input.getSource())) {
+                uiMappingForOtherSources(value, input);
+            }
+            // Add Constraint for UI
+            OperationInput operationInput = new OperationInput(input);
+            operationInput.setConstraints(interfaceOperationBL.setInputConstraint(input));
+            operationInputs.add(operationInput);
+        }
+        return operationInputs;
+    }
 
-          serviceConsumptionDataMap.get(operationId).add(serviceDataEither.left().value());
+    private void uiMappingForOtherSources(String value, OperationInputDefinition input) {
+        try {
+            Map<String, Object> valueAsMap = (new Gson()).fromJson(value, Map.class);
+            String toscaFunction = valueAsMap.keySet().iterator().next();
+            Object consumptionValueName = valueAsMap.values().iterator().next();
+            if (consumptionValueName instanceof List) {
+                List<Object> toscaFunctionList = (List<Object>) consumptionValueName;
+                String consumptionInputValue = null;
+                if (ToscaFunctions.GET_PROPERTY.getFunctionName().equals(toscaFunction)) {
+                    String propertyValue = toscaFunctionList.stream().map(Object::toString).filter(val -> !val.equals(SELF))
+                        .collect(Collectors.joining("_"));
+                    consumptionInputValue = String.valueOf(propertyValue);
+                } else if (ToscaFunctions.GET_OPERATION_OUTPUT.getFunctionName().equals(toscaFunction)) {
+                    //Return full output name
+                    consumptionInputValue = toscaFunctionList.get(1) + "." + toscaFunctionList.get(2) + "." + toscaFunctionList.get(3);
+                }
+                input.setValue(consumptionInputValue);
+            } else {
+                input.setValue(String.valueOf(consumptionValueName));
+            }
+        } catch (JsonParseException ex) {
+            log.info("This means it is static value for which no changes are needed");
         }
-      }
     }
-    catch (ParseException e) {
-      log.info("Conetnt is invalid - {}", data);
-      return Either.right(getComponentsUtils().getResponseFormat(ActionStatus.INVALID_CONTENT));
+
+    private Either<Map<String, List<ServiceConsumptionData>>, ResponseFormat> getServiceConsumptionData(String data, User user) {
+        JSONParser parser = new JSONParser();
+        Map<String, List<ServiceConsumptionData>> serviceConsumptionDataMap = new HashMap<>();
+        try {
+            JSONArray operationsArray = (JSONArray) parser.parse(data);
+            Iterator iterator = operationsArray.iterator();
+            while (iterator.hasNext()) {
+                Map next = (Map) iterator.next();
+                Entry consumptionEntry = (Entry) next.entrySet().iterator().next();
+                String operationId = (String) consumptionEntry.getKey();
+                Object value = consumptionEntry.getValue();
+                JSONArray inputsArray = (JSONArray) parser.parse(value.toString());
+                serviceConsumptionDataMap.putIfAbsent(operationId, new ArrayList<>());
+                for (Object consumptionObject : inputsArray) {
+                    Either<ServiceConsumptionData, ResponseFormat> serviceDataEither = getComponentsUtils()
+                        .convertJsonToObjectUsingObjectMapper(consumptionObject.toString(), user, ServiceConsumptionData.class,
+                            AuditingActionEnum.CREATE_RESOURCE, ComponentTypeEnum.SERVICE);
+                    if (serviceDataEither.isRight()) {
+                        return Either.right(serviceDataEither.right().value());
+                    }
+                    serviceConsumptionDataMap.get(operationId).add(serviceDataEither.left().value());
+                }
+            }
+        } catch (ParseException e) {
+            log.info("Conetnt is invalid - {}", data);
+            return Either.right(getComponentsUtils().getResponseFormat(ActionStatus.INVALID_CONTENT));
+        }
+        return Either.left(serviceConsumptionDataMap);
     }
-    return Either.left(serviceConsumptionDataMap);
-  }
 }
index 253acd5..652dfa0 100644 (file)
@@ -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.
  * limitations under the License.
  * ============LICENSE_END=========================================================
  */
-
 package org.openecomp.sdc.be.servlets;
 
-
 import com.google.common.collect.Sets;
 import com.jcabi.aspects.Loggable;
 import fj.data.Either;
@@ -34,6 +32,23 @@ import io.swagger.v3.oas.annotations.servers.Server;
 import io.swagger.v3.oas.annotations.servers.Servers;
 import io.swagger.v3.oas.annotations.tags.Tag;
 import io.swagger.v3.oas.annotations.tags.Tags;
+import java.io.IOException;
+import java.util.Collections;
+import java.util.Set;
+import javax.inject.Inject;
+import javax.servlet.http.HttpServletRequest;
+import javax.ws.rs.Consumes;
+import javax.ws.rs.DELETE;
+import javax.ws.rs.GET;
+import javax.ws.rs.HeaderParam;
+import javax.ws.rs.POST;
+import javax.ws.rs.PUT;
+import javax.ws.rs.Path;
+import javax.ws.rs.PathParam;
+import javax.ws.rs.Produces;
+import javax.ws.rs.core.Context;
+import javax.ws.rs.core.MediaType;
+import javax.ws.rs.core.Response;
 import org.apache.commons.collections.MapUtils;
 import org.openecomp.sdc.be.components.impl.ComponentInstanceBusinessLogic;
 import org.openecomp.sdc.be.components.impl.ResourceImportManager;
@@ -58,24 +73,6 @@ import org.openecomp.sdc.common.log.wrappers.Logger;
 import org.openecomp.sdc.exception.ResponseFormat;
 import org.springframework.stereotype.Controller;
 
-import javax.inject.Inject;
-import javax.servlet.http.HttpServletRequest;
-import javax.ws.rs.Consumes;
-import javax.ws.rs.DELETE;
-import javax.ws.rs.GET;
-import javax.ws.rs.HeaderParam;
-import javax.ws.rs.POST;
-import javax.ws.rs.PUT;
-import javax.ws.rs.Path;
-import javax.ws.rs.PathParam;
-import javax.ws.rs.Produces;
-import javax.ws.rs.core.Context;
-import javax.ws.rs.core.MediaType;
-import javax.ws.rs.core.Response;
-import java.io.IOException;
-import java.util.Collections;
-import java.util.Set;
-
 @Loggable(prepend = true, value = Loggable.DEBUG, trim = false)
 @Path("/v1/catalog/services/{serviceId}/paths")
 @Consumes(MediaType.APPLICATION_JSON)
@@ -91,11 +88,9 @@ public class ServiceForwardingPathServlet extends AbstractValidationsServlet {
     private final ServiceBusinessLogic serviceBusinessLogic;
 
     @Inject
-    public ServiceForwardingPathServlet(UserBusinessLogic userBusinessLogic,
-        ComponentInstanceBusinessLogic componentInstanceBL,
-        ComponentsUtils componentsUtils, ServletUtils servletUtils,
-        ResourceImportManager resourceImportManager,
-        ServiceBusinessLogic serviceBusinessLogic) {
+    public ServiceForwardingPathServlet(UserBusinessLogic userBusinessLogic, ComponentInstanceBusinessLogic componentInstanceBL,
+                                        ComponentsUtils componentsUtils, ServletUtils servletUtils, ResourceImportManager resourceImportManager,
+                                        ServiceBusinessLogic serviceBusinessLogic) {
         super(userBusinessLogic, componentInstanceBL, componentsUtils, servletUtils, resourceImportManager);
         this.serviceBusinessLogic = serviceBusinessLogic;
     }
@@ -104,56 +99,47 @@ public class ServiceForwardingPathServlet extends AbstractValidationsServlet {
     @Consumes(MediaType.APPLICATION_JSON)
     @Produces(MediaType.APPLICATION_JSON)
     @Path("/")
-    @Operation(description = "Create Forwarding Path", method = "POST", summary = "Create Forwarding Path",
-            responses = {@ApiResponse(
-                    content = @Content(array = @ArraySchema(schema = @Schema(implementation = Service.class)))),
-                    @ApiResponse(responseCode = "201", description = "Create Forwarding Path"),
-                    @ApiResponse(responseCode = "403", description = "Restricted operation"),
-                    @ApiResponse(responseCode = "400", description = "Invalid content / Missing content"),
-                    @ApiResponse(responseCode = "409", description = "Forwarding Path already exist")})
+    @Operation(description = "Create Forwarding Path", method = "POST", summary = "Create Forwarding Path", responses = {
+        @ApiResponse(content = @Content(array = @ArraySchema(schema = @Schema(implementation = Service.class)))),
+        @ApiResponse(responseCode = "201", description = "Create Forwarding Path"),
+        @ApiResponse(responseCode = "403", description = "Restricted operation"),
+        @ApiResponse(responseCode = "400", description = "Invalid content / Missing content"),
+        @ApiResponse(responseCode = "409", description = "Forwarding Path already exist")})
     @PermissionAllowed(AafPermission.PermNames.INTERNAL_ALL_VALUE)
-    public Response createForwardingPath(
-            @Parameter(description = "Forwarding Path to create", required = true) String data,
-            @Parameter(description = "Service Id") @PathParam("serviceId") String serviceId,
-            @Context final HttpServletRequest request,
-            @HeaderParam(value = Constants.USER_ID_HEADER) String userId) throws IOException {
+    public Response createForwardingPath(@Parameter(description = "Forwarding Path to create", required = true) String data,
+                                         @Parameter(description = "Service Id") @PathParam("serviceId") String serviceId,
+                                         @Context final HttpServletRequest request, @HeaderParam(value = Constants.USER_ID_HEADER) String userId)
+        throws IOException {
         return createOrUpdate(data, serviceId, request, userId, false);
     }
 
-
-
     @PUT
     @Consumes(MediaType.APPLICATION_JSON)
     @Produces(MediaType.APPLICATION_JSON)
     @Path("/")
     @Operation(description = "Update Forwarding Path", method = "PUT", summary = "Update Forwarding Path", responses = {
-            @ApiResponse(content = @Content(array = @ArraySchema(schema = @Schema(implementation = Service.class)))),
-            @ApiResponse(responseCode = "201", description = "Update Forwarding Path"),
-            @ApiResponse(responseCode = "403", description = "Restricted operation"),
-            @ApiResponse(responseCode = "400", description = "Invalid content / Missing content"),
-            @ApiResponse(responseCode = "409", description = "Forwarding Path already exist")})
+        @ApiResponse(content = @Content(array = @ArraySchema(schema = @Schema(implementation = Service.class)))),
+        @ApiResponse(responseCode = "201", description = "Update Forwarding Path"),
+        @ApiResponse(responseCode = "403", description = "Restricted operation"),
+        @ApiResponse(responseCode = "400", description = "Invalid content / Missing content"),
+        @ApiResponse(responseCode = "409", description = "Forwarding Path already exist")})
     @PermissionAllowed(AafPermission.PermNames.INTERNAL_ALL_VALUE)
-    public Response updateForwardingPath(
-            @Parameter(description = "Update Path to create", required = true) String data,
-            @Parameter(description = "Service Id") @PathParam("serviceId") String serviceId,
-            @Context final HttpServletRequest request,
-            @HeaderParam(value = Constants.USER_ID_HEADER) String userId) throws IOException {
+    public Response updateForwardingPath(@Parameter(description = "Update Path to create", required = true) String data,
+                                         @Parameter(description = "Service Id") @PathParam("serviceId") String serviceId,
+                                         @Context final HttpServletRequest request, @HeaderParam(value = Constants.USER_ID_HEADER) String userId)
+        throws IOException {
         return createOrUpdate(data, serviceId, request, userId, true);
     }
 
-    private Response createOrUpdate( String data, String serviceId, HttpServletRequest request, String userId, boolean isUpdate) throws IOException {
+    private Response createOrUpdate(String data, String serviceId, HttpServletRequest request, String userId, boolean isUpdate) throws IOException {
         String url = request.getMethod() + " " + request.getRequestURI();
         log.debug(START_HANDLE_REQUEST_OF, url);
-
         User modifier = new User();
         modifier.setUserId(userId);
         log.debug(MODIFIER_ID_IS, userId);
-
         Response response;
-
         try {
             String serviceIdLower = serviceId.toLowerCase();
-
             Either<Service, ResponseFormat> convertResponse = parseToService(data, modifier);
             if (convertResponse.isRight()) {
                 log.debug("failed to parse service");
@@ -161,17 +147,15 @@ public class ServiceForwardingPathServlet extends AbstractValidationsServlet {
                 return response;
             }
             Service updatedService = convertResponse.left().value();
-            Service actionResponse ;
+            Service actionResponse;
             if (isUpdate) {
                 actionResponse = serviceBusinessLogic.updateForwardingPath(serviceIdLower, updatedService, modifier, true);
             } else {
                 actionResponse = serviceBusinessLogic.createForwardingPath(serviceIdLower, updatedService, modifier, true);
             }
-
             Service service = actionResponse;
             Object result = RepresentationUtils.toRepresentation(service);
             return buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), result);
-
         } catch (IOException e) {
             BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Forward Path Creation or update");
             log.debug("create or update forwarding path with an error", e);
@@ -184,42 +168,35 @@ public class ServiceForwardingPathServlet extends AbstractValidationsServlet {
     @Produces(MediaType.APPLICATION_JSON)
     @Path("/{forwardingPathId}")
     @Operation(description = "Get Forwarding Path", method = "GET", summary = "GET Forwarding Path", responses = {
-            @ApiResponse(content = @Content(
-                    array = @ArraySchema(schema = @Schema(implementation = ForwardingPathDataDefinition.class)))),
-            @ApiResponse(responseCode = "201", description = "Get Forwarding Path"),
-            @ApiResponse(responseCode = "403", description = "Restricted operation"),
-            @ApiResponse(responseCode = "400", description = "Invalid content / Missing content"),
-            @ApiResponse(responseCode = "409", description = "Forwarding Path already exist")})
+        @ApiResponse(content = @Content(array = @ArraySchema(schema = @Schema(implementation = ForwardingPathDataDefinition.class)))),
+        @ApiResponse(responseCode = "201", description = "Get Forwarding Path"),
+        @ApiResponse(responseCode = "403", description = "Restricted operation"),
+        @ApiResponse(responseCode = "400", description = "Invalid content / Missing content"),
+        @ApiResponse(responseCode = "409", description = "Forwarding Path already exist")})
     @PermissionAllowed(AafPermission.PermNames.INTERNAL_ALL_VALUE)
-    public Response getForwardingPath(
-            @Parameter(description = "Forwarding Path to create", required = true) String datax,
-            @Parameter(description = "Service Id") @PathParam("serviceId") String serviceId,
-            @Parameter(description = "Forwarding Path Id") @PathParam("forwardingPathId") String forwardingPathId,
-            @Context final HttpServletRequest request,
-            @HeaderParam(value = Constants.USER_ID_HEADER) String userId) throws IOException {
+    public Response getForwardingPath(@Parameter(description = "Forwarding Path to create", required = true) String datax,
+                                      @Parameter(description = "Service Id") @PathParam("serviceId") String serviceId,
+                                      @Parameter(description = "Forwarding Path Id") @PathParam("forwardingPathId") String forwardingPathId,
+                                      @Context final HttpServletRequest request, @HeaderParam(value = Constants.USER_ID_HEADER) String userId)
+        throws IOException {
         String url = request.getMethod() + " " + request.getRequestURI();
         log.debug(START_HANDLE_REQUEST_OF, url);
-
         User modifier = new User();
         modifier.setUserId(userId);
         log.debug(MODIFIER_ID_IS, userId);
-
-
         try {
-            Either<UiComponentDataTransfer, ResponseFormat> serviceResponse = serviceBusinessLogic.getComponentDataFilteredByParams(serviceId, modifier, Collections.singletonList(ComponentFieldsEnum.FORWARDING_PATHS.getValue()));
+            Either<UiComponentDataTransfer, ResponseFormat> serviceResponse = serviceBusinessLogic
+                .getComponentDataFilteredByParams(serviceId, modifier, Collections.singletonList(ComponentFieldsEnum.FORWARDING_PATHS.getValue()));
             if (serviceResponse.isRight()) {
                 return buildErrorResponse(serviceResponse.right().value());
             }
-
             UiServiceDataTransfer uiServiceDataTransfer = (UiServiceDataTransfer) serviceResponse.left().value();
-
             ForwardingPathDataDefinition forwardingPathDataDefinition = new ForwardingPathDataDefinition();
             if (!MapUtils.isEmpty(uiServiceDataTransfer.getForwardingPaths())) {
                 forwardingPathDataDefinition = uiServiceDataTransfer.getForwardingPaths().get(forwardingPathId);
             }
-            return buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), RepresentationUtils.toRepresentation(forwardingPathDataDefinition));
-
-
+            return buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK),
+                RepresentationUtils.toRepresentation(forwardingPathDataDefinition));
         } catch (Exception e) {
             BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Update Service Metadata");
             log.debug("update service metadata failed with exception", e);
@@ -231,35 +208,28 @@ public class ServiceForwardingPathServlet extends AbstractValidationsServlet {
     @Consumes(MediaType.APPLICATION_JSON)
     @Produces(MediaType.APPLICATION_JSON)
     @Path("/{forwardingPathId}")
-    @Operation(description = "Delete Forwarding Path", method = "DELETE", summary = "Delete Forwarding Path",
-            responses = {@ApiResponse(
-                    content = @Content(array = @ArraySchema(schema = @Schema(implementation = Service.class)))),
-                    @ApiResponse(responseCode = "201", description = "Delete Forwarding Path"),
-                    @ApiResponse(responseCode = "403", description = "Restricted operation"),
-                    @ApiResponse(responseCode = "400", description = "Invalid content / Missing content"),
-                    @ApiResponse(responseCode = "409", description = "Forwarding Path already exist")})
+    @Operation(description = "Delete Forwarding Path", method = "DELETE", summary = "Delete Forwarding Path", responses = {
+        @ApiResponse(content = @Content(array = @ArraySchema(schema = @Schema(implementation = Service.class)))),
+        @ApiResponse(responseCode = "201", description = "Delete Forwarding Path"),
+        @ApiResponse(responseCode = "403", description = "Restricted operation"),
+        @ApiResponse(responseCode = "400", description = "Invalid content / Missing content"),
+        @ApiResponse(responseCode = "409", description = "Forwarding Path already exist")})
     @PermissionAllowed(AafPermission.PermNames.INTERNAL_ALL_VALUE)
-    public Response deleteForwardingPath(
-            @Parameter(description = "Forwarding Path Id") @PathParam("forwardingPathId") String forwardingPathId,
-            @Parameter(description = "Service Id") @PathParam("serviceId") String serviceId,
-            @Context final HttpServletRequest request,
-            @HeaderParam(value = Constants.USER_ID_HEADER) String userId) throws IOException {
+    public Response deleteForwardingPath(@Parameter(description = "Forwarding Path Id") @PathParam("forwardingPathId") String forwardingPathId,
+                                         @Parameter(description = "Service Id") @PathParam("serviceId") String serviceId,
+                                         @Context final HttpServletRequest request, @HeaderParam(value = Constants.USER_ID_HEADER) String userId)
+        throws IOException {
         String url = request.getMethod() + " " + request.getRequestURI();
         log.debug(START_HANDLE_REQUEST_OF, url);
-
         User modifier = new User();
         modifier.setUserId(userId);
         log.debug(MODIFIER_ID_IS, userId);
-
         Response response;
-
         try {
             String serviceIdLower = serviceId.toLowerCase();
-
             Set<String> deletedPaths = serviceBusinessLogic.deleteForwardingPaths(serviceIdLower, Sets.newHashSet(forwardingPathId), modifier, true);
             Object result = RepresentationUtils.toRepresentation(deletedPaths);
             return buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), result);
-
         } catch (IOException e) {
             BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Delete forward paths");
             log.debug("Delete service paths with an error", e);
@@ -267,8 +237,8 @@ public class ServiceForwardingPathServlet extends AbstractValidationsServlet {
         }
     }
 
-
     private Either<Service, ResponseFormat> parseToService(String serviceJson, User user) {
-        return getComponentsUtils().convertJsonToObjectUsingObjectMapper(serviceJson, user, Service.class, AuditingActionEnum.CREATE_RESOURCE, ComponentTypeEnum.SERVICE);//TODO: change sSERVICE constant
+        return getComponentsUtils().convertJsonToObjectUsingObjectMapper(serviceJson, user, Service.class, AuditingActionEnum.CREATE_RESOURCE,
+            ComponentTypeEnum.SERVICE);//TODO: change sSERVICE constant
     }
 }
index f0ef707..1affe75 100644 (file)
@@ -17,7 +17,6 @@
  * limitations under the License.
  * ============LICENSE_END=========================================================
  */
-
 package org.openecomp.sdc.be.servlets;
 
 import com.fasterxml.jackson.core.JsonProcessingException;
@@ -37,6 +36,26 @@ import io.swagger.v3.oas.annotations.tags.Tag;
 import io.swagger.v3.oas.annotations.tags.Tags;
 import java.io.File;
 import java.io.FileNotFoundException;
+import java.io.IOException;
+import java.lang.reflect.Type;
+import java.util.ArrayList;
+import java.util.List;
+import java.util.Map;
+import javax.inject.Inject;
+import javax.servlet.ServletContext;
+import javax.servlet.http.HttpServletRequest;
+import javax.ws.rs.Consumes;
+import javax.ws.rs.DELETE;
+import javax.ws.rs.GET;
+import javax.ws.rs.HeaderParam;
+import javax.ws.rs.POST;
+import javax.ws.rs.PUT;
+import javax.ws.rs.Path;
+import javax.ws.rs.PathParam;
+import javax.ws.rs.Produces;
+import javax.ws.rs.core.Context;
+import javax.ws.rs.core.MediaType;
+import javax.ws.rs.core.Response;
 import org.apache.http.HttpStatus;
 import org.glassfish.jersey.media.multipart.FormDataContentDisposition;
 import org.glassfish.jersey.media.multipart.FormDataParam;
@@ -77,27 +96,6 @@ import org.openecomp.sdc.common.zip.exception.ZipException;
 import org.openecomp.sdc.exception.ResponseFormat;
 import org.springframework.stereotype.Controller;
 
-import javax.inject.Inject;
-import javax.servlet.ServletContext;
-import javax.servlet.http.HttpServletRequest;
-import javax.ws.rs.Consumes;
-import javax.ws.rs.DELETE;
-import javax.ws.rs.GET;
-import javax.ws.rs.HeaderParam;
-import javax.ws.rs.POST;
-import javax.ws.rs.PUT;
-import javax.ws.rs.Path;
-import javax.ws.rs.PathParam;
-import javax.ws.rs.Produces;
-import javax.ws.rs.core.Context;
-import javax.ws.rs.core.MediaType;
-import javax.ws.rs.core.Response;
-import java.io.IOException;
-import java.lang.reflect.Type;
-import java.util.ArrayList;
-import java.util.List;
-import java.util.Map;
-
 @Loggable(prepend = true, value = Loggable.DEBUG, trim = false)
 @Path("/v1/catalog")
 @Tags({@Tag(name = "SDC Internal APIs")})
@@ -105,22 +103,17 @@ import java.util.Map;
 @Controller
 public class ServiceServlet extends AbstractValidationsServlet {
 
-    private final ElementBusinessLogic elementBusinessLogic;
     private static final Logger log = Logger.getLogger(ServiceServlet.class);
     private static final LoggerSupportability loggerSupportability = LoggerSupportability.getLogger(ServiceServlet.class.getName());
-
     private static final String START_HANDLE_REQUEST_OF = "Start handle request of {}";
     private static final String MODIFIER_ID_IS = "modifier id is {}";
-
+    private final ElementBusinessLogic elementBusinessLogic;
     private final ServiceBusinessLogic serviceBusinessLogic;
 
     @Inject
-    public ServiceServlet(UserBusinessLogic userBusinessLogic,
-        ComponentInstanceBusinessLogic componentInstanceBL,
-        ComponentsUtils componentsUtils, ServletUtils servletUtils,
-        ResourceImportManager resourceImportManager,
-        ServiceBusinessLogic serviceBusinessLogic,
-        ResourceBusinessLogic resourceBusinessLogic, ElementBusinessLogic elementBusinessLogic) {
+    public ServiceServlet(UserBusinessLogic userBusinessLogic, ComponentInstanceBusinessLogic componentInstanceBL, ComponentsUtils componentsUtils,
+                          ServletUtils servletUtils, ResourceImportManager resourceImportManager, ServiceBusinessLogic serviceBusinessLogic,
+                          ResourceBusinessLogic resourceBusinessLogic, ElementBusinessLogic elementBusinessLogic) {
         super(userBusinessLogic, componentInstanceBL, componentsUtils, servletUtils, resourceImportManager);
         this.serviceBusinessLogic = serviceBusinessLogic;
         this.elementBusinessLogic = elementBusinessLogic;
@@ -131,68 +124,58 @@ public class ServiceServlet extends AbstractValidationsServlet {
     @Consumes(MediaType.APPLICATION_JSON)
     @Produces(MediaType.APPLICATION_JSON)
     @Operation(description = "Create Service", method = "POST", summary = "Returns created service", responses = {
-            @ApiResponse(content = @Content(array = @ArraySchema(schema = @Schema(implementation = Service.class)))),
-            @ApiResponse(responseCode = "201", description = "Service created"),
-            @ApiResponse(responseCode = "403", description = "Restricted operation"),
-            @ApiResponse(responseCode = "400", description = "Invalid content / Missing content"),
-            @ApiResponse(responseCode = "409", description = "Service already exist")})
+        @ApiResponse(content = @Content(array = @ArraySchema(schema = @Schema(implementation = Service.class)))),
+        @ApiResponse(responseCode = "201", description = "Service created"), @ApiResponse(responseCode = "403", description = "Restricted operation"),
+        @ApiResponse(responseCode = "400", description = "Invalid content / Missing content"),
+        @ApiResponse(responseCode = "409", description = "Service already exist")})
     @PermissionAllowed(AafPermission.PermNames.INTERNAL_ALL_VALUE)
     public Response createService(@Parameter(description = "Service object to be created", required = true) String data,
-            @Context final HttpServletRequest request, @HeaderParam(value = Constants.USER_ID_HEADER) String userId) {
-
+                                  @Context final HttpServletRequest request, @HeaderParam(value = Constants.USER_ID_HEADER) String userId) {
         String url = request.getMethod() + " " + request.getRequestURI();
         log.debug(START_HANDLE_REQUEST_OF, url);
         User modifier = new User();
         modifier.setUserId(userId);
         log.debug(MODIFIER_ID_IS, userId);
-        loggerSupportability.log(LoggerSupportabilityActions.CREATE_SERVICE,StatusCode.STARTED,"Starting to create a service by user {} ",userId);
-
+        loggerSupportability.log(LoggerSupportabilityActions.CREATE_SERVICE, StatusCode.STARTED, "Starting to create a service by user {} ", userId);
         validateNotEmptyBody(data);
         Either<Service, ResponseFormat> convertResponse = parseToService(data, modifier);
         if (convertResponse.isRight()) {
             throw new ByResponseFormatComponentException(convertResponse.right().value());
         }
-
         Service service = convertResponse.left().value();
         Either<Service, ResponseFormat> actionResponse = serviceBusinessLogic.createService(service, modifier);
-
         if (actionResponse.isRight()) {
             log.debug("Failed to create service");
             throw new ByResponseFormatComponentException(actionResponse.right().value());
         }
-
-        loggerSupportability.log(LoggerSupportabilityActions.CREATE_SERVICE,service.getComponentMetadataForSupportLog(),StatusCode.COMPLETE,"Service {} has been created by user {} ",service.getName(), userId );
-
+        loggerSupportability.log(LoggerSupportabilityActions.CREATE_SERVICE, service.getComponentMetadataForSupportLog(), StatusCode.COMPLETE,
+            "Service {} has been created by user {} ", service.getName(), userId);
         return buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.CREATED), actionResponse.left().value());
     }
 
     public Either<Service, ResponseFormat> parseToService(String serviceJson, User user) {
-        return getComponentsUtils().convertJsonToObjectUsingObjectMapper(serviceJson, user, Service.class, AuditingActionEnum.CREATE_RESOURCE, ComponentTypeEnum.SERVICE);
+        return getComponentsUtils()
+            .convertJsonToObjectUsingObjectMapper(serviceJson, user, Service.class, AuditingActionEnum.CREATE_RESOURCE, ComponentTypeEnum.SERVICE);
     }
 
     @GET
     @Path("/services/validate-name/{serviceName}")
     @Consumes(MediaType.APPLICATION_JSON)
     @Produces(MediaType.APPLICATION_JSON)
-    @Operation(description = "validate service name", method = "GET",
-            summary = "checks if the chosen service name is available ", responses = {
-            @ApiResponse(content = @Content(array = @ArraySchema(schema = @Schema(implementation = Response.class)))),
-            @ApiResponse(responseCode = "200", description = "Service found"),
-            @ApiResponse(responseCode = "403", description = "Restricted operation")})
+    @Operation(description = "validate service name", method = "GET", summary = "checks if the chosen service name is available ", responses = {
+        @ApiResponse(content = @Content(array = @ArraySchema(schema = @Schema(implementation = Response.class)))),
+        @ApiResponse(responseCode = "200", description = "Service found"), @ApiResponse(responseCode = "403", description = "Restricted operation")})
     @PermissionAllowed(AafPermission.PermNames.INTERNAL_ALL_VALUE)
-    public Response validateServiceName(@PathParam("serviceName") final String serviceName,
-            @Context final HttpServletRequest request, @HeaderParam(value = Constants.USER_ID_HEADER) String userId) {
+    public Response validateServiceName(@PathParam("serviceName") final String serviceName, @Context final HttpServletRequest request,
+                                        @HeaderParam(value = Constants.USER_ID_HEADER) String userId) {
         String url = request.getMethod() + " " + request.getRequestURI();
         log.debug(START_HANDLE_REQUEST_OF, url);
-
         // get modifier id
         User modifier = new User();
         modifier.setUserId(userId);
         log.debug(MODIFIER_ID_IS, userId);
         try {
-            Either<Map<String, Boolean>, ResponseFormat> actionResponse =
-                    serviceBusinessLogic.validateServiceNameExists(serviceName, userId);
-
+            Either<Map<String, Boolean>, ResponseFormat> actionResponse = serviceBusinessLogic.validateServiceNameExists(serviceName, userId);
             if (actionResponse.isRight()) {
                 log.debug("failed to get validate service name");
                 return buildErrorResponse(actionResponse.right().value());
@@ -209,20 +192,18 @@ public class ServiceServlet extends AbstractValidationsServlet {
     @Path("/audit-records/{componentType}/{componentUniqueId}")
     @Consumes(MediaType.APPLICATION_JSON)
     @Produces(MediaType.APPLICATION_JSON)
-    @Operation(description = "get component audit records", method = "GET",
-            summary = "get audit records for a service or a resource", responses = {
-            @ApiResponse(content = @Content(array = @ArraySchema(schema = @Schema(implementation = Response.class)))),
-            @ApiResponse(responseCode = "200", description = "Service found"),
-            @ApiResponse(responseCode = "403", description = "Restricted operation")})
+    @Operation(description = "get component audit records", method = "GET", summary = "get audit records for a service or a resource", responses = {
+        @ApiResponse(content = @Content(array = @ArraySchema(schema = @Schema(implementation = Response.class)))),
+        @ApiResponse(responseCode = "200", description = "Service found"), @ApiResponse(responseCode = "403", description = "Restricted operation")})
     @PermissionAllowed(AafPermission.PermNames.INTERNAL_ALL_VALUE)
     public Response getComponentAuditRecords(@PathParam("componentType") final String componentType,
-            @PathParam("componentUniqueId") final String componentUniqueId, @Context final HttpServletRequest request,
-            @HeaderParam(value = Constants.USER_ID_HEADER) String userId) {
+                                             @PathParam("componentUniqueId") final String componentUniqueId,
+                                             @Context final HttpServletRequest request,
+                                             @HeaderParam(value = Constants.USER_ID_HEADER) String userId) {
         init();
         ServletContext context = request.getSession().getServletContext();
         String url = request.getMethod() + " " + request.getRequestURI();
         log.debug(START_HANDLE_REQUEST_OF, url);
-
         User modifier = new User();
         modifier.setUserId(userId);
         log.debug(MODIFIER_ID_IS, userId);
@@ -232,14 +213,13 @@ public class ServiceServlet extends AbstractValidationsServlet {
         Wrapper<User> userWrapper = new Wrapper<>();
         try {
             validateUserExist(responseWrapper, userWrapper, userId);
-
             if (responseWrapper.isEmpty()) {
-                fillUUIDAndVersion(responseWrapper, uuidWrapper, versionWrapper, userWrapper.getInnerElement(), validateComponentType(componentType), componentUniqueId, context);
+                fillUUIDAndVersion(responseWrapper, uuidWrapper, versionWrapper, userWrapper.getInnerElement(), validateComponentType(componentType),
+                    componentUniqueId, context);
             }
-
             if (responseWrapper.isEmpty()) {
-                Either<List<Map<String, Object>>, ResponseFormat> eitherServiceAudit = serviceBusinessLogic.getComponentAuditRecords(versionWrapper.getInnerElement(), uuidWrapper.getInnerElement(), userId);
-
+                Either<List<Map<String, Object>>, ResponseFormat> eitherServiceAudit = serviceBusinessLogic
+                    .getComponentAuditRecords(versionWrapper.getInnerElement(), uuidWrapper.getInnerElement(), userId);
                 if (eitherServiceAudit.isRight()) {
                     Response errorResponse = buildErrorResponse(eitherServiceAudit.right().value());
                     responseWrapper.setInnerElement(errorResponse);
@@ -247,10 +227,8 @@ public class ServiceServlet extends AbstractValidationsServlet {
                     List<Map<String, Object>> auditRecords = eitherServiceAudit.left().value();
                     Response okResponse = buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), auditRecords);
                     responseWrapper.setInnerElement(okResponse);
-
                 }
             }
-
         } catch (Exception e) {
             BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Validate Service Name");
             log.debug("get Service Audit Records failed with exception", e);
@@ -259,8 +237,8 @@ public class ServiceServlet extends AbstractValidationsServlet {
         return responseWrapper.getInnerElement();
     }
 
-    private void fillUUIDAndVersion(Wrapper<Response> responseWrapper, Wrapper<String> uuidWrapper, Wrapper<String> versionWrapper, User user, final ComponentTypeEnum componentTypeEnum, final String componentUniqueId, ServletContext context) {
-
+    private void fillUUIDAndVersion(Wrapper<Response> responseWrapper, Wrapper<String> uuidWrapper, Wrapper<String> versionWrapper, User user,
+                                    final ComponentTypeEnum componentTypeEnum, final String componentUniqueId, ServletContext context) {
         if (componentTypeEnum == ComponentTypeEnum.RESOURCE) {
             Either<Resource, ResponseFormat> eitherResource = getResourceBL(context).getResource(componentUniqueId, user);
             if (eitherResource.isLeft()) {
@@ -269,7 +247,6 @@ public class ServiceServlet extends AbstractValidationsServlet {
             } else {
                 responseWrapper.setInnerElement(buildErrorResponse(eitherResource.right().value()));
             }
-
         } else {
             Either<Service, ResponseFormat> eitherService = getServiceBL(context).getService(componentUniqueId, user);
             if (eitherService.isLeft()) {
@@ -277,7 +254,6 @@ public class ServiceServlet extends AbstractValidationsServlet {
                 versionWrapper.setInnerElement(eitherService.left().value().getVersion());
             } else {
                 responseWrapper.setInnerElement(buildErrorResponse(eitherService.right().value()));
-
             }
         }
     }
@@ -285,17 +261,15 @@ public class ServiceServlet extends AbstractValidationsServlet {
     @DELETE
     @Path("/services/{serviceId}")
     @Operation(description = "Delete Service", method = "DELETE", summary = "Return no content", responses = {
-            @ApiResponse(content = @Content(array = @ArraySchema(schema = @Schema(implementation = Service.class)))),
-            @ApiResponse(responseCode = "204", description = "Service deleted"),
-            @ApiResponse(responseCode = "403", description = "Restricted operation"),
-            @ApiResponse(responseCode = "400", description = "Invalid content / Missing content"),
-            @ApiResponse(responseCode = "404", description = "Service not found")})
+        @ApiResponse(content = @Content(array = @ArraySchema(schema = @Schema(implementation = Service.class)))),
+        @ApiResponse(responseCode = "204", description = "Service deleted"), @ApiResponse(responseCode = "403", description = "Restricted operation"),
+        @ApiResponse(responseCode = "400", description = "Invalid content / Missing content"),
+        @ApiResponse(responseCode = "404", description = "Service not found")})
     @PermissionAllowed(AafPermission.PermNames.INTERNAL_ALL_VALUE)
     public Response deleteService(@PathParam("serviceId") final String serviceId, @Context final HttpServletRequest request) {
         ServletContext context = request.getSession().getServletContext();
         String url = request.getMethod() + " " + request.getRequestURI();
         log.debug(START_HANDLE_REQUEST_OF, url);
-
         // get modifier id
         String userId = request.getHeader(Constants.USER_ID_HEADER);
         User modifier = new User();
@@ -303,16 +277,18 @@ public class ServiceServlet extends AbstractValidationsServlet {
         log.debug(MODIFIER_ID_IS, userId);
         try {
             String serviceIdLower = serviceId.toLowerCase();
-            loggerSupportability.log(LoggerSupportabilityActions.DELETE_SERVICE, StatusCode.STARTED,"Starting to delete service {} by user {} ",serviceIdLower, userId);
+            loggerSupportability
+                .log(LoggerSupportabilityActions.DELETE_SERVICE, StatusCode.STARTED, "Starting to delete service {} by user {} ", serviceIdLower,
+                    userId);
             ServiceBusinessLogic businessLogic = getServiceBL(context);
             ResponseFormat actionResponse = businessLogic.deleteService(serviceIdLower, modifier);
             if (actionResponse.getStatus() != HttpStatus.SC_NO_CONTENT) {
                 log.debug("failed to delete service");
                 return buildErrorResponse(actionResponse);
             }
-            loggerSupportability.log(LoggerSupportabilityActions.DELETE_SERVICE,StatusCode.COMPLETE,"Ended deleting service {} by user {}",serviceIdLower, userId);
+            loggerSupportability
+                .log(LoggerSupportabilityActions.DELETE_SERVICE, StatusCode.COMPLETE, "Ended deleting service {} by user {}", serviceIdLower, userId);
             return buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.NO_CONTENT), null);
-
         } catch (Exception e) {
             BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Delete Service");
             log.debug("delete service failed with exception", e);
@@ -322,22 +298,17 @@ public class ServiceServlet extends AbstractValidationsServlet {
 
     @DELETE
     @Path("/services/{serviceName}/{version}")
-    @Operation(description = "Delete Service By Name And Version", method = "DELETE", summary = "Returns no content",
-            responses = {@ApiResponse(
-                    content = @Content(array = @ArraySchema(schema = @Schema(implementation = Resource.class)))),
-                    @ApiResponse(responseCode = "204", description = "Service deleted"),
-                    @ApiResponse(responseCode = "403", description = "Restricted operation"),
-                    @ApiResponse(responseCode = "400", description = "Invalid content / Missing content"),
-                    @ApiResponse(responseCode = "404", description = "Service not found")})
+    @Operation(description = "Delete Service By Name And Version", method = "DELETE", summary = "Returns no content", responses = {
+        @ApiResponse(content = @Content(array = @ArraySchema(schema = @Schema(implementation = Resource.class)))),
+        @ApiResponse(responseCode = "204", description = "Service deleted"), @ApiResponse(responseCode = "403", description = "Restricted operation"),
+        @ApiResponse(responseCode = "400", description = "Invalid content / Missing content"),
+        @ApiResponse(responseCode = "404", description = "Service not found")})
     @PermissionAllowed(AafPermission.PermNames.INTERNAL_ALL_VALUE)
-    public Response deleteServiceByNameAndVersion(@PathParam("serviceName") final String serviceName,
-                                                  @PathParam("version") final String version,
+    public Response deleteServiceByNameAndVersion(@PathParam("serviceName") final String serviceName, @PathParam("version") final String version,
                                                   @Context final HttpServletRequest request) {
         User modifier = getUser(request);
-
         try {
             ResponseFormat actionResponse = serviceBusinessLogic.deleteServiceByNameAndVersion(serviceName, version, modifier);
-
             if (actionResponse.getStatus() != HttpStatus.SC_NO_CONTENT) {
                 log.debug("failed to delete service");
                 return buildErrorResponse(actionResponse);
@@ -353,7 +324,6 @@ public class ServiceServlet extends AbstractValidationsServlet {
     private User getUser(HttpServletRequest request) {
         String url = request.getMethod() + " " + request.getRequestURI();
         log.debug(START_HANDLE_REQUEST_OF, url);
-
         // get modifier id
         String userId = request.getHeader(Constants.USER_ID_HEADER);
         User modifier = new User();
@@ -366,27 +336,22 @@ public class ServiceServlet extends AbstractValidationsServlet {
     @Path("/services/{serviceId}/metadata")
     @Consumes(MediaType.APPLICATION_JSON)
     @Produces(MediaType.APPLICATION_JSON)
-    @Operation(description = "Update Service Metadata", method = "PUT", summary = "Returns updated service",
-            responses = {@ApiResponse(
-                    content = @Content(array = @ArraySchema(schema = @Schema(implementation = Service.class)))),
-                    @ApiResponse(responseCode = "200", description = "Service Updated"),
-                    @ApiResponse(responseCode = "403", description = "Restricted operation"),
-                    @ApiResponse(responseCode = "400", description = "Invalid content / Missing content")})
+    @Operation(description = "Update Service Metadata", method = "PUT", summary = "Returns updated service", responses = {
+        @ApiResponse(content = @Content(array = @ArraySchema(schema = @Schema(implementation = Service.class)))),
+        @ApiResponse(responseCode = "200", description = "Service Updated"), @ApiResponse(responseCode = "403", description = "Restricted operation"),
+        @ApiResponse(responseCode = "400", description = "Invalid content / Missing content")})
     @PermissionAllowed(AafPermission.PermNames.INTERNAL_ALL_VALUE)
     public Response updateServiceMetadata(@PathParam("serviceId") final String serviceId,
-            @Parameter(description = "Service object to be Updated", required = true) String data,
-            @Context final HttpServletRequest request, @HeaderParam(value = Constants.USER_ID_HEADER) String userId) throws IOException {
-
+                                          @Parameter(description = "Service object to be Updated", required = true) String data,
+                                          @Context final HttpServletRequest request, @HeaderParam(value = Constants.USER_ID_HEADER) String userId)
+        throws IOException {
         String url = request.getMethod() + " " + request.getRequestURI();
         log.debug(START_HANDLE_REQUEST_OF, url);
-
         User modifier = new User();
         modifier.setUserId(userId);
         log.debug(MODIFIER_ID_IS, userId);
-
         try {
             String serviceIdLower = serviceId.toLowerCase();
-
             Either<Service, ResponseFormat> convertResponse = parseToService(data, modifier);
             if (convertResponse.isRight()) {
                 log.debug("failed to parse service");
@@ -394,25 +359,24 @@ public class ServiceServlet extends AbstractValidationsServlet {
             }
             Service updatedService = convertResponse.left().value();
             Either<Service, ResponseFormat> actionResponse = serviceBusinessLogic.updateServiceMetadata(serviceIdLower, updatedService, modifier);
-
             if (actionResponse.isRight()) {
                 log.debug("failed to update service");
                 return buildErrorResponse(actionResponse.right().value());
             }
-
             Service service = actionResponse.left().value();
             Object result = RepresentationUtils.toRepresentation(service);
             return buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), result);
-
         } catch (Exception e) {
             BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Update Service Metadata");
             log.debug("update service metadata failed with exception", e);
             throw e;
         }
     }
+
     /**
-     * updates group instance property values
-     * Note, than in case of group instance updated successfully, related resourceInstance and containing component modification time will be updated
+     * updates group instance property values Note, than in case of group instance updated successfully, related resourceInstance and containing
+     * component modification time will be updated
+     *
      * @param serviceId
      * @param componentInstanceId
      * @param groupInstanceId
@@ -425,48 +389,46 @@ public class ServiceServlet extends AbstractValidationsServlet {
     @Path("/{containerComponentType}/{serviceId}/resourceInstance/{componentInstanceId}/groupInstance/{groupInstanceId}")
     @Consumes(MediaType.APPLICATION_JSON)
     @Produces(MediaType.APPLICATION_JSON)
-    @Operation(description = "Update Group Instance Property Values", method = "PUT",
-            summary = "Returns updated group instance", responses = {
-            @ApiResponse(content = @Content(array = @ArraySchema(schema = @Schema(implementation = Service.class)))),
-            @ApiResponse(responseCode = "200", description = "Group Instance Property Values Updated"),
-            @ApiResponse(responseCode = "403", description = "Restricted operation"),
-            @ApiResponse(responseCode = "400", description = "Invalid content / Missing content")})
+    @Operation(description = "Update Group Instance Property Values", method = "PUT", summary = "Returns updated group instance", responses = {
+        @ApiResponse(content = @Content(array = @ArraySchema(schema = @Schema(implementation = Service.class)))),
+        @ApiResponse(responseCode = "200", description = "Group Instance Property Values Updated"),
+        @ApiResponse(responseCode = "403", description = "Restricted operation"),
+        @ApiResponse(responseCode = "400", description = "Invalid content / Missing content")})
     @PermissionAllowed(AafPermission.PermNames.INTERNAL_ALL_VALUE)
     public Response updateGroupInstancePropertyValues(@PathParam("serviceId") final String serviceId,
-            @PathParam("componentInstanceId") final String componentInstanceId,
-            @PathParam("groupInstanceId") final String groupInstanceId,
-            @Parameter(description = "Group instance object to be Updated", required = true) String data,
-            @Context final HttpServletRequest request, @HeaderParam(value = Constants.USER_ID_HEADER) String userId) throws JsonProcessingException {
-
+                                                      @PathParam("componentInstanceId") final String componentInstanceId,
+                                                      @PathParam("groupInstanceId") final String groupInstanceId,
+                                                      @Parameter(description = "Group instance object to be Updated", required = true) String data,
+                                                      @Context final HttpServletRequest request,
+                                                      @HeaderParam(value = Constants.USER_ID_HEADER) String userId) throws JsonProcessingException {
         String url = request.getMethod() + " " + request.getRequestURI();
         log.debug(START_HANDLE_REQUEST_OF, url);
-
         User modifier = new User();
         modifier.setUserId(userId);
-        log.debug(MODIFIER_ID_IS,userId);
-
+        log.debug(MODIFIER_ID_IS, userId);
         Either<List<GroupInstanceProperty>, ResponseFormat> actionResponse = null;
         try {
             List<GroupInstanceProperty> updatedProperties;
-            Type listType = new TypeToken<ArrayList<GroupInstanceProperty>>(){}.getType();
+            Type listType = new TypeToken<ArrayList<GroupInstanceProperty>>() {
+            }.getType();
             ArrayList<GroupInstanceProperty> newProperties = gson.fromJson(data, listType);
             if (newProperties == null) {
                 actionResponse = Either.right(getComponentsUtils().getResponseFormat(ActionStatus.INVALID_CONTENT));
             }
-            if(actionResponse == null){
+            if (actionResponse == null) {
                 log.debug("Start handle update group instance property values request. Received group instance is {}", groupInstanceId);
-                actionResponse = serviceBusinessLogic.updateGroupInstancePropertyValues(modifier, serviceId, componentInstanceId, groupInstanceId, newProperties);
-                if(actionResponse.isRight()){
+                actionResponse = serviceBusinessLogic
+                    .updateGroupInstancePropertyValues(modifier, serviceId, componentInstanceId, groupInstanceId, newProperties);
+                if (actionResponse.isRight()) {
                     actionResponse = Either.right(actionResponse.right().value());
                 }
             }
-            if(actionResponse.isLeft()){
+            if (actionResponse.isLeft()) {
                 updatedProperties = actionResponse.left().value();
                 ObjectMapper mapper = new ObjectMapper();
                 String result = mapper.writeValueAsString(updatedProperties);
                 return buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), result);
-            }
-            else{
+            } else {
                 return buildErrorResponse(actionResponse.right().value());
             }
         } catch (Exception e) {
@@ -479,39 +441,30 @@ public class ServiceServlet extends AbstractValidationsServlet {
     @Path("/services/{serviceId}")
     @Consumes(MediaType.APPLICATION_JSON)
     @Produces(MediaType.APPLICATION_JSON)
-    @Operation(description = "Retrieve Service", method = "GET", summary = "Returns service according to serviceId",
-            responses = {@ApiResponse(
-                    content = @Content(array = @ArraySchema(schema = @Schema(implementation = Service.class)))),
-                    @ApiResponse(responseCode = "200", description = "Service found"),
-                    @ApiResponse(responseCode = "403", description = "Restricted operation"),
-                    @ApiResponse(responseCode = "404", description = "Service not found")})
+    @Operation(description = "Retrieve Service", method = "GET", summary = "Returns service according to serviceId", responses = {
+        @ApiResponse(content = @Content(array = @ArraySchema(schema = @Schema(implementation = Service.class)))),
+        @ApiResponse(responseCode = "200", description = "Service found"), @ApiResponse(responseCode = "403", description = "Restricted operation"),
+        @ApiResponse(responseCode = "404", description = "Service not found")})
     @PermissionAllowed(AafPermission.PermNames.INTERNAL_ALL_VALUE)
-    public Response getServiceById(@PathParam("serviceId") final String serviceId,
-            @Context final HttpServletRequest request, @HeaderParam(value = Constants.USER_ID_HEADER) String userId) throws IOException {
-
+    public Response getServiceById(@PathParam("serviceId") final String serviceId, @Context final HttpServletRequest request,
+                                   @HeaderParam(value = Constants.USER_ID_HEADER) String userId) throws IOException {
         String url = request.getMethod() + " " + request.getRequestURI();
         log.debug(START_HANDLE_REQUEST_OF, url);
-
         // get modifier id
         User modifier = new User();
         modifier.setUserId(userId);
         log.debug(MODIFIER_ID_IS, userId);
-
         try {
             String serviceIdLower = serviceId.toLowerCase();
             log.debug("get service with id {}", serviceId);
             Either<Service, ResponseFormat> actionResponse = serviceBusinessLogic.getService(serviceIdLower, modifier);
-
             if (actionResponse.isRight()) {
                 log.debug("failed to get service");
                 return buildErrorResponse(actionResponse.right().value());
             }
-
             Service service = actionResponse.left().value();
             Object result = RepresentationUtils.toRepresentation(service);
-
             return buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), result);
-
         } catch (Exception e) {
             BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Get Service");
             log.debug("get service failed with exception", e);
@@ -523,34 +476,26 @@ public class ServiceServlet extends AbstractValidationsServlet {
     @Path("/services/serviceName/{serviceName}/serviceVersion/{serviceVersion}")
     @Consumes(MediaType.APPLICATION_JSON)
     @Produces(MediaType.APPLICATION_JSON)
-    @Operation(description = "Retrieve Service", method = "GET",
-            summary = "Returns service according to name and version", responses = {
-            @ApiResponse(content = @Content(array = @ArraySchema(schema = @Schema(implementation = Service.class)))),
-            @ApiResponse(responseCode = "200", description = "Service found"),
-            @ApiResponse(responseCode = "403", description = "Restricted operation"),
-            @ApiResponse(responseCode = "404", description = "Service not found")})
+    @Operation(description = "Retrieve Service", method = "GET", summary = "Returns service according to name and version", responses = {
+        @ApiResponse(content = @Content(array = @ArraySchema(schema = @Schema(implementation = Service.class)))),
+        @ApiResponse(responseCode = "200", description = "Service found"), @ApiResponse(responseCode = "403", description = "Restricted operation"),
+        @ApiResponse(responseCode = "404", description = "Service not found")})
     @PermissionAllowed(AafPermission.PermNames.INTERNAL_ALL_VALUE)
     public Response getServiceByNameAndVersion(@PathParam("serviceName") final String serviceName,
-            @PathParam("serviceVersion") final String serviceVersion, @Context final HttpServletRequest request,
-            @HeaderParam(value = Constants.USER_ID_HEADER) String userId) throws IOException {
-
+                                               @PathParam("serviceVersion") final String serviceVersion, @Context final HttpServletRequest request,
+                                               @HeaderParam(value = Constants.USER_ID_HEADER) String userId) throws IOException {
         // get modifier id
         User modifier = new User();
         modifier.setUserId(userId);
         log.debug(MODIFIER_ID_IS, userId);
-
         try {
             Either<Service, ResponseFormat> actionResponse = serviceBusinessLogic.getServiceByNameAndVersion(serviceName, serviceVersion, userId);
-
             if (actionResponse.isRight()) {
                 return buildErrorResponse(actionResponse.right().value());
             }
-
             Service service = actionResponse.left().value();
             Object result = RepresentationUtils.toRepresentation(service);
-
             return buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), result);
-
         } catch (Exception e) {
             BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Get Service by name and version");
             log.debug("get service failed with exception", e);
@@ -562,25 +507,21 @@ public class ServiceServlet extends AbstractValidationsServlet {
     @Path("/services/{serviceId}/distribution/{env}/activate")
     @Consumes(MediaType.APPLICATION_JSON)
     @Produces(MediaType.APPLICATION_JSON)
-    @Operation(description = "Activate distribution", method = "POST", summary = "activate distribution",
-            responses = {@ApiResponse(responseCode = "200", description = "OK"), @ApiResponse(responseCode = "409",
-                    description = "Service cannot be distributed due to missing deployment artifacts"),
-                    @ApiResponse(responseCode = "404", description = "Requested service was not found"),
-                    @ApiResponse(responseCode = "500", description = "Internal Server Error. Please try again later.")})
+    @Operation(description = "Activate distribution", method = "POST", summary = "activate distribution", responses = {
+        @ApiResponse(responseCode = "200", description = "OK"),
+        @ApiResponse(responseCode = "409", description = "Service cannot be distributed due to missing deployment artifacts"),
+        @ApiResponse(responseCode = "404", description = "Requested service was not found"),
+        @ApiResponse(responseCode = "500", description = "Internal Server Error. Please try again later.")})
     @PermissionAllowed(AafPermission.PermNames.INTERNAL_ALL_VALUE)
-    public Response activateDistribution(@PathParam("serviceId") final String serviceId,
-            @PathParam("env") final String env, @Context final HttpServletRequest request,
-            @HeaderParam(value = Constants.USER_ID_HEADER) String userId) throws IOException {
-
+    public Response activateDistribution(@PathParam("serviceId") final String serviceId, @PathParam("env") final String env,
+                                         @Context final HttpServletRequest request, @HeaderParam(value = Constants.USER_ID_HEADER) String userId)
+        throws IOException {
         String url = request.getMethod() + " " + request.getRequestURI();
         log.debug(START_HANDLE_REQUEST_OF, url);
-
         User modifier = new User();
         modifier.setUserId(userId);
         log.debug(MODIFIER_ID_IS, userId);
-
         Either<Service, ResponseFormat> distResponse = serviceBusinessLogic.activateDistribution(serviceId, env, modifier, request);
-
         if (distResponse.isRight()) {
             log.debug("failed to activate service distribution");
             return buildErrorResponse(distResponse.right().value());
@@ -601,29 +542,24 @@ public class ServiceServlet extends AbstractValidationsServlet {
     @Path("/services/{serviceId}/distribution/{did}/markDeployed")
     @Consumes(MediaType.APPLICATION_JSON)
     @Produces(MediaType.APPLICATION_JSON)
-    @Operation(description = "Mark distribution as deployed", method = "POST",
-            summary = "relevant audit record will be created",
-            responses = {@ApiResponse(responseCode = "200", description = "Service was marked as deployed"),
-                    @ApiResponse(responseCode = "409", description = "Restricted operation"),
-                    @ApiResponse(responseCode = "403", description = "Service is not available"),
-                    @ApiResponse(responseCode = "400", description = "Invalid content / Missing content"),
-                    @ApiResponse(responseCode = "404", description = "Requested service was not found"),
-                    @ApiResponse(responseCode = "500", description = "Internal Server Error. Please try again later.")})
+    @Operation(description = "Mark distribution as deployed", method = "POST", summary = "relevant audit record will be created", responses = {
+        @ApiResponse(responseCode = "200", description = "Service was marked as deployed"),
+        @ApiResponse(responseCode = "409", description = "Restricted operation"),
+        @ApiResponse(responseCode = "403", description = "Service is not available"),
+        @ApiResponse(responseCode = "400", description = "Invalid content / Missing content"),
+        @ApiResponse(responseCode = "404", description = "Requested service was not found"),
+        @ApiResponse(responseCode = "500", description = "Internal Server Error. Please try again later.")})
     @PermissionAllowed(AafPermission.PermNames.INTERNAL_ALL_VALUE)
-    public Response markDistributionAsDeployed(@PathParam("serviceId") final String serviceId,
-            @PathParam("did") final String did, @Context final HttpServletRequest request,
-            @HeaderParam(value = Constants.USER_ID_HEADER) String userId) throws IOException {
-
+    public Response markDistributionAsDeployed(@PathParam("serviceId") final String serviceId, @PathParam("did") final String did,
+                                               @Context final HttpServletRequest request,
+                                               @HeaderParam(value = Constants.USER_ID_HEADER) String userId) throws IOException {
         String url = request.getMethod() + " " + request.getRequestURI();
         log.debug(START_HANDLE_REQUEST_OF, url);
-
         User modifier = new User();
         modifier.setUserId(userId);
         log.debug(MODIFIER_ID_IS, userId);
-
         try {
             Either<Service, ResponseFormat> distResponse = serviceBusinessLogic.markDistributionAsDeployed(serviceId, did, modifier);
-
             if (distResponse.isRight()) {
                 log.debug("failed to mark distribution as deployed");
                 return buildErrorResponse(distResponse.right().value());
@@ -643,22 +579,20 @@ public class ServiceServlet extends AbstractValidationsServlet {
     @Consumes(MediaType.APPLICATION_JSON)
     @Produces(MediaType.APPLICATION_JSON)
     @Operation(responses = {@ApiResponse(responseCode = "200", description = "OK"),
-            @ApiResponse(responseCode = "500", description = "Internal Server Error. Please try again later.")})
+        @ApiResponse(responseCode = "500", description = "Internal Server Error. Please try again later.")})
     @PermissionAllowed(AafPermission.PermNames.INTERNAL_ALL_VALUE)
-    public Response tempUrlToBeDeleted(@PathParam("serviceId") final String serviceId, @Context final HttpServletRequest request, @HeaderParam(value = Constants.USER_ID_HEADER) String userId) {
-
+    public Response tempUrlToBeDeleted(@PathParam("serviceId") final String serviceId, @Context final HttpServletRequest request,
+                                       @HeaderParam(value = Constants.USER_ID_HEADER) String userId) {
         ServletContext context = request.getSession().getServletContext();
         String url = request.getMethod() + " " + request.getRequestURI();
         log.debug(START_HANDLE_REQUEST_OF, url);
-
         User modifier = new User();
         modifier.setUserId(userId);
         log.debug(MODIFIER_ID_IS, userId);
-
         try {
             Service service = (serviceBusinessLogic.getService(serviceId, modifier)).left().value();
-            Either<Service, ResponseFormat> res = serviceBusinessLogic.updateDistributionStatusForActivation(service, modifier, DistributionStatusEnum.DISTRIBUTED);
-
+            Either<Service, ResponseFormat> res = serviceBusinessLogic
+                .updateDistributionStatusForActivation(service, modifier, DistributionStatusEnum.DISTRIBUTED);
             if (res.isRight()) {
                 buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR));
             }
@@ -670,45 +604,34 @@ public class ServiceServlet extends AbstractValidationsServlet {
         }
     }
 
-
     @GET
     @Path("/services/{serviceId}/linksMap")
     @Consumes(MediaType.APPLICATION_JSON)
     @Produces(MediaType.APPLICATION_JSON)
-    @Operation(description = "Retrieve Service component relations map", method = "GET",
-            summary = "Returns service components relations", responses = {@ApiResponse(
-            content = @Content(array = @ArraySchema(schema = @Schema(implementation = ServiceRelations.class)))),
-            @ApiResponse(responseCode = "200", description = "Service found"),
-            @ApiResponse(responseCode = "403", description = "Restricted operation"),
-            @ApiResponse(responseCode = "404", description = "Service not found")})
+    @Operation(description = "Retrieve Service component relations map", method = "GET", summary = "Returns service components relations", responses = {
+        @ApiResponse(content = @Content(array = @ArraySchema(schema = @Schema(implementation = ServiceRelations.class)))),
+        @ApiResponse(responseCode = "200", description = "Service found"), @ApiResponse(responseCode = "403", description = "Restricted operation"),
+        @ApiResponse(responseCode = "404", description = "Service not found")})
     @PermissionAllowed(AafPermission.PermNames.INTERNAL_ALL_VALUE)
-    public Response getServiceComponentRelationMap(@PathParam("serviceId") final String serviceId,
-                                                   @Context final HttpServletRequest request,
+    public Response getServiceComponentRelationMap(@PathParam("serviceId") final String serviceId, @Context final HttpServletRequest request,
                                                    @HeaderParam(value = Constants.USER_ID_HEADER) String userId) throws IOException {
-
         String url = request.getMethod() + " " + request.getRequestURI();
         log.debug(START_HANDLE_REQUEST_OF, url);
-
         // get modifier id
         User modifier = new User();
         modifier.setUserId(userId);
         log.debug(MODIFIER_ID_IS, userId);
-
         try {
             String serviceIdLower = serviceId.toLowerCase();
             log.debug("get service components relations with id {}", serviceId);
             Either<ServiceRelations, ResponseFormat> actionResponse = serviceBusinessLogic.getServiceComponentsRelations(serviceIdLower, modifier);
-
             if (actionResponse.isRight()) {
                 log.debug("failed to get service relations data");
                 return buildErrorResponse(actionResponse.right().value());
             }
-
             ServiceRelations serviceRelations = actionResponse.left().value();
             Object result = RepresentationUtils.toRepresentation(serviceRelations);
-
             return buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), result);
-
         } catch (Exception e) {
             BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Get Service");
             log.debug("get service relations data failed with exception", e);
@@ -721,23 +644,21 @@ public class ServiceServlet extends AbstractValidationsServlet {
     @Consumes(MediaType.APPLICATION_JSON)
     @Produces(MediaType.APPLICATION_JSON)
     @Operation(description = "Import Service", method = "POST", summary = "Returns imported service", responses = {
-    @ApiResponse(responseCode = "201", description = "Service created"), @ApiResponse(responseCode = "403", description = "Restricted operation"), @ApiResponse(responseCode = "400", description = "Invalid content / Missing content"), @ApiResponse(responseCode = "409", description = "Service already exist")})
-    public Response importNsService(@Parameter(description = "Service object to be imported", required = true) String data, @Context final HttpServletRequest request, @HeaderParam(value = Constants.USER_ID_HEADER) String userId) {
-
+        @ApiResponse(responseCode = "201", description = "Service created"), @ApiResponse(responseCode = "403", description = "Restricted operation"),
+        @ApiResponse(responseCode = "400", description = "Invalid content / Missing content"),
+        @ApiResponse(responseCode = "409", description = "Service already exist")})
+    public Response importNsService(@Parameter(description = "Service object to be imported", required = true) String data,
+                                    @Context final HttpServletRequest request, @HeaderParam(value = Constants.USER_ID_HEADER) String userId) {
         userId = (userId != null) ? userId : request.getHeader(Constants.USER_ID_HEADER);
         initSpringFromContext();
-
         String url = request.getMethod() + " " + request.getRequestURI();
-        log.debug("Start handle request of {}" , url);
-
+        log.debug("Start handle request of {}", url);
         // get modifier id
         User modifier = new User();
         modifier.setUserId(userId);
         log.debug("modifier id is {}", userId);
-
         Response response;
         try {
-
             Wrapper<Response> responseWrapper = new Wrapper<>();
             performUIImport(responseWrapper, data, request, userId, null);
             return responseWrapper.getInnerElement();
@@ -749,25 +670,23 @@ public class ServiceServlet extends AbstractValidationsServlet {
         }
     }
 
-    private void performUIImport(Wrapper<Response> responseWrapper, String data, final HttpServletRequest request, String userId, String ServiceUniqueId)
-        throws FileNotFoundException, ZipException {
-
+    private void performUIImport(Wrapper<Response> responseWrapper, String data, final HttpServletRequest request, String userId,
+                                 String ServiceUniqueId) throws FileNotFoundException, ZipException {
         Wrapper<User> userWrapper = new Wrapper<>();
         Wrapper<UploadServiceInfo> uploadServiceInfoWrapper = new Wrapper<>();
         Wrapper<String> yamlStringWrapper = new Wrapper<>();
-
         ServiceAuthorityTypeEnum ServiceAuthorityEnum = ServiceAuthorityTypeEnum.USER_TYPE_UI;
-
         commonServiceGeneralValidations(responseWrapper, userWrapper, uploadServiceInfoWrapper, ServiceAuthorityEnum, userId, data);
-
-        specificServiceAuthorityValidations(responseWrapper, uploadServiceInfoWrapper, yamlStringWrapper, userWrapper.getInnerElement(), request, data, ServiceAuthorityEnum);
-
+        specificServiceAuthorityValidations(responseWrapper, uploadServiceInfoWrapper, yamlStringWrapper, userWrapper.getInnerElement(), request,
+            data, ServiceAuthorityEnum);
         if (responseWrapper.isEmpty()) {
-            handleImportService(responseWrapper, userWrapper.getInnerElement(), uploadServiceInfoWrapper.getInnerElement(), yamlStringWrapper.getInnerElement(), ServiceAuthorityEnum, true, ServiceUniqueId);
+            handleImportService(responseWrapper, userWrapper.getInnerElement(), uploadServiceInfoWrapper.getInnerElement(),
+                yamlStringWrapper.getInnerElement(), ServiceAuthorityEnum, true, ServiceUniqueId);
         }
     }
 
-    /**import ReplaceService 
+    /**
+     * import ReplaceService
      *
      * @param userId
      * @param requestId
@@ -785,61 +704,41 @@ public class ServiceServlet extends AbstractValidationsServlet {
     @Path("/services/serviceUUID/{uuid}/importReplaceService")
     @Produces(MediaType.APPLICATION_JSON)
     @Operation(description = "Import Service", method = "POST", summary = "Returns imported service", responses = {
-            @ApiResponse(responseCode = "201", description = "Service created"),
-            @ApiResponse(responseCode = "403", description = "Restricted operation"),
-            @ApiResponse(responseCode = "400", description = "Invalid content / Missing content"),
-            @ApiResponse(responseCode = "409", description = "Service already exist")})
+        @ApiResponse(responseCode = "201", description = "Service created"), @ApiResponse(responseCode = "403", description = "Restricted operation"),
+        @ApiResponse(responseCode = "400", description = "Invalid content / Missing content"),
+        @ApiResponse(responseCode = "409", description = "Service already exist")})
     @PermissionAllowed(AafPermission.PermNames.INTERNAL_ALL_VALUE)
     public Response importReplaceService(
-            @Parameter(description = "The user id",
-                    required = true) @HeaderParam(value = Constants.USER_ID_HEADER) String userId,
-            @Parameter(description = "X-ECOMP-RequestID header",
-                    required = false) @HeaderParam(value = Constants.X_ECOMP_REQUEST_ID_HEADER) String requestId,
-            @Parameter(description = "X-ECOMP-InstanceID header", required = true) @HeaderParam(
-                    value = Constants.X_ECOMP_INSTANCE_ID_HEADER) final String instanceIdHeader,
-            @Parameter(description = "Determines the format of the body of the response",
-                    required = false) @HeaderParam(value = Constants.ACCEPT_HEADER) String accept,
-            @Parameter(description = "The username and password",
-                    required = true) @HeaderParam(value = Constants.AUTHORIZATION_HEADER) String authorization,
-            @Context final HttpServletRequest request,
-            @Parameter(description = "FileInputStream")
-            @FormDataParam("serviceZip") File file,
-            @Parameter(description = "ContentDisposition")
-            @FormDataParam("serviceZip") FormDataContentDisposition contentDispositionHeader,
-            @Parameter(description = "serviceMetadata")
-            @FormDataParam("serviceZipMetadata") String serviceInfoJsonString,
-            @Parameter(description = "The requested asset uuid",
-                    required = true) @PathParam("uuid") final String uuid) {
-
+        @Parameter(description = "The user id", required = true) @HeaderParam(value = Constants.USER_ID_HEADER) String userId,
+        @Parameter(description = "X-ECOMP-RequestID header", required = false) @HeaderParam(value = Constants.X_ECOMP_REQUEST_ID_HEADER) String requestId,
+        @Parameter(description = "X-ECOMP-InstanceID header", required = true) @HeaderParam(value = Constants.X_ECOMP_INSTANCE_ID_HEADER) final String instanceIdHeader,
+        @Parameter(description = "Determines the format of the body of the response", required = false) @HeaderParam(value = Constants.ACCEPT_HEADER) String accept,
+        @Parameter(description = "The username and password", required = true) @HeaderParam(value = Constants.AUTHORIZATION_HEADER) String authorization,
+        @Context final HttpServletRequest request, @Parameter(description = "FileInputStream") @FormDataParam("serviceZip") File file,
+        @Parameter(description = "ContentDisposition") @FormDataParam("serviceZip") FormDataContentDisposition contentDispositionHeader,
+        @Parameter(description = "serviceMetadata") @FormDataParam("serviceZipMetadata") String serviceInfoJsonString,
+        @Parameter(description = "The requested asset uuid", required = true) @PathParam("uuid") final String uuid) {
         initSpringFromContext();
-
         String requestURI = request.getRequestURI();
         String url = request.getMethod() + " " + requestURI;
         log.debug("importReplaceService,Start handle request of {}", url);
-
         // get modifier id
         User modifier = new User();
         modifier.setUserId(userId);
         log.debug("importReplaceService,modifier id is {}", userId);
-
-        log.debug("importReplaceService,get file:{},fileName:{}",file,file.getName());
-
+        log.debug("importReplaceService,get file:{},fileName:{}", file, file.getName());
         Response response;
-        ResponseFormat responseFormat =null;
+        ResponseFormat responseFormat = null;
         AuditingActionEnum auditingActionEnum = AuditingActionEnum.Import_Replace_Service;
         String assetType = "services";
-
-        Either<List<? extends Component>, ResponseFormat> assetTypeData = elementBusinessLogic.getCatalogComponentsByUuidAndAssetType(assetType, uuid);
-
+        Either<List<? extends Component>, ResponseFormat> assetTypeData = elementBusinessLogic
+            .getCatalogComponentsByUuidAndAssetType(assetType, uuid);
         if (assetTypeData.isRight() || assetTypeData.left().value().size() != 1) {
             log.debug("getServiceAbstractStatus: Service Fetching Failed");
             throw new ByResponseFormatComponentException(assetTypeData.right().value());
         }
-
         log.debug("getServiceAbstractStatus: Service Fetching Success");
-
         Service oldService = (Service) assetTypeData.left().value().get(0);
-
         ComponentTypeEnum componentType = ComponentTypeEnum.findByParamName(assetType);
         ResourceCommonInfo resourceCommonInfo = new ResourceCommonInfo(componentType.getValue());
         DistributionData distributionData = new DistributionData(instanceIdHeader, requestURI);
@@ -847,43 +746,36 @@ public class ServiceServlet extends AbstractValidationsServlet {
         if (instanceIdHeader == null || instanceIdHeader.isEmpty()) {
             log.debug("importReplaceService: Missing X-ECOMP-InstanceID header");
             responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.MISSING_X_ECOMP_INSTANCE_ID);
-            getComponentsUtils().auditExternalGetAsset(responseFormat, auditingActionEnum, distributionData,
-                    resourceCommonInfo, requestId, null);
+            getComponentsUtils().auditExternalGetAsset(responseFormat, auditingActionEnum, distributionData, resourceCommonInfo, requestId, null);
             return buildErrorResponse(responseFormat);
         }
-
         try {
             Wrapper<Response> responseWrapper = new Wrapper<>();
             // file import
             Wrapper<User> userWrapper = new Wrapper<>();
             Wrapper<UploadServiceInfo> uploadServiceInfoWrapper = new Wrapper<>();
             Wrapper<String> yamlStringWrapper = new Wrapper<>();
-
             ServiceUploadServlet.ServiceAuthorityTypeEnum serviceAuthorityEnum = ServiceUploadServlet.ServiceAuthorityTypeEnum.CSAR_TYPE_BE;
-
             // PayLoad Validations
-            commonServiceGeneralValidations(responseWrapper, userWrapper, uploadServiceInfoWrapper, serviceAuthorityEnum, userId, serviceInfoJsonString);
-
-            fillServicePayload(responseWrapper, uploadServiceInfoWrapper, yamlStringWrapper, modifier, serviceInfoJsonString, serviceAuthorityEnum, file);
-
-            specificServiceAuthorityValidations(responseWrapper, uploadServiceInfoWrapper, yamlStringWrapper, userWrapper.getInnerElement(), request, serviceInfoJsonString, serviceAuthorityEnum);
-
+            commonServiceGeneralValidations(responseWrapper, userWrapper, uploadServiceInfoWrapper, serviceAuthorityEnum, userId,
+                serviceInfoJsonString);
+            fillServicePayload(responseWrapper, uploadServiceInfoWrapper, yamlStringWrapper, modifier, serviceInfoJsonString, serviceAuthorityEnum,
+                file);
+            specificServiceAuthorityValidations(responseWrapper, uploadServiceInfoWrapper, yamlStringWrapper, userWrapper.getInnerElement(), request,
+                serviceInfoJsonString, serviceAuthorityEnum);
             log.debug("importReplaceService:get payload:{}", uploadServiceInfoWrapper.getInnerElement().getPayloadData());
-
-            ServiceMetadataDataDefinition serviceMetadataDataDefinition = (ServiceMetadataDataDefinition)oldService.getComponentMetadataDefinition().getMetadataDataDefinition();
-
+            ServiceMetadataDataDefinition serviceMetadataDataDefinition = (ServiceMetadataDataDefinition) oldService.getComponentMetadataDefinition()
+                .getMetadataDataDefinition();
             uploadServiceInfoWrapper.getInnerElement().setServiceVendorModelNumber(serviceMetadataDataDefinition.getServiceVendorModelNumber());
             uploadServiceInfoWrapper.getInnerElement().setDescription(oldService.getDescription());
             uploadServiceInfoWrapper.getInnerElement().setCategories(oldService.getCategories());
             uploadServiceInfoWrapper.getInnerElement().setIcon(oldService.getIcon());
             uploadServiceInfoWrapper.getInnerElement().setProjectCode(oldService.getProjectCode());
-
-
             if (responseWrapper.isEmpty()) {
                 log.debug("importReplaceService:start handleImportService");
-                handleImportService(responseWrapper, userWrapper.getInnerElement(), uploadServiceInfoWrapper.getInnerElement(), yamlStringWrapper.getInnerElement(), serviceAuthorityEnum, true, null);
+                handleImportService(responseWrapper, userWrapper.getInnerElement(), uploadServiceInfoWrapper.getInnerElement(),
+                    yamlStringWrapper.getInnerElement(), serviceAuthorityEnum, true, null);
             }
-
             return responseWrapper.getInnerElement();
         } catch (IOException | ZipException e) {
             BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Import Service");
index 2855685..20a259d 100644 (file)
  * limitations under the License.
  * ============LICENSE_END=========================================================
  */
-
 package org.openecomp.sdc.be.servlets;
 
 import com.jcabi.aspects.Loggable;
-import io.swagger.v3.oas.annotations.Operation;
-import io.swagger.v3.oas.annotations.Parameter;
-import io.swagger.v3.oas.annotations.media.Schema;
-import io.swagger.v3.oas.annotations.responses.ApiResponse;
-import io.swagger.v3.oas.annotations.servers.Server;
-import io.swagger.v3.oas.annotations.servers.Servers;
 import io.swagger.v3.oas.annotations.tags.Tag;
 import io.swagger.v3.oas.annotations.tags.Tags;
-import java.io.File;
 import javax.inject.Singleton;
-import javax.servlet.ServletContext;
-import javax.servlet.http.HttpServletRequest;
-import javax.ws.rs.Consumes;
-import javax.ws.rs.DefaultValue;
-import javax.ws.rs.HeaderParam;
-import javax.ws.rs.POST;
 import javax.ws.rs.Path;
-import javax.ws.rs.PathParam;
-import javax.ws.rs.Produces;
-import javax.ws.rs.QueryParam;
-import javax.ws.rs.core.Context;
-import javax.ws.rs.core.MediaType;
-import javax.ws.rs.core.Response;
-import org.glassfish.jersey.media.multipart.FormDataContentDisposition;
-import org.glassfish.jersey.media.multipart.FormDataParam;
 import org.openecomp.sdc.be.components.impl.ComponentInstanceBusinessLogic;
 import org.openecomp.sdc.be.components.impl.ResourceImportManager;
-import org.openecomp.sdc.be.components.impl.ServiceImportManager;
-import org.openecomp.sdc.be.config.BeEcompErrorManager;
-import org.openecomp.sdc.be.dao.api.ActionStatus;
-import org.openecomp.sdc.be.datatypes.enums.ComponentTypeEnum;
 import org.openecomp.sdc.be.impl.ComponentsUtils;
 import org.openecomp.sdc.be.impl.ServletUtils;
-import org.openecomp.sdc.be.impl.WebAppContextWrapper;
-import org.openecomp.sdc.be.model.UploadServiceInfo;
-import org.openecomp.sdc.be.model.User;
 import org.openecomp.sdc.be.user.UserBusinessLogic;
-import org.openecomp.sdc.common.api.Constants;
-import org.openecomp.sdc.common.datastructure.Wrapper;
 import org.openecomp.sdc.common.log.wrappers.Logger;
-import org.springframework.stereotype.Controller;
-import org.springframework.web.context.WebApplicationContext;
 
 /**
  * Root service (exposed at "/" path)
@@ -73,29 +40,31 @@ import org.springframework.web.context.WebApplicationContext;
 @Path("/v1/catalog/uploadservice")
 @Tags({@Tag(name = "SDC Internal APIs")})
 @Singleton
-
 public class ServiceUploadServlet extends AbstractValidationsServlet {
 
-    private static final Logger log = Logger.getLogger(ServiceUploadServlet.class);
     public static final String NORMATIVE_TYPE_SERVICE = "multipart";
     public static final String CSAR_TYPE_SERVICE = "csar";
     public static final String USER_TYPE_SERVICE = "user-service";
     public static final String USER_TYPE_SERVICE_UI_IMPORT = "user-servcie-ui-import";
+    private static final Logger log = Logger.getLogger(ServiceUploadServlet.class);
 
-    public ServiceUploadServlet(UserBusinessLogic userBusinessLogic,
-        ComponentInstanceBusinessLogic componentInstanceBL,
-        ComponentsUtils componentsUtils, ServletUtils servletUtils,
-        ResourceImportManager resourceImportManager) {
+    public ServiceUploadServlet(UserBusinessLogic userBusinessLogic, ComponentInstanceBusinessLogic componentInstanceBL,
+                                ComponentsUtils componentsUtils, ServletUtils servletUtils, ResourceImportManager resourceImportManager) {
         super(userBusinessLogic, componentInstanceBL, componentsUtils, servletUtils, resourceImportManager);
     }
 
     public enum ServiceAuthorityTypeEnum {
-        NORMATIVE_TYPE_BE(NORMATIVE_TYPE_SERVICE, true, false), USER_TYPE_BE(USER_TYPE_SERVICE, true, true),
-        USER_TYPE_UI(USER_TYPE_SERVICE_UI_IMPORT, false, true), CSAR_TYPE_BE(CSAR_TYPE_SERVICE, true, true);
-
+        NORMATIVE_TYPE_BE(NORMATIVE_TYPE_SERVICE, true, false), USER_TYPE_BE(USER_TYPE_SERVICE, true, true), USER_TYPE_UI(USER_TYPE_SERVICE_UI_IMPORT,
+            false, true), CSAR_TYPE_BE(CSAR_TYPE_SERVICE, true, true);
         private String urlPath;
         private boolean isBackEndImport, isUserTypeService;
 
+        private ServiceAuthorityTypeEnum(String urlPath, boolean isBackEndImport, boolean isUserTypeService) {
+            this.urlPath = urlPath;
+            this.isBackEndImport = isBackEndImport;
+            this.isUserTypeService = isUserTypeService;
+        }
+
         public static ServiceAuthorityTypeEnum findByUrlPath(String urlPath) {
             ServiceAuthorityTypeEnum found = null;
             for (ServiceAuthorityTypeEnum curr : ServiceAuthorityTypeEnum.values()) {
@@ -107,12 +76,6 @@ public class ServiceUploadServlet extends AbstractValidationsServlet {
             return found;
         }
 
-        private ServiceAuthorityTypeEnum(String urlPath, boolean isBackEndImport, boolean isUserTypeService) {
-            this.urlPath = urlPath;
-            this.isBackEndImport = isBackEndImport;
-            this.isUserTypeService = isUserTypeService;
-        }
-
         public String getUrlPath() {
             return urlPath;
         }
@@ -126,4 +89,3 @@ public class ServiceUploadServlet extends AbstractValidationsServlet {
         }
     }
 }
-
index df53919..884cbcc 100644 (file)
@@ -17,7 +17,6 @@
  * limitations under the License.
  * ============LICENSE_END=========================================================
  */
-
 package org.openecomp.sdc.be.servlets;
 
 import com.jcabi.aspects.Loggable;
@@ -59,36 +58,31 @@ import org.openecomp.sdc.common.log.wrappers.Logger;
 @Singleton
 public class TogglingServlet extends AbstractValidationsServlet {
 
+    private static final Logger log = Logger.getLogger(TogglingServlet.class);
+    private static final String ALL_FEATURES_STATES_WERE_SET_SUCCESSFULLY = "All features states were set successfully";
+    private static final String START_HANDLE_REQUEST_OF = "Start handle request of {}";
+    private static final String FEATURE_STATE_WAS_UPDATED_SUCCESSFULLY = "Feature state was updated successfully";
     private final TogglingBusinessLogic togglingBusinessLogic;
 
     @Inject
-    public TogglingServlet(UserBusinessLogic userBusinessLogic, ComponentInstanceBusinessLogic componentInstanceBL,
-            ComponentsUtils componentsUtils, ServletUtils servletUtils, ResourceImportManager resourceImportManager,
-            TogglingBusinessLogic togglingBusinessLogic) {
+    public TogglingServlet(UserBusinessLogic userBusinessLogic, ComponentInstanceBusinessLogic componentInstanceBL, ComponentsUtils componentsUtils,
+                           ServletUtils servletUtils, ResourceImportManager resourceImportManager, TogglingBusinessLogic togglingBusinessLogic) {
         super(userBusinessLogic, componentInstanceBL, componentsUtils, servletUtils, resourceImportManager);
         this.togglingBusinessLogic = togglingBusinessLogic;
     }
 
-    private static final Logger log = Logger.getLogger(TogglingServlet.class);
-    private static final String ALL_FEATURES_STATES_WERE_SET_SUCCESSFULLY = "All features states were set successfully";
-    private static final String START_HANDLE_REQUEST_OF = "Start handle request of {}";
-    private static final String FEATURE_STATE_WAS_UPDATED_SUCCESSFULLY = "Feature state was updated successfully";
-
-
     @GET
     @Path("/")
     @Consumes(MediaType.APPLICATION_JSON)
     @Produces(MediaType.APPLICATION_JSON)
     @Operation(description = "Get all Toggleable features", method = "GET", summary = "Returns list of toggleable features", responses = {
-            @ApiResponse(content = @Content(array = @ArraySchema(schema = @Schema(implementation = javax.ws.rs.core.Response.class)))),
-            @ApiResponse(responseCode = "200", description = "Success"),
-            @ApiResponse(responseCode = "403", description = "Restricted operation"),
-            @ApiResponse(responseCode = "400", description = "Invalid content / Missing content"),
-            @ApiResponse(responseCode = "404", description = "Toggleable features not found")})
+        @ApiResponse(content = @Content(array = @ArraySchema(schema = @Schema(implementation = javax.ws.rs.core.Response.class)))),
+        @ApiResponse(responseCode = "200", description = "Success"), @ApiResponse(responseCode = "403", description = "Restricted operation"),
+        @ApiResponse(responseCode = "400", description = "Invalid content / Missing content"),
+        @ApiResponse(responseCode = "404", description = "Toggleable features not found")})
     public Response getAllFeatures(@Context final HttpServletRequest request) {
         String url = request.getMethod() + " " + request.getRequestURI();
         log.debug(START_HANDLE_REQUEST_OF, url);
-
         try {
             Map<String, Boolean> features = togglingBusinessLogic.getAllFeatureStates();
             return buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), features);
@@ -102,15 +96,13 @@ public class TogglingServlet extends AbstractValidationsServlet {
     @Consumes(MediaType.APPLICATION_JSON)
     @Produces(MediaType.APPLICATION_JSON)
     @Operation(description = "Get Toggleable feature state", method = "GET", summary = "Returns one toggleable feature state", responses = {
-            @ApiResponse(content = @Content(array = @ArraySchema(schema = @Schema(implementation = javax.ws.rs.core.Response.class)))),
-            @ApiResponse(responseCode = "200", description = "Success"),
-            @ApiResponse(responseCode = "403", description = "Restricted operation"),
-            @ApiResponse(responseCode = "400", description = "Invalid content / Missing content"),
-            @ApiResponse(responseCode = "404", description = "Toggleable feature not found")})
+        @ApiResponse(content = @Content(array = @ArraySchema(schema = @Schema(implementation = javax.ws.rs.core.Response.class)))),
+        @ApiResponse(responseCode = "200", description = "Success"), @ApiResponse(responseCode = "403", description = "Restricted operation"),
+        @ApiResponse(responseCode = "400", description = "Invalid content / Missing content"),
+        @ApiResponse(responseCode = "404", description = "Toggleable feature not found")})
     public Response getToggleableFeature(@PathParam("featureName") String featureName, @Context final HttpServletRequest request) {
         String url = request.getMethod() + " " + request.getRequestURI();
         log.debug(START_HANDLE_REQUEST_OF, url);
-
         try {
             boolean featureState = togglingBusinessLogic.getFeatureState(featureName);
             return buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), featureState);
@@ -124,15 +116,13 @@ public class TogglingServlet extends AbstractValidationsServlet {
     @Consumes(MediaType.APPLICATION_JSON)
     @Produces(MediaType.APPLICATION_JSON)
     @Operation(description = "Update all feature toggle state", method = "PUT", summary = "Update all feature status", responses = {
-            @ApiResponse(content = @Content(array = @ArraySchema(schema = @Schema(implementation = javax.ws.rs.core.Response.class)))),
-            @ApiResponse(responseCode = "200", description = "Success"),
-            @ApiResponse(responseCode = "403", description = "Restricted operation"),
-            @ApiResponse(responseCode = "400", description = "Invalid content / Missing content"),
-            @ApiResponse(responseCode = "404", description = "Toggleable features not found")})
+        @ApiResponse(content = @Content(array = @ArraySchema(schema = @Schema(implementation = javax.ws.rs.core.Response.class)))),
+        @ApiResponse(responseCode = "200", description = "Success"), @ApiResponse(responseCode = "403", description = "Restricted operation"),
+        @ApiResponse(responseCode = "400", description = "Invalid content / Missing content"),
+        @ApiResponse(responseCode = "404", description = "Toggleable features not found")})
     public Response setAllFeatures(@PathParam("state") boolean state, @Context final HttpServletRequest request) {
         String url = request.getMethod() + " " + request.getRequestURI();
         log.debug(START_HANDLE_REQUEST_OF, url);
-
         try {
             togglingBusinessLogic.setAllFeatures(state);
             return buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), ALL_FEATURES_STATES_WERE_SET_SUCCESSFULLY);
@@ -146,16 +136,14 @@ public class TogglingServlet extends AbstractValidationsServlet {
     @Consumes(MediaType.APPLICATION_JSON)
     @Produces(MediaType.APPLICATION_JSON)
     @Operation(description = "Update feature toggle state", method = "PUT", summary = "Update feature status", responses = {
-            @ApiResponse(content = @Content(array = @ArraySchema(schema = @Schema(implementation = javax.ws.rs.core.Response.class)))),
-            @ApiResponse(responseCode = "200", description = "Success"),
-            @ApiResponse(responseCode = "403", description = "Restricted operation"),
-            @ApiResponse(responseCode = "400", description = "Invalid content / Missing content"),
-            @ApiResponse(responseCode = "404", description = "Toggleable features not found")})
-    public Response updateFeatureState(@PathParam("featureName") String featureName,
-            @PathParam("state") boolean state, @Context final HttpServletRequest request) {
+        @ApiResponse(content = @Content(array = @ArraySchema(schema = @Schema(implementation = javax.ws.rs.core.Response.class)))),
+        @ApiResponse(responseCode = "200", description = "Success"), @ApiResponse(responseCode = "403", description = "Restricted operation"),
+        @ApiResponse(responseCode = "400", description = "Invalid content / Missing content"),
+        @ApiResponse(responseCode = "404", description = "Toggleable features not found")})
+    public Response updateFeatureState(@PathParam("featureName") String featureName, @PathParam("state") boolean state,
+                                       @Context final HttpServletRequest request) {
         String url = request.getMethod() + " " + request.getRequestURI();
         log.debug("(get) Start handle request of {}", url);
-
         try {
             togglingBusinessLogic.updateFeatureState(featureName, state);
             return buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), FEATURE_STATE_WAS_UPDATED_SUCCESSFULLY);
@@ -163,6 +151,4 @@ public class TogglingServlet extends AbstractValidationsServlet {
             return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR));
         }
     }
-
-
 }
index 526e023..7683f69 100644 (file)
@@ -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.
@@ -17,7 +17,6 @@
  * limitations under the License.
  * ============LICENSE_END=========================================================
  */
-
 package org.openecomp.sdc.be.servlets;
 
 import com.jcabi.aspects.Loggable;
@@ -31,6 +30,21 @@ import io.swagger.v3.oas.annotations.servers.Server;
 import io.swagger.v3.oas.annotations.servers.Servers;
 import io.swagger.v3.oas.annotations.tags.Tag;
 import io.swagger.v3.oas.annotations.tags.Tags;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+import java.util.stream.Collectors;
+import javax.inject.Inject;
+import javax.servlet.ServletContext;
+import javax.servlet.http.HttpServletRequest;
+import javax.ws.rs.Consumes;
+import javax.ws.rs.GET;
+import javax.ws.rs.HeaderParam;
+import javax.ws.rs.Path;
+import javax.ws.rs.Produces;
+import javax.ws.rs.core.Context;
+import javax.ws.rs.core.MediaType;
+import javax.ws.rs.core.Response;
 import org.apache.commons.collections4.ListUtils;
 import org.openecomp.sdc.be.components.impl.CapabilitiesBusinessLogic;
 import org.openecomp.sdc.be.components.impl.ComponentBusinessLogic;
@@ -62,23 +76,6 @@ import org.openecomp.sdc.common.log.wrappers.Logger;
 import org.openecomp.sdc.exception.ResponseFormat;
 import org.springframework.stereotype.Controller;
 
-import javax.inject.Inject;
-import javax.servlet.ServletContext;
-import javax.servlet.http.HttpServletRequest;
-import javax.ws.rs.Consumes;
-import javax.ws.rs.GET;
-import javax.ws.rs.HeaderParam;
-import javax.ws.rs.Path;
-import javax.ws.rs.Produces;
-import javax.ws.rs.core.Context;
-import javax.ws.rs.core.MediaType;
-import javax.ws.rs.core.Response;
-import java.util.HashMap;
-import java.util.List;
-import java.util.Map;
-import java.util.stream.Collectors;
-
-
 @Loggable(prepend = true, value = Loggable.DEBUG, trim = false)
 @Path("/v1/catalog")
 @Tags({@Tag(name = "SDC Internal APIs")})
@@ -95,15 +92,10 @@ public class TypesFetchServlet extends AbstractValidationsServlet {
     private final ResourceBusinessLogic resourceBusinessLogic;
 
     @Inject
-    public TypesFetchServlet(UserBusinessLogic userBusinessLogic,
-        ComponentInstanceBusinessLogic componentInstanceBL,
-        ComponentsUtils componentsUtils, ServletUtils servletUtils,
-        ResourceImportManager resourceImportManager,
-        PropertyBusinessLogic propertyBusinessLogic,
-        RelationshipTypeBusinessLogic relationshipTypeBusinessLogic,
-        CapabilitiesBusinessLogic capabilitiesBusinessLogic,
-        InterfaceOperationBusinessLogic interfaceOperationBusinessLogic,
-        ResourceBusinessLogic resourceBusinessLogic) {
+    public TypesFetchServlet(UserBusinessLogic userBusinessLogic, ComponentInstanceBusinessLogic componentInstanceBL, ComponentsUtils componentsUtils,
+                             ServletUtils servletUtils, ResourceImportManager resourceImportManager, PropertyBusinessLogic propertyBusinessLogic,
+                             RelationshipTypeBusinessLogic relationshipTypeBusinessLogic, CapabilitiesBusinessLogic capabilitiesBusinessLogic,
+                             InterfaceOperationBusinessLogic interfaceOperationBusinessLogic, ResourceBusinessLogic resourceBusinessLogic) {
         super(userBusinessLogic, componentInstanceBL, componentsUtils, servletUtils, resourceImportManager);
         this.propertyBusinessLogic = propertyBusinessLogic;
         this.relationshipTypeBusinessLogic = relationshipTypeBusinessLogic;
@@ -117,74 +109,59 @@ public class TypesFetchServlet extends AbstractValidationsServlet {
     @Consumes(MediaType.APPLICATION_JSON)
     @Produces(MediaType.APPLICATION_JSON)
     @Operation(description = "Get data types", method = "GET", summary = "Returns data types", responses = {
-            @ApiResponse(content = @Content(array = @ArraySchema(schema = @Schema(implementation = Response.class)))),
-            @ApiResponse(responseCode = "200", description = "datatypes"),
-            @ApiResponse(responseCode = "403", description = "Restricted operation"),
-            @ApiResponse(responseCode = "400", description = "Invalid content / Missing content"),
-            @ApiResponse(responseCode = "404", description = "Data types not found")})
+        @ApiResponse(content = @Content(array = @ArraySchema(schema = @Schema(implementation = Response.class)))),
+        @ApiResponse(responseCode = "200", description = "datatypes"), @ApiResponse(responseCode = "403", description = "Restricted operation"),
+        @ApiResponse(responseCode = "400", description = "Invalid content / Missing content"),
+        @ApiResponse(responseCode = "404", description = "Data types not found")})
     @PermissionAllowed(AafPermission.PermNames.INTERNAL_ALL_VALUE)
     public Response getAllDataTypesServlet(@Context final HttpServletRequest request, @HeaderParam(value = Constants.USER_ID_HEADER) String userId) {
-
         Wrapper<Response> responseWrapper = new Wrapper<>();
         Wrapper<User> userWrapper = new Wrapper<>();
-
         init();
         validateUserExist(responseWrapper, userWrapper, userId);
-
         if (responseWrapper.isEmpty()) {
             String url = request.getMethod() + " " + request.getRequestURI();
             log.debug("Start handle request of {} - modifier id is {}", url, userId);
-
             Map<String, DataTypeDefinition> dataTypes = propertyBusinessLogic.getAllDataTypes();
             String dataTypeJson = gson.toJson(dataTypes);
             Response okResponse = buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), dataTypeJson);
             responseWrapper.setInnerElement(okResponse);
         }
-
-            return responseWrapper.getInnerElement();
-   }
+        return responseWrapper.getInnerElement();
+    }
 
     @GET
     @Path("interfaceLifecycleTypes")
     @Consumes(MediaType.APPLICATION_JSON)
     @Produces(MediaType.APPLICATION_JSON)
-    @Operation(description = "Get interface lifecycle types", method = "GET",
-            summary = "Returns interface lifecycle types", responses = {
-            @ApiResponse(content = @Content(array = @ArraySchema(schema = @Schema(implementation = Response.class)))),
-            @ApiResponse(responseCode = "200", description = "Interface lifecycle types"),
-            @ApiResponse(responseCode = "403", description = "Restricted operation"),
-            @ApiResponse(responseCode = "400", description = "Invalid content / Missing content"),
-            @ApiResponse(responseCode = "404", description = "Interface lifecycle types not found")})
+    @Operation(description = "Get interface lifecycle types", method = "GET", summary = "Returns interface lifecycle types", responses = {
+        @ApiResponse(content = @Content(array = @ArraySchema(schema = @Schema(implementation = Response.class)))),
+        @ApiResponse(responseCode = "200", description = "Interface lifecycle types"),
+        @ApiResponse(responseCode = "403", description = "Restricted operation"),
+        @ApiResponse(responseCode = "400", description = "Invalid content / Missing content"),
+        @ApiResponse(responseCode = "404", description = "Interface lifecycle types not found")})
     @PermissionAllowed(AafPermission.PermNames.INTERNAL_ALL_VALUE)
-    public Response getInterfaceLifecycleTypes(@Context final HttpServletRequest request, @HeaderParam(value = Constants.USER_ID_HEADER) String userId) {
-
+    public Response getInterfaceLifecycleTypes(@Context final HttpServletRequest request,
+                                               @HeaderParam(value = Constants.USER_ID_HEADER) String userId) {
         Wrapper<Response> responseWrapper = new Wrapper<>();
         Wrapper<User> userWrapper = new Wrapper<>();
-
         try {
             validateUserExist(responseWrapper, userWrapper, userId);
-
             if (responseWrapper.isEmpty()) {
                 String url = request.getMethod() + " " + request.getRequestURI();
                 log.info("Start handle request of {} | modifier id is {}", url, userId);
-
-                Either<Map<String, InterfaceDefinition>, ResponseFormat> allInterfaceLifecycleTypes =
-                        interfaceOperationBusinessLogic.getAllInterfaceLifecycleTypes();
-
+                Either<Map<String, InterfaceDefinition>, ResponseFormat> allInterfaceLifecycleTypes = interfaceOperationBusinessLogic
+                    .getAllInterfaceLifecycleTypes();
                 if (allInterfaceLifecycleTypes.isRight()) {
-                    log.info("Failed to get all interface lifecycle types. Reason - {}",
-                        allInterfaceLifecycleTypes.right().value());
+                    log.info("Failed to get all interface lifecycle types. Reason - {}", allInterfaceLifecycleTypes.right().value());
                     Response errorResponse = buildErrorResponse(allInterfaceLifecycleTypes.right().value());
                     responseWrapper.setInnerElement(errorResponse);
-
                 } else {
                     String interfaceLifecycleTypeJson = gson.toJson(allInterfaceLifecycleTypes.left().value());
                     Response okResponse = buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), interfaceLifecycleTypeJson);
                     responseWrapper.setInnerElement(okResponse);
-
                 }
             }
-
             return responseWrapper.getInnerElement();
         } catch (Exception e) {
             log.debug("get all interface lifecycle types failed with exception", e);
@@ -192,50 +169,39 @@ public class TypesFetchServlet extends AbstractValidationsServlet {
             return buildErrorResponse(responseFormat);
         }
     }
+
     @GET
     @Path("capabilityTypes")
     @Consumes(MediaType.APPLICATION_JSON)
     @Produces(MediaType.APPLICATION_JSON)
     @Operation(description = "Get capability types", method = "GET", summary = "Returns capability types", responses = {
-            @ApiResponse(content = @Content(array = @ArraySchema(schema = @Schema(implementation = Response.class)))),
-            @ApiResponse(responseCode = "200", description = "capabilityTypes"),
-            @ApiResponse(responseCode = "403", description = "Restricted operation"),
-            @ApiResponse(responseCode = "400", description = "Invalid content / Missing content"),
-            @ApiResponse(responseCode = "404", description = "Capability types not found")})
+        @ApiResponse(content = @Content(array = @ArraySchema(schema = @Schema(implementation = Response.class)))),
+        @ApiResponse(responseCode = "200", description = "capabilityTypes"), @ApiResponse(responseCode = "403", description = "Restricted operation"),
+        @ApiResponse(responseCode = "400", description = "Invalid content / Missing content"),
+        @ApiResponse(responseCode = "404", description = "Capability types not found")})
     @PermissionAllowed(AafPermission.PermNames.INTERNAL_ALL_VALUE)
-    public Response getAllCapabilityTypesServlet(@Context final HttpServletRequest request, @HeaderParam(value =
-            Constants.USER_ID_HEADER) String userId) {
-
+    public Response getAllCapabilityTypesServlet(@Context final HttpServletRequest request,
+                                                 @HeaderParam(value = Constants.USER_ID_HEADER) String userId) {
         Wrapper<Response> responseWrapper = new Wrapper<>();
         Wrapper<User> userWrapper = new Wrapper<>();
-
         try {
             init();
             validateUserExist(responseWrapper, userWrapper, userId);
-
             if (responseWrapper.isEmpty()) {
                 String url = request.getMethod() + " " + request.getRequestURI();
                 log.debug("Start handle request of {} | modifier id is {}", url, userId);
-
-                Either<Map<String, CapabilityTypeDefinition>, ResponseFormat> allDataTypes =
-                    capabilitiesBusinessLogic.getAllCapabilityTypes();
-
+                Either<Map<String, CapabilityTypeDefinition>, ResponseFormat> allDataTypes = capabilitiesBusinessLogic.getAllCapabilityTypes();
                 if (allDataTypes.isRight()) {
                     log.info("Failed to get all capability types. Reason - {}", allDataTypes.right().value());
                     Response errorResponse = buildErrorResponse(allDataTypes.right().value());
                     responseWrapper.setInnerElement(errorResponse);
-
                 } else {
-
                     Map<String, CapabilityTypeDefinition> dataTypes = allDataTypes.left().value();
                     String dataTypeJson = gson.toJson(dataTypes);
-                    Response okResponse =
-                            buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), dataTypeJson);
+                    Response okResponse = buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), dataTypeJson);
                     responseWrapper.setInnerElement(okResponse);
-
                 }
             }
-
             return responseWrapper.getInnerElement();
         } catch (Exception e) {
             BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Get Capability Types");
@@ -249,47 +215,36 @@ public class TypesFetchServlet extends AbstractValidationsServlet {
     @Path("relationshipTypes")
     @Consumes(MediaType.APPLICATION_JSON)
     @Produces(MediaType.APPLICATION_JSON)
-    @Operation(description = "Get relationship types", method = "GET", summary = "Returns relationship types",
-            responses = {@ApiResponse(
-                    content = @Content(array = @ArraySchema(schema = @Schema(implementation = Response.class)))),
-                    @ApiResponse(responseCode = "200", description = "relationshipTypes"),
-                    @ApiResponse(responseCode = "403", description = "Restricted operation"),
-                    @ApiResponse(responseCode = "400", description = "Invalid content / Missing content"),
-                    @ApiResponse(responseCode = "404", description = "Relationship types not found")})
+    @Operation(description = "Get relationship types", method = "GET", summary = "Returns relationship types", responses = {
+        @ApiResponse(content = @Content(array = @ArraySchema(schema = @Schema(implementation = Response.class)))),
+        @ApiResponse(responseCode = "200", description = "relationshipTypes"),
+        @ApiResponse(responseCode = "403", description = "Restricted operation"),
+        @ApiResponse(responseCode = "400", description = "Invalid content / Missing content"),
+        @ApiResponse(responseCode = "404", description = "Relationship types not found")})
     @PermissionAllowed(AafPermission.PermNames.INTERNAL_ALL_VALUE)
-    public Response getAllRelationshipTypesServlet(@Context final HttpServletRequest request, @HeaderParam(value =
-            Constants.USER_ID_HEADER) String userId) {
-
+    public Response getAllRelationshipTypesServlet(@Context final HttpServletRequest request,
+                                                   @HeaderParam(value = Constants.USER_ID_HEADER) String userId) {
         Wrapper<Response> responseWrapper = new Wrapper<>();
         Wrapper<User> userWrapper = new Wrapper<>();
-
         try {
             init();
             validateUserExist(responseWrapper, userWrapper, userId);
-
             if (responseWrapper.isEmpty()) {
                 String url = request.getMethod() + " " + request.getRequestURI();
                 log.debug("Start handle request of {} | modifier id is {}", url, userId);
-
-                Either<Map<String, RelationshipTypeDefinition>, ResponseFormat> allDataTypes =
-                    relationshipTypeBusinessLogic.getAllRelationshipTypes();
-
+                Either<Map<String, RelationshipTypeDefinition>, ResponseFormat> allDataTypes = relationshipTypeBusinessLogic
+                    .getAllRelationshipTypes();
                 if (allDataTypes.isRight()) {
                     log.info("Failed to get all relationship types. Reason - {}", allDataTypes.right().value());
                     Response errorResponse = buildErrorResponse(allDataTypes.right().value());
                     responseWrapper.setInnerElement(errorResponse);
-
                 } else {
-
                     Map<String, RelationshipTypeDefinition> dataTypes = allDataTypes.left().value();
                     String dataTypeJson = gson.toJson(dataTypes);
-                    Response okResponse =
-                            buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), dataTypeJson);
+                    Response okResponse = buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), dataTypeJson);
                     responseWrapper.setInnerElement(okResponse);
-
                 }
             }
-
             return responseWrapper.getInnerElement();
         } catch (Exception e) {
             BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Get Relationship Types");
@@ -304,47 +259,37 @@ public class TypesFetchServlet extends AbstractValidationsServlet {
     @Consumes(MediaType.APPLICATION_JSON)
     @Produces(MediaType.APPLICATION_JSON)
     @Operation(description = "Get node types", method = "GET", summary = "Returns node types", responses = {
-            @ApiResponse(content = @Content(array = @ArraySchema(schema = @Schema(implementation = Response.class)))),
-            @ApiResponse(responseCode = "200", description = "nodeTypes"),
-            @ApiResponse(responseCode = "403", description = "Restricted operation"),
-            @ApiResponse(responseCode = "400", description = "Invalid content / Missing content"),
-            @ApiResponse(responseCode = "404", description = "Node types not found")})
+        @ApiResponse(content = @Content(array = @ArraySchema(schema = @Schema(implementation = Response.class)))),
+        @ApiResponse(responseCode = "200", description = "nodeTypes"), @ApiResponse(responseCode = "403", description = "Restricted operation"),
+        @ApiResponse(responseCode = "400", description = "Invalid content / Missing content"),
+        @ApiResponse(responseCode = "404", description = "Node types not found")})
     @PermissionAllowed(AafPermission.PermNames.INTERNAL_ALL_VALUE)
-    public Response getAllNodeTypesServlet(@Context final HttpServletRequest request, @HeaderParam(value =
-            Constants.USER_ID_HEADER) String userId) {
-
+    public Response getAllNodeTypesServlet(@Context final HttpServletRequest request, @HeaderParam(value = Constants.USER_ID_HEADER) String userId) {
         Wrapper<Response> responseWrapper = new Wrapper<>();
         Wrapper<User> userWrapper = new Wrapper<>();
         ServletContext context = request.getSession().getServletContext();
         Either<Map<String, Component>, Response> response;
         Map<String, Component> componentMap;
-
         try {
             init();
             validateUserExist(responseWrapper, userWrapper, userId);
-
             if (responseWrapper.isEmpty()) {
                 String url = request.getMethod() + " " + request.getRequestURI();
                 log.debug("Start handle request of {} | modifier id is {}", url, userId);
-
                 response = getComponent(resourceBusinessLogic, true, userId);
                 if (response.isRight()) {
                     return response.right().value();
                 }
                 componentMap = new HashMap<>(response.left().value());
-
                 response = getComponent(resourceBusinessLogic, false, userId);
                 if (response.isRight()) {
                     return response.right().value();
                 }
                 componentMap.putAll(response.left().value());
-
                 String nodeTypesJson = gson.toJson(componentMap);
-                Response okResponse =
-                        buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), nodeTypesJson);
+                Response okResponse = buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), nodeTypesJson);
                 responseWrapper.setInnerElement(okResponse);
             }
-
             return responseWrapper.getInnerElement();
         } catch (Exception e) {
             BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Get Node Types");
@@ -354,27 +299,20 @@ public class TypesFetchServlet extends AbstractValidationsServlet {
         }
     }
 
-    private Either<Map<String, Component>, Response> getComponent(ComponentBusinessLogic resourceBL, boolean isAbstract,
-                                                                  String userId) {
+    private Either<Map<String, Component>, Response> getComponent(ComponentBusinessLogic resourceBL, boolean isAbstract, String userId) {
         Either<List<Component>, ResponseFormat> actionResponse;
         List<Component> componentList;
-
-        actionResponse =
-                resourceBL.getLatestVersionNotAbstractComponentsMetadata(isAbstract, HighestFilterEnum.HIGHEST_ONLY
-                        , ComponentTypeEnum.RESOURCE, null, userId);
+        actionResponse = resourceBL
+            .getLatestVersionNotAbstractComponentsMetadata(isAbstract, HighestFilterEnum.HIGHEST_ONLY, ComponentTypeEnum.RESOURCE, null, userId);
         if (actionResponse.isRight()) {
             log.debug(FAILED_TO_GET_ALL_NON_ABSTRACT, ComponentTypeEnum.RESOURCE.getValue());
             return Either.right(buildErrorResponse(actionResponse.right().value()));
         }
-
         componentList = actionResponse.left().value();
-
-        return Either.left(ListUtils.emptyIfNull(componentList).stream()
-                .filter(component -> ((ResourceMetadataDataDefinition) component
-                        .getComponentMetadataDefinition().getMetadataDataDefinition()).getToscaResourceName() != null)
-                .collect(Collectors.toMap(
-                        component -> ((ResourceMetadataDataDefinition) component
-                                .getComponentMetadataDefinition().getMetadataDataDefinition()).getToscaResourceName(),
-                        component -> component, (component1, component2) -> component1)));
+        return Either.left(ListUtils.emptyIfNull(componentList).stream().filter(component ->
+            ((ResourceMetadataDataDefinition) component.getComponentMetadataDefinition().getMetadataDataDefinition()).getToscaResourceName() != null)
+            .collect(Collectors.toMap(
+                component -> ((ResourceMetadataDataDefinition) component.getComponentMetadataDefinition().getMetadataDataDefinition())
+                    .getToscaResourceName(), component -> component, (component1, component2) -> component1)));
     }
 }
index b0b897d..8d3f58e 100644 (file)
@@ -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.
@@ -17,7 +17,6 @@
  * limitations under the License.
  * ============LICENSE_END=========================================================
  */
-
 package org.openecomp.sdc.be.servlets;
 
 import com.google.common.annotations.VisibleForTesting;
@@ -32,6 +31,16 @@ import io.swagger.v3.oas.annotations.servers.Server;
 import io.swagger.v3.oas.annotations.servers.Servers;
 import io.swagger.v3.oas.annotations.tags.Tag;
 import io.swagger.v3.oas.annotations.tags.Tags;
+import java.io.File;
+import java.util.List;
+import java.util.Map;
+import javax.ws.rs.Consumes;
+import javax.ws.rs.HeaderParam;
+import javax.ws.rs.POST;
+import javax.ws.rs.Path;
+import javax.ws.rs.Produces;
+import javax.ws.rs.core.MediaType;
+import javax.ws.rs.core.Response;
 import org.apache.commons.lang3.tuple.ImmutablePair;
 import org.glassfish.jersey.media.multipart.FormDataParam;
 import org.openecomp.sdc.be.components.impl.CommonImportManager;
@@ -51,16 +60,6 @@ import org.slf4j.LoggerFactory;
 import org.springframework.http.HttpStatus;
 import org.springframework.stereotype.Controller;
 
-import javax.ws.rs.Consumes;
-import javax.ws.rs.HeaderParam;
-import javax.ws.rs.POST;
-import javax.ws.rs.Path;
-import javax.ws.rs.Produces;
-import javax.ws.rs.core.MediaType;
-import javax.ws.rs.core.Response;
-import java.io.File;
-import java.util.List;
-import java.util.Map;
 /**
  * Here new APIs for types upload written in an attempt to gradually servlet code
  */
@@ -71,47 +70,21 @@ import java.util.Map;
 @Tags({@Tag(name = "SDC Internal APIs")})
 @Servers({@Server(url = "/sdc2/rest")})
 @Controller
-public class TypesUploadEndpoint extends BeGenericServlet{
-    private static final Logger LOGGER = LoggerFactory.getLogger(TypesUploadEndpoint.class);
+public class TypesUploadEndpoint extends BeGenericServlet {
 
+    private static final Logger LOGGER = LoggerFactory.getLogger(TypesUploadEndpoint.class);
     private final CommonImportManager commonImportManager;
     private final AnnotationTypeOperations annotationTypeOperations;
     private final AccessValidations accessValidations;
 
-    public TypesUploadEndpoint(UserBusinessLogic userBusinessLogic,
-        ComponentsUtils componentsUtils, CommonImportManager commonImportManager, AnnotationTypeOperations annotationTypeOperations, AccessValidations accessValidations) {
+    public TypesUploadEndpoint(UserBusinessLogic userBusinessLogic, ComponentsUtils componentsUtils, CommonImportManager commonImportManager,
+                               AnnotationTypeOperations annotationTypeOperations, AccessValidations accessValidations) {
         super(userBusinessLogic, componentsUtils);
         this.commonImportManager = commonImportManager;
         this.annotationTypeOperations = annotationTypeOperations;
         this.accessValidations = accessValidations;
     }
 
-    @POST
-    @Path("/annotationtypes")
-    @Operation(description = "Create AnnotationTypes from yaml", method = "POST",
-            summary = "Returns created annotation types", responses = {
-            @ApiResponse(content = @Content(array = @ArraySchema(schema = @Schema(implementation = Response.class)))),
-            @ApiResponse(responseCode = "201", description = "annotation types created"),
-            @ApiResponse(responseCode = "403", description = "Restricted operation"),
-            @ApiResponse(responseCode = "400", description = "Invalid content / Missing content"),
-            @ApiResponse(responseCode = "409", description = "annotation types already exist")})
-    @PermissionAllowed(AafPermission.PermNames.INTERNAL_ALL_VALUE)
-    public Response uploadAnnotationTypes(@Parameter(description = "FileInputStream") @FormDataParam("annotationTypesZip") File file,
-            @HeaderParam("USER_ID") String userId) {
-        accessValidations.validateUserExists(userId, "Annotation Types Creation");
-        final Wrapper<String> yamlStringWrapper = new Wrapper<>();
-        try {
-            AbstractValidationsServlet.extractZipContents(yamlStringWrapper, file);
-        } catch (final ZipException e) {
-            LOGGER.error("Could not extract zip contents", e);
-        }
-        List<ImmutablePair<AnnotationTypeDefinition, Boolean>> typesResults = commonImportManager.createElementTypes(yamlStringWrapper.getInnerElement(), TypesUploadEndpoint::buildAnnotationFromFieldMap, annotationTypeOperations);
-        HttpStatus status = getHttpStatus(typesResults);
-        return Response.status(status.value())
-                .entity(typesResults)
-                .build();
-    }
-
     @VisibleForTesting
     static <T extends ToscaDataDefinition> HttpStatus getHttpStatus(List<ImmutablePair<T, Boolean>> typesResults) {
         boolean typeActionFailed = false;
@@ -119,7 +92,7 @@ public class TypesUploadEndpoint extends BeGenericServlet{
         boolean typeActionSucceeded = false;
         for (ImmutablePair<T, Boolean> typeResult : typesResults) {
             Boolean result = typeResult.getRight();
-            if (result==null) {
+            if (result == null) {
                 typeExists = true;
             } else if (result) {
                 typeActionSucceeded = true;
@@ -129,7 +102,7 @@ public class TypesUploadEndpoint extends BeGenericServlet{
         }
         HttpStatus status = HttpStatus.OK;
         if (typeActionFailed) {
-            status =  HttpStatus.BAD_REQUEST;
+            status = HttpStatus.BAD_REQUEST;
         } else if (typeActionSucceeded) {
             status = HttpStatus.CREATED;
         } else if (typeExists) {
@@ -148,5 +121,27 @@ public class TypesUploadEndpoint extends BeGenericServlet{
         return (T) annotationType;
     }
 
-
+    @POST
+    @Path("/annotationtypes")
+    @Operation(description = "Create AnnotationTypes from yaml", method = "POST", summary = "Returns created annotation types", responses = {
+        @ApiResponse(content = @Content(array = @ArraySchema(schema = @Schema(implementation = Response.class)))),
+        @ApiResponse(responseCode = "201", description = "annotation types created"),
+        @ApiResponse(responseCode = "403", description = "Restricted operation"),
+        @ApiResponse(responseCode = "400", description = "Invalid content / Missing content"),
+        @ApiResponse(responseCode = "409", description = "annotation types already exist")})
+    @PermissionAllowed(AafPermission.PermNames.INTERNAL_ALL_VALUE)
+    public Response uploadAnnotationTypes(@Parameter(description = "FileInputStream") @FormDataParam("annotationTypesZip") File file,
+                                          @HeaderParam("USER_ID") String userId) {
+        accessValidations.validateUserExists(userId, "Annotation Types Creation");
+        final Wrapper<String> yamlStringWrapper = new Wrapper<>();
+        try {
+            AbstractValidationsServlet.extractZipContents(yamlStringWrapper, file);
+        } catch (final ZipException e) {
+            LOGGER.error("Could not extract zip contents", e);
+        }
+        List<ImmutablePair<AnnotationTypeDefinition, Boolean>> typesResults = commonImportManager
+            .createElementTypes(yamlStringWrapper.getInnerElement(), TypesUploadEndpoint::buildAnnotationFromFieldMap, annotationTypeOperations);
+        HttpStatus status = getHttpStatus(typesResults);
+        return Response.status(status.value()).entity(typesResults).build();
+    }
 }
index 953346e..9e945d6 100644 (file)
@@ -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.
@@ -17,7 +17,6 @@
  * limitations under the License.
  * ============LICENSE_END=========================================================
  */
-
 package org.openecomp.sdc.be.servlets;
 
 import com.google.gson.reflect.TypeToken;
@@ -33,6 +32,23 @@ import io.swagger.v3.oas.annotations.servers.Server;
 import io.swagger.v3.oas.annotations.servers.Servers;
 import io.swagger.v3.oas.annotations.tags.Tag;
 import io.swagger.v3.oas.annotations.tags.Tags;
+import java.io.File;
+import java.io.IOException;
+import java.util.List;
+import java.util.Map;
+import java.util.Set;
+import java.util.function.Supplier;
+import java.util.stream.Collectors;
+import javax.inject.Inject;
+import javax.servlet.http.HttpServletRequest;
+import javax.ws.rs.Consumes;
+import javax.ws.rs.HeaderParam;
+import javax.ws.rs.POST;
+import javax.ws.rs.Path;
+import javax.ws.rs.Produces;
+import javax.ws.rs.core.Context;
+import javax.ws.rs.core.MediaType;
+import javax.ws.rs.core.Response;
 import org.apache.commons.lang3.tuple.ImmutablePair;
 import org.glassfish.jersey.media.multipart.FormDataParam;
 import org.openecomp.sdc.be.components.impl.CapabilityTypeImportManager;
@@ -66,24 +82,6 @@ import org.openecomp.sdc.common.log.wrappers.Logger;
 import org.openecomp.sdc.exception.ResponseFormat;
 import org.springframework.stereotype.Controller;
 
-import javax.inject.Inject;
-import javax.servlet.http.HttpServletRequest;
-import javax.ws.rs.Consumes;
-import javax.ws.rs.HeaderParam;
-import javax.ws.rs.POST;
-import javax.ws.rs.Path;
-import javax.ws.rs.Produces;
-import javax.ws.rs.core.Context;
-import javax.ws.rs.core.MediaType;
-import javax.ws.rs.core.Response;
-import java.io.File;
-import java.io.IOException;
-import java.util.List;
-import java.util.Map;
-import java.util.Set;
-import java.util.function.Supplier;
-import java.util.stream.Collectors;
-
 @Loggable(prepend = true, value = Loggable.DEBUG, trim = false)
 @Path("/v1/catalog/uploadType")
 @Consumes(MediaType.MULTIPART_FORM_DATA)
@@ -92,9 +90,9 @@ import java.util.stream.Collectors;
 @Servers({@Server(url = "/sdc2/rest")})
 @Controller
 public class TypesUploadServlet extends AbstractValidationsServlet {
-    private static final Logger log = Logger.getLogger(TypesUploadServlet.class);
-    public static final String CREATE = "Create ";
 
+    public static final String CREATE = "Create ";
+    private static final Logger log = Logger.getLogger(TypesUploadServlet.class);
     private final CapabilityTypeImportManager capabilityTypeImportManager;
     private final InterfaceLifecycleTypeImportManager interfaceLifecycleTypeImportManager;
     private final CategoriesImportManager categoriesImportManager;
@@ -104,17 +102,13 @@ public class TypesUploadServlet extends AbstractValidationsServlet {
     private final RelationshipTypeImportManager relationshipTypeImportManager;
 
     @Inject
-    public TypesUploadServlet(UserBusinessLogic userBusinessLogic,
-        ComponentInstanceBusinessLogic componentInstanceBL,
-        ComponentsUtils componentsUtils, ServletUtils servletUtils,
-        ResourceImportManager resourceImportManager,
-        CapabilityTypeImportManager capabilityTypeImportManager,
-        InterfaceLifecycleTypeImportManager interfaceLifecycleTypeImportManager,
-        CategoriesImportManager categoriesImportManager,
-        DataTypeImportManager dataTypeImportManager,
-        GroupTypeImportManager groupTypeImportManager,
-        PolicyTypeImportManager policyTypeImportManager,
-        RelationshipTypeImportManager relationshipTypeImportManager) {
+    public TypesUploadServlet(UserBusinessLogic userBusinessLogic, ComponentInstanceBusinessLogic componentInstanceBL,
+                              ComponentsUtils componentsUtils, ServletUtils servletUtils, ResourceImportManager resourceImportManager,
+                              CapabilityTypeImportManager capabilityTypeImportManager,
+                              InterfaceLifecycleTypeImportManager interfaceLifecycleTypeImportManager,
+                              CategoriesImportManager categoriesImportManager, DataTypeImportManager dataTypeImportManager,
+                              GroupTypeImportManager groupTypeImportManager, PolicyTypeImportManager policyTypeImportManager,
+                              RelationshipTypeImportManager relationshipTypeImportManager) {
         super(userBusinessLogic, componentInstanceBL, componentsUtils, servletUtils, resourceImportManager);
         this.capabilityTypeImportManager = capabilityTypeImportManager;
         this.interfaceLifecycleTypeImportManager = interfaceLifecycleTypeImportManager;
@@ -127,142 +121,124 @@ public class TypesUploadServlet extends AbstractValidationsServlet {
 
     @POST
     @Path("/capability")
-    @Operation(description = "Create Capability Type from yaml", method = "POST",
-            summary = "Returns created Capability Type", responses = {
-            @ApiResponse(content = @Content(array = @ArraySchema(schema = @Schema(implementation = Response.class)))),
-            @ApiResponse(responseCode = "201", description = "Capability Type created"),
-            @ApiResponse(responseCode = "403", description = "Restricted operation"),
-            @ApiResponse(responseCode = "400", description = "Invalid content / Missing content"),
-            @ApiResponse(responseCode = "409", description = "Capability Type already exist")})
+    @Operation(description = "Create Capability Type from yaml", method = "POST", summary = "Returns created Capability Type", responses = {
+        @ApiResponse(content = @Content(array = @ArraySchema(schema = @Schema(implementation = Response.class)))),
+        @ApiResponse(responseCode = "201", description = "Capability Type created"),
+        @ApiResponse(responseCode = "403", description = "Restricted operation"),
+        @ApiResponse(responseCode = "400", description = "Invalid content / Missing content"),
+        @ApiResponse(responseCode = "409", description = "Capability Type already exist")})
     @PermissionAllowed(AafPermission.PermNames.INTERNAL_ALL_VALUE)
     public Response uploadCapabilityType(@Parameter(description = "FileInputStream") @FormDataParam("capabilityTypeZip") File file,
-            @Context final HttpServletRequest request, @HeaderParam("USER_ID") String creator) {
-        ConsumerTwoParam<Wrapper<Response>, String> createElementsMethod =
-                (responseWrapper, ymlPayload) -> createElementsType(responseWrapper,
-                        () -> capabilityTypeImportManager.createCapabilityTypes(ymlPayload));
-        return uploadElementTypeServletLogic(createElementsMethod, file, request, creator,
-                NodeTypeEnum.CapabilityType.name());
+                                         @Context final HttpServletRequest request, @HeaderParam("USER_ID") String creator) {
+        ConsumerTwoParam<Wrapper<Response>, String> createElementsMethod = (responseWrapper, ymlPayload) -> createElementsType(responseWrapper,
+            () -> capabilityTypeImportManager.createCapabilityTypes(ymlPayload));
+        return uploadElementTypeServletLogic(createElementsMethod, file, request, creator, NodeTypeEnum.CapabilityType.name());
     }
 
     @POST
     @Path("/relationship")
-    @Operation(description = "Create Relationship Type from yaml", method = "POST",
-            summary = "Returns created Relationship Type", responses = {
-            @ApiResponse(content = @Content(array = @ArraySchema(schema = @Schema(implementation = Response.class)))),
-            @ApiResponse(responseCode = "201", description = "Relationship Type created"),
-            @ApiResponse(responseCode = "403", description = "Restricted operation"),
-            @ApiResponse(responseCode = "400", description = "Invalid content / Missing content"),
-            @ApiResponse(responseCode = "409", description = "Relationship Type already exist")})
+    @Operation(description = "Create Relationship Type from yaml", method = "POST", summary = "Returns created Relationship Type", responses = {
+        @ApiResponse(content = @Content(array = @ArraySchema(schema = @Schema(implementation = Response.class)))),
+        @ApiResponse(responseCode = "201", description = "Relationship Type created"),
+        @ApiResponse(responseCode = "403", description = "Restricted operation"),
+        @ApiResponse(responseCode = "400", description = "Invalid content / Missing content"),
+        @ApiResponse(responseCode = "409", description = "Relationship Type already exist")})
     @PermissionAllowed(AafPermission.PermNames.INTERNAL_ALL_VALUE)
     public Response uploadRelationshipType(@Parameter(description = "FileInputStream") @FormDataParam("relationshipTypeZip") File file,
-                                           @Context final HttpServletRequest request,
-                                           @HeaderParam("USER_ID") String creator) {
-        return uploadElementTypeServletLogic(this::createRelationshipTypes, file, request, creator,
-                NodeTypeEnum.RelationshipType.getName());
+                                           @Context final HttpServletRequest request, @HeaderParam("USER_ID") String creator) {
+        return uploadElementTypeServletLogic(this::createRelationshipTypes, file, request, creator, NodeTypeEnum.RelationshipType.getName());
     }
 
     @POST
     @Path("/interfaceLifecycle")
-    @Operation(description = "Create Interface Lyfecycle Type from yaml", method = "POST",
-            summary = "Returns created Interface Lifecycle Type", responses = {
-            @ApiResponse(content = @Content(array = @ArraySchema(schema = @Schema(implementation = Response.class)))),
-            @ApiResponse(responseCode = "201", description = "Interface Lifecycle Type created"),
-            @ApiResponse(responseCode = "403", description = "Restricted operation"),
-            @ApiResponse(responseCode = "400", description = "Invalid content / Missing content"),
-            @ApiResponse(responseCode = "409", description = "Interface Lifecycle Type already exist")})
+    @Operation(description = "Create Interface Lyfecycle Type from yaml", method = "POST", summary = "Returns created Interface Lifecycle Type", responses = {
+        @ApiResponse(content = @Content(array = @ArraySchema(schema = @Schema(implementation = Response.class)))),
+        @ApiResponse(responseCode = "201", description = "Interface Lifecycle Type created"),
+        @ApiResponse(responseCode = "403", description = "Restricted operation"),
+        @ApiResponse(responseCode = "400", description = "Invalid content / Missing content"),
+        @ApiResponse(responseCode = "409", description = "Interface Lifecycle Type already exist")})
     @PermissionAllowed(AafPermission.PermNames.INTERNAL_ALL_VALUE)
-    public Response uploadInterfaceLifecycleType(
-            @Parameter(description = "FileInputStream") @FormDataParam("interfaceLifecycleTypeZip") File file,
-            @Context final HttpServletRequest request, @HeaderParam("USER_ID") String creator) {
-        ConsumerTwoParam<Wrapper<Response>, String> createElementsMethod =
-                (responseWrapper, ymlPayload) -> createElementsType(responseWrapper,
-                        () -> interfaceLifecycleTypeImportManager.createLifecycleTypes(ymlPayload));
+    public Response uploadInterfaceLifecycleType(@Parameter(description = "FileInputStream") @FormDataParam("interfaceLifecycleTypeZip") File file,
+                                                 @Context final HttpServletRequest request, @HeaderParam("USER_ID") String creator) {
+        ConsumerTwoParam<Wrapper<Response>, String> createElementsMethod = (responseWrapper, ymlPayload) -> createElementsType(responseWrapper,
+            () -> interfaceLifecycleTypeImportManager.createLifecycleTypes(ymlPayload));
         return uploadElementTypeServletLogic(createElementsMethod, file, request, creator, "Interface Types");
     }
 
     @POST
     @Path("/categories")
-    @Operation(description = "Create Categories from yaml", method = "POST", summary = "Returns created categories",
-            responses = {@ApiResponse(
-                    content = @Content(array = @ArraySchema(schema = @Schema(implementation = Response.class)))),
-                    @ApiResponse(responseCode = "201", description = "Categories created"),
-                    @ApiResponse(responseCode = "403", description = "Restricted operation"),
-                    @ApiResponse(responseCode = "400", description = "Invalid content / Missing content"),
-                    @ApiResponse(responseCode = "409", description = "Category already exist")})
+    @Operation(description = "Create Categories from yaml", method = "POST", summary = "Returns created categories", responses = {
+        @ApiResponse(content = @Content(array = @ArraySchema(schema = @Schema(implementation = Response.class)))),
+        @ApiResponse(responseCode = "201", description = "Categories created"),
+        @ApiResponse(responseCode = "403", description = "Restricted operation"),
+        @ApiResponse(responseCode = "400", description = "Invalid content / Missing content"),
+        @ApiResponse(responseCode = "409", description = "Category already exist")})
     @PermissionAllowed(AafPermission.PermNames.INTERNAL_ALL_VALUE)
     public Response uploadCategories(@Parameter(description = "FileInputStream") @FormDataParam("categoriesZip") File file,
-            @Context final HttpServletRequest request, @HeaderParam("USER_ID") String creator) {
-        ConsumerTwoParam<Wrapper<Response>, String> createElementsMethod =
-                (responseWrapper, ymlPayload) -> createElementsType(responseWrapper,
-                        () -> categoriesImportManager.createCategories(ymlPayload));
+                                     @Context final HttpServletRequest request, @HeaderParam("USER_ID") String creator) {
+        ConsumerTwoParam<Wrapper<Response>, String> createElementsMethod = (responseWrapper, ymlPayload) -> createElementsType(responseWrapper,
+            () -> categoriesImportManager.createCategories(ymlPayload));
         return uploadElementTypeServletLogic(createElementsMethod, file, request, creator, "categories");
     }
 
     @POST
     @Path("/datatypes")
-    @Operation(description = "Create Categories from yaml", method = "POST", summary = "Returns created data types",
-            responses = {@ApiResponse(
-                    content = @Content(array = @ArraySchema(schema = @Schema(implementation = Response.class)))),
-                    @ApiResponse(responseCode = "201", description = "Data types created"),
-                    @ApiResponse(responseCode = "403", description = "Restricted operation"),
-                    @ApiResponse(responseCode = "400", description = "Invalid content / Missing content"),
-                    @ApiResponse(responseCode = "409", description = "Data types already exist")})
+    @Operation(description = "Create Categories from yaml", method = "POST", summary = "Returns created data types", responses = {
+        @ApiResponse(content = @Content(array = @ArraySchema(schema = @Schema(implementation = Response.class)))),
+        @ApiResponse(responseCode = "201", description = "Data types created"),
+        @ApiResponse(responseCode = "403", description = "Restricted operation"),
+        @ApiResponse(responseCode = "400", description = "Invalid content / Missing content"),
+        @ApiResponse(responseCode = "409", description = "Data types already exist")})
     @PermissionAllowed(AafPermission.PermNames.INTERNAL_ALL_VALUE)
     public Response uploadDataTypes(@Parameter(description = "FileInputStream") @FormDataParam("dataTypesZip") File file,
-            @Context final HttpServletRequest request, @HeaderParam("USER_ID") String creator) {
+                                    @Context final HttpServletRequest request, @HeaderParam("USER_ID") String creator) {
         ConsumerTwoParam<Wrapper<Response>, String> createElementsMethod = this::createDataTypes;
-        return uploadElementTypeServletLogic(createElementsMethod, file, request, creator,
-                NodeTypeEnum.DataType.getName());
+        return uploadElementTypeServletLogic(createElementsMethod, file, request, creator, NodeTypeEnum.DataType.getName());
     }
 
     @POST
     @Path("/grouptypes")
-    @Operation(description = "Create GroupTypes from yaml", method = "POST", summary = "Returns created group types",
-            responses = {@ApiResponse(
-                    content = @Content(array = @ArraySchema(schema = @Schema(implementation = Response.class)))),
-                    @ApiResponse(responseCode = "201", description = "group types created"),
-                    @ApiResponse(responseCode = "403", description = "Restricted operation"),
-                    @ApiResponse(responseCode = "400", description = "Invalid content / Missing content"),
-                    @ApiResponse(responseCode = "409", description = "group types already exist")})
+    @Operation(description = "Create GroupTypes from yaml", method = "POST", summary = "Returns created group types", responses = {
+        @ApiResponse(content = @Content(array = @ArraySchema(schema = @Schema(implementation = Response.class)))),
+        @ApiResponse(responseCode = "201", description = "group types created"),
+        @ApiResponse(responseCode = "403", description = "Restricted operation"),
+        @ApiResponse(responseCode = "400", description = "Invalid content / Missing content"),
+        @ApiResponse(responseCode = "409", description = "group types already exist")})
     @PermissionAllowed(AafPermission.PermNames.INTERNAL_ALL_VALUE)
-    public Response uploadGroupTypes(
-            @Parameter(description = "toscaTypeMetadata") @FormDataParam("toscaTypeMetadata") String toscaTypesMetaData,
-            @Parameter(description = "FileInputStream") @FormDataParam("groupTypesZip") File file,
-            @Context final HttpServletRequest request, @HeaderParam("USER_ID") String creator) {
+    public Response uploadGroupTypes(@Parameter(description = "toscaTypeMetadata") @FormDataParam("toscaTypeMetadata") String toscaTypesMetaData,
+                                     @Parameter(description = "FileInputStream") @FormDataParam("groupTypesZip") File file,
+                                     @Context final HttpServletRequest request, @HeaderParam("USER_ID") String creator) {
         Map<String, ToscaTypeMetadata> typesMetadata = getTypesMetadata(toscaTypesMetaData);
-        return uploadTypesWithMetaData(this::createGroupTypes, typesMetadata, file, request, creator,
-                NodeTypeEnum.GroupType.getName());
+        return uploadTypesWithMetaData(this::createGroupTypes, typesMetadata, file, request, creator, NodeTypeEnum.GroupType.getName());
     }
 
     @POST
     @Path("/policytypes")
-    @Operation(description = "Create PolicyTypes from yaml", method = "POST", summary = "Returns created policy types",
-            responses = {@ApiResponse(
-                    content = @Content(array = @ArraySchema(schema = @Schema(implementation = Response.class)))),
-                    @ApiResponse(responseCode = "201", description = "policy types created"),
-                    @ApiResponse(responseCode = "403", description = "Restricted operation"),
-                    @ApiResponse(responseCode = "400", description = "Invalid content / Missing content"),
-                    @ApiResponse(responseCode = "409", description = "policy types already exist")})
+    @Operation(description = "Create PolicyTypes from yaml", method = "POST", summary = "Returns created policy types", responses = {
+        @ApiResponse(content = @Content(array = @ArraySchema(schema = @Schema(implementation = Response.class)))),
+        @ApiResponse(responseCode = "201", description = "policy types created"),
+        @ApiResponse(responseCode = "403", description = "Restricted operation"),
+        @ApiResponse(responseCode = "400", description = "Invalid content / Missing content"),
+        @ApiResponse(responseCode = "409", description = "policy types already exist")})
     @PermissionAllowed(AafPermission.PermNames.INTERNAL_ALL_VALUE)
-    public Response uploadPolicyTypes(
-            @Parameter(description = "toscaTypeMetadata") @FormDataParam("toscaTypeMetadata") String toscaTypesMetaData,
-            @Parameter(description = "FileInputStream") @FormDataParam("policyTypesZip") File file,
-            @Context final HttpServletRequest request, @HeaderParam("USER_ID") String creator) {
+    public Response uploadPolicyTypes(@Parameter(description = "toscaTypeMetadata") @FormDataParam("toscaTypeMetadata") String toscaTypesMetaData,
+                                      @Parameter(description = "FileInputStream") @FormDataParam("policyTypesZip") File file,
+                                      @Context final HttpServletRequest request, @HeaderParam("USER_ID") String creator) {
         Map<String, ToscaTypeMetadata> typesMetadata = getTypesMetadata(toscaTypesMetaData);
-        return uploadTypesWithMetaData(this::createPolicyTypes, typesMetadata, file, request, creator,
-                NodeTypeEnum.PolicyType.getName());
+        return uploadTypesWithMetaData(this::createPolicyTypes, typesMetadata, file, request, creator, NodeTypeEnum.PolicyType.getName());
     }
 
     private Map<String, ToscaTypeMetadata> getTypesMetadata(String toscaTypesMetaData) {
-        return gson.fromJson(toscaTypesMetaData, new TypeToken<Map<String, ToscaTypeMetadata>>(){}.getType());
+        return gson.fromJson(toscaTypesMetaData, new TypeToken<Map<String, ToscaTypeMetadata>>() {
+        }.getType());
     }
 
-    private Response uploadElementTypeServletLogic(ConsumerTwoParam<Wrapper<Response>, String> createElementsMethod, File file, final HttpServletRequest request, String creator, String elementTypeName) {
+    private Response uploadElementTypeServletLogic(ConsumerTwoParam<Wrapper<Response>, String> createElementsMethod, File file,
+                                                   final HttpServletRequest request, String creator, String elementTypeName) {
         init();
         String userId = initHeaderParam(creator, request, Constants.USER_ID_HEADER);
         try {
             Wrapper<String> yamlStringWrapper = new Wrapper<>();
-
             String url = request.getMethod() + " " + request.getRequestURI();
             log.debug("Start handle request of {}", url);
             Wrapper<Response> responseWrapper = doUploadTypeValidations(request, userId, file);
@@ -283,23 +259,21 @@ public class TypesUploadServlet extends AbstractValidationsServlet {
     private Wrapper<Response> doUploadTypeValidations(final HttpServletRequest request, String userId, File file) {
         Wrapper<Response> responseWrapper = new Wrapper<>();
         Wrapper<User> userWrapper = new Wrapper<>();
-
         String url = request.getMethod() + " " + request.getRequestURI();
         log.debug("Start handle request of {}", url);
-
         validateUserExist(responseWrapper, userWrapper, userId);
-
         if (responseWrapper.isEmpty()) {
             validateUserRole(responseWrapper, userWrapper.getInnerElement());
         }
-
         if (responseWrapper.isEmpty()) {
             validateDataNotNull(responseWrapper, file);
         }
         return responseWrapper;
     }
 
-    private Response uploadTypesWithMetaData(ConsumerTwoParam<Wrapper<Response>, ToscaTypeImportData> createElementsMethod, Map<String, ToscaTypeMetadata> typesMetaData, File file, final HttpServletRequest request, String creator, String elementTypeName) {
+    private Response uploadTypesWithMetaData(ConsumerTwoParam<Wrapper<Response>, ToscaTypeImportData> createElementsMethod,
+                                             Map<String, ToscaTypeMetadata> typesMetaData, File file, final HttpServletRequest request,
+                                             String creator, String elementTypeName) {
         init();
         String userId = initHeaderParam(creator, request, Constants.USER_ID_HEADER);
         Wrapper<String> yamlStringWrapper = new Wrapper<>();
@@ -327,7 +301,8 @@ public class TypesUploadServlet extends AbstractValidationsServlet {
             responseWrapper.setInnerElement(response);
         } else {
             try {
-                Response response = buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.CREATED), RepresentationUtils.toRepresentation(eitherResult.left().value()));
+                Response response = buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.CREATED),
+                    RepresentationUtils.toRepresentation(eitherResult.left().value()));
                 responseWrapper.setInnerElement(response);
             } catch (Exception e) {
                 Response response = buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR));
@@ -339,32 +314,33 @@ public class TypesUploadServlet extends AbstractValidationsServlet {
 
     // data types
     private void createDataTypes(Wrapper<Response> responseWrapper, String dataTypesYml) {
-        final Supplier<Either<List<ImmutablePair<DataTypeDefinition, Boolean>>, ResponseFormat>> generateElementTypeFromYml =
-                () -> dataTypeImportManager.createDataTypes(dataTypesYml);
-        buildStatusForElementTypeCreate(responseWrapper, generateElementTypeFromYml,
-                ActionStatus.DATA_TYPE_ALREADY_EXIST, NodeTypeEnum.DataType.name());
+        final Supplier<Either<List<ImmutablePair<DataTypeDefinition, Boolean>>, ResponseFormat>> generateElementTypeFromYml = () -> dataTypeImportManager
+            .createDataTypes(dataTypesYml);
+        buildStatusForElementTypeCreate(responseWrapper, generateElementTypeFromYml, ActionStatus.DATA_TYPE_ALREADY_EXIST,
+            NodeTypeEnum.DataType.name());
     }
 
     // group types
     private void createGroupTypes(Wrapper<Response> responseWrapper, ToscaTypeImportData toscaTypeImportData) {
-        final Supplier<Either<List<ImmutablePair<GroupTypeDefinition, Boolean>>, ResponseFormat>> generateElementTypeFromYml =
-                () -> groupTypeImportManager.createGroupTypes(toscaTypeImportData);
-        buildStatusForElementTypeCreate(responseWrapper, generateElementTypeFromYml,
-                ActionStatus.GROUP_TYPE_ALREADY_EXIST, NodeTypeEnum.GroupType.name());
+        final Supplier<Either<List<ImmutablePair<GroupTypeDefinition, Boolean>>, ResponseFormat>> generateElementTypeFromYml = () -> groupTypeImportManager
+            .createGroupTypes(toscaTypeImportData);
+        buildStatusForElementTypeCreate(responseWrapper, generateElementTypeFromYml, ActionStatus.GROUP_TYPE_ALREADY_EXIST,
+            NodeTypeEnum.GroupType.name());
     }
 
     // policy types
     private void createPolicyTypes(Wrapper<Response> responseWrapper, ToscaTypeImportData toscaTypeImportData) {
-        final Supplier<Either<List<ImmutablePair<PolicyTypeDefinition, Boolean>>, ResponseFormat>> generateElementTypeFromYml =
-                () -> policyTypeImportManager.createPolicyTypes(toscaTypeImportData);
-        buildStatusForElementTypeCreate(responseWrapper, generateElementTypeFromYml,
-                ActionStatus.POLICY_TYPE_ALREADY_EXIST, NodeTypeEnum.PolicyType.name());
+        final Supplier<Either<List<ImmutablePair<PolicyTypeDefinition, Boolean>>, ResponseFormat>> generateElementTypeFromYml = () -> policyTypeImportManager
+            .createPolicyTypes(toscaTypeImportData);
+        buildStatusForElementTypeCreate(responseWrapper, generateElementTypeFromYml, ActionStatus.POLICY_TYPE_ALREADY_EXIST,
+            NodeTypeEnum.PolicyType.name());
     }
 
     // data types
-    private <ElementTypeDefinition> void buildStatusForElementTypeCreate(Wrapper<Response> responseWrapper, Supplier<Either<List<ImmutablePair<ElementTypeDefinition, Boolean>>, ResponseFormat>> generateElementTypeFromYml, ActionStatus alreadyExistStatus, String elementTypeName) {
+    private <ElementTypeDefinition> void buildStatusForElementTypeCreate(Wrapper<Response> responseWrapper,
+                                                                         Supplier<Either<List<ImmutablePair<ElementTypeDefinition, Boolean>>, ResponseFormat>> generateElementTypeFromYml,
+                                                                         ActionStatus alreadyExistStatus, String elementTypeName) {
         Either<List<ImmutablePair<ElementTypeDefinition, Boolean>>, ResponseFormat> eitherResult = generateElementTypeFromYml.get();
-
         if (eitherResult.isRight()) {
             Response response = buildErrorResponse(eitherResult.right().value());
             responseWrapper.setInnerElement(response);
@@ -374,11 +350,13 @@ public class TypesUploadServlet extends AbstractValidationsServlet {
                 List<ImmutablePair<ElementTypeDefinition, Boolean>> list = eitherResult.left().value();
                 ActionStatus status = ActionStatus.OK;
                 if (list != null) {
-
                     // Group result by the right value - true or false.
+
                     // I.e., get the number of data types which are new and
+
                     // which are old.
-                    Map<Boolean, List<ImmutablePair<ElementTypeDefinition, Boolean>>> collect = list.stream().collect(Collectors.groupingBy(ImmutablePair<ElementTypeDefinition, Boolean>::getRight));
+                    Map<Boolean, List<ImmutablePair<ElementTypeDefinition, Boolean>>> collect = list.stream()
+                        .collect(Collectors.groupingBy(ImmutablePair<ElementTypeDefinition, Boolean>::getRight));
                     if (collect != null) {
                         Set<Boolean> keySet = collect.keySet();
                         if (keySet.size() == 1) {
@@ -388,17 +366,14 @@ public class TypesUploadServlet extends AbstractValidationsServlet {
                                 status = ActionStatus.CREATED;
                             } else {
                                 // All data types already exists
-
                                 status = alreadyExistStatus;
                             }
                         }
                     }
                 }
                 representation = RepresentationUtils.toRepresentation(eitherResult.left().value());
-
                 Response response = buildOkResponse(getComponentsUtils().getResponseFormat(status), representation);
                 responseWrapper.setInnerElement(response);
-
             } catch (IOException e) {
                 BeEcompErrorManager.getInstance().logBeRestApiGeneralError(CREATE + elementTypeName);
                 log.debug("failed to convert {} to json", elementTypeName, e);
@@ -407,12 +382,12 @@ public class TypesUploadServlet extends AbstractValidationsServlet {
             }
         }
     }
+
     // relationship types
     private void createRelationshipTypes(Wrapper<Response> responseWrapper, String relationshipTypesYml) {
-        final Supplier<Either<List<ImmutablePair<RelationshipTypeDefinition, Boolean>>, ResponseFormat>>
-                generateElementTypeFromYml =
-                () -> relationshipTypeImportManager.createRelationshipTypes(relationshipTypesYml);
-        buildStatusForElementTypeCreate(responseWrapper, generateElementTypeFromYml,
-                ActionStatus.RELATIONSHIP_TYPE_ALREADY_EXIST, NodeTypeEnum.RelationshipType.name());
+        final Supplier<Either<List<ImmutablePair<RelationshipTypeDefinition, Boolean>>, ResponseFormat>> generateElementTypeFromYml = () -> relationshipTypeImportManager
+            .createRelationshipTypes(relationshipTypesYml);
+        buildStatusForElementTypeCreate(responseWrapper, generateElementTypeFromYml, ActionStatus.RELATIONSHIP_TYPE_ALREADY_EXIST,
+            NodeTypeEnum.RelationshipType.name());
     }
 }
index 1cd9844..84a88f3 100644 (file)
@@ -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.
@@ -17,7 +17,6 @@
  * limitations under the License.
  * ============LICENSE_END=========================================================
  */
-
 package org.openecomp.sdc.be.servlets;
 
 import com.jcabi.aspects.Loggable;
@@ -31,18 +30,10 @@ import io.swagger.v3.oas.annotations.servers.Server;
 import io.swagger.v3.oas.annotations.servers.Servers;
 import io.swagger.v3.oas.annotations.tags.Tag;
 import io.swagger.v3.oas.annotations.tags.Tags;
-import org.eclipse.jetty.http.HttpStatus;
-import org.openecomp.sdc.be.components.impl.aaf.AafPermission;
-import org.openecomp.sdc.be.components.impl.aaf.PermissionAllowed;
-import org.openecomp.sdc.be.impl.ComponentsUtils;
-import org.openecomp.sdc.be.model.User;
-import org.openecomp.sdc.be.user.Role;
-import org.openecomp.sdc.be.user.UserBusinessLogic;
-import org.openecomp.sdc.be.user.UserBusinessLogicExt;
-import org.openecomp.sdc.common.api.Constants;
-import org.openecomp.sdc.common.log.wrappers.Logger;
-import org.springframework.stereotype.Controller;
-
+import java.io.UnsupportedEncodingException;
+import java.net.URLDecoder;
+import java.util.ArrayList;
+import java.util.List;
 import javax.servlet.http.HttpServletRequest;
 import javax.ws.rs.Consumes;
 import javax.ws.rs.DELETE;
@@ -56,10 +47,18 @@ import javax.ws.rs.QueryParam;
 import javax.ws.rs.core.Context;
 import javax.ws.rs.core.MediaType;
 import javax.ws.rs.core.Response;
-import java.io.UnsupportedEncodingException;
-import java.net.URLDecoder;
-import java.util.ArrayList;
-import java.util.List;
+import org.eclipse.jetty.http.HttpStatus;
+import org.openecomp.sdc.be.components.impl.aaf.AafPermission;
+import org.openecomp.sdc.be.components.impl.aaf.PermissionAllowed;
+import org.openecomp.sdc.be.impl.ComponentsUtils;
+import org.openecomp.sdc.be.model.User;
+import org.openecomp.sdc.be.user.Role;
+import org.openecomp.sdc.be.user.UserBusinessLogic;
+import org.openecomp.sdc.be.user.UserBusinessLogicExt;
+import org.openecomp.sdc.common.api.Constants;
+import org.openecomp.sdc.common.log.wrappers.Logger;
+import org.springframework.stereotype.Controller;
+
 @Loggable(prepend = true, value = Loggable.DEBUG, trim = false)
 @Path("/v1/user")
 @Tags({@Tag(name = "SDC Internal APIs")})
@@ -68,140 +67,105 @@ import java.util.List;
 public class UserAdminServlet extends BeGenericServlet {
 
     private static final String UTF_8 = "UTF-8";
-       private static final String ROLE_DELIMITER = ",";
+    private static final String ROLE_DELIMITER = ",";
     private static final Logger log = Logger.getLogger(UserAdminServlet.class);
     private final UserBusinessLogic userBusinessLogic;
     private final UserBusinessLogicExt userBusinessLogicExt;
 
-    static class UserRole {
-        Role role;
-
-        public Role getRole() {
-            return role;
-        }
-
-        public void setRole(Role role) {
-            this.role = role;
-        }
-
-    }
-
-    UserAdminServlet(UserBusinessLogic userBusinessLogic,
-                     ComponentsUtils componentsUtils, UserBusinessLogicExt userBusinessLogicExt) {
+    UserAdminServlet(UserBusinessLogic userBusinessLogic, ComponentsUtils componentsUtils, UserBusinessLogicExt userBusinessLogicExt) {
         super(userBusinessLogic, componentsUtils);
         this.userBusinessLogic = userBusinessLogic;
         this.userBusinessLogicExt = userBusinessLogicExt;
     }
 
-    /////////////////////////////////////////////////////////////////////////////////////////////////////
     // retrieve all user details
     @GET
     @Path("/{userId}")
     @Consumes(MediaType.APPLICATION_JSON)
     @Produces(MediaType.APPLICATION_JSON)
-
-    @Operation(description = "retrieve user details", method = "GET",
-            summary = "Returns user details according to userId",responses = {
-            @ApiResponse(content = @Content(array = @ArraySchema(schema = @Schema(implementation = User.class)))),
-            @ApiResponse(responseCode = "200", description = "Returns user Ok"),
-            @ApiResponse(responseCode = "404", description = "User not found"),
-            @ApiResponse(responseCode = "405", description = "Method Not Allowed"),
-            @ApiResponse(responseCode = "500", description = "Internal Server Error")
-    })
+    @Operation(description = "retrieve user details", method = "GET", summary = "Returns user details according to userId", responses = {
+        @ApiResponse(content = @Content(array = @ArraySchema(schema = @Schema(implementation = User.class)))),
+        @ApiResponse(responseCode = "200", description = "Returns user Ok"), @ApiResponse(responseCode = "404", description = "User not found"),
+        @ApiResponse(responseCode = "405", description = "Method Not Allowed"),
+        @ApiResponse(responseCode = "500", description = "Internal Server Error")})
     @PermissionAllowed(AafPermission.PermNames.INTERNAL_ALL_VALUE)
-    public User get(
-        @Parameter(description = "userId of user to get", required = true) @PathParam("userId") final String userId,
-        @Context final HttpServletRequest request) {
+    public User get(@Parameter(description = "userId of user to get", required = true) @PathParam("userId") final String userId,
+                    @Context final HttpServletRequest request) {
         return userBusinessLogic.getUser(userId, false);
     }
+    /////////////////////////////////////////////////////////////////////////////////////////////////////
 
     @GET
     @Path("/{userId}/role")
     @Consumes(MediaType.APPLICATION_JSON)
     @Produces(MediaType.APPLICATION_JSON)
     @Operation(description = "retrieve user role", summary = "Returns user role according to userId", responses = {
-            @ApiResponse(content = @Content(array = @ArraySchema(schema = @Schema(implementation = String.class)))),
-            @ApiResponse(responseCode = "200", description = "Returns user role Ok"),
-            @ApiResponse(responseCode = "404", description = "User not found"),
-            @ApiResponse(responseCode = "405", description = "Method Not Allowed"),
-            @ApiResponse(responseCode = "500", description = "Internal Server Error")})
+        @ApiResponse(content = @Content(array = @ArraySchema(schema = @Schema(implementation = String.class)))),
+        @ApiResponse(responseCode = "200", description = "Returns user role Ok"), @ApiResponse(responseCode = "404", description = "User not found"),
+        @ApiResponse(responseCode = "405", description = "Method Not Allowed"),
+        @ApiResponse(responseCode = "500", description = "Internal Server Error")})
     @PermissionAllowed(AafPermission.PermNames.INTERNAL_ALL_VALUE)
-    public String getRole(
-        @Parameter(description = "userId of user to get", required = true) @PathParam("userId") final String userId,
-        @Context final HttpServletRequest request) {
+    public String getRole(@Parameter(description = "userId of user to get", required = true) @PathParam("userId") final String userId,
+                          @Context final HttpServletRequest request) {
         User user = userBusinessLogic.getUser(userId, false);
         return "{ \"role\" : \"" + user.getRole() + "\" }";
     }
 
-    /////////////////////////////////////////////////////////////////////////////////////////////////////
     // update user role
     @POST
     @Path("/{userId}/role")
     @Consumes(MediaType.APPLICATION_JSON)
     @Produces(MediaType.APPLICATION_JSON)
     @Operation(description = "update user role", summary = "Update user role", responses = {
-            @ApiResponse(content = @Content(array = @ArraySchema(schema = @Schema(implementation = User.class)))),
-            @ApiResponse(responseCode = "200", description = "Update user OK"),
-            @ApiResponse(responseCode = "400", description = "Invalid Content."),
-            @ApiResponse(responseCode = "403", description = "Missing information/Restricted operation"),
-            @ApiResponse(responseCode = "404", description = "User not found"),
-            @ApiResponse(responseCode = "405", description = "Method Not Allowed"),
-            @ApiResponse(responseCode = "409", description = "User already exists"),
-            @ApiResponse(responseCode = "500", description = "Internal Server Error")})
+        @ApiResponse(content = @Content(array = @ArraySchema(schema = @Schema(implementation = User.class)))),
+        @ApiResponse(responseCode = "200", description = "Update user OK"), @ApiResponse(responseCode = "400", description = "Invalid Content."),
+        @ApiResponse(responseCode = "403", description = "Missing information/Restricted operation"),
+        @ApiResponse(responseCode = "404", description = "User not found"), @ApiResponse(responseCode = "405", description = "Method Not Allowed"),
+        @ApiResponse(responseCode = "409", description = "User already exists"),
+        @ApiResponse(responseCode = "500", description = "Internal Server Error")})
     @PermissionAllowed(AafPermission.PermNames.INTERNAL_ALL_VALUE)
-    public User updateUserRole(
-            @Parameter(description = "userId of user to get",
-            required = true) @PathParam("userId") final String userIdUpdateUser,
-            @Context final HttpServletRequest request,
-            @Parameter(description = "json describe the update role", required = true) UserRole newRole,
-            @HeaderParam(value = Constants.USER_ID_HEADER) String modifierUserId) {
-
+    public User updateUserRole(@Parameter(description = "userId of user to get", required = true) @PathParam("userId") final String userIdUpdateUser,
+                               @Context final HttpServletRequest request,
+                               @Parameter(description = "json describe the update role", required = true) UserRole newRole,
+                               @HeaderParam(value = Constants.USER_ID_HEADER) String modifierUserId) {
         return userBusinessLogic.updateUserRole(modifierUserId, userIdUpdateUser, newRole.getRole().name());
     }
+    /////////////////////////////////////////////////////////////////////////////////////////////////////
 
     @POST
     @Consumes(MediaType.APPLICATION_JSON)
     @Produces(MediaType.APPLICATION_JSON)
     @Operation(description = "add user", method = "POST", summary = "Provision new user", responses = {
-            @ApiResponse(content = @Content(array = @ArraySchema(schema = @Schema(implementation = User.class)))),
-            @ApiResponse(responseCode = "201", description = "New user created"),
-            @ApiResponse(responseCode = "400", description = "Invalid Content."),
-            @ApiResponse(responseCode = "403", description = "Missing information"),
-            @ApiResponse(responseCode = "405", description = "Method Not Allowed"),
-            @ApiResponse(responseCode = "409", description = "User already exists"),
-            @ApiResponse(responseCode = "500", description = "Internal Server Error")})
+        @ApiResponse(content = @Content(array = @ArraySchema(schema = @Schema(implementation = User.class)))),
+        @ApiResponse(responseCode = "201", description = "New user created"), @ApiResponse(responseCode = "400", description = "Invalid Content."),
+        @ApiResponse(responseCode = "403", description = "Missing information"),
+        @ApiResponse(responseCode = "405", description = "Method Not Allowed"),
+        @ApiResponse(responseCode = "409", description = "User already exists"),
+        @ApiResponse(responseCode = "500", description = "Internal Server Error")})
     public Response createUser(@Context final HttpServletRequest request,
-            @Parameter(description = "json describe the user", required = true) User newUser,
-            @HeaderParam(value = Constants.USER_ID_HEADER) String modifierAttId) {
-
+                               @Parameter(description = "json describe the user", required = true) User newUser,
+                               @HeaderParam(value = Constants.USER_ID_HEADER) String modifierAttId) {
         log.debug("modifier id is {}", modifierAttId);
         User user = userBusinessLogic.createUser(modifierAttId, newUser);
-        return Response.status(HttpStatus.CREATED_201)
-                .entity(user)
-                .build();
+        return Response.status(HttpStatus.CREATED_201).entity(user).build();
     }
 
     @GET
     @Path("/authorize")
     @Consumes(MediaType.APPLICATION_JSON)
     @Produces(MediaType.APPLICATION_JSON)
-
     @Operation(description = "authorize", summary = "authorize user", responses = {
-            @ApiResponse(content = @Content(array = @ArraySchema(schema = @Schema(implementation = User.class)))),
-            @ApiResponse(responseCode = "200", description = "Returns user Ok"),
-            @ApiResponse(responseCode = "403", description = "Restricted Access"),
-            @ApiResponse(responseCode = "500", description = "Internal Server Error")})
+        @ApiResponse(content = @Content(array = @ArraySchema(schema = @Schema(implementation = User.class)))),
+        @ApiResponse(responseCode = "200", description = "Returns user Ok"), @ApiResponse(responseCode = "403", description = "Restricted Access"),
+        @ApiResponse(responseCode = "500", description = "Internal Server Error")})
     @PermissionAllowed(AafPermission.PermNames.INTERNAL_ALL_VALUE)
-    public User authorize(@HeaderParam(value = Constants.USER_ID_HEADER) String userId,
-                          @HeaderParam("HTTP_CSP_FIRSTNAME") String firstName,
-                          @HeaderParam("HTTP_CSP_LASTNAME") String lastName,
-            @HeaderParam("HTTP_CSP_EMAIL") String email) throws UnsupportedEncodingException {
-
+    public User authorize(@HeaderParam(value = Constants.USER_ID_HEADER) String userId, @HeaderParam("HTTP_CSP_FIRSTNAME") String firstName,
+                          @HeaderParam("HTTP_CSP_LASTNAME") String lastName, @HeaderParam("HTTP_CSP_EMAIL") String email)
+        throws UnsupportedEncodingException {
         userId = userId != null ? URLDecoder.decode(userId, UTF_8) : null;
         firstName = firstName != null ? URLDecoder.decode(firstName, UTF_8) : null;
         lastName = lastName != null ? URLDecoder.decode(lastName, UTF_8) : null;
         email = email != null ? URLDecoder.decode(email, UTF_8) : null;
-
         User authUser = new User();
         authUser.setUserId(userId);
         authUser.setFirstName(firstName);
@@ -214,12 +178,10 @@ public class UserAdminServlet extends BeGenericServlet {
     @Path("/admins")
     @Consumes(MediaType.APPLICATION_JSON)
     @Produces(MediaType.APPLICATION_JSON)
-    @Operation(description = "retrieve all administrators", method = "GET", summary = "Returns all administrators",
-            responses = {@ApiResponse(
-                    content = @Content(array = @ArraySchema(schema = @Schema(implementation = User.class)))),
-                    @ApiResponse(responseCode = "200", description = "Returns user Ok"),
-                    @ApiResponse(responseCode = "405", description = "Method Not Allowed"),
-                    @ApiResponse(responseCode = "500", description = "Internal Server Error")})
+    @Operation(description = "retrieve all administrators", method = "GET", summary = "Returns all administrators", responses = {
+        @ApiResponse(content = @Content(array = @ArraySchema(schema = @Schema(implementation = User.class)))),
+        @ApiResponse(responseCode = "200", description = "Returns user Ok"), @ApiResponse(responseCode = "405", description = "Method Not Allowed"),
+        @ApiResponse(responseCode = "500", description = "Internal Server Error")})
     @PermissionAllowed(AafPermission.PermNames.INTERNAL_ALL_VALUE)
     public List<User> getAdminsUser(@Context final HttpServletRequest request) {
         return userBusinessLogic.getAllAdminUsers();
@@ -229,24 +191,17 @@ public class UserAdminServlet extends BeGenericServlet {
     @Path("/users")
     @Consumes(MediaType.APPLICATION_JSON)
     @Produces(MediaType.APPLICATION_JSON)
-    @Operation(description = "Retrieve the list of all active ASDC users or only group of users having specific roles.",
-            method = "GET",
-            summary = "Returns list of users with the specified roles, or all of users in the case of empty 'roles' header",
-            responses = {@ApiResponse(
-                    content = @Content(array = @ArraySchema(schema = @Schema(implementation = User.class)))),
-                    @ApiResponse(responseCode = "200", description = "Returns users Ok"),
-                    @ApiResponse(responseCode = "204", description = "No provisioned ASDC users of requested role"),
-                    @ApiResponse(responseCode = "403", description = "Restricted Access"),
-                    @ApiResponse(responseCode = "400", description = "Missing content"),
-                    @ApiResponse(responseCode = "500", description = "Internal Server Error")})
-    public List<User> getUsersList(@Context final HttpServletRequest request, @Parameter(
-            description = "Any active user's USER_ID ") @HeaderParam(Constants.USER_ID_HEADER) final String userId,
-            @Parameter(
-                    description = "TESTER,DESIGNER,PRODUCT_STRATEGIST,OPS,PRODUCT_MANAGER,GOVERNOR, ADMIN OR all users by not typing anything") @QueryParam("roles") final String roles) {
-
+    @Operation(description = "Retrieve the list of all active ASDC users or only group of users having specific roles.", method = "GET", summary = "Returns list of users with the specified roles, or all of users in the case of empty 'roles' header", responses = {
+        @ApiResponse(content = @Content(array = @ArraySchema(schema = @Schema(implementation = User.class)))),
+        @ApiResponse(responseCode = "200", description = "Returns users Ok"),
+        @ApiResponse(responseCode = "204", description = "No provisioned ASDC users of requested role"),
+        @ApiResponse(responseCode = "403", description = "Restricted Access"), @ApiResponse(responseCode = "400", description = "Missing content"),
+        @ApiResponse(responseCode = "500", description = "Internal Server Error")})
+    public List<User> getUsersList(@Context final HttpServletRequest request,
+                                   @Parameter(description = "Any active user's USER_ID ") @HeaderParam(Constants.USER_ID_HEADER) final String userId,
+                                   @Parameter(description = "TESTER,DESIGNER,PRODUCT_STRATEGIST,OPS,PRODUCT_MANAGER,GOVERNOR, ADMIN OR all users by not typing anything") @QueryParam("roles") final String roles) {
         String url = request.getMethod() + " " + request.getRequestURI();
         log.debug("Start handle request of {} modifier id is {}", url, userId);
-
         List<String> rolesList = new ArrayList<>();
         if (roles != null && !roles.trim().isEmpty()) {
             String[] rolesArr = roles.split(ROLE_DELIMITER);
@@ -262,19 +217,28 @@ public class UserAdminServlet extends BeGenericServlet {
     @Consumes(MediaType.APPLICATION_JSON)
     @Produces(MediaType.APPLICATION_JSON)
     @Operation(description = "delete user", summary = "Delete user", responses = {
-            @ApiResponse(content = @Content(array = @ArraySchema(schema = @Schema(implementation = User.class)))),
-            @ApiResponse(responseCode = "200", description = "Update deleted OK"),
-            @ApiResponse(responseCode = "400", description = "Invalid Content."),
-            @ApiResponse(responseCode = "403", description = "Missing information"),
-            @ApiResponse(responseCode = "404", description = "User not found"),
-            @ApiResponse(responseCode = "405", description = "Method Not Allowed"),
-            @ApiResponse(responseCode = "409", description = "Restricted operation"),
-            @ApiResponse(responseCode = "500", description = "Internal Server Error")})
+        @ApiResponse(content = @Content(array = @ArraySchema(schema = @Schema(implementation = User.class)))),
+        @ApiResponse(responseCode = "200", description = "Update deleted OK"), @ApiResponse(responseCode = "400", description = "Invalid Content."),
+        @ApiResponse(responseCode = "403", description = "Missing information"), @ApiResponse(responseCode = "404", description = "User not found"),
+        @ApiResponse(responseCode = "405", description = "Method Not Allowed"),
+        @ApiResponse(responseCode = "409", description = "Restricted operation"),
+        @ApiResponse(responseCode = "500", description = "Internal Server Error")})
     @PermissionAllowed(AafPermission.PermNames.INTERNAL_ALL_VALUE)
-    public User deActivateUser(
-            @Parameter(description = "userId of user to get", required = true) @PathParam("userId") final String userId,
-            @Context final HttpServletRequest request,
-            @HeaderParam(value = Constants.USER_ID_HEADER) String modifierId) {
+    public User deActivateUser(@Parameter(description = "userId of user to get", required = true) @PathParam("userId") final String userId,
+                               @Context final HttpServletRequest request, @HeaderParam(value = Constants.USER_ID_HEADER) String modifierId) {
         return userBusinessLogicExt.deActivateUser(modifierId, userId);
     }
+
+    static class UserRole {
+
+        Role role;
+
+        public Role getRole() {
+            return role;
+        }
+
+        public void setRole(Role role) {
+            this.role = role;
+        }
+    }
 }
index 72b2362..4b12b95 100644 (file)
@@ -23,6 +23,11 @@ package org.openecomp.sdc.be.servlets.exception;
 
 import com.google.gson.Gson;
 import com.google.gson.GsonBuilder;
+import java.io.IOException;
+import javax.servlet.http.HttpServletResponse;
+import javax.ws.rs.core.Response;
+import javax.ws.rs.ext.ExceptionMapper;
+import javax.ws.rs.ext.Provider;
 import org.onap.sdc.security.RepresentationUtils;
 import org.openecomp.sdc.be.components.impl.ResponseFormatManager;
 import org.openecomp.sdc.be.components.impl.exceptions.ComponentException;
@@ -31,12 +36,6 @@ import org.openecomp.sdc.common.log.wrappers.Logger;
 import org.openecomp.sdc.exception.ResponseFormat;
 import org.springframework.stereotype.Component;
 
-import javax.servlet.http.HttpServletResponse;
-import javax.ws.rs.core.Response;
-import javax.ws.rs.ext.ExceptionMapper;
-import javax.ws.rs.ext.Provider;
-import java.io.IOException;
-
 @Component
 @Provider
 public class ComponentExceptionMapper implements ExceptionMapper<ComponentException> {
@@ -54,28 +53,22 @@ public class ComponentExceptionMapper implements ExceptionMapper<ComponentExcept
         // TODO log this? BeEcompErrorManager.getInstance().logBeRestApiGeneralError(requestURI);
         log.debug("#toResponse - An error occurred: ", exception);
         ResponseFormat responseFormat = exception.getResponseFormat();
-        if (exception.getResponseFormat()==null) {
+        if (exception.getResponseFormat() == null) {
             if (exception.getResource() == null) {
                 responseFormat = componentsUtils.getResponseFormat(exception.getActionStatus(), exception.getParams());
-            }
-            else {
+            } else {
                 responseFormat = componentsUtils.getResponseFormatByResource(exception.getActionStatus(), exception.getResource());
             }
         }
-
-        return Response.status(responseFormat.getStatus())
-                .entity(gson.toJson(responseFormat.getRequestError()))
-                .build();
+        return Response.status(responseFormat.getStatus()).entity(gson.toJson(responseFormat.getRequestError())).build();
     }
 
     public void writeToResponse(ComponentException ce, HttpServletResponse httpResponse) throws IOException {
         log.info("Error during request filter= {}", ce.getActionStatus());
-        ResponseFormat responseFormat = ResponseFormatManager.getInstance()
-                .getResponseFormat(ce.getActionStatus(), ce.getParams());
+        ResponseFormat responseFormat = ResponseFormatManager.getInstance().getResponseFormat(ce.getActionStatus(), ce.getParams());
         httpResponse.setStatus(responseFormat.getStatus());
         httpResponse.setContentType("application/json");
         httpResponse.setCharacterEncoding("UTF-8");
         httpResponse.getWriter().write(RepresentationUtils.toRepresentation(responseFormat.getRequestError()));
     }
-
 }
index 516ab5d..23c75a3 100644 (file)
  * limitations under the License.
  * ============LICENSE_END=========================================================
  */
-
 package org.openecomp.sdc.be.servlets.exception;
 
-import org.openecomp.sdc.be.config.ErrorInfo;
-import org.springframework.stereotype.Component;
+import static javax.ws.rs.core.Response.Status.BAD_REQUEST;
 
+import java.util.Set;
 import javax.validation.ConstraintViolation;
 import javax.validation.ConstraintViolationException;
 import javax.ws.rs.core.Response;
 import javax.ws.rs.ext.ExceptionMapper;
 import javax.ws.rs.ext.Provider;
-import java.util.Set;
-
-import static javax.ws.rs.core.Response.Status.BAD_REQUEST;
+import org.openecomp.sdc.be.config.ErrorInfo;
+import org.springframework.stereotype.Component;
 
 @Component
 @Provider
@@ -42,8 +40,6 @@ public class ConstraintViolationExceptionMapper implements ExceptionMapper<Const
         ErrorInfo error = new ErrorInfo();
         error.setCode(500);
         error.setMessage(constraintViolations.toString());
-        return Response.status(BAD_REQUEST)
-                .entity(error)
-                .build();
+        return Response.status(BAD_REQUEST).entity(error).build();
     }
 }
index 1b8bf8f..6b161f9 100644 (file)
@@ -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.
  * limitations under the License.
  * ============LICENSE_END=========================================================
  */
-
 package org.openecomp.sdc.be.servlets.exception;
 
-import org.eclipse.jetty.http.HttpStatus;
-import org.openecomp.sdc.common.log.wrappers.Logger;
-import org.springframework.stereotype.Component;
-
 import javax.ws.rs.core.Response;
 import javax.ws.rs.ext.ExceptionMapper;
 import javax.ws.rs.ext.Provider;
+import org.eclipse.jetty.http.HttpStatus;
+import org.openecomp.sdc.common.log.wrappers.Logger;
+import org.springframework.stereotype.Component;
 
 @Component
 @Provider
@@ -37,8 +35,6 @@ public class DefaultExceptionMapper implements ExceptionMapper<Exception> {
     @Override
     public Response toResponse(Exception exception) {
         log.debug("#toResponse - An error occurred: ", exception);
-        return Response.status(HttpStatus.INTERNAL_SERVER_ERROR_500)
-                .entity(exception.getMessage())
-                .build();
+        return Response.status(HttpStatus.INTERNAL_SERVER_ERROR_500).entity(exception.getMessage()).build();
     }
 }
index cc90ecf..320839a 100644 (file)
  * limitations under the License.
  * ============LICENSE_END=========================================================
  */
-
 package org.openecomp.sdc.be.servlets.exception;
 
-
 import com.google.gson.Gson;
 import com.google.gson.GsonBuilder;
+import javax.ws.rs.core.Response;
+import javax.ws.rs.ext.ExceptionMapper;
+import javax.ws.rs.ext.Provider;
 import org.openecomp.sdc.be.impl.ComponentsUtils;
 import org.openecomp.sdc.be.model.tosca.constraints.exception.PropertyConstraintException;
 import org.openecomp.sdc.common.log.wrappers.Logger;
 import org.openecomp.sdc.exception.ResponseFormat;
 import org.springframework.stereotype.Component;
 
-import javax.ws.rs.core.Response;
-import javax.ws.rs.ext.ExceptionMapper;
-import javax.ws.rs.ext.Provider;
-
 @Component
 @Provider
-public class PropertyConstraintExceptionMapper implements ExceptionMapper<PropertyConstraintException>  {
+public class PropertyConstraintExceptionMapper implements ExceptionMapper<PropertyConstraintException> {
 
     private static final Logger log = Logger.getLogger(PropertyConstraintExceptionMapper.class);
     private final Gson gson = new GsonBuilder().setPrettyPrinting().create();
@@ -49,9 +46,6 @@ public class PropertyConstraintExceptionMapper implements ExceptionMapper<Proper
     public Response toResponse(PropertyConstraintException exception) {
         log.debug("#toResponse - An error occurred: ", exception);
         ResponseFormat responseFormat = componentsUtils.getResponseFormat(exception.getActionStatus(), exception.getParams());
-        return Response.status(responseFormat.getStatus())
-                .entity(gson.toJson(responseFormat.getRequestError()))
-                .build();
+        return Response.status(responseFormat.getStatus()).entity(gson.toJson(responseFormat.getRequestError())).build();
     }
-
 }
index 40355f2..18e5a15 100644 (file)
@@ -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.
  * limitations under the License.
  * ============LICENSE_END=========================================================
  */
-
 package org.openecomp.sdc.be.servlets.exception;
 
-
 import com.google.gson.Gson;
 import com.google.gson.GsonBuilder;
+import javax.ws.rs.core.Response;
+import javax.ws.rs.ext.ExceptionMapper;
+import javax.ws.rs.ext.Provider;
 import org.openecomp.sdc.be.dao.api.ActionStatus;
 import org.openecomp.sdc.be.impl.ComponentsUtils;
 import org.openecomp.sdc.be.model.operations.StorageException;
@@ -30,13 +31,9 @@ import org.openecomp.sdc.common.log.wrappers.Logger;
 import org.openecomp.sdc.exception.ResponseFormat;
 import org.springframework.stereotype.Component;
 
-import javax.ws.rs.core.Response;
-import javax.ws.rs.ext.ExceptionMapper;
-import javax.ws.rs.ext.Provider;
-
 @Component
 @Provider
-public class StorageExceptionMapper implements ExceptionMapper<StorageException>  {
+public class StorageExceptionMapper implements ExceptionMapper<StorageException> {
 
     private static final Logger log = Logger.getLogger(DefaultExceptionMapper.class);
     private final Gson gson = new GsonBuilder().setPrettyPrinting().create();
@@ -51,9 +48,6 @@ public class StorageExceptionMapper implements ExceptionMapper<StorageException>
         log.debug("#toResponse - An error occurred: ", exception);
         ActionStatus actionStatus = componentsUtils.convertFromStorageResponse(exception.getStorageOperationStatus());
         ResponseFormat responseFormat = componentsUtils.getResponseFormat(actionStatus, exception.getParams());
-        return Response.status(responseFormat.getStatus())
-                .entity(gson.toJson(responseFormat.getRequestError()))
-                .build();
+        return Response.status(responseFormat.getStatus()).entity(gson.toJson(responseFormat.getRequestError())).build();
     }
-
 }
index fec00d2..b5a4be4 100644 (file)
@@ -17,7 +17,6 @@
  * limitations under the License.
  * ============LICENSE_END=========================================================
  */
-
 package org.openecomp.sdc.be.switchover.detector;
 
 import com.google.common.annotations.VisibleForTesting;
@@ -39,41 +38,86 @@ import org.openecomp.sdc.common.http.client.api.HttpRequest;
 import org.openecomp.sdc.common.log.wrappers.Logger;
 import org.springframework.stereotype.Component;
 
-
 @Component("switchover-detector")
 public class SwitchoverDetector {
 
     private static final String SWITCHOVER_DETECTOR_LOG_CONTEXT = "switchover.detector";
-
+    private static final Logger logger = Logger.getLogger(SwitchoverDetector.class);
+    ScheduledExecutorService switchoverDetectorScheduler = Executors
+        .newSingleThreadScheduledExecutor(runnable -> new Thread(runnable, "Switchover-Detector-Task"));
+    SwitchoverDetectorScheduledTask switchoverDetectorScheduledTask = null;
     private SwitchoverDetectorConfig switchoverDetectorConfig;
-
     private Properties authHeader = null;
-
     private long detectorInterval = 60;
-
     private int maxBeQueryAttempts = 3;
-
     private int maxFeQueryAttempts = 3;
-
     private Boolean beMatch = null;
-
     private Boolean feMatch = null;
+    private volatile String siteMode = SwitchoverDetectorState.UNKNOWN.getState();
+    private ScheduledFuture<?> scheduledFuture = null;
 
-    private static final Logger logger = Logger.getLogger(SwitchoverDetector.class);
+    public String getSiteMode() {
+        return siteMode;
+    }
 
-    private volatile String siteMode = SwitchoverDetectorState.UNKNOWN.getState();
+    public void setSiteMode(String mode) {
+        this.siteMode = mode;
+    }
 
-    private ScheduledFuture<?> scheduledFuture = null;
+    @VisibleForTesting
+    void setSwitchoverDetectorConfig(SwitchoverDetectorConfig switchoverDetectorConfig) {
+        this.switchoverDetectorConfig = switchoverDetectorConfig;
+    }
 
-    ScheduledExecutorService switchoverDetectorScheduler =
-            Executors.newSingleThreadScheduledExecutor(runnable -> new Thread(runnable, "Switchover-Detector-Task"));
+    @PostConstruct
+    private void init() {
+        logger.info("Enter init method of SwitchoverDetector");
+        switchoverDetectorConfig = ConfigurationManager.getConfigurationManager().getConfiguration().getSwitchoverDetector();
+        if (!switchoverDetectorConfig.getEnabled()) {
+            logger.info("switchover detector service is disabled");
+            return;
+        }
+        Long detectorIntervalConfig = switchoverDetectorConfig.getInterval();
+        if (detectorIntervalConfig != null) {
+            detectorInterval = detectorIntervalConfig;
+        }
+        Integer maxAttempts = switchoverDetectorConfig.getBeResolveAttempts();
+        if (maxAttempts != null) {
+            maxBeQueryAttempts = maxAttempts;
+        }
+        maxAttempts = switchoverDetectorConfig.getFeResolveAttempts();
+        if (maxAttempts != null) {
+            maxFeQueryAttempts = maxAttempts;
+        }
+        logger.info("switchover detector service is enabled, interval is {} seconds", detectorInterval);
+        this.switchoverDetectorScheduledTask = new SwitchoverDetectorScheduledTask();
+        startSwitchoverDetectorTask();
+        logger.trace("Exit init method of SwitchoverDetector");
+    }
 
-    SwitchoverDetectorScheduledTask switchoverDetectorScheduledTask = null;
+    @PreDestroy
+    private void destroy() {
+        if (scheduledFuture != null) {
+            scheduledFuture.cancel(true);
+            scheduledFuture = null;
+        }
+        if (switchoverDetectorScheduler != null) {
+            switchoverDetectorScheduler.shutdown();
+        }
+    }
 
-    public enum SwitchoverDetectorState {
+    /**
+     * This method starts the switchover detector threads in the background.
+     */
+    public void startSwitchoverDetectorTask() {
+        if (this.scheduledFuture == null) {
+            this.scheduledFuture = this.switchoverDetectorScheduler
+                .scheduleAtFixedRate(switchoverDetectorScheduledTask, 0, detectorInterval, TimeUnit.SECONDS);
+        }
+    }
 
+    public enum SwitchoverDetectorState {
         UNKNOWN("unknown"), ACTIVE("active"), STANDBY("standby");
-
         private String state;
 
         SwitchoverDetectorState(String state) {
@@ -86,9 +130,7 @@ public class SwitchoverDetector {
     }
 
     public enum SwitchoverDetectorGroup {
-
         BE_SET("beSet"), FE_SET("feSet");
-
         private String group;
 
         SwitchoverDetectorGroup(String group) {
@@ -100,26 +142,18 @@ public class SwitchoverDetector {
         }
     }
 
-    public String getSiteMode() {
-        return siteMode;
-    }
-
-    public void setSiteMode(String mode) {
-        this.siteMode = mode;
-    }
-
     public class SwitchoverDetectorScheduledTask implements Runnable {
 
-        private Boolean queryGss(String fqdn, String vip, int maxAttempts) {
+        ExecutorService switchoverDetectorExecutor = Executors
+            .newSingleThreadExecutor(runnable -> new Thread(runnable, "Switchover-Detector-Thread"));
 
+        private Boolean queryGss(String fqdn, String vip, int maxAttempts) {
             Boolean result = null;
             int attempts = 0;
-
             while (result == null && (++attempts < maxAttempts)) {
                 try {
                     InetAddress inetAddress = InetAddress.getByName(fqdn);
                     result = inetAddress.getHostAddress().equals(vip);
-
                 } catch (Exception e) {
                     String message = e.getMessage();
                     if (message == null) {
@@ -129,28 +163,24 @@ public class SwitchoverDetector {
                 }
             }
             if (null == result) {
-                BeEcompErrorManager.getInstance().logFqdnResolveError(SWITCHOVER_DETECTOR_LOG_CONTEXT,
-                        "host " + fqdn + " not resolved after " + attempts + " attempts");
+                BeEcompErrorManager.getInstance()
+                    .logFqdnResolveError(SWITCHOVER_DETECTOR_LOG_CONTEXT, "host " + fqdn + " not resolved after " + attempts + " attempts");
             }
             return result;
         }
 
         private Boolean queryBe() {
-            return queryGss(switchoverDetectorConfig.getgBeFqdn(), switchoverDetectorConfig.getBeVip(),
-                    maxBeQueryAttempts);
+            return queryGss(switchoverDetectorConfig.getgBeFqdn(), switchoverDetectorConfig.getBeVip(), maxBeQueryAttempts);
         }
 
         private Boolean queryFe() {
-            return queryGss(switchoverDetectorConfig.getgFeFqdn(), switchoverDetectorConfig.getFeVip(),
-                    maxFeQueryAttempts);
+            return queryGss(switchoverDetectorConfig.getgFeFqdn(), switchoverDetectorConfig.getFeVip(), maxFeQueryAttempts);
         }
 
         private void initializeSiteMode() {
             while (siteMode.equals(SwitchoverDetectorState.UNKNOWN.getState())) {
-
                 beMatch = queryBe();
                 feMatch = queryFe();
-
                 if (beMatch != null && beMatch.equals(feMatch)) {
                     if (beMatch) {
                         setSiteMode(SwitchoverDetectorState.ACTIVE.getState());
@@ -164,29 +194,20 @@ public class SwitchoverDetector {
         @Override
         public void run() {
             logger.trace("Executing Switchover Detector Task - Start");
-
             initializeSiteMode();
-
             Boolean beRes = queryBe();
             Boolean feRes = queryFe();
-
             if (null == beRes || null == feRes) {
                 return;
             }
-
-            Boolean updateRequired = siteMode.equals(SwitchoverDetectorState.STANDBY.getState()) && (beRes || feRes)
-                    && (!beMatch.equals(beRes) || !feMatch.equals(feRes));
+            Boolean updateRequired =
+                siteMode.equals(SwitchoverDetectorState.STANDBY.getState()) && (beRes || feRes) && (!beMatch.equals(beRes) || !feMatch.equals(feRes));
             Boolean prevModeStandby = siteMode.equals(SwitchoverDetectorState.STANDBY.getState());
-
             updateSiteModeAndPriority(beRes && feRes, prevModeStandby, updateRequired);
-
             beMatch = beRes;
             feMatch = feRes;
         }
 
-        ExecutorService switchoverDetectorExecutor =
-                Executors.newSingleThreadExecutor(runnable -> new Thread(runnable, "Switchover-Detector-Thread"));
-
         private void updateSiteModeAndPriority(Boolean bothMatch, Boolean previousModeStandby, Boolean updateRequired) {
             if (bothMatch && previousModeStandby) {
                 logger.trace("Site switch over was done. Site is now in active mode");
@@ -205,10 +226,8 @@ public class SwitchoverDetector {
         }
 
         private void changeSitePriority(String groupToSet) {
-
             String url = switchoverDetectorConfig.getGroups().get(groupToSet).getChangePriorityUrl();
             String body = switchoverDetectorConfig.getGroups().get(groupToSet).getChangePriorityBody();
-
             try {
                 HttpRequest.put(url, authHeader, new StringEntity(body, ContentType.APPLICATION_JSON));
             } catch (Exception e) {
@@ -218,11 +237,9 @@ public class SwitchoverDetector {
                 }
                 logger.debug("Error occurred during change site priority request, Result is {}", message, e);
             }
-
         }
 
         private void publishNetwork() {
-
             String url = switchoverDetectorConfig.getPublishNetworkUrl();
             String body = switchoverDetectorConfig.getPublishNetworkBody();
             try {
@@ -235,70 +252,5 @@ public class SwitchoverDetector {
                 logger.debug("Error occurred during publish network request, Result is {}", message, e);
             }
         }
-
-    }
-
-    @VisibleForTesting
-    void setSwitchoverDetectorConfig(SwitchoverDetectorConfig switchoverDetectorConfig) {
-        this.switchoverDetectorConfig = switchoverDetectorConfig;
-    }
-
-    @PostConstruct
-    private void init() {
-        logger.info("Enter init method of SwitchoverDetector");
-
-        switchoverDetectorConfig =
-                ConfigurationManager.getConfigurationManager().getConfiguration().getSwitchoverDetector();
-
-        if (!switchoverDetectorConfig.getEnabled()) {
-            logger.info("switchover detector service is disabled");
-            return;
-        }
-
-        Long detectorIntervalConfig = switchoverDetectorConfig.getInterval();
-        if (detectorIntervalConfig != null) {
-            detectorInterval = detectorIntervalConfig;
-        }
-
-        Integer maxAttempts = switchoverDetectorConfig.getBeResolveAttempts();
-        if (maxAttempts != null) {
-            maxBeQueryAttempts = maxAttempts;
-        }
-        maxAttempts = switchoverDetectorConfig.getFeResolveAttempts();
-        if (maxAttempts != null) {
-            maxFeQueryAttempts = maxAttempts;
-        }
-
-        logger.info("switchover detector service is enabled, interval is {} seconds", detectorInterval);
-
-        this.switchoverDetectorScheduledTask = new SwitchoverDetectorScheduledTask();
-        startSwitchoverDetectorTask();
-        logger.trace("Exit init method of SwitchoverDetector");
-
-    }
-
-    @PreDestroy
-    private void destroy() {
-
-        if (scheduledFuture != null) {
-            scheduledFuture.cancel(true);
-            scheduledFuture = null;
-        }
-
-        if (switchoverDetectorScheduler != null) {
-            switchoverDetectorScheduler.shutdown();
-        }
-
     }
-
-    /**
-     * This method starts the switchover detector threads in the background.
-     */
-    public void startSwitchoverDetectorTask() {
-        if (this.scheduledFuture == null) {
-            this.scheduledFuture = this.switchoverDetectorScheduler
-                    .scheduleAtFixedRate(switchoverDetectorScheduledTask, 0, detectorInterval, TimeUnit.SECONDS);
-        }
-    }
-
 }
index 5e2f416..f8f85fd 100644 (file)
  * limitations under the License.
  * ============LICENSE_END=========================================================
  */
-
 package org.openecomp.sdc.be.togglz;
 
 import com.google.common.annotations.VisibleForTesting;
+import java.util.List;
+import java.util.stream.Collectors;
+import javax.annotation.PostConstruct;
 import org.openecomp.sdc.be.dao.cassandra.CassandraOperationStatus;
 import org.openecomp.sdc.be.dao.cassandra.FeatureToggleDao;
 import org.openecomp.sdc.be.resources.data.togglz.FeatureToggleEvent;
@@ -30,10 +32,6 @@ import org.togglz.core.Feature;
 import org.togglz.core.repository.FeatureState;
 import org.togglz.core.repository.StateRepository;
 
-import javax.annotation.PostConstruct;
-import java.util.List;
-import java.util.stream.Collectors;
-
 @Component
 public class CassandraCustomStateRepository implements StateRepository {
 
@@ -52,15 +50,13 @@ public class CassandraCustomStateRepository implements StateRepository {
     @VisibleForTesting
     void removeUnusedItems() {
         List<FeatureToggleEvent> allEvents = featureToggleDao.getAllFeatures();
-
-        List<FeatureToggleEvent> eventsToDelete = allEvents.stream()
-                .filter(e-> ToggleableFeature.getFeatureByName(e.getFeatureName()) == null)
-                .collect(Collectors.toList());
+        List<FeatureToggleEvent> eventsToDelete = allEvents.stream().filter(e -> ToggleableFeature.getFeatureByName(e.getFeatureName()) == null)
+            .collect(Collectors.toList());
         if (!eventsToDelete.isEmpty()) {
             logger.debug("Found Feature toggles not in use [{}], they will be deleted",
-                    eventsToDelete.stream().map(FeatureToggleEvent::getFeatureName).collect(Collectors.toList()));
+                eventsToDelete.stream().map(FeatureToggleEvent::getFeatureName).collect(Collectors.toList()));
         }
-        eventsToDelete.forEach(e->featureToggleDao.delete(e.getFeatureName()));
+        eventsToDelete.forEach(e -> featureToggleDao.delete(e.getFeatureName()));
     }
 
     @Override
@@ -71,7 +67,6 @@ public class CassandraCustomStateRepository implements StateRepository {
         }
         FeatureState state = null;
         FeatureToggleEvent event = featureToggleDao.get(feature.name());
-
         if (event != null) {
             state = event.getFeatureState();
             logger.debug("State of feature {} is {}", feature, state.getFeature());
@@ -87,5 +82,4 @@ public class CassandraCustomStateRepository implements StateRepository {
         CassandraOperationStatus status = featureToggleDao.save(new FeatureToggleEvent(featureState));
         logger.debug("setFeatureState=> FeatureState {} is set with status {}", featureState.getFeature(), status);
     }
-
 }
index a0f8d8b..83799e6 100644 (file)
@@ -16,7 +16,6 @@
  *  SPDX-License-Identifier: Apache-2.0
  *  ============LICENSE_END=========================================================
  */
-
 package org.openecomp.sdc.be.tosca;
 
 import com.google.gson.JsonElement;
@@ -72,8 +71,8 @@ public class AttributeConverter {
      */
     public ToscaAttribute convert(final AttributeDefinition attributeDefinition) throws ToscaConversionException {
         final ToscaAttribute toscaAttribute = new ToscaAttribute();
-        LOGGER.trace("Converting attribute '{}' from type '{}' with default value '{}'",
-            attributeDefinition.getName(), attributeDefinition.getType(), attributeDefinition.getDefaultValue());
+        LOGGER.trace("Converting attribute '{}' from type '{}' with default value '{}'", attributeDefinition.getName(), attributeDefinition.getType(),
+            attributeDefinition.getDefaultValue());
         toscaAttribute.setEntrySchema(convert(attributeDefinition.getEntry_schema()));
         toscaAttribute.setType(attributeDefinition.getType());
         toscaAttribute.setDescription(attributeDefinition.getDescription());
@@ -83,12 +82,11 @@ public class AttributeConverter {
         if (defaultValue != null) {
             toscaAttribute.setDefault(defaultValue);
         }
-        final Object value = convertToToscaObject(attributeDefinition.getName(), attributeDefinition.getType(),
-            attributeDefinition.getValue(), attributeDefinition.getEntry_schema(), false);
+        final Object value = convertToToscaObject(attributeDefinition.getName(), attributeDefinition.getType(), attributeDefinition.getValue(),
+            attributeDefinition.getEntry_schema(), false);
         if (value != null) {
             toscaAttribute.setValue(value);
         }
-
         return toscaAttribute;
     }
 
@@ -96,28 +94,24 @@ public class AttributeConverter {
         if (entrySchema == null) {
             return null;
         }
-
         final ToscaSchemaDefinition toscaSchemaDefinition = new ToscaSchemaDefinition();
         toscaSchemaDefinition.setType(entrySchema.getType());
         toscaSchemaDefinition.setDescription(entrySchema.getDescription());
         return toscaSchemaDefinition;
     }
 
-    private Object convertToToscaObject(final String name, final String attributeType, String value,
-                                        final EntrySchema schemaDefinition, final boolean preserveEmptyValue) throws ToscaConversionException {
+    private Object convertToToscaObject(final String name, final String attributeType, String value, final EntrySchema schemaDefinition,
+                                        final boolean preserveEmptyValue) throws ToscaConversionException {
         final String innerType = schemaDefinition == null ? attributeType : schemaDefinition.getType();
-        LOGGER.trace("Converting attribute '{}' of type '{}', value '{}', innerType '{}'",
-            name, attributeType, value, innerType);
+        LOGGER.trace("Converting attribute '{}' of type '{}', value '{}', innerType '{}'", name, attributeType, value, innerType);
         if (StringUtils.isEmpty(value)) {
             value = getTypeDefaultValue(attributeType);
             if (StringUtils.isEmpty(value)) {
                 return null;
             }
         }
-
         try {
             boolean isScalar = true;
-
             ToscaPropertyType predefinedType = ToscaPropertyType.isValidType(attributeType);
             if (predefinedType == null) {
                 //not predefined, search in existing data types
@@ -133,7 +127,6 @@ public class AttributeConverter {
             if (isValueGetAttribute(valueAsJson)) {
                 return ToscaMapValueConverter.getInstance().handleComplexJsonValue(valueAsJson.getAsJsonObject());
             }
-
             //if it has a converter
             if (predefinedType != null && predefinedType.getValueConverter() != null) {
                 LOGGER.trace("It's well defined type. convert it");
@@ -143,23 +136,17 @@ public class AttributeConverter {
             if (isScalar) {
                 return toscaMapValueConverter.handleComplexJsonValue(valueAsJson);
             }
-
             //if it is a data type
-            return toscaMapValueConverter.convertDataTypeToToscaObject(
-                innerType, dataTypes, null, false, valueAsJson, preserveEmptyValue);
-
+            return toscaMapValueConverter.convertDataTypeToToscaObject(innerType, dataTypes, null, false, valueAsJson, preserveEmptyValue);
         } catch (final JsonParseException e) {
             final String errorMsg = "Failed to parse json value";
-            LOGGER.error(EcompLoggerErrorCode.SCHEMA_ERROR, "Attribute Converter",
-                errorMsg, e);
+            LOGGER.error(EcompLoggerErrorCode.SCHEMA_ERROR, "Attribute Converter", errorMsg, e);
             throw new ToscaConversionException(errorMsg, e);
         } catch (final Exception e) {
             final String errorMsg = "Unexpected error occurred while converting attribute value to TOSCA";
-            LOGGER.error(EcompLoggerErrorCode.UNKNOWN_ERROR, "Attribute Converter",
-                errorMsg, e);
+            LOGGER.error(EcompLoggerErrorCode.UNKNOWN_ERROR, "Attribute Converter", errorMsg, e);
             throw new ToscaConversionException(errorMsg, e);
         }
-
     }
 
     private JsonElement parseToJson(final String value) {
@@ -180,5 +167,4 @@ public class AttributeConverter {
     private String getTypeDefaultValue(final String attributeType) {
         return DataTypePropertyConverter.getInstance().getDataTypePropertiesDefaultValuesRec(attributeType, dataTypes);
     }
-
 }
index 74704ca..ac4f8bf 100644 (file)
@@ -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.
@@ -17,7 +17,6 @@
  * limitations under the License.
  * ============LICENSE_END=========================================================
  */
-
 package org.openecomp.sdc.be.tosca;
 
 import static org.apache.commons.collections.CollectionUtils.isNotEmpty;
@@ -70,7 +69,6 @@ import org.springframework.context.annotation.Scope;
 
 /**
  * Allows to convert requirements\capabilities of a component to requirements\capabilities of a substitution mappings section of a tosca template
- *
  */
 @org.springframework.stereotype.Component("capabilty-requirement-convertor")
 @Scope(value = "singleton")
@@ -78,17 +76,17 @@ public class CapabilityRequirementConverter {
 
     private static final String NO_CAPABILITIES = "No Capabilities for node type";
     private static final String NO_REQUIREMENTS = "No Requirements for node type";
-    private static CapabilityRequirementConverter instance;
     private static final Logger logger = Logger.getLogger(CapabilityRequirementConverter.class);
     private static final String PATH_DELIMITER = ".";
-    private static final String FAILED_TO_FIND_CI_IN_PATH ="Failed to find ci in the path is {} component {}";
-
+    private static final String FAILED_TO_FIND_CI_IN_PATH = "Failed to find ci in the path is {} component {}";
+    private static CapabilityRequirementConverter instance;
     @Autowired
     private ToscaOperationFacade toscaOperationFacade;
     @Autowired
     private PropertyConvertor propertyConvertor;
 
-    public CapabilityRequirementConverter() {}
+    public CapabilityRequirementConverter() {
+    }
 
     public static synchronized CapabilityRequirementConverter getInstance() {
         if (instance == null) {
@@ -97,24 +95,22 @@ public class CapabilityRequirementConverter {
         return instance;
     }
 
-    public String buildCapabilityNameForComponentInstance( Map<String,Component> componentCache , ComponentInstance componentInstance, CapabilityDefinition c) {
+    public String buildCapabilityNameForComponentInstance(Map<String, Component> componentCache, ComponentInstance componentInstance,
+                                                          CapabilityDefinition c) {
         String prefix = buildCapReqNamePrefix(componentInstance.getNormalizedName());
-        if(ComponentUtilities.isNotUpdatedCapReqName(prefix, c.getName(), c.getPreviousName())){
-            return buildSubstitutedName(componentCache, c.getName(), c.getPreviousName(), c.getPath(), c.getOwnerId(), componentInstance)
-                    .left()
-                    .orValue(c.getName());
+        if (ComponentUtilities.isNotUpdatedCapReqName(prefix, c.getName(), c.getPreviousName())) {
+            return buildSubstitutedName(componentCache, c.getName(), c.getPreviousName(), c.getPath(), c.getOwnerId(), componentInstance).left()
+                .orValue(c.getName());
         }
         return c.getPreviousName();
     }
 
-    public String buildRequirementNameForComponentInstance(Map<String,Component> componentCache,
-                                                           ComponentInstance componentInstance,
+    public String buildRequirementNameForComponentInstance(Map<String, Component> componentCache, ComponentInstance componentInstance,
                                                            RequirementDefinition r) {
         String prefix = buildCapReqNamePrefix(componentInstance.getNormalizedName());
         if (ComponentUtilities.isNotUpdatedCapReqName(prefix, r.getName(), r.getPreviousName())) {
-            return buildSubstitutedName(componentCache, r.getName(), r.getPreviousName(), r.getPath(), r.getOwnerId(),
-                    componentInstance).left()
-                    .orValue(r.getName());
+            return buildSubstitutedName(componentCache, r.getName(), r.getPreviousName(), r.getPath(), r.getOwnerId(), componentInstance).left()
+                .orValue(r.getName());
         }
         return r.getPreviousName();
     }
@@ -125,23 +121,24 @@ public class CapabilityRequirementConverter {
 
     /**
      * Allows to convert capabilities of a component to capabilities of a substitution mappings section of a tosca template
+     *
      * @param componentInstance
      * @param dataTypes
      * @param nodeTemplate
      * @return
      */
-    public Either<ToscaNodeTemplate, ToscaError> convertComponentInstanceCapabilities(ComponentInstance componentInstance, Map<String, DataTypeDefinition> dataTypes, ToscaNodeTemplate nodeTemplate) {
-
+    public Either<ToscaNodeTemplate, ToscaError> convertComponentInstanceCapabilities(ComponentInstance componentInstance,
+                                                                                      Map<String, DataTypeDefinition> dataTypes,
+                                                                                      ToscaNodeTemplate nodeTemplate) {
         Map<String, List<CapabilityDefinition>> capabilitiesInst = componentInstance.getCapabilities();
-        Map<String,Component> componentCache = new HashMap<>();
+        Map<String, Component> componentCache = new HashMap<>();
         if (capabilitiesInst != null && !capabilitiesInst.isEmpty()) {
             Map<String, ToscaTemplateCapability> capabilities = new HashMap<>();
-            capabilitiesInst.entrySet().forEach( e -> {
+            capabilitiesInst.entrySet().forEach(e -> {
                 List<CapabilityDefinition> capList = e.getValue();
-                if ( capList != null && !capList.isEmpty() ) {
-                    capList.stream()
-                            .forEach( c -> convertOverridenProperties( componentInstance, dataTypes, capabilities, c ,
-                                buildCapabilityNameForComponentInstance( componentCache , componentInstance , c )));
+                if (capList != null && !capList.isEmpty()) {
+                    capList.stream().forEach(c -> convertOverridenProperties(componentInstance, dataTypes, capabilities, c,
+                        buildCapabilityNameForComponentInstance(componentCache, componentInstance, c)));
                 }
             });
             if (MapUtils.isNotEmpty(capabilities)) {
@@ -151,21 +148,20 @@ public class CapabilityRequirementConverter {
         return Either.left(nodeTemplate);
     }
 
-    private void convertOverridenProperties(ComponentInstance componentInstance, Map<String, DataTypeDefinition> dataTypes, Map<String, ToscaTemplateCapability> capabilties, CapabilityDefinition c , String capabilityName) {
+    private void convertOverridenProperties(ComponentInstance componentInstance, Map<String, DataTypeDefinition> dataTypes,
+                                            Map<String, ToscaTemplateCapability> capabilties, CapabilityDefinition c, String capabilityName) {
         if (isNotEmpty(c.getProperties())) {
-            c.getProperties()
-            .stream()
-            .filter(p -> p.getValue() != null || p.getDefaultValue() != null)
-            .forEach(p -> convertOverriddenProperty(componentInstance, dataTypes, capabilties , p ,capabilityName));
+            c.getProperties().stream().filter(p -> p.getValue() != null || p.getDefaultValue() != null)
+                .forEach(p -> convertOverriddenProperty(componentInstance, dataTypes, capabilties, p, capabilityName));
         }
     }
 
-    private void convertOverriddenProperty(ComponentInstance componentInstance, Map<String, DataTypeDefinition> dataTypes, Map<String, ToscaTemplateCapability> capabilties, ComponentInstanceProperty p , String capabilityName) {
+    private void convertOverriddenProperty(ComponentInstance componentInstance, Map<String, DataTypeDefinition> dataTypes,
+                                           Map<String, ToscaTemplateCapability> capabilties, ComponentInstanceProperty p, String capabilityName) {
         if (logger.isDebugEnabled()) {
             logger.debug("Exist d property {} for capability {} with value {}", p.getName(), capabilityName, p.getValue());
         }
-        ToscaTemplateCapability toscaTemplateCapability = capabilties.computeIfAbsent( capabilityName , key -> new ToscaTemplateCapability() );
-
+        ToscaTemplateCapability toscaTemplateCapability = capabilties.computeIfAbsent(capabilityName, key -> new ToscaTemplateCapability());
         Map<String, Object> toscaCapProp = toscaTemplateCapability.getProperties();
         if (toscaCapProp == null) {
             toscaCapProp = new HashMap<>();
@@ -175,38 +171,43 @@ public class CapabilityRequirementConverter {
         toscaTemplateCapability.setProperties(toscaCapProp);
     }
 
-    private Object convertInstanceProperty(Map<String, DataTypeDefinition> dataTypes, ComponentInstance componentInstance, ComponentInstanceProperty prop) {
+    private Object convertInstanceProperty(Map<String, DataTypeDefinition> dataTypes, ComponentInstance componentInstance,
+                                           ComponentInstanceProperty prop) {
         logger.debug("Convert property {} for instance {}", prop.getName(), componentInstance.getUniqueId());
         String propValue = prop.getValue() == null ? prop.getDefaultValue() : prop.getValue();
         return propertyConvertor.convertToToscaObject(prop, propValue, dataTypes, false);
     }
+
     /**
      * Allows to convert requirements of a node type to tosca template requirements representation
+     *
      * @param component
      * @param nodeType
      * @return
      */
-    public Either<ToscaNodeType, ToscaError> convertRequirements(Map<String, Component> componentsCache, Component component, ToscaNodeType nodeType) {
+    public Either<ToscaNodeType, ToscaError> convertRequirements(Map<String, Component> componentsCache, Component component,
+                                                                 ToscaNodeType nodeType) {
         List<Map<String, ToscaRequirement>> toscaRequirements = convertRequirementsAsList(componentsCache, component);
         if (!toscaRequirements.isEmpty()) {
             nodeType.setRequirements(toscaRequirements);
         }
         logger.debug("Finish convert Requirements for node type");
-
         return Either.left(nodeType);
     }
 
     /**
      * Allows to convert component requirements to the tosca template substitution mappings requirements
+     *
      * @param componentsCache
      * @param component
      * @param substitutionMappings
      * @return
      */
-    public Either<SubstitutionMapping, ToscaError> convertSubstitutionMappingRequirements(Map<String,Component> componentsCache, Component component, SubstitutionMapping substitutionMappings) {
+    public Either<SubstitutionMapping, ToscaError> convertSubstitutionMappingRequirements(Map<String, Component> componentsCache, Component component,
+                                                                                          SubstitutionMapping substitutionMappings) {
         Either<SubstitutionMapping, ToscaError> result = Either.left(substitutionMappings);
         Either<Map<String, String[]>, ToscaError> toscaRequirementsRes = convertSubstitutionMappingRequirementsAsMap(componentsCache, component);
-        if(toscaRequirementsRes.isRight()){
+        if (toscaRequirementsRes.isRight()) {
             result = Either.right(toscaRequirementsRes.right().value());
             logger.debug("Failed convert requirements for the component {}. ", component.getName());
         } else if (MapUtils.isNotEmpty(toscaRequirementsRes.left().value())) {
@@ -219,19 +220,17 @@ public class CapabilityRequirementConverter {
 
     /**
      * Allows to convert requirements of a server proxy node type to tosca template requirements
+     *
      * @param instanceProxy
      * @return converted tosca template requirements
      */
-    List<Map<String, ToscaRequirement>> convertProxyRequirements(Map<String, Component> componentCache,
-                                                                 ComponentInstance instanceProxy) {
+    List<Map<String, ToscaRequirement>> convertProxyRequirements(Map<String, Component> componentCache, ComponentInstance instanceProxy) {
         Map<String, List<RequirementDefinition>> requirements = instanceProxy.getRequirements();
         List<Map<String, ToscaRequirement>> toscaRequirements = new ArrayList<>();
         if (requirements != null) {
-            requirements.entrySet().stream()
-                    .flatMap(e -> e.getValue().stream())
-                    .forEach(req -> {
+            requirements.entrySet().stream().flatMap(e -> e.getValue().stream()).forEach(req -> {
                 ImmutablePair<String, ToscaRequirement> pair = convertProxyRequirement(
-                        buildRequirementNameForComponentInstance(componentCache, instanceProxy, req), req);
+                    buildRequirementNameForComponentInstance(componentCache, instanceProxy, req), req);
                 Map<String, ToscaRequirement> requirement = new HashMap<>();
                 requirement.put(pair.left, pair.right);
                 toscaRequirements.add(requirement);
@@ -239,12 +238,10 @@ public class CapabilityRequirementConverter {
         } else {
             logger.debug(NO_REQUIREMENTS);
         }
-
         return toscaRequirements;
     }
 
-    private ImmutablePair<String, ToscaRequirement> convertProxyRequirement(String requirementName,
-                                                                            RequirementDefinition r) {
+    private ImmutablePair<String, ToscaRequirement> convertProxyRequirement(String requirementName, RequirementDefinition r) {
         ToscaRequirement toscaRequirement = createToscaRequirement(r);
         return new ImmutablePair<>(requirementName, toscaRequirement);
     }
@@ -255,9 +252,9 @@ public class CapabilityRequirementConverter {
         if (requirements != null) {
             for (Map.Entry<String, List<RequirementDefinition>> entry : requirements.entrySet()) {
                 entry.getValue().stream().filter(r -> filter(component, r.getOwnerId())).forEach(r -> {
-                    ImmutablePair<String, ToscaRequirement> pair = convertRequirement(componentsCache, component, ModelConverter.isAtomicComponent(component), r);
+                    ImmutablePair<String, ToscaRequirement> pair = convertRequirement(componentsCache, component,
+                        ModelConverter.isAtomicComponent(component), r);
                     Map<String, ToscaRequirement> requirement = new HashMap<>();
-
                     requirement.put(pair.left, pair.right);
                     toscaRequirements.add(requirement);
                 });
@@ -270,21 +267,23 @@ public class CapabilityRequirementConverter {
     }
 
     private boolean filter(Component component, String ownerId) {
-        return !ModelConverter.isAtomicComponent(component) || isNodeTypeOwner(component, ownerId) || (ModelConverter.isAtomicComponent(component) && ownerId == null);
+        return !ModelConverter.isAtomicComponent(component) || isNodeTypeOwner(component, ownerId) || (ModelConverter.isAtomicComponent(component)
+            && ownerId == null);
     }
 
     private boolean isNodeTypeOwner(Component component, String ownerId) {
         return ModelConverter.isAtomicComponent(component) && component.getUniqueId().equals(ownerId);
     }
 
-    private String dropLast( String path, String delimiter ) {
-        if (isBlank(path) || isBlank(delimiter)){
+    private String dropLast(String path, String delimiter) {
+        if (isBlank(path) || isBlank(delimiter)) {
             return path;
         }
         return path.substring(0, path.lastIndexOf(delimiter));
     }
 
-    private Either<Map<String, String[]>, ToscaError> convertSubstitutionMappingRequirementsAsMap(Map<String, Component> componentsCache, Component component) {
+    private Either<Map<String, String[]>, ToscaError> convertSubstitutionMappingRequirementsAsMap(Map<String, Component> componentsCache,
+                                                                                                  Component component) {
         Map<String, List<RequirementDefinition>> requirements = component.getRequirements();
         Either<Map<String, String[]>, ToscaError> result;
         if (requirements != null) {
@@ -296,53 +295,54 @@ public class CapabilityRequirementConverter {
         return result;
     }
 
-    private Either<Map<String, String[]>, ToscaError> buildAddSubstitutionMappingsRequirements(Map<String, Component> componentsCache, Component component, Map<String, List<RequirementDefinition>> requirements) {
-
+    private Either<Map<String, String[]>, ToscaError> buildAddSubstitutionMappingsRequirements(Map<String, Component> componentsCache,
+                                                                                               Component component,
+                                                                                               Map<String, List<RequirementDefinition>> requirements) {
         Map<String, String[]> toscaRequirements = new HashMap<>();
         Either<Map<String, String[]>, ToscaError> result = null;
         for (Map.Entry<String, List<RequirementDefinition>> entry : requirements.entrySet()) {
-            Optional<RequirementDefinition> failedToAddRequirement = entry.getValue()
-                    .stream().filter(RequirementDefinition::isExternal)
-                    .filter(r->!addEntry(componentsCache, toscaRequirements, component, new SubstitutionEntry(r.getName(), r.getParentName(), ""), r.getPreviousName(), r.getOwnerId(), r.getPath()))
-                    .findAny();
-            if(failedToAddRequirement.isPresent()){
+            Optional<RequirementDefinition> failedToAddRequirement = entry.getValue().stream().filter(RequirementDefinition::isExternal).filter(
+                r -> !addEntry(componentsCache, toscaRequirements, component, new SubstitutionEntry(r.getName(), r.getParentName(), ""),
+                    r.getPreviousName(), r.getOwnerId(), r.getPath())).findAny();
+            if (failedToAddRequirement.isPresent()) {
                 logger.debug("Failed to convert requirement {} for substitution mappings section of a tosca template of the component {}. ",
-                        failedToAddRequirement.get().getName(), component.getName());
+                    failedToAddRequirement.get().getName(), component.getName());
                 result = Either.right(ToscaError.NODE_TYPE_REQUIREMENT_ERROR);
             }
             logger.debug("Finish convert requirements for the component {}. ", component.getName());
         }
-        if(result == null){
+        if (result == null) {
             result = Either.left(toscaRequirements);
         }
         return result;
     }
 
-    private Either<Map<String, String[]>, ToscaError> buildAddSubstitutionMappingsCapabilities(Map<String, Component> componentsCache, Component component, Map<String, List<CapabilityDefinition>> capabilities) {
-
+    private Either<Map<String, String[]>, ToscaError> buildAddSubstitutionMappingsCapabilities(Map<String, Component> componentsCache,
+                                                                                               Component component,
+                                                                                               Map<String, List<CapabilityDefinition>> capabilities) {
         Map<String, String[]> toscaCapabilities = new HashMap<>();
         Either<Map<String, String[]>, ToscaError> result = null;
         for (Map.Entry<String, List<CapabilityDefinition>> entry : capabilities.entrySet()) {
-            Optional<CapabilityDefinition> failedToAddRequirement = entry.getValue()
-                    .stream()
-                    .filter(c->!addEntry(componentsCache, toscaCapabilities, component, new SubstitutionEntry(c.getName(), c.getParentName(), ""), c.getPreviousName(), c.getOwnerId(), c.getPath()))
-                    .findAny();
-            if(failedToAddRequirement.isPresent()){
+            Optional<CapabilityDefinition> failedToAddRequirement = entry.getValue().stream().filter(
+                c -> !addEntry(componentsCache, toscaCapabilities, component, new SubstitutionEntry(c.getName(), c.getParentName(), ""),
+                    c.getPreviousName(), c.getOwnerId(), c.getPath())).findAny();
+            if (failedToAddRequirement.isPresent()) {
                 logger.debug("Failed to convert capability {} for substitution mappings section of a tosca template of the component {}. ",
-                        failedToAddRequirement.get().getName(), component.getName());
+                    failedToAddRequirement.get().getName(), component.getName());
                 result = Either.right(ToscaError.NODE_TYPE_CAPABILITY_ERROR);
             }
             logger.debug("Finish convert capabilities for the component {}. ", component.getName());
         }
-        if(result == null){
+        if (result == null) {
             result = Either.left(toscaCapabilities);
         }
         return result;
     }
 
-    private boolean addEntry(Map<String, Component> componentsCache, Map<String, String[]> capReqMap, Component component, SubstitutionEntry entry, String previousName, String ownerId, List<String> path){
-    
-        if(shouldBuildSubstitutionName(component, path) && !buildSubstitutedNamePerInstance(componentsCache, component, entry.getFullName(), previousName, path, ownerId, entry)){
+    private boolean addEntry(Map<String, Component> componentsCache, Map<String, String[]> capReqMap, Component component, SubstitutionEntry entry,
+                             String previousName, String ownerId, List<String> path) {
+        if (shouldBuildSubstitutionName(component, path) && !buildSubstitutedNamePerInstance(componentsCache, component, entry.getFullName(),
+            previousName, path, ownerId, entry)) {
             return false;
         }
         logger.debug("The requirement/capability {} belongs to the component {} ", entry.getFullName(), component.getUniqueId());
@@ -351,22 +351,22 @@ public class CapabilityRequirementConverter {
         }
         logger.debug("Finish convert the requirement/capability {} for the component {}. ", entry.getFullName(), component.getName());
         return true;
-
     }
 
     private boolean shouldBuildSubstitutionName(Component component, List<String> path) {
         return ToscaUtils.isNotComplexVfc(component) && isNotEmpty(path) && path.iterator().hasNext();
     }
 
-    private boolean buildSubstitutedNamePerInstance(Map<String, Component> componentsCache, Component component, String name, String previousName, List<String> path, String ownerId, SubstitutionEntry entry) {
+    private boolean buildSubstitutedNamePerInstance(Map<String, Component> componentsCache, Component component, String name, String previousName,
+                                                    List<String> path, String ownerId, SubstitutionEntry entry) {
         String fullName;
         String sourceName;
         String prefix;
-        if(CollectionUtils.isNotEmpty(component.getGroups())) {
+        if (CollectionUtils.isNotEmpty(component.getGroups())) {
             Optional<GroupDefinition> groupOpt = component.getGroups().stream().filter(g -> g.getUniqueId().equals(ownerId)).findFirst();
             if (groupOpt.isPresent()) {
                 prefix = buildCapReqNamePrefix(groupOpt.get().getNormalizedName());
-                if(ComponentUtilities.isNotUpdatedCapReqName(prefix, name, previousName)){
+                if (ComponentUtilities.isNotUpdatedCapReqName(prefix, name, previousName)) {
                     sourceName = name;
                     fullName = prefix + sourceName;
                 } else {
@@ -379,22 +379,19 @@ public class CapabilityRequirementConverter {
                 return true;
             }
         }
-
-        Optional<ComponentInstance> ci =
-                component.safeGetComponentInstances().stream().filter(c->c.getUniqueId().equals(Iterables.getLast(path))).findFirst();
-        if(!ci.isPresent()){
+        Optional<ComponentInstance> ci = component.safeGetComponentInstances().stream().filter(c -> c.getUniqueId().equals(Iterables.getLast(path)))
+            .findFirst();
+        if (!ci.isPresent()) {
             logger.debug(FAILED_TO_FIND_CI_IN_PATH, path, component.getUniqueId());
-
             Collections.reverse(path);
-
             logger.debug("try to reverse path {} component {}", path, component.getUniqueId());
-            ci = component.safeGetComponentInstances().stream().filter(c->c.getUniqueId().equals(Iterables.getLast(path))).findFirst();
+            ci = component.safeGetComponentInstances().stream().filter(c -> c.getUniqueId().equals(Iterables.getLast(path))).findFirst();
         }
-        if(ci.isPresent()){
+        if (ci.isPresent()) {
             prefix = buildCapReqNamePrefix(ci.get().getNormalizedName());
-            if(ComponentUtilities.isNotUpdatedCapReqName(prefix, name, previousName)){
+            if (ComponentUtilities.isNotUpdatedCapReqName(prefix, name, previousName)) {
                 Either<String, Boolean> buildSubstitutedName = buildSubstitutedName(componentsCache, name, previousName, path, ownerId, ci.get());
-                if(buildSubstitutedName.isRight()){
+                if (buildSubstitutedName.isRight()) {
                     logger.debug("Failed buildSubstitutedName name {}  path {} component {}", name, path, component.getUniqueId());
                     return false;
                 }
@@ -414,23 +411,27 @@ public class CapabilityRequirementConverter {
     }
 
     private void addEntry(Map<String, String[]> toscaRequirements, Component component, List<String> capPath, SubstitutionEntry entry) {
-        Optional<ComponentInstance> findFirst = component.safeGetComponentInstances().stream().filter(ci -> ci.getUniqueId().equals(Iterables.getLast(capPath))).findFirst();
+        Optional<ComponentInstance> findFirst = component.safeGetComponentInstances().stream()
+            .filter(ci -> ci.getUniqueId().equals(Iterables.getLast(capPath))).findFirst();
         findFirst.ifPresent(componentInstance -> entry.setOwner(componentInstance.getName()));
         if (StringUtils.isNotEmpty(entry.getOwner()) && StringUtils.isNotEmpty(entry.getSourceName())) {
-            toscaRequirements.put(entry.getFullName(), new String[] { entry.getOwner(), entry.getSourceName() });
+            toscaRequirements.put(entry.getFullName(), new String[]{entry.getOwner(), entry.getSourceName()});
         }
     }
 
-    public Either<String, Boolean> buildSubstitutedName(Map<String, Component> componentsCache, String name, String previousName, List<String> path, String ownerId, ComponentInstance instance) {
-        if(StringUtils.isNotEmpty(previousName)){
+    public Either<String, Boolean> buildSubstitutedName(Map<String, Component> componentsCache, String name, String previousName, List<String> path,
+                                                        String ownerId, ComponentInstance instance) {
+        if (StringUtils.isNotEmpty(previousName)) {
             return Either.left(name);
         }
         Either<Component, Boolean> getOriginRes = getOriginComponent(componentsCache, instance);
-        if(getOriginRes.isRight()){
-            logger.debug("Failed to build substituted name for the capability/requirement {}. Failed to get an origin component with uniqueId {}", name, instance.getComponentUid());
+        if (getOriginRes.isRight()) {
+            logger
+                .debug("Failed to build substituted name for the capability/requirement {}. Failed to get an origin component with uniqueId {}", name,
+                    instance.getComponentUid());
             return Either.right(false);
         }
-        List<String> reducedPath = ownerId !=null ? getReducedPathByOwner(path , ownerId ) : getReducedPath(path) ;
+        List<String> reducedPath = ownerId != null ? getReducedPathByOwner(path, ownerId) : getReducedPath(path);
         logger.debug("reducedPath for ownerId {}, reducedPath {} ", ownerId, reducedPath);
         reducedPath.remove(reducedPath.size() - 1);
         return buildSubstitutedName(componentsCache, getOriginRes.left().value(), reducedPath, name, previousName);
@@ -440,7 +441,8 @@ public class CapabilityRequirementConverter {
         return buildCapReqNamePerOwnerByPath(componentsCache, component, r.getName(), r.getPreviousName(), r.getPath());
     }
 
-    private ImmutablePair<String, ToscaRequirement> convertRequirement(Map<String, Component> componentsCache, Component component, boolean isNodeType, RequirementDefinition r) {
+    private ImmutablePair<String, ToscaRequirement> convertRequirement(Map<String, Component> componentsCache, Component component,
+                                                                       boolean isNodeType, RequirementDefinition r) {
         String name = r.getName();
         if (!isNodeType && ToscaUtils.isNotComplexVfc(component)) {
             name = buildReqNamePerOwnerByPath(componentsCache, component, r);
@@ -452,7 +454,6 @@ public class CapabilityRequirementConverter {
 
     private ToscaRequirement createToscaRequirement(RequirementDefinition r) {
         ToscaRequirement toscaRequirement = new ToscaRequirement();
-
         List<Object> occurrences = new ArrayList<>();
         occurrences.add(Integer.valueOf(r.getMinOccurrences()));
         if (r.getMaxOccurrences().equals(RequirementDataDefinition.MAX_OCCURRENCES)) {
@@ -469,57 +470,58 @@ public class CapabilityRequirementConverter {
 
     /**
      * Allows to convert capabilities of a node type to tosca template capabilities
+     *
      * @param component
      * @param dataTypes
      * @return
      */
-    public Map<String, ToscaCapability> convertCapabilities(Map<String, Component> componentsCache, Component component, Map<String, DataTypeDefinition> dataTypes) {
+    public Map<String, ToscaCapability> convertCapabilities(Map<String, Component> componentsCache, Component component,
+                                                            Map<String, DataTypeDefinition> dataTypes) {
         Map<String, List<CapabilityDefinition>> capabilities = component.getCapabilities();
         Map<String, ToscaCapability> toscaCapabilities = new HashMap<>();
         if (capabilities != null) {
             boolean isNodeType = ModelConverter.isAtomicComponent(component);
             for (Map.Entry<String, List<CapabilityDefinition>> entry : capabilities.entrySet()) {
-                entry.getValue().stream().filter(c -> filter(component, c.getOwnerId())).forEach(c -> convertCapability(componentsCache, component, toscaCapabilities, isNodeType, c, dataTypes , c.getName()));
+                entry.getValue().stream().filter(c -> filter(component, c.getOwnerId()))
+                    .forEach(c -> convertCapability(componentsCache, component, toscaCapabilities, isNodeType, c, dataTypes, c.getName()));
             }
         } else {
             logger.debug(NO_CAPABILITIES);
         }
-
         return toscaCapabilities;
     }
 
     /**
      * Allows to convert capabilities of a server proxy node type to tosca template capabilities
+     *
      * @param instanceProxy
      * @param dataTypes
      * @return
      */
-    public Map<String, ToscaCapability> convertProxyCapabilities(Map<String, Component> componentCache,
-                                                                 ComponentInstance instanceProxy,
+    public Map<String, ToscaCapability> convertProxyCapabilities(Map<String, Component> componentCache, ComponentInstance instanceProxy,
                                                                  Map<String, DataTypeDefinition> dataTypes) {
         Map<String, List<CapabilityDefinition>> capabilities = instanceProxy.getCapabilities();
         Map<String, ToscaCapability> toscaCapabilities = new HashMap<>();
         if (capabilities != null) {
             for (Map.Entry<String, List<CapabilityDefinition>> entry : capabilities.entrySet()) {
-                entry.getValue()
-                        .stream()
-                        .forEach(c -> convertProxyCapability(toscaCapabilities, c, dataTypes ,
-                                buildCapabilityNameForComponentInstance( componentCache , instanceProxy , c )));
+                entry.getValue().stream().forEach(c -> convertProxyCapability(toscaCapabilities, c, dataTypes,
+                    buildCapabilityNameForComponentInstance(componentCache, instanceProxy, c)));
             }
         } else {
             logger.debug(NO_CAPABILITIES);
         }
-
         return toscaCapabilities;
     }
 
     /**
      * Allows to convert component capabilities to the tosca template substitution mappings capabilities
+     *
      * @param componentsCache
      * @param component
      * @return
      */
-    public Either<Map<String, String[]>, ToscaError> convertSubstitutionMappingCapabilities(Map<String, Component> componentsCache, Component component) {
+    public Either<Map<String, String[]>, ToscaError> convertSubstitutionMappingCapabilities(Map<String, Component> componentsCache,
+                                                                                            Component component) {
         Map<String, List<CapabilityDefinition>> capabilities = component.getCapabilities();
         Either<Map<String, String[]>, ToscaError> res;
         if (capabilities != null) {
@@ -540,7 +542,8 @@ public class CapabilityRequirementConverter {
         createToscaCapability(toscaCapabilities, c, dataTypes, capabilityName);
     }
 
-    private void convertCapability(Map<String, Component> componentsCache, Component component, Map<String, ToscaCapability> toscaCapabilities, boolean isNodeType, CapabilityDefinition c, Map<String, DataTypeDefinition> dataTypes , String capabilityName) {
+    private void convertCapability(Map<String, Component> componentsCache, Component component, Map<String, ToscaCapability> toscaCapabilities,
+                                   boolean isNodeType, CapabilityDefinition c, Map<String, DataTypeDefinition> dataTypes, String capabilityName) {
         String name = isNoneBlank(capabilityName) ? capabilityName : c.getName();
         if (!isNodeType && ToscaUtils.isNotComplexVfc(component)) {
             name = buildCapNamePerOwnerByPath(componentsCache, c, component);
@@ -554,7 +557,6 @@ public class CapabilityRequirementConverter {
         ToscaCapability toscaCapability = new ToscaCapability();
         toscaCapability.setDescription(c.getDescription());
         toscaCapability.setType(c.getType());
-
         List<Object> occurrences = new ArrayList<>();
         occurrences.add(Integer.valueOf(c.getMinOccurrences()));
         if (c.getMaxOccurrences().equals(CapabilityDataDefinition.MAX_OCCURRENCES)) {
@@ -563,7 +565,6 @@ public class CapabilityRequirementConverter {
             occurrences.add(Integer.valueOf(c.getMaxOccurrences()));
         }
         toscaCapability.setOccurrences(occurrences);
-
         toscaCapability.setValid_source_types(c.getValidSourceTypes());
         List<ComponentInstanceProperty> properties = c.getProperties();
         if (isNotEmpty(properties)) {
@@ -577,36 +578,36 @@ public class CapabilityRequirementConverter {
         toscaCapabilities.put(name, toscaCapability);
     }
 
-    private String buildCapReqNamePerOwnerByPath(Map<String, Component> componentsCache, Component component, String name, String previousName, List<String> path) {
+    private String buildCapReqNamePerOwnerByPath(Map<String, Component> componentsCache, Component component, String name, String previousName,
+                                                 List<String> path) {
         if (CollectionUtils.isEmpty(path)) {
             return name;
         }
         String ownerId = path.get(path.size() - 1);
         String prefix;
-        if(CollectionUtils.isNotEmpty(component.getGroups())) {
+        if (CollectionUtils.isNotEmpty(component.getGroups())) {
             Optional<GroupDefinition> groupOpt = component.getGroups().stream().filter(g -> g.getUniqueId().equals(ownerId)).findFirst();
             if (groupOpt.isPresent()) {
                 prefix = buildCapReqNamePrefix(groupOpt.get().getNormalizedName());
-                if(ComponentUtilities.isNotUpdatedCapReqName(prefix, name, previousName)){
+                if (ComponentUtilities.isNotUpdatedCapReqName(prefix, name, previousName)) {
                     return prefix + name;
                 }
                 return name;
             }
         }
-        Optional<ComponentInstance> ci = component.safeGetComponentInstances().stream().filter(c->c.getUniqueId().equals(Iterables.getLast(path))).findFirst();
-        if(!ci.isPresent()){
+        Optional<ComponentInstance> ci = component.safeGetComponentInstances().stream().filter(c -> c.getUniqueId().equals(Iterables.getLast(path)))
+            .findFirst();
+        if (!ci.isPresent()) {
             logger.debug(FAILED_TO_FIND_CI_IN_PATH, path, component.getUniqueId());
-
             Collections.reverse(path);
-
             logger.debug("try to reverse path {} component {}", path, component.getUniqueId());
-            ci = component.safeGetComponentInstances().stream().filter(c->c.getUniqueId().equals(Iterables.getLast(path))).findFirst();
+            ci = component.safeGetComponentInstances().stream().filter(c -> c.getUniqueId().equals(Iterables.getLast(path))).findFirst();
         }
-        if(ci.isPresent()){
+        if (ci.isPresent()) {
             prefix = buildCapReqNamePrefix(ci.get().getNormalizedName());
-            if(ComponentUtilities.isNotUpdatedCapReqName(prefix, name, previousName)){
+            if (ComponentUtilities.isNotUpdatedCapReqName(prefix, name, previousName)) {
                 Either<String, Boolean> buildSubstitutedName = buildSubstitutedName(componentsCache, name, previousName, path, ownerId, ci.get());
-                if(buildSubstitutedName.isRight()){
+                if (buildSubstitutedName.isRight()) {
                     logger.debug("Failed buildSubstitutedName name {}  path {} component {}", name, path, component.getUniqueId());
                 }
                 return prefix + buildSubstitutedName.left().value();
@@ -615,8 +616,10 @@ public class CapabilityRequirementConverter {
         }
         return StringUtils.EMPTY;
     }
+
     /**
      * Allows to build substituted name of capability\requirement of the origin component instance according to the path
+     *
      * @param componentsCache
      * @param originComponent
      * @param path
@@ -624,13 +627,14 @@ public class CapabilityRequirementConverter {
      * @param previousName
      * @return
      */
-    public Either<String, Boolean> buildSubstitutedName(Map<String, Component> componentsCache, Component originComponent, List<String> path, String name, String previousName) {
-        if(StringUtils.isNotEmpty(previousName)){
+    public Either<String, Boolean> buildSubstitutedName(Map<String, Component> componentsCache, Component originComponent, List<String> path,
+                                                        String name, String previousName) {
+        if (StringUtils.isNotEmpty(previousName)) {
             return Either.left(name);
         }
         StringBuilder substitutedName = new StringBuilder();
         boolean nameBuiltSuccessfully = true;
-        if(isNotEmpty(path) && ToscaUtils.isNotComplexVfc(originComponent)){
+        if (isNotEmpty(path) && ToscaUtils.isNotComplexVfc(originComponent)) {
             List<String> reducedPath = getReducedPath(path);
             Collections.reverse(reducedPath);
             nameBuiltSuccessfully = appendNameRecursively(componentsCache, originComponent, reducedPath.iterator(), substitutedName);
@@ -638,46 +642,51 @@ public class CapabilityRequirementConverter {
         return nameBuiltSuccessfully ? Either.left(substitutedName.append(name).toString()) : Either.right(nameBuiltSuccessfully);
     }
 
-    protected List<String> getReducedPathByOwner(List<String> path , String ownerId) {
+    protected List<String> getReducedPathByOwner(List<String> path, String ownerId) {
         logger.debug("ownerId {}, path {} ", ownerId, path);
-        if ( CollectionUtils.isEmpty(path) ){
+        if (CollectionUtils.isEmpty(path)) {
             logger.debug("cannot perform reduce by owner, path to component is empty");
             return path;
         }
-        if ( isBlank(ownerId) ){
+        if (isBlank(ownerId)) {
             logger.debug("cannot perform reduce by owner, component owner is empty");
             return path;
         }
         //reduce by owner
-        Map map = path.stream().collect( Collectors.toMap( it -> dropLast(it,PATH_DELIMITER) , Function.identity() , ( a , b ) ->  a.endsWith(ownerId) ? a : b ));
+        Map map = path.stream()
+            .collect(Collectors.toMap(it -> dropLast(it, PATH_DELIMITER), Function.identity(), (a, b) -> a.endsWith(ownerId) ? a : b));
         //reduce list&duplicates and preserve order
-        return path.stream().distinct().filter(it -> map.values().contains(it) ).collect(Collectors.toList());
+        return path.stream().distinct().filter(it -> map.values().contains(it)).collect(Collectors.toList());
     }
 
     private List<String> getReducedPath(List<String> path) {
         return path.stream().distinct().collect(Collectors.toList());
     }
 
-    private boolean appendNameRecursively(Map<String, Component> componentsCache, Component originComponent, Iterator<String> instanceIdIter, StringBuilder substitutedName) {
-        if(isNotEmpty(originComponent.getComponentInstances()) && instanceIdIter.hasNext() && ToscaUtils.isNotComplexVfc(originComponent)){
+    private boolean appendNameRecursively(Map<String, Component> componentsCache, Component originComponent, Iterator<String> instanceIdIter,
+                                          StringBuilder substitutedName) {
+        if (isNotEmpty(originComponent.getComponentInstances()) && instanceIdIter.hasNext() && ToscaUtils.isNotComplexVfc(originComponent)) {
             String ownerId = instanceIdIter.next();
-            Optional<ComponentInstance> instanceOpt = originComponent.getComponentInstances().stream().filter(i -> i.getUniqueId().equals(ownerId)).findFirst();
-            if(instanceOpt.isPresent()){
+            Optional<ComponentInstance> instanceOpt = originComponent.getComponentInstances().stream().filter(i -> i.getUniqueId().equals(ownerId))
+                .findFirst();
+            if (instanceOpt.isPresent()) {
                 substitutedName.append(instanceOpt.get().getNormalizedName()).append(PATH_DELIMITER);
                 Either<Component, Boolean> getOriginRes = getOriginComponent(componentsCache, instanceOpt.get());
-                if(getOriginRes.isRight()){
+                if (getOriginRes.isRight()) {
                     return false;
                 }
                 appendNameRecursively(componentsCache, getOriginRes.left().value(), instanceIdIter, substitutedName);
-            } else if(CollectionUtils.isNotEmpty(originComponent.getGroups())){
+            } else if (CollectionUtils.isNotEmpty(originComponent.getGroups())) {
                 Optional<GroupDefinition> groupOpt = originComponent.getGroups().stream().filter(g -> g.getUniqueId().equals(ownerId)).findFirst();
-                if(!groupOpt.isPresent()){
-                    logger.debug("Failed to find an capability owner with uniqueId {} on a component with uniqueId {}", ownerId, originComponent.getUniqueId());
+                if (!groupOpt.isPresent()) {
+                    logger.debug("Failed to find an capability owner with uniqueId {} on a component with uniqueId {}", ownerId,
+                        originComponent.getUniqueId());
                     return false;
                 }
                 substitutedName.append(groupOpt.get().getNormalizedName()).append(PATH_DELIMITER);
             } else {
-                logger.debug("Failed to find an capability owner with uniqueId {} on a component with uniqueId {}", ownerId, originComponent.getUniqueId());
+                logger.debug("Failed to find an capability owner with uniqueId {} on a component with uniqueId {}", ownerId,
+                    originComponent.getUniqueId());
                 return false;
             }
         }
@@ -687,12 +696,12 @@ public class CapabilityRequirementConverter {
     Either<Component, Boolean> getOriginComponent(Map<String, Component> componentsCache, ComponentInstance instance) {
         Either<Component, Boolean> result;
         Either<Component, StorageOperationStatus> getOriginRes;
-        if(componentsCache.containsKey(instance.getActualComponentUid())){
+        if (componentsCache.containsKey(instance.getActualComponentUid())) {
             result = Either.left(componentsCache.get(instance.getActualComponentUid()));
         } else {
             ComponentParametersView filter = getFilter(instance);
             getOriginRes = toscaOperationFacade.getToscaElement(instance.getActualComponentUid(), filter);
-            if(getOriginRes.isRight()){
+            if (getOriginRes.isRight()) {
                 logger.debug("Failed to get an origin component with uniqueId {}", instance.getActualComponentUid());
                 result = Either.right(false);
             } else {
@@ -706,15 +715,14 @@ public class CapabilityRequirementConverter {
     private ComponentParametersView getFilter(ComponentInstance instance) {
         ComponentParametersView filter = new ComponentParametersView(true);
         filter.setIgnoreComponentInstances(false);
-        if(instance.getIsProxy()){
+        if (instance.getIsProxy()) {
             filter.setIgnoreCapabilities(false);
             filter.setIgnoreRequirements(false);
             filter.setIgnoreCategories(false);
         }
-        if(instance.getOriginType() == OriginTypeEnum.VF){
+        if (instance.getOriginType() == OriginTypeEnum.VF) {
             filter.setIgnoreGroups(false);
         }
         return filter;
     }
-
-}
\ No newline at end of file
+}
index 7871176..57ebcf6 100644 (file)
@@ -17,7 +17,6 @@
  * limitations under the License.
  * ============LICENSE_END=========================================================
  */
-
 package org.openecomp.sdc.be.tosca;
 
 import static org.openecomp.sdc.be.utils.CommonBeUtils.compareAsdcComponentVersions;
@@ -35,11 +34,11 @@ import org.openecomp.sdc.be.model.Component;
  * Provides caching abilities for components
  */
 public final class ComponentCache {
-
     // TODO: Make this final whenever possible. The current code using the class
+
+    private final BinaryOperator<CacheEntry> merge;
     // does not allow this.
     private Map<String, CacheEntry> entries = HashMap.empty();
-    private final BinaryOperator<CacheEntry> merge;
 
     private ComponentCache(BinaryOperator<CacheEntry> merge) {
         this.merge = merge;
@@ -47,6 +46,7 @@ public final class ComponentCache {
 
     /**
      * Creates an overwritable cache based on a merging strategy
+     *
      * @param merge The strategy used to merge two values which keys are the same
      */
     public static ComponentCache overwritable(BinaryOperator<CacheEntry> merge) {
@@ -55,8 +55,9 @@ public final class ComponentCache {
 
     /**
      * Creates a cached entry
-     * @param id The id of the entry
-     * @param fileName the filename of the entry
+     *
+     * @param id        The id of the entry
+     * @param fileName  the filename of the entry
      * @param component the cached component
      */
     public static CacheEntry entry(String id, String fileName, Component component) {
@@ -65,57 +66,22 @@ public final class ComponentCache {
 
     /**
      * Decorate the cache with a listener called whenever a value is merged
+     *
      * @param bc the consumer called when a value is merged
      */
     public ComponentCache onMerge(BiConsumer<CacheEntry, CacheEntry> bc) {
         return new ComponentCache((oldValue, newValue) -> {
             CacheEntry value = merge.apply(oldValue, newValue);
-            if(value.equals(newValue)) {
+            if (value.equals(newValue)) {
                 bc.accept(oldValue, newValue);
             }
             return value;
         });
     }
 
-    public interface MergeStrategy {
-
-        /**
-         * A strategy designed to favour the latest component version when merging two cached entries
-         */
-        static BinaryOperator<CacheEntry> overwriteIfSameVersions() {
-            return (oldValue, newValue) ->
-                compareAsdcComponentVersions(newValue.getComponentVersion(), oldValue.getComponentVersion()) ?
-                    newValue : oldValue;
-        }
-    }
-
-    /**
-     * Entry stored by the cache
-     */
-    @EqualsAndHashCode
-    public static final class CacheEntry {
-        final String id;
-
-        final String fileName;
-
-        final Component component;
-        CacheEntry(String id, String fileName, Component component) {
-            this.id = id;
-            this.fileName = fileName;
-            this.component = component;
-        }
-
-        public String getComponentVersion() {
-            return component.getVersion();
-        }
-    }
-
-    // TODO: Encapsulate the cache and expose functions to interact with it
     // For now we'll keep this as is, to prevent the refactoring to be too big
     public Iterable<ImmutableTriple<String, String, Component>> iterable() {
-        return all().map(e ->
-            new ImmutableTriple<>(e.id, e.fileName, e.component)
-        );
+        return all().map(e -> new ImmutableTriple<>(e.id, e.fileName, e.component));
     }
 
     /**
@@ -124,9 +90,11 @@ public final class ComponentCache {
     public Stream<CacheEntry> all() {
         return entries.values().toStream();
     }
+    // TODO: Encapsulate the cache and expose functions to interact with it
 
     /**
      * Tells if an entry has been cached for a specific key
+     *
      * @param key The key used to index the entry
      */
     public boolean notCached(String key) {
@@ -134,23 +102,50 @@ public final class ComponentCache {
     }
 
     /**
-     * Store an entry in the cache. Keep in mind that currently this mutates the cache and does not work in a
-     * referentially transparent way (This should be fixed whenever possible).
+     * Store an entry in the cache. Keep in mind that currently this mutates the cache and does not work in a referentially transparent way (This
+     * should be fixed whenever possible).
      *
-     * @param id The id of the entry
-     * @param fileName the filename of the entry
+     * @param id        The id of the entry
+     * @param fileName  the filename of the entry
      * @param component the cached component
      */
-    public ComponentCache put(
-        String id,
-        String fileName,
-        Component component
-    ) {
+    public ComponentCache put(String id, String fileName, Component component) {
         String uuid = component.getInvariantUUID();
         CacheEntry entry = new CacheEntry(id, fileName, component);
         // TODO: Make the entries final whenever possible. The current code using the class does not allow this
         entries = entries.put(uuid, entry, merge);
-
         return this;
     }
+
+    public interface MergeStrategy {
+
+        /**
+         * A strategy designed to favour the latest component version when merging two cached entries
+         */
+        static BinaryOperator<CacheEntry> overwriteIfSameVersions() {
+            return (oldValue, newValue) -> compareAsdcComponentVersions(newValue.getComponentVersion(), oldValue.getComponentVersion()) ? newValue
+                : oldValue;
+        }
+    }
+
+    /**
+     * Entry stored by the cache
+     */
+    @EqualsAndHashCode
+    public static final class CacheEntry {
+
+        final String id;
+        final String fileName;
+        final Component component;
+
+        CacheEntry(String id, String fileName, Component component) {
+            this.id = id;
+            this.fileName = fileName;
+            this.component = component;
+        }
+
+        public String getComponentVersion() {
+            return component.getVersion();
+        }
+    }
 }
index fe802f9..3597c5c 100644 (file)
  * limitations under the License.
  * ============LICENSE_END=========================================================
  */
-
 package org.openecomp.sdc.be.tosca;
 
-
 import static org.openecomp.sdc.be.tosca.ComponentCache.MergeStrategy.overwriteIfSameVersions;
 import static org.openecomp.sdc.be.tosca.FJToVavrHelper.Try0.fromEither;
 
 import fj.F;
 import fj.data.Either;
-import java.text.SimpleDateFormat;
 import io.vavr.Tuple2;
 import io.vavr.control.Option;
 import io.vavr.control.Try;
@@ -34,6 +31,7 @@ import java.io.BufferedOutputStream;
 import java.io.ByteArrayInputStream;
 import java.io.File;
 import java.io.IOException;
+import java.text.SimpleDateFormat;
 import java.util.ArrayList;
 import java.util.Arrays;
 import java.util.Date;
@@ -114,76 +112,67 @@ import org.yaml.snakeyaml.Yaml;
 
 /**
  * @author tg851x
- *
  */
 @org.springframework.stereotype.Component("csar-utils")
 public class CsarUtils {
+
+    public static final String NODES_YML = "nodes.yml";
+    public static final String ARTIFACTS_PATH = "Artifacts/";
+    public static final String WORKFLOW_ARTIFACT_DIR = "Workflows" + File.separator + "BPMN" + File.separator;
+    public static final String DEPLOYMENT_ARTIFACTS_DIR = "Deployment" + File.separator;
+    public static final String ARTIFACTS = "Artifacts";
+    public static final String ARTIFACT_CREATED_FROM_CSAR = "Artifact created from csar";
     private static final Logger log = Logger.getLogger(CsarUtils.class);
     private static final LoggerSupportability loggerSupportability = LoggerSupportability.getLogger(CsarUtils.class.getName());
     private static final String PATH_DELIMITER = "/";
-    public static final String NODES_YML = "nodes.yml";
-    @Autowired
-    private SdcSchemaFilesCassandraDao sdcSchemaFilesCassandraDao;
-    @Autowired
-    private ArtifactCassandraDao artifactCassandraDao;
-    @Autowired
-    private ComponentsUtils componentsUtils;
-    @Autowired
-    private ToscaExportHandler toscaExportUtils;
-    @Autowired
-    protected ToscaOperationFacade toscaOperationFacade;
-
-    @Autowired(required = false)
-    private List<CsarEntryGenerator> generators;
-
     private static final String CONFORMANCE_LEVEL = ConfigurationManager.getConfigurationManager().getConfiguration().getToscaConformanceLevel();
     private static final String SDC_VERSION = ExternalConfiguration.getAppVersion();
-    public static final String ARTIFACTS_PATH = "Artifacts/";
     private static final String RESOURCES_PATH = "Resources/";
     private static final String DEFINITIONS_PATH = "Definitions/";
-    public static final String WORKFLOW_ARTIFACT_DIR = "Workflows"+File.separator+"BPMN"+File.separator;
-    public static final String DEPLOYMENT_ARTIFACTS_DIR = "Deployment"+File.separator;
     private static final String CSAR_META_VERSION = "1.0";
     private static final String CSAR_META_PATH_FILE_NAME = "csar.meta";
     private static final String TOSCA_META_PATH_FILE_NAME = "TOSCA-Metadata/TOSCA.meta";
     private static final String TOSCA_META_VERSION = "1.0";
     private static final String CSAR_VERSION = "1.1";
     // add manifest
-       private static final String Service_Manifest = "NS.mf";
-    public static final String ARTIFACTS = "Artifacts";
+    private static final String Service_Manifest = "NS.mf";
     private static final String DEFINITION = "Definitions";
     private static final String DEL_PATTERN = "([/\\\\]+)";
     private static final String WORD_PATTERN = "\\w\\_\\@\\-\\.\\s]+)";
     public static final String VALID_ENGLISH_ARTIFACT_NAME = "([" + WORD_PATTERN;
+    public static final String VF_NODE_TYPE_ARTIFACTS_PATH_PATTERN = ARTIFACTS + DEL_PATTERN +
+        // Artifact Group (i.e Deployment/Informational)
+        VALID_ENGLISH_ARTIFACT_NAME + DEL_PATTERN +
+        // Artifact Type
+        VALID_ENGLISH_ARTIFACT_NAME + DEL_PATTERN +
+        // Artifact Any File Name
+        ".+";
+    public static final String SERVICE_TEMPLATE_PATH_PATTERN = DEFINITION + DEL_PATTERN +
+        // Service Template File Name
+        VALID_ENGLISH_ARTIFACT_NAME;
     private static final String VALID_ENGLISH_ARTIFACT_NAME_WITH_DIGITS = "([\\d" + WORD_PATTERN;
     private static final String ARTIFACT_NAME_UNIQUE_ID = "ArtifactName {}, unique ID {}";
-
-    private static final String VFC_NODE_TYPE_ARTIFACTS_PATH_PATTERN = ARTIFACTS + DEL_PATTERN +
-                                                                              ImportUtils.Constants.USER_DEFINED_RESOURCE_NAMESPACE_PREFIX +
-                                                                              VALID_ENGLISH_ARTIFACT_NAME_WITH_DIGITS + DEL_PATTERN +
-                                                                              VALID_ENGLISH_ARTIFACT_NAME_WITH_DIGITS + DEL_PATTERN +
-                                                                              VALID_ENGLISH_ARTIFACT_NAME_WITH_DIGITS + DEL_PATTERN +
-                                                                              VALID_ENGLISH_ARTIFACT_NAME_WITH_DIGITS;
-
-    public static final String VF_NODE_TYPE_ARTIFACTS_PATH_PATTERN = ARTIFACTS + DEL_PATTERN+
-                                                                             // Artifact Group (i.e Deployment/Informational)
-                                                                             VALID_ENGLISH_ARTIFACT_NAME + DEL_PATTERN +
-                                                                             // Artifact Type
-                                                                             VALID_ENGLISH_ARTIFACT_NAME  + DEL_PATTERN +
-                                                                             // Artifact Any File Name
-                                                                             ".+";
-
-    public static final String SERVICE_TEMPLATE_PATH_PATTERN = DEFINITION + DEL_PATTERN+
-                                                                       // Service Template File Name
-                                                                       VALID_ENGLISH_ARTIFACT_NAME;
-
-    public static final String ARTIFACT_CREATED_FROM_CSAR = "Artifact created from csar";
+    private static final String VFC_NODE_TYPE_ARTIFACTS_PATH_PATTERN =
+        ARTIFACTS + DEL_PATTERN + ImportUtils.Constants.USER_DEFINED_RESOURCE_NAMESPACE_PREFIX + VALID_ENGLISH_ARTIFACT_NAME_WITH_DIGITS + DEL_PATTERN
+            + VALID_ENGLISH_ARTIFACT_NAME_WITH_DIGITS + DEL_PATTERN + VALID_ENGLISH_ARTIFACT_NAME_WITH_DIGITS + DEL_PATTERN
+            + VALID_ENGLISH_ARTIFACT_NAME_WITH_DIGITS;
     private static final String BLOCK_0_TEMPLATE = "SDC-TOSCA-Meta-File-Version: %s\nSDC-TOSCA-Definitions-Version: %s\n";
-
+    @Autowired
+    protected ToscaOperationFacade toscaOperationFacade;
+    @Autowired
+    private SdcSchemaFilesCassandraDao sdcSchemaFilesCassandraDao;
+    @Autowired
+    private ArtifactCassandraDao artifactCassandraDao;
+    @Autowired
+    private ComponentsUtils componentsUtils;
+    @Autowired
+    private ToscaExportHandler toscaExportUtils;
+    @Autowired(required = false)
+    private List<CsarEntryGenerator> generators;
     private String versionFirstThreeOctets;
 
     public CsarUtils() {
-        if(SDC_VERSION != null && !SDC_VERSION.isEmpty()){
+        if (SDC_VERSION != null && !SDC_VERSION.isEmpty()) {
             Matcher matcher = Pattern.compile("(?!\\.)(\\d+(\\.\\d+)+)(?![\\d\\.])").matcher(SDC_VERSION);
             matcher.find();
             setVersionFirstThreeOctets(matcher.group(0));
@@ -192,39 +181,201 @@ public class CsarUtils {
         }
     }
 
+    private static <L, R> F<L, Either<L, R>> iff(Predicate<L> p, Function<L, Either<L, R>> ifTrue) {
+        return l -> p.test(l) ? ifTrue.apply(l) : Either.left(l);
+    }
+
+    private static <A, B> F<A, B> iff(Predicate<A> p, Supplier<B> s, Function<A, B> orElse) {
+        return a -> p.test(a) ? s.get() : orElse.apply(a);
+    }
+
+    /**
+     * Extracts artifacts of VFCs from CSAR
+     *
+     * @param csar
+     * @return Map of <String, List<ArtifactDefinition>> the contains Lists of artifacts according vfcToscaNamespace
+     */
+    public static Map<String, List<ArtifactDefinition>> extractVfcsArtifactsFromCsar(Map<String, byte[]> csar) {
+        Map<String, List<ArtifactDefinition>> artifacts = new HashMap<>();
+        if (csar != null) {
+            log.debug("************* Going to extract VFCs artifacts from Csar. ");
+            Map<String, Set<List<String>>> collectedWarningMessages = new HashMap<>();
+            csar.entrySet().stream()
+                // filter CSAR entry by node type artifact path
+                .filter(e -> Pattern.compile(VFC_NODE_TYPE_ARTIFACTS_PATH_PATTERN).matcher(e.getKey()).matches())
+                // extract ArtifactDefinition from CSAR entry for each entry with matching artifact path
+                .forEach(e -> extractVfcArtifact(e, collectedWarningMessages).ifPresent(ip -> addExtractedVfcArtifact(ip, artifacts)));
+            // add counter suffix to artifact labels
+            handleWarningMessages(collectedWarningMessages);
+        }
+        return artifacts;
+    }
+
+    /**
+     * Print warnings to log
+     *
+     * @param collectedWarningMessages
+     */
+    public static void handleWarningMessages(Map<String, Set<List<String>>> collectedWarningMessages) {
+        collectedWarningMessages.entrySet().stream()
+            // for each vfc
+            .forEach(e -> e.getValue().stream()
+                // add each warning message to log
+                .forEach(args -> log.warn(e.getKey(), args.toArray())));
+    }
+
+    private static void addExtractedVfcArtifact(ImmutablePair<String, ArtifactDefinition> extractedVfcArtifact,
+                                                Map<String, List<ArtifactDefinition>> artifacts) {
+        String vfcToscaNamespace = extractedVfcArtifact.getKey();
+        artifacts.computeIfAbsent(vfcToscaNamespace, k -> new ArrayList<>());
+        artifacts.get(vfcToscaNamespace).add(extractedVfcArtifact.getValue());
+    }
+
+    private static Optional<ImmutablePair<String, ArtifactDefinition>> extractVfcArtifact(Entry<String, byte[]> entry,
+                                                                                          Map<String, Set<List<String>>> collectedWarningMessages) {
+        String[] parsedCsarArtifactPath = entry.getKey().split(PATH_DELIMITER);
+        String groupType = parsedCsarArtifactPath[2].toUpperCase();
+        return detectArtifactGroupType(groupType, collectedWarningMessages).left()
+            .map(buildArtifactDefinitionFromCsarArtifactPath(entry, collectedWarningMessages, parsedCsarArtifactPath))
+            .either(ad -> Optional.of(new ImmutablePair<>(parsedCsarArtifactPath[1], ad)), b -> Optional.empty());
+    }
+
+    private static Either<ArtifactGroupTypeEnum, Boolean> detectArtifactGroupType(String groupType,
+                                                                                  Map<String, Set<List<String>>> collectedWarningMessages) {
+        Either<ArtifactGroupTypeEnum, Boolean> result;
+        try {
+            ArtifactGroupTypeEnum artifactGroupType = ArtifactGroupTypeEnum.findType(groupType.toUpperCase());
+            if (artifactGroupType == null || (artifactGroupType != ArtifactGroupTypeEnum.INFORMATIONAL
+                && artifactGroupType != ArtifactGroupTypeEnum.DEPLOYMENT)) {
+                String warningMessage = "Warning - unrecognized artifact group type {} was received.";
+                List<String> messageArguments = new ArrayList<>();
+                messageArguments.add(groupType);
+                if (!collectedWarningMessages.containsKey(warningMessage)) {
+                    Set<List<String>> messageArgumentLists = new HashSet<>();
+                    messageArgumentLists.add(messageArguments);
+                    collectedWarningMessages.put(warningMessage, messageArgumentLists);
+                } else {
+                    collectedWarningMessages.get(warningMessage).add(messageArguments);
+                }
+                result = Either.right(false);
+            } else {
+                result = Either.left(artifactGroupType);
+            }
+        } catch (Exception e) {
+            log.debug("detectArtifactGroupType failed with exception", e);
+            result = Either.right(false);
+        }
+        return result;
+    }
+
+    private static F<ArtifactGroupTypeEnum, ArtifactDefinition> buildArtifactDefinitionFromCsarArtifactPath(Entry<String, byte[]> entry,
+                                                                                                            Map<String, Set<List<String>>> collectedWarningMessages,
+                                                                                                            String[] parsedCsarArtifactPath) {
+        return artifactGroupType -> {
+            ArtifactDefinition artifact;
+            artifact = new ArtifactDefinition();
+            artifact.setArtifactGroupType(artifactGroupType);
+            artifact.setArtifactType(
+                detectArtifactTypeVFC(artifactGroupType, parsedCsarArtifactPath[3], parsedCsarArtifactPath[1], collectedWarningMessages));
+            artifact.setArtifactName(ValidationUtils.normalizeFileName(parsedCsarArtifactPath[parsedCsarArtifactPath.length - 1]));
+            artifact.setPayloadData(Base64.encodeBase64String(entry.getValue()));
+            artifact.setArtifactDisplayName(
+                artifact.getArtifactName().lastIndexOf('.') > 0 ? artifact.getArtifactName().substring(0, artifact.getArtifactName().lastIndexOf('.'))
+                    : artifact.getArtifactName());
+            artifact.setArtifactLabel(ValidationUtils.normalizeArtifactLabel(artifact.getArtifactName()));
+            artifact.setDescription(ARTIFACT_CREATED_FROM_CSAR);
+            artifact.setIsFromCsar(true);
+            artifact.setArtifactChecksum(GeneralUtility.calculateMD5Base64EncodedByByteArray(entry.getValue()));
+            return artifact;
+        };
+    }
+
     /**
+     * This method checks the artifact GroupType & Artifact Type. <br> if there is any problem warning messages are added to collectedWarningMessages
      *
+     * @param artifactPath
+     * @param collectedWarningMessages
+     * @return
+     */
+    public static Either<NonMetaArtifactInfo, Boolean> validateNonMetaArtifact(String artifactPath, byte[] payloadData,
+                                                                               Map<String, Set<List<String>>> collectedWarningMessages) {
+        try {
+            String[] parsedArtifactPath = artifactPath.split(PATH_DELIMITER);
+            String groupType = parsedArtifactPath[1];
+            String receivedTypeName = parsedArtifactPath[2];
+            String artifactFileNameType = parsedArtifactPath[3];
+            return detectArtifactGroupType(groupType, collectedWarningMessages).left().bind(artifactGroupType -> {
+                String artifactType = detectArtifactTypeVF(artifactGroupType, receivedTypeName, collectedWarningMessages);
+                return Either
+                    .left(new NonMetaArtifactInfo(artifactFileNameType, artifactPath, artifactType, artifactGroupType, payloadData, null, true));
+            });
+        } catch (Exception e) {
+            log.debug("detectArtifactGroupType failed with exception", e);
+            return Either.right(false);
+        }
+    }
+
+    private static String detectArtifactTypeVFC(ArtifactGroupTypeEnum artifactGroupType, String receivedTypeName, String parentVfName,
+                                                Map<String, Set<List<String>>> collectedWarningMessages) {
+        String warningMessage = "Warning - artifact type {} that was provided for VFC {} is not recognized.";
+        return detectArtifactType(artifactGroupType, receivedTypeName, warningMessage, collectedWarningMessages, parentVfName);
+    }
+
+    private static String detectArtifactTypeVF(ArtifactGroupTypeEnum artifactGroupType, String receivedTypeName,
+                                               Map<String, Set<List<String>>> collectedWarningMessages) {
+        String warningMessage = "Warning - artifact type {} that was provided for VF is not recognized.";
+        return detectArtifactType(artifactGroupType, receivedTypeName, warningMessage, collectedWarningMessages);
+    }
+
+    private static String detectArtifactType(final ArtifactGroupTypeEnum artifactGroupType, final String receivedTypeName,
+                                             final String warningMessage, final Map<String, Set<List<String>>> collectedWarningMessages,
+                                             final String... arguments) {
+        final ArtifactConfiguration artifactConfiguration = ArtifactConfigManager.getInstance()
+            .find(receivedTypeName, artifactGroupType, ComponentType.RESOURCE).orElse(null);
+        if (artifactConfiguration == null) {
+            final List<String> messageArguments = new ArrayList<>();
+            messageArguments.add(receivedTypeName);
+            messageArguments.addAll(Arrays.asList(arguments));
+            if (!collectedWarningMessages.containsKey(warningMessage)) {
+                final Set<List<String>> messageArgumentLists = new HashSet<>();
+                messageArgumentLists.add(messageArguments);
+                collectedWarningMessages.put(warningMessage, messageArgumentLists);
+            } else {
+                collectedWarningMessages.get(warningMessage).add(messageArguments);
+            }
+        }
+        return artifactConfiguration == null ? ArtifactTypeEnum.OTHER.getType() : receivedTypeName;
+    }
+
+    /**
      * @param component
      * @param getFromCS
      * @param isInCertificationRequest
      * @return
      */
     public Either<byte[], ResponseFormat> createCsar(Component component, boolean getFromCS, boolean isInCertificationRequest) {
-        loggerSupportability.log(LoggerSupportabilityActions.GENERATE_CSAR, StatusCode.STARTED,"Starting to create Csar for component {} ",component.getName());
+        loggerSupportability
+            .log(LoggerSupportabilityActions.GENERATE_CSAR, StatusCode.STARTED, "Starting to create Csar for component {} ", component.getName());
         final String createdBy = component.getCreatorFullName();
         String fileName;
         Map<String, ArtifactDefinition> toscaArtifacts = component.getToscaArtifacts();
         ArtifactDefinition artifactDefinition = toscaArtifacts.get(ToscaExportHandler.ASSET_TOSCA_TEMPLATE);
         fileName = artifactDefinition.getArtifactName();
-
         String toscaConformanceLevel = ConfigurationManager.getConfigurationManager().getConfiguration().getToscaConformanceLevel();
         String csarBlock0 = createCsarBlock0(CSAR_META_VERSION, toscaConformanceLevel);
         byte[] csarBlock0Byte = csarBlock0.getBytes();
-
         final String toscaBlock0 = createToscaBlock0(TOSCA_META_VERSION, CSAR_VERSION, createdBy, fileName);
         byte[] toscaBlock0Byte = toscaBlock0.getBytes();
-
-        return generateCsarZip(csarBlock0Byte, toscaBlock0Byte, component, getFromCS, isInCertificationRequest)
-            .left().map(responseFormat -> {
-            loggerSupportability.log(LoggerSupportabilityActions.GENERATE_CSAR, StatusCode.COMPLETE,
-                "Ended create Csar for component {} ", component.getName());
+        return generateCsarZip(csarBlock0Byte, toscaBlock0Byte, component, getFromCS, isInCertificationRequest).left().map(responseFormat -> {
+            loggerSupportability
+                .log(LoggerSupportabilityActions.GENERATE_CSAR, StatusCode.COMPLETE, "Ended create Csar for component {} ", component.getName());
             return responseFormat;
         });
     }
 
-    private Either<byte[], ResponseFormat> generateCsarZip(byte[] csarBlock0Byte, byte[] toscaBlock0Byte, Component component, boolean getFromCS, boolean isInCertificationRequest) {
-        try (ByteArrayOutputStream out = new ByteArrayOutputStream();
-             ZipOutputStream zip = new ZipOutputStream(out)) {
+    private Either<byte[], ResponseFormat> generateCsarZip(byte[] csarBlock0Byte, byte[] toscaBlock0Byte, Component component, boolean getFromCS,
+                                                           boolean isInCertificationRequest) {
+        try (ByteArrayOutputStream out = new ByteArrayOutputStream(); ZipOutputStream zip = new ZipOutputStream(out)) {
             zip.putNextEntry(new ZipEntry(CSAR_META_PATH_FILE_NAME));
             zip.write(csarBlock0Byte);
             zip.putNextEntry(new ZipEntry(TOSCA_META_PATH_FILE_NAME));
@@ -234,160 +385,118 @@ public class CsarUtils {
                 log.debug("Failed to populate CSAR zip file {}. Please fix DB table accordingly ", populateZip.right().value());
                 return Either.right(populateZip.right().value());
             }
-
             zip.finish();
             byte[] byteArray = out.toByteArray();
-
             return Either.left(byteArray);
         } catch (IOException e) {
             log.debug("Failed with IOexception to create CSAR zip for component {}. Please fix DB table accordingly ", component.getUniqueId(), e);
-
             ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR);
             return Either.right(responseFormat);
         }
-}
-
-    private Either<ZipOutputStream, ResponseFormat> populateZip(Component component, boolean getFromCS, ZipOutputStream zip, boolean isInCertificationRequest) throws IOException {
-
-        ArtifactDefinition artifactDef = component
-            .getToscaArtifacts()
-            .get(ToscaExportHandler.ASSET_TOSCA_TEMPLATE);
-
-        Either<ToscaRepresentation, ResponseFormat> toscaRepresentation =
-            fetchToscaRepresentation(component, getFromCS, artifactDef);
+    }
 
+    private Either<ZipOutputStream, ResponseFormat> populateZip(Component component, boolean getFromCS, ZipOutputStream zip,
+                                                                boolean isInCertificationRequest) throws IOException {
+        ArtifactDefinition artifactDef = component.getToscaArtifacts().get(ToscaExportHandler.ASSET_TOSCA_TEMPLATE);
+        Either<ToscaRepresentation, ResponseFormat> toscaRepresentation = fetchToscaRepresentation(component, getFromCS, artifactDef);
         // This should not be done but in order to keep the refactoring small enough we stop here.
+
         // TODO: Refactor the rest of this function
         byte[] mainYaml;
         List<Triple<String, String, Component>> dependencies;
-        if(toscaRepresentation.isLeft()) {
+        if (toscaRepresentation.isLeft()) {
             mainYaml = toscaRepresentation.left().value().getMainYaml();
             dependencies = toscaRepresentation.left().value().getDependencies().getOrElse(new ArrayList<>());
         } else {
             return Either.right(toscaRepresentation.right().value());
         }
-
         String fileName = artifactDef.getArtifactName();
         zip.putNextEntry(new ZipEntry(DEFINITIONS_PATH + fileName));
         zip.write(mainYaml);
-               
         LifecycleStateEnum lifecycleState = component.getLifecycleState();
         addServiceMf(component, zip, lifecycleState, isInCertificationRequest, fileName, mainYaml);
-
         //US798487 - Abstraction of complex types
-        if (!ModelConverter.isAtomicComponent(component)){
+        if (!ModelConverter.isAtomicComponent(component)) {
             log.debug("Component {} is complex - generating abstract type for it..", component.getName());
-                             writeComponentInterface(component, zip, fileName, false);
+            writeComponentInterface(component, zip, fileName, false);
         }
-
         //UID <cassandraId,filename,component>
         Either<ZipOutputStream, ResponseFormat> zipOutputStreamOrResponseFormat = getZipOutputStreamResponseFormatEither(zip, dependencies);
         if (zipOutputStreamOrResponseFormat != null && zipOutputStreamOrResponseFormat.isRight()) {
-                return zipOutputStreamOrResponseFormat;
+            return zipOutputStreamOrResponseFormat;
         }
-
         //retrieve SDC.zip from Cassandra
         Either<byte[], ResponseFormat> latestSchemaFilesFromCassandra = getLatestSchemaFilesFromCassandra();
-
-        if(latestSchemaFilesFromCassandra.isRight()){
+        if (latestSchemaFilesFromCassandra.isRight()) {
             log.error("Error retrieving SDC Schema files from cassandra");
             return Either.right(latestSchemaFilesFromCassandra.right().value());
         }
-
         final byte[] schemaFileZip = latestSchemaFilesFromCassandra.left().value();
-
         final List<String> nodesFromPackage = findNonRootNodesFromPackage(dependencies);
-
         //add files from retrieved SDC.zip to Definitions folder in CSAR
         addSchemaFilesFromCassandra(zip, schemaFileZip, nodesFromPackage);
-
         Either<CsarDefinition, ResponseFormat> collectedComponentCsarDefinition = collectComponentCsarDefinition(component);
-
         if (collectedComponentCsarDefinition.isRight()) {
             return Either.right(collectedComponentCsarDefinition.right().value());
         }
-
         if (generators != null) {
-               for (CsarEntryGenerator generator: generators) {
-                   log.debug("Invoking CsarEntryGenerator: {}", generator.getClass().getName());
-                       for (Entry<String, byte[]> pluginGeneratedFile : generator.generateCsarEntries(component).entrySet()) {
+            for (CsarEntryGenerator generator : generators) {
+                log.debug("Invoking CsarEntryGenerator: {}", generator.getClass().getName());
+                for (Entry<String, byte[]> pluginGeneratedFile : generator.generateCsarEntries(component).entrySet()) {
                     zip.putNextEntry(new ZipEntry(pluginGeneratedFile.getKey()));
                     zip.write(pluginGeneratedFile.getValue());
-                       }
-               }
+                }
+            }
         }
-
         return writeAllFilesToCsar(component, collectedComponentCsarDefinition.left().value(), zip, isInCertificationRequest);
     }
 
-    private void addServiceMf(Component component, ZipOutputStream zip, LifecycleStateEnum lifecycleState, boolean isInCertificationRequest, String fileName, byte[] mainYaml) throws IOException{
+    private void addServiceMf(Component component, ZipOutputStream zip, LifecycleStateEnum lifecycleState, boolean isInCertificationRequest,
+                              String fileName, byte[] mainYaml) throws IOException {
         // add mf
-        if((component.getComponentType() == ComponentTypeEnum.SERVICE) && (lifecycleState != LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT)){
+        if ((component.getComponentType() == ComponentTypeEnum.SERVICE) && (lifecycleState != LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT)) {
             String serviceName = component.getName();
             String createdBy = component.getCreatorUserId();
             String serviceVersion;
-            if(isInCertificationRequest){
+            if (isInCertificationRequest) {
                 int tmp = Integer.valueOf(component.getVersion().split("\\.")[0]) + 1;
                 serviceVersion = String.valueOf(tmp) + ".0";
-            }
-            else{
+            } else {
                 serviceVersion = component.getVersion();
             }
-
             SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd'T'hh:mm:ss'Z'");
             format.setTimeZone(TimeZone.getTimeZone("UTC"));
-
             Date date = new Date();
             String releaseTime = format.format(date);
-
-            if (component.getCategories() == null || component.getCategories().get(0) == null){
+            if (component.getCategories() == null || component.getCategories().get(0) == null) {
                 return;
             }
-
             String serviceType = component.getCategories().get(0).getName();
             String description = component.getDescription();
             String serviceTemplate = DEFINITIONS_PATH + fileName;
             String hash = GeneralUtility.calculateMD5Base64EncodedByByteArray(mainYaml);
-            String nsMfBlock0 = createNsMfBlock0(serviceName, createdBy, serviceVersion, releaseTime, serviceType, description, serviceTemplate, hash);
+            String nsMfBlock0 = createNsMfBlock0(serviceName, createdBy, serviceVersion, releaseTime, serviceType, description, serviceTemplate,
+                hash);
             byte[] nsMfBlock0Byte = nsMfBlock0.getBytes();
             zip.putNextEntry(new ZipEntry(Service_Manifest));
             zip.write(nsMfBlock0Byte);
         }
     }
 
-    private Either<ToscaRepresentation, ResponseFormat> fetchToscaRepresentation(
-        Component component,
-        boolean getFromCS,
-        ArtifactDefinition artifactDef
-    ) {
+    private Either<ToscaRepresentation, ResponseFormat> fetchToscaRepresentation(Component component, boolean getFromCS,
+                                                                                 ArtifactDefinition artifactDef) {
         LifecycleStateEnum lifecycleState = component.getLifecycleState();
-
-        boolean shouldBeFetchedFromCassandra = getFromCS ||
-            !(lifecycleState == LifecycleStateEnum.NOT_CERTIFIED_CHECKIN ||
-                lifecycleState == LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT);
-
+        boolean shouldBeFetchedFromCassandra =
+            getFromCS || !(lifecycleState == LifecycleStateEnum.NOT_CERTIFIED_CHECKIN || lifecycleState == LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT);
         Either<ToscaRepresentation, ResponseFormat> toscaRepresentation =
-            shouldBeFetchedFromCassandra ?
-                fetchToscaRepresentation(artifactDef) :
-                generateToscaRepresentation(component);
-
-        return toscaRepresentation.left().bind(iff(
-            myd -> !myd.getDependencies().isDefined(),
-            myd -> fetchToscaTemplateDependencies(myd.getMainYaml(), component)
-        ));
-    }
-
-    private static <L, R> F<L, Either<L, R>> iff(Predicate<L> p, Function<L, Either<L, R>> ifTrue) {
-        return l -> p.test(l) ? ifTrue.apply(l) : Either.left(l);
+            shouldBeFetchedFromCassandra ? fetchToscaRepresentation(artifactDef) : generateToscaRepresentation(component);
+        return toscaRepresentation.left()
+            .bind(iff(myd -> !myd.getDependencies().isDefined(), myd -> fetchToscaTemplateDependencies(myd.getMainYaml(), component)));
     }
 
-    private Either<ToscaRepresentation, ResponseFormat> fetchToscaTemplateDependencies(
-        byte[] mainYml,
-        Component component
-    ) {
+    private Either<ToscaRepresentation, ResponseFormat> fetchToscaTemplateDependencies(byte[] mainYml, Component component) {
         return toscaExportUtils.getDependencies(component).right().map(toscaError -> {
-            log.debug("Failed to retrieve dependencies for component {}, error {}",
-                component.getUniqueId(), toscaError);
+            log.debug("Failed to retrieve dependencies for component {}, error {}", component.getUniqueId(), toscaError);
             return componentsUtils.getResponseFormat(componentsUtils.convertFromToscaError(toscaError));
         }).left().map(tt -> ToscaRepresentation.make(mainYml, tt));
     }
@@ -420,8 +529,7 @@ public class CsarUtils {
                 if (dependency.getRight() instanceof Resource) {
                     final Resource resource = (Resource) dependency.getRight();
                     if (CollectionUtils.isNotEmpty(resource.getDerivedList())) {
-                        resource.getDerivedList().stream()
-                            .filter(node -> !nodes.contains(node) && !NATIVE_ROOT.equalsIgnoreCase(node))
+                        resource.getDerivedList().stream().filter(node -> !nodes.contains(node) && !NATIVE_ROOT.equalsIgnoreCase(node))
                             .forEach(node -> nodes.add(node));
                     }
                 }
@@ -444,30 +552,23 @@ public class CsarUtils {
         while ((read = zipInputStream.read(buffer, 0, initSize)) >= 0) {
             zipEntry.append(new String(buffer, 0, read));
         }
-
         return (Map<String, Object>) new Yaml().load(zipEntry.toString());
     }
 
     /**
      * Filters and removes all duplicated nodes found
      *
-     * @param nodesFromPackage a List of all derived nodes found on the given package
+     * @param nodesFromPackage      a List of all derived nodes found on the given package
      * @param nodesFromArtifactFile represents the nodes.yml file stored in Cassandra
      * @return a nodes Map updated
      */
-    private Map<String, Object> updateNodeYml(final List<String> nodesFromPackage,
-                                              final Map<String, Object> nodesFromArtifactFile) {
-
+    private Map<String, Object> updateNodeYml(final List<String> nodesFromPackage, final Map<String, Object> nodesFromArtifactFile) {
         if (MapUtils.isNotEmpty(nodesFromArtifactFile)) {
             final String nodeTypeBlock = ToscaTagNamesEnum.NODE_TYPES.getElementName();
             final Map<String, Object> nodeTypes = (Map<String, Object>) nodesFromArtifactFile.get(nodeTypeBlock);
-            nodesFromPackage.stream()
-                .filter(nodeTypes::containsKey)
-                .forEach(nodeTypes::remove);
-
+            nodesFromPackage.stream().filter(nodeTypes::containsKey).forEach(nodeTypes::remove);
             nodesFromArtifactFile.replace(nodeTypeBlock, nodeTypes);
         }
-
         return nodesFromArtifactFile;
     }
 
@@ -475,63 +576,50 @@ public class CsarUtils {
      * Updates the zip entry from the given parameters
      *
      * @param byteArrayOutputStream an output stream in which the data is written into a byte array.
-     * @param nodesYaml a Map of nodes to be written
+     * @param nodesYaml             a Map of nodes to be written
      */
-    private void updateZipEntry(final ByteArrayOutputStream byteArrayOutputStream,
-                                final Map<String, Object> nodesYaml) throws IOException {
+    private void updateZipEntry(final ByteArrayOutputStream byteArrayOutputStream, final Map<String, Object> nodesYaml) throws IOException {
         if (MapUtils.isNotEmpty(nodesYaml)) {
             byteArrayOutputStream.write(new YamlUtil().objectToYaml(nodesYaml).getBytes());
         }
     }
 
-    private Either<ZipOutputStream, ResponseFormat> getZipOutputStreamResponseFormatEither(
-        ZipOutputStream zip,
-        List<Triple<String, String, Component>> dependencies
-    ) throws IOException {
-
-        ComponentCache innerComponentsCache = ComponentCache
-            .overwritable(overwriteIfSameVersions())
-            .onMerge((oldValue, newValue) -> {
-                log.warn("Overwriting component invariantID {} of version {} with a newer version {}",
-                    oldValue.id, oldValue.getComponentVersion(), newValue.getComponentVersion()
-                );
-            });
-
+    private Either<ZipOutputStream, ResponseFormat> getZipOutputStreamResponseFormatEither(ZipOutputStream zip,
+                                                                                           List<Triple<String, String, Component>> dependencies)
+        throws IOException {
+        ComponentCache innerComponentsCache = ComponentCache.overwritable(overwriteIfSameVersions()).onMerge((oldValue, newValue) -> {
+            log.warn("Overwriting component invariantID {} of version {} with a newer version {}", oldValue.id, oldValue.getComponentVersion(),
+                newValue.getComponentVersion());
+        });
         if (dependencies != null && !dependencies.isEmpty()) {
             for (Triple<String, String, Component> d : dependencies) {
                 String cassandraId = d.getMiddle();
                 Component childComponent = d.getRight();
-
-                Either<byte[], ResponseFormat> entryData = getEntryData(cassandraId, childComponent)
-                    .right().map(x -> componentsUtils.getResponseFormat(x));
-
+                Either<byte[], ResponseFormat> entryData = getEntryData(cassandraId, childComponent).right()
+                    .map(x -> componentsUtils.getResponseFormat(x));
                 if (entryData.isRight()) {
                     return Either.right(entryData.right().value());
                 }
-
                 //fill innerComponentsCache
                 String fileName = d.getLeft();
                 innerComponentsCache.put(cassandraId, fileName, childComponent);
                 addInnerComponentsToCache(innerComponentsCache, childComponent);
             }
-
             //add inner components to CSAR
             return addInnerComponentsToCSAR(zip, innerComponentsCache);
         }
         return null;
     }
 
-    private Either<ZipOutputStream, ResponseFormat> addInnerComponentsToCSAR(
-        ZipOutputStream zip,
-        ComponentCache innerComponentsCache
-    ) throws IOException {
+    private Either<ZipOutputStream, ResponseFormat> addInnerComponentsToCSAR(ZipOutputStream zip, ComponentCache innerComponentsCache)
+        throws IOException {
         for (ImmutableTriple<String, String, Component> ict : innerComponentsCache.iterable()) {
             Component innerComponent = ict.getRight();
-
             String icFileName = ict.getMiddle();
             // add component to zip
             Either<Tuple2<byte[], ZipEntry>, ResponseFormat> zipEntry = toZipEntry(ict);
             // TODO: this should not be done, we should instead compose this either further,
+
             // but in order to keep this refactoring small, we'll stop here.
             if (zipEntry.isRight()) {
                 return Either.right(zipEntry.right().value());
@@ -547,36 +635,29 @@ public class CsarUtils {
         return null;
     }
 
-    private Either<Tuple2<byte[], ZipEntry>, ResponseFormat> toZipEntry(
-        ImmutableTriple<String, String, Component> cachedEntry
-    ) {
+    private Either<Tuple2<byte[], ZipEntry>, ResponseFormat> toZipEntry(ImmutableTriple<String, String, Component> cachedEntry) {
         String cassandraId = cachedEntry.getLeft();
         String fileName = cachedEntry.getMiddle();
         Component innerComponent = cachedEntry.getRight();
-        return getEntryData(cassandraId, innerComponent)
-            .right().map(status -> {
-                log.debug("Failed adding to zip component {}, error {}", cassandraId, status);
-                return componentsUtils.getResponseFormat(status);
-            }).left().map(content -> new Tuple2<>(content, new ZipEntry(DEFINITIONS_PATH + fileName)));
+        return getEntryData(cassandraId, innerComponent).right().map(status -> {
+            log.debug("Failed adding to zip component {}, error {}", cassandraId, status);
+            return componentsUtils.getResponseFormat(status);
+        }).left().map(content -> new Tuple2<>(content, new ZipEntry(DEFINITIONS_PATH + fileName)));
     }
 
     /**
      * Writes to a CSAR zip from casandra schema data
      *
-     * @param zipOutputStream stores the input stream content
-     * @param schemaFileZip zip data from Cassandra
+     * @param zipOutputStream  stores the input stream content
+     * @param schemaFileZip    zip data from Cassandra
      * @param nodesFromPackage list of all nodes found on the onboarded package
      */
-    private void addSchemaFilesFromCassandra(final ZipOutputStream zipOutputStream,
-                                             final byte[] schemaFileZip,
-                                             final List<String> nodesFromPackage) {
+    private void addSchemaFilesFromCassandra(final ZipOutputStream zipOutputStream, final byte[] schemaFileZip, final List<String> nodesFromPackage) {
         final int initSize = 2048;
         log.debug("Starting copy from Schema file zip to CSAR zip");
-        try (final ZipInputStream zipInputStream = new ZipInputStream(new ByteArrayInputStream(schemaFileZip));
-            final ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
-            final BufferedOutputStream bufferedOutputStream =
-                new BufferedOutputStream(byteArrayOutputStream, initSize)) {
-
+        try (final ZipInputStream zipInputStream = new ZipInputStream(new ByteArrayInputStream(
+            schemaFileZip)); final ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream(); final BufferedOutputStream bufferedOutputStream = new BufferedOutputStream(
+            byteArrayOutputStream, initSize)) {
             ZipEntry entry;
             while ((entry = zipInputStream.getNextEntry()) != null) {
                 ZipUtils.checkForZipSlipInRead(entry);
@@ -607,58 +688,49 @@ public class CsarUtils {
     }
 
     /**
-     *  Checks if the zip entry should or should not be added to the CSAR based on the given global type list
+     * Checks if the zip entry should or should not be added to the CSAR based on the given global type list
      *
      * @param entryName the zip entry name
      * @return true if the zip entry should be handled
      */
     private boolean shouldZipEntryBeHandled(final String entryName) {
-        return ConfigurationManager.getConfigurationManager().getConfiguration()
-            .getGlobalCsarImports().stream()
+        return ConfigurationManager.getConfigurationManager().getConfiguration().getGlobalCsarImports().stream()
             .anyMatch(entry -> entry.contains(entryName));
     }
 
     /**
      * Handles the nodes.yml zip entry, updating the nodes.yml to avoid duplicated nodes on it.
      *
-     * @param zipInputStream the zip entry to be read
+     * @param zipInputStream        the zip entry to be read
      * @param byteArrayOutputStream an output stream in which the data is written into a byte array.
-     * @param nodesFromPackage list of all nodes found on the onboarded package
+     * @param nodesFromPackage      list of all nodes found on the onboarded package
      */
-    private void handleNode(final ZipInputStream zipInputStream,
-                            final ByteArrayOutputStream byteArrayOutputStream,
+    private void handleNode(final ZipInputStream zipInputStream, final ByteArrayOutputStream byteArrayOutputStream,
                             final List<String> nodesFromPackage) throws IOException {
-
         final Map<String, Object> nodesFromArtifactFile = readYamlZipEntry(zipInputStream);
         final Map<String, Object> nodesYaml = updateNodeYml(nodesFromPackage, nodesFromArtifactFile);
         updateZipEntry(byteArrayOutputStream, nodesYaml);
     }
 
     private void addInnerComponentsToCache(ComponentCache componentCache, Component childComponent) {
-        javaListToVavrList(childComponent.getComponentInstances())
-            .filter(ci -> componentCache.notCached(ci.getComponentUid()))
-            .forEach(ci -> {
-                // all resource must be only once!
-                Either<Resource, StorageOperationStatus> resource =
-                    toscaOperationFacade.getToscaElement(ci.getComponentUid());
-                Component componentRI = checkAndAddComponent(componentCache, ci, resource);
-                //if not atomic - insert inner components as well
-                // TODO: This could potentially create a StackOverflowException if the call stack
-                // happens to be too large. Tail-recursive optimization should be used here.
-                if (!ModelConverter.isAtomicComponent(componentRI)) {
-                    addInnerComponentsToCache(componentCache, componentRI);
-                }
-            });
+        javaListToVavrList(childComponent.getComponentInstances()).filter(ci -> componentCache.notCached(ci.getComponentUid())).forEach(ci -> {
+            // all resource must be only once!
+            Either<Resource, StorageOperationStatus> resource = toscaOperationFacade.getToscaElement(ci.getComponentUid());
+            Component componentRI = checkAndAddComponent(componentCache, ci, resource);
+            //if not atomic - insert inner components as well
+
+            // TODO: This could potentially create a StackOverflowException if the call stack
+
+            // happens to be too large. Tail-recursive optimization should be used here.
+            if (!ModelConverter.isAtomicComponent(componentRI)) {
+                addInnerComponentsToCache(componentCache, componentRI);
+            }
+        });
     }
 
     // TODO: Move this function in FJToVavrHelper.java once Change 108540 is merged
-    private io.vavr.collection.List<ComponentInstance> javaListToVavrList(
-        List<ComponentInstance> componentInstances
-    ) {
-        return Option
-                .of(componentInstances)
-                .map(io.vavr.collection.List::ofAll)
-                .getOrElse(io.vavr.collection.List::empty);
+    private io.vavr.collection.List<ComponentInstance> javaListToVavrList(List<ComponentInstance> componentInstances) {
+        return Option.of(componentInstances).map(io.vavr.collection.List::ofAll).getOrElse(io.vavr.collection.List::empty);
     }
 
     private Component checkAndAddComponent(ComponentCache componentCache, ComponentInstance ci, Either<Resource, StorageOperationStatus> resource) {
@@ -666,61 +738,35 @@ public class CsarUtils {
             log.debug("Failed to fetch resource with id {} for instance {}", ci.getComponentUid(), ci.getName());
         }
         Component componentRI = resource.left().value();
-
         Map<String, ArtifactDefinition> childToscaArtifacts = componentRI.getToscaArtifacts();
         ArtifactDefinition childArtifactDefinition = childToscaArtifacts.get(ToscaExportHandler.ASSET_TOSCA_TEMPLATE);
         if (childArtifactDefinition != null) {
             //add to cache
-            componentCache.put(
-                childArtifactDefinition.getEsId(),
-                childArtifactDefinition.getArtifactName(),
-                componentRI
-            );
+            componentCache.put(childArtifactDefinition.getEsId(), childArtifactDefinition.getArtifactName(), componentRI);
         }
         return componentRI;
     }
 
-    private Either<ZipOutputStream, ResponseFormat> writeComponentInterface(
-        Component component,
-        ZipOutputStream zip,
-        String fileName,
-        boolean isAssociatedComponent
-    ) {
+    private Either<ZipOutputStream, ResponseFormat> writeComponentInterface(Component component, ZipOutputStream zip, String fileName,
+                                                                            boolean isAssociatedComponent) {
         // TODO: This should not be done but we need this to keep the refactoring small enough to be easily reviewable
         return writeComponentInterface(component, fileName, isAssociatedComponent, ZipWriter.live(zip))
-            .map(void0 -> Either.<ZipOutputStream, ResponseFormat>left(zip))
-            .recover(th -> {
+            .map(void0 -> Either.<ZipOutputStream, ResponseFormat>left(zip)).recover(th -> {
                 log.error("#writeComponentInterface - zip writing failed with error: ", th);
                 return Either.right(componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR));
             }).get();
     }
 
-    private Try<Void> writeComponentInterface(
-        Component component,
-        String fileName,
-        boolean isAssociatedComponent,
-        ZipWriter zw
-    ) {
-        Either<byte[], ToscaError> yml = toscaExportUtils
-            .exportComponentInterface(component, isAssociatedComponent)
-            .left().map(ToscaRepresentation::getMainYaml);
-
-        return fromEither(yml, ToscaErrorException::new)
-            .flatMap(zw.write(DEFINITIONS_PATH + ToscaExportHandler.getInterfaceFilename(fileName)));
-    }
-
-    public static class ToscaErrorException extends Exception {
-
-        ToscaErrorException(ToscaError error) {
-            super("Error while exporting component's interface (toscaError:" + error + ")");
-        }
+    private Try<Void> writeComponentInterface(Component component, String fileName, boolean isAssociatedComponent, ZipWriter zw) {
+        Either<byte[], ToscaError> yml = toscaExportUtils.exportComponentInterface(component, isAssociatedComponent).left()
+            .map(ToscaRepresentation::getMainYaml);
+        return fromEither(yml, ToscaErrorException::new).flatMap(zw.write(DEFINITIONS_PATH + ToscaExportHandler.getInterfaceFilename(fileName)));
     }
 
     private Either<byte[], ActionStatus> getEntryData(String cassandraId, Component childComponent) {
         if (cassandraId == null || cassandraId.isEmpty()) {
-            return toscaExportUtils.exportComponent(childComponent)
-                .right().map(toscaErrorToActionStatus(childComponent))
-                .left().map(ToscaRepresentation::getMainYaml);
+            return toscaExportUtils.exportComponent(childComponent).right().map(toscaErrorToActionStatus(childComponent)).left()
+                .map(ToscaRepresentation::getMainYaml);
         } else {
             return getFromCassandra(cassandraId);
         }
@@ -728,55 +774,37 @@ public class CsarUtils {
 
     private F<ToscaError, ActionStatus> toscaErrorToActionStatus(Component childComponent) {
         return toscaError -> {
-            log.debug("Failed to export tosca template for child component {} error {}",
-                childComponent.getUniqueId(), toscaError);
+            log.debug("Failed to export tosca template for child component {} error {}", childComponent.getUniqueId(), toscaError);
             return componentsUtils.convertFromToscaError(toscaError);
         };
     }
 
     private Either<byte[], ResponseFormat> getLatestSchemaFilesFromCassandra() {
         String fto = getVersionFirstThreeOctets();
-        return sdcSchemaFilesCassandraDao.getSpecificSchemaFiles(fto, CONFORMANCE_LEVEL)
-            .right().map(schemaFilesFetchDBError(fto))
-            .left().bind(iff(
-                List::isEmpty,
-                () -> schemaFileFetchError(fto),
-                s -> Either.left(s.iterator().next().getPayloadAsArray())
-                )
-            );
-    }
-
-    private static <A, B> F<A, B> iff(Predicate<A> p, Supplier<B> s, Function<A, B> orElse) {
-        return a -> p.test(a) ? s.get() : orElse.apply(a);
+        return sdcSchemaFilesCassandraDao.getSpecificSchemaFiles(fto, CONFORMANCE_LEVEL).right().map(schemaFilesFetchDBError(fto)).left()
+            .bind(iff(List::isEmpty, () -> schemaFileFetchError(fto), s -> Either.left(s.iterator().next().getPayloadAsArray())));
     }
 
     private F<CassandraOperationStatus, ResponseFormat> schemaFilesFetchDBError(String firstThreeOctets) {
         return cos -> {
-            log.debug(
-                "Failed to get the schema files SDC-Version: {} Conformance-Level {}. Please fix DB table accordingly.",
-                firstThreeOctets, CONFORMANCE_LEVEL);
+            log.debug("Failed to get the schema files SDC-Version: {} Conformance-Level {}. Please fix DB table accordingly.", firstThreeOctets,
+                CONFORMANCE_LEVEL);
             StorageOperationStatus sos = DaoStatusConverter.convertCassandraStatusToStorageStatus(cos);
             return componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(sos));
         };
     }
 
     private Either<byte[], ResponseFormat> schemaFileFetchError(String firstThreeOctets) {
-        log.debug("Failed to get the schema files SDC-Version: {} Conformance-Level {}",
-            firstThreeOctets, CONFORMANCE_LEVEL);
-        return Either.right(
-            componentsUtils.getResponseFormat(
-                ActionStatus.TOSCA_SCHEMA_FILES_NOT_FOUND, firstThreeOctets, CONFORMANCE_LEVEL
-            )
-        );
+        log.debug("Failed to get the schema files SDC-Version: {} Conformance-Level {}", firstThreeOctets, CONFORMANCE_LEVEL);
+        return Either.right(componentsUtils.getResponseFormat(ActionStatus.TOSCA_SCHEMA_FILES_NOT_FOUND, firstThreeOctets, CONFORMANCE_LEVEL));
     }
 
     private Either<byte[], ActionStatus> getFromCassandra(String cassandraId) {
-        return artifactCassandraDao.getArtifact(cassandraId)
-            .right().map(cos -> {
-                log.debug("Failed to fetch artifact from Cassandra by id {} error {} ", cassandraId, cos);
-                StorageOperationStatus storageStatus = DaoStatusConverter.convertCassandraStatusToStorageStatus(cos);
-                return componentsUtils.convertFromStorageResponse(storageStatus);
-            }).left().map(DAOArtifactData::getDataAsArray);
+        return artifactCassandraDao.getArtifact(cassandraId).right().map(cos -> {
+            log.debug("Failed to fetch artifact from Cassandra by id {} error {} ", cassandraId, cos);
+            StorageOperationStatus storageStatus = DaoStatusConverter.convertCassandraStatusToStorageStatus(cos);
+            return componentsUtils.convertFromStorageResponse(storageStatus);
+        }).left().map(DAOArtifactData::getDataAsArray);
     }
 
     private String createCsarBlock0(String metaFileVersion, String toscaConformanceLevel) {
@@ -787,297 +815,50 @@ public class CsarUtils {
         final String block0template = "TOSCA-Meta-File-Version: %s\nCSAR-Version: %s\nCreated-By: %s\nEntry-Definitions: Definitions/%s\n\nName: csar.meta\nContent-Type: text/plain\n";
         return String.format(block0template, metaFileVersion, csarVersion, createdBy, entryDef);
     }
-       
-    private String createNsMfBlock0(String serviceName, String createdBy, String serviceVersion, String releaseTime,
-        String serviceType, String description, String serviceTemplate, String hash) {
-        final String block0template = "metadata??\n" +
-            "ns_product_name: %s\n" +
-            "ns_provider_id: %s\n" +
-            "ns_package_version: %s\n" +
+
+    private String createNsMfBlock0(String serviceName, String createdBy, String serviceVersion, String releaseTime, String serviceType,
+                                    String description, String serviceTemplate, String hash) {
+        final String block0template = "metadata??\n" + "ns_product_name: %s\n" + "ns_provider_id: %s\n" + "ns_package_version: %s\n" +
             //"ns_create_date_time: %s\n" +
-            "ns_release_data_time: %s\n" +
-            "ns_type: %s\n" +
-            "ns_package_description: %s\n\n" +
-            "Source: %s\n" +
-            "Algorithm: MD5\n" +
-            "Hash: %s\n\n";
-        return String
-            .format(block0template, serviceName, createdBy, serviceVersion, releaseTime, serviceType, description,
-                serviceTemplate, hash);
+            "ns_release_data_time: %s\n" + "ns_type: %s\n" + "ns_package_description: %s\n\n" + "Source: %s\n" + "Algorithm: MD5\n" + "Hash: %s\n\n";
+        return String.format(block0template, serviceName, createdBy, serviceVersion, releaseTime, serviceType, description, serviceTemplate, hash);
     }
 
-    /**
-     * Extracts artifacts of VFCs from CSAR
-     *
-     * @param csar
-     * @return Map of <String, List<ArtifactDefinition>> the contains Lists of artifacts according vfcToscaNamespace
-     */
-    public static Map<String, List<ArtifactDefinition>> extractVfcsArtifactsFromCsar(Map<String, byte[]> csar) {
-
-        Map<String, List<ArtifactDefinition>> artifacts = new HashMap<>();
-        if (csar != null) {
-            log.debug("************* Going to extract VFCs artifacts from Csar. ");
-            Map<String, Set<List<String>>> collectedWarningMessages = new HashMap<>();
-            csar.entrySet().stream()
-                // filter CSAR entry by node type artifact path
-                .filter(e -> Pattern.compile(VFC_NODE_TYPE_ARTIFACTS_PATH_PATTERN).matcher(e.getKey()).matches())
-                // extract ArtifactDefinition from CSAR entry for each entry with matching artifact path
-                .forEach(e ->
-                    extractVfcArtifact(e, collectedWarningMessages).ifPresent(ip ->
-                        addExtractedVfcArtifact(ip, artifacts)
-                    )
-                );
-            // add counter suffix to artifact labels
-            handleWarningMessages(collectedWarningMessages);
-
-        }
-        return artifacts;
-    }
-
-    /**
-     * Print warnings to log
-     *
-     * @param collectedWarningMessages
-     */
-    public static void handleWarningMessages(Map<String, Set<List<String>>> collectedWarningMessages) {
-        collectedWarningMessages.entrySet().stream()
-                                // for each vfc
-                                .forEach(e -> e.getValue().stream()
-                                               // add each warning message to log
-                                               .forEach(args -> log.warn(e.getKey(), args.toArray())));
-
-    }
-
-    private static void addExtractedVfcArtifact(
-        ImmutablePair<String, ArtifactDefinition> extractedVfcArtifact,
-        Map<String, List<ArtifactDefinition>> artifacts
-    ) {
-        String vfcToscaNamespace = extractedVfcArtifact.getKey();
-
-        artifacts.computeIfAbsent(vfcToscaNamespace, k -> new ArrayList<>());
-        artifacts.get(vfcToscaNamespace).add(extractedVfcArtifact.getValue());
-    }
-
-    private static Optional<ImmutablePair<String, ArtifactDefinition>> extractVfcArtifact(
-        Entry<String, byte[]> entry,
-        Map<String, Set<List<String>>> collectedWarningMessages
-    ) {
-        String[] parsedCsarArtifactPath = entry.getKey().split(PATH_DELIMITER);
-        String groupType = parsedCsarArtifactPath[2].toUpperCase();
-
-        return detectArtifactGroupType(groupType, collectedWarningMessages)
-            .left()
-            .map(buildArtifactDefinitionFromCsarArtifactPath(entry, collectedWarningMessages, parsedCsarArtifactPath))
-            .either(
-                ad -> Optional.of(new ImmutablePair<>(parsedCsarArtifactPath[1], ad)),
-                b -> Optional.empty()
-            );
-    }
-
-    private static Either<ArtifactGroupTypeEnum, Boolean> detectArtifactGroupType(String groupType, Map<String, Set<List<String>>> collectedWarningMessages) {
-        Either<ArtifactGroupTypeEnum, Boolean> result;
-        try {
-            ArtifactGroupTypeEnum artifactGroupType = ArtifactGroupTypeEnum.findType(groupType.toUpperCase());
-            if (artifactGroupType == null || (artifactGroupType != ArtifactGroupTypeEnum.INFORMATIONAL && artifactGroupType != ArtifactGroupTypeEnum.DEPLOYMENT)) {
-                String warningMessage = "Warning - unrecognized artifact group type {} was received.";
-                List<String> messageArguments = new ArrayList<>();
-                messageArguments.add(groupType);
-                if (!collectedWarningMessages.containsKey(warningMessage)) {
-                    Set<List<String>> messageArgumentLists = new HashSet<>();
-                    messageArgumentLists.add(messageArguments);
-                    collectedWarningMessages.put(warningMessage, messageArgumentLists);
-                } else {
-                    collectedWarningMessages.get(warningMessage).add(messageArguments);
-                }
-
-                result = Either.right(false);
-            } else {
-
-                result = Either.left(artifactGroupType);
-            }
-        } catch (Exception e) {
-            log.debug("detectArtifactGroupType failed with exception", e);
-            result = Either.right(false);
-        }
-        return result;
-    }
-
-    private static F<ArtifactGroupTypeEnum, ArtifactDefinition> buildArtifactDefinitionFromCsarArtifactPath(
-        Entry<String, byte[]> entry,
-        Map<String, Set<List<String>>> collectedWarningMessages,
-        String[] parsedCsarArtifactPath
-    ) {
-        return artifactGroupType -> {
-            ArtifactDefinition artifact;
-            artifact = new ArtifactDefinition();
-            artifact.setArtifactGroupType(artifactGroupType);
-            artifact.setArtifactType(
-                detectArtifactTypeVFC(artifactGroupType, parsedCsarArtifactPath[3], parsedCsarArtifactPath[1],
-                    collectedWarningMessages));
-            artifact.setArtifactName(
-                ValidationUtils.normalizeFileName(parsedCsarArtifactPath[parsedCsarArtifactPath.length - 1]));
-            artifact.setPayloadData(Base64.encodeBase64String(entry.getValue()));
-            artifact.setArtifactDisplayName(artifact.getArtifactName().lastIndexOf('.') > 0 ? artifact.getArtifactName()
-                .substring(0, artifact.getArtifactName().lastIndexOf('.')) : artifact.getArtifactName());
-            artifact.setArtifactLabel(ValidationUtils.normalizeArtifactLabel(artifact.getArtifactName()));
-            artifact.setDescription(ARTIFACT_CREATED_FROM_CSAR);
-            artifact.setIsFromCsar(true);
-            artifact.setArtifactChecksum(GeneralUtility.calculateMD5Base64EncodedByByteArray(entry.getValue()));
-            return artifact;
-        };
-    }
-
-    @Getter
-    public static final class NonMetaArtifactInfo {
-        @Setter
-        private String artifactUniqueId;
-        private final String path;
-        private final String artifactName;
-        private final String displayName;
-        private final String artifactLabel;
-        private final String artifactType;
-        private final ArtifactGroupTypeEnum artifactGroupType;
-        private final String payloadData;
-        private final String artifactChecksum;
-        private final boolean isFromCsar;
-
-        public NonMetaArtifactInfo(final String artifactName, final String path, final String artifactType,
-                                   final ArtifactGroupTypeEnum artifactGroupType, final byte[] payloadData,
-                                   final String artifactUniqueId, final boolean isFromCsar) {
-            super();
-            this.path = path;
-            this.isFromCsar = isFromCsar;
-            this.artifactName = ValidationUtils.normalizeFileName(artifactName);
-            this.artifactType = artifactType;
-            this.artifactGroupType = artifactGroupType;
-            final int pointIndex = artifactName.lastIndexOf('.');
-            if (pointIndex > 0) {
-                displayName = artifactName.substring(0, pointIndex);
-            } else {
-                displayName = artifactName;
-            }
-            this.artifactLabel = ValidationUtils.normalizeArtifactLabel(artifactName);
-            if (payloadData == null) {
-                this.payloadData = null;
-                this.artifactChecksum = null;
-            } else {
-                this.payloadData = Base64.encodeBase64String(payloadData);
-                this.artifactChecksum = GeneralUtility.calculateMD5Base64EncodedByByteArray(payloadData);
-            }
-            this.artifactUniqueId = artifactUniqueId;
-        }
-
-    }
-
-    /**
-     * This method checks the artifact GroupType & Artifact Type. <br>
-     * if there is any problem warning messages are added to collectedWarningMessages
-     *
-     * @param artifactPath
-     * @param collectedWarningMessages
-     * @return
-     */
-    public static Either<NonMetaArtifactInfo, Boolean> validateNonMetaArtifact(
-        String artifactPath,
-        byte[] payloadData,
-        Map<String, Set<List<String>>> collectedWarningMessages
-    ) {
-        try {
-            String[] parsedArtifactPath = artifactPath.split(PATH_DELIMITER);
-            String groupType = parsedArtifactPath[1];
-            String receivedTypeName = parsedArtifactPath[2];
-            String artifactFileNameType = parsedArtifactPath[3];
-
-            return detectArtifactGroupType(groupType, collectedWarningMessages)
-                .left().bind(artifactGroupType -> {
-                    String artifactType =
-                        detectArtifactTypeVF(artifactGroupType, receivedTypeName, collectedWarningMessages);
-
-                    return Either.left(new NonMetaArtifactInfo(
-                        artifactFileNameType, artifactPath, artifactType,
-                        artifactGroupType, payloadData, null, true
-                    ));
-                });
-        } catch (Exception e) {
-            log.debug("detectArtifactGroupType failed with exception", e);
-            return Either.right(false);
-        }
-    }
-
-    private static String detectArtifactTypeVFC(ArtifactGroupTypeEnum artifactGroupType, String receivedTypeName, String parentVfName, Map<String, Set<List<String>>> collectedWarningMessages) {
-        String warningMessage = "Warning - artifact type {} that was provided for VFC {} is not recognized.";
-        return detectArtifactType(artifactGroupType, receivedTypeName, warningMessage, collectedWarningMessages, parentVfName);
-    }
-
-    private static String detectArtifactTypeVF(ArtifactGroupTypeEnum artifactGroupType, String receivedTypeName, Map<String, Set<List<String>>> collectedWarningMessages) {
-        String warningMessage = "Warning - artifact type {} that was provided for VF is not recognized.";
-        return detectArtifactType(artifactGroupType, receivedTypeName, warningMessage, collectedWarningMessages);
-    }
-
-    private static String detectArtifactType(final ArtifactGroupTypeEnum artifactGroupType,
-                                             final String receivedTypeName, final String warningMessage,
-                                             final Map<String, Set<List<String>>> collectedWarningMessages,
-                                             final String... arguments) {
-        final ArtifactConfiguration artifactConfiguration =
-            ArtifactConfigManager.getInstance()
-                .find(receivedTypeName, artifactGroupType, ComponentType.RESOURCE)
-                .orElse(null);
-
-        if (artifactConfiguration == null) {
-            final List<String> messageArguments = new ArrayList<>();
-            messageArguments.add(receivedTypeName);
-            messageArguments.addAll(Arrays.asList(arguments));
-            if (!collectedWarningMessages.containsKey(warningMessage)) {
-                final Set<List<String>> messageArgumentLists = new HashSet<>();
-                messageArgumentLists.add(messageArguments);
-                collectedWarningMessages.put(warningMessage, messageArgumentLists);
-            } else {
-                collectedWarningMessages.get(warningMessage).add(messageArguments);
-            }
-        }
-
-        return artifactConfiguration == null ? ArtifactTypeEnum.OTHER.getType() : receivedTypeName;
-    }
-
-    private Either<ZipOutputStream, ResponseFormat> writeAllFilesToCsar(Component mainComponent, CsarDefinition csarDefinition, ZipOutputStream zipstream, boolean isInCertificationRequest) throws IOException{
+    private Either<ZipOutputStream, ResponseFormat> writeAllFilesToCsar(Component mainComponent, CsarDefinition csarDefinition,
+                                                                        ZipOutputStream zipstream, boolean isInCertificationRequest)
+        throws IOException {
         ComponentArtifacts componentArtifacts = csarDefinition.getComponentArtifacts();
-
-        Either<ZipOutputStream, ResponseFormat> writeComponentArtifactsToSpecifiedPath = writeComponentArtifactsToSpecifiedPath(mainComponent, componentArtifacts, zipstream, ARTIFACTS_PATH, isInCertificationRequest);
-
-        if(writeComponentArtifactsToSpecifiedPath.isRight()){
+        Either<ZipOutputStream, ResponseFormat> writeComponentArtifactsToSpecifiedPath = writeComponentArtifactsToSpecifiedPath(mainComponent,
+            componentArtifacts, zipstream, ARTIFACTS_PATH, isInCertificationRequest);
+        if (writeComponentArtifactsToSpecifiedPath.isRight()) {
             return Either.right(writeComponentArtifactsToSpecifiedPath.right().value());
         }
-
         ComponentTypeArtifacts mainTypeAndCIArtifacts = componentArtifacts.getMainTypeAndCIArtifacts();
-        writeComponentArtifactsToSpecifiedPath = writeArtifactsInfoToSpecifiedPath(mainComponent, mainTypeAndCIArtifacts.getComponentArtifacts(), zipstream, ARTIFACTS_PATH, isInCertificationRequest);
-
-        if(writeComponentArtifactsToSpecifiedPath.isRight()){
+        writeComponentArtifactsToSpecifiedPath = writeArtifactsInfoToSpecifiedPath(mainComponent, mainTypeAndCIArtifacts.getComponentArtifacts(),
+            zipstream, ARTIFACTS_PATH, isInCertificationRequest);
+        if (writeComponentArtifactsToSpecifiedPath.isRight()) {
             return Either.right(writeComponentArtifactsToSpecifiedPath.right().value());
         }
-
         Map<String, ArtifactsInfo> componentInstancesArtifacts = mainTypeAndCIArtifacts.getComponentInstancesArtifacts();
         Set<String> keySet = componentInstancesArtifacts.keySet();
-
         String currentPath = ARTIFACTS_PATH + RESOURCES_PATH;
         for (String keyAssetName : keySet) {
             ArtifactsInfo artifactsInfo = componentInstancesArtifacts.get(keyAssetName);
             String pathWithAssetName = currentPath + keyAssetName + PATH_DELIMITER;
-            writeComponentArtifactsToSpecifiedPath = writeArtifactsInfoToSpecifiedPath(mainComponent, artifactsInfo, zipstream, pathWithAssetName, isInCertificationRequest);
-
-            if(writeComponentArtifactsToSpecifiedPath.isRight()){
+            writeComponentArtifactsToSpecifiedPath = writeArtifactsInfoToSpecifiedPath(mainComponent, artifactsInfo, zipstream, pathWithAssetName,
+                isInCertificationRequest);
+            if (writeComponentArtifactsToSpecifiedPath.isRight()) {
                 return Either.right(writeComponentArtifactsToSpecifiedPath.right().value());
             }
         }
         writeComponentArtifactsToSpecifiedPath = writeOperationsArtifactsToCsar(mainComponent, zipstream);
-
         if (writeComponentArtifactsToSpecifiedPath.isRight()) {
             return Either.right(writeComponentArtifactsToSpecifiedPath.right().value());
         }
         return Either.left(zipstream);
     }
 
-    private Either<ZipOutputStream, ResponseFormat> writeOperationsArtifactsToCsar(Component component,
-            ZipOutputStream zipstream) {
+    private Either<ZipOutputStream, ResponseFormat> writeOperationsArtifactsToCsar(Component component, ZipOutputStream zipstream) {
         if (checkComponentBeforeOperation(component)) {
             return Either.left(zipstream);
         }
@@ -1096,48 +877,43 @@ public class CsarUtils {
                     final String artifactName = operation.getImplementation().getArtifactName();
                     if (artifactFromCassandra.isRight()) {
                         log.error(ARTIFACT_NAME_UNIQUE_ID, artifactName, artifactUUID);
-                        log.error("Failed to get {} payload from DB reason: {}", artifactName,
-                            artifactFromCassandra.right().value());
-                        return Either.right(componentsUtils.getResponseFormat(
-                            ActionStatus.ARTIFACT_PAYLOAD_NOT_FOUND_DURING_CSAR_CREATION, "Resource",
-                            component.getUniqueId(), artifactName, artifactUUID));
+                        log.error("Failed to get {} payload from DB reason: {}", artifactName, artifactFromCassandra.right().value());
+                        return Either.right(componentsUtils
+                            .getResponseFormat(ActionStatus.ARTIFACT_PAYLOAD_NOT_FOUND_DURING_CSAR_CREATION, "Resource", component.getUniqueId(),
+                                artifactName, artifactUUID));
                     }
                     final byte[] payloadData = artifactFromCassandra.left().value();
-                    zipstream.putNextEntry(new ZipEntry(OperationArtifactUtil.createOperationArtifactPath(
-                        component, null, operation, true)));
+                    zipstream.putNextEntry(new ZipEntry(OperationArtifactUtil.createOperationArtifactPath(component, null, operation, true)));
                     zipstream.write(payloadData);
                 } catch (IOException e) {
-                    log.error("Component Name {},  Interface Name {}, Operation Name {}", component.getNormalizedName(),
-                        interfaceEntry.getKey(), operation.getName());
+                    log.error("Component Name {},  Interface Name {}, Operation Name {}", component.getNormalizedName(), interfaceEntry.getKey(),
+                        operation.getName());
                     log.error("Error while writing the operation's artifacts to the CSAR " + "{}", e);
-                    return Either.right(componentsUtils
-                        .getResponseFormat(ActionStatus.ERROR_DURING_CSAR_CREATION, "Resource",
-                            component.getUniqueId()));
+                    return Either
+                        .right(componentsUtils.getResponseFormat(ActionStatus.ERROR_DURING_CSAR_CREATION, "Resource", component.getUniqueId()));
                 }
             }
         }
         return Either.left(zipstream);
     }
 
-    private boolean checkComponentBeforeWrite(Component component, Entry<String, InterfaceDefinition> interfaceEntry, OperationDataDefinition operation) {
+    private boolean checkComponentBeforeWrite(Component component, Entry<String, InterfaceDefinition> interfaceEntry,
+                                              OperationDataDefinition operation) {
         final ArtifactDataDefinition implementation = operation.getImplementation();
         if (Objects.isNull(implementation)) {
-            log.debug("Component Name {}, Interface Id {}, Operation Name {} - no Operation Implementation found",
-                    component.getNormalizedName(), interfaceEntry.getValue().getUniqueId(),
-                    operation.getName());
+            log.debug("Component Name {}, Interface Id {}, Operation Name {} - no Operation Implementation found", component.getNormalizedName(),
+                interfaceEntry.getValue().getUniqueId(), operation.getName());
             return true;
         }
         final String artifactName = implementation.getArtifactName();
         if (Objects.isNull(artifactName)) {
-            log.debug("Component Name {}, Interface Id {}, Operation Name {} - no artifact found",
-                    component.getNormalizedName(), interfaceEntry.getValue().getUniqueId(),
-                    operation.getName());
+            log.debug("Component Name {}, Interface Id {}, Operation Name {} - no artifact found", component.getNormalizedName(),
+                interfaceEntry.getValue().getUniqueId(), operation.getName());
             return true;
         }
         if (OperationArtifactUtil.artifactNameIsALiteralValue(artifactName)) {
             log.debug("Component Name {}, Interface Id {}, Operation Name {} - artifact name is a literal value rather than an SDC artifact",
-                    component.getNormalizedName(), interfaceEntry.getValue().getUniqueId(),
-                    operation.getName());
+                component.getNormalizedName(), interfaceEntry.getValue().getUniqueId(), operation.getName());
             return true;
         }
         return false;
@@ -1154,47 +930,42 @@ public class CsarUtils {
         return false;
     }
 
-    private Either<ZipOutputStream, ResponseFormat> writeComponentArtifactsToSpecifiedPath(Component mainComponent, ComponentArtifacts componentArtifacts, ZipOutputStream zipstream,
-            String currentPath, boolean isInCertificationRequest) throws IOException {
+    private Either<ZipOutputStream, ResponseFormat> writeComponentArtifactsToSpecifiedPath(Component mainComponent,
+                                                                                           ComponentArtifacts componentArtifacts,
+                                                                                           ZipOutputStream zipstream, String currentPath,
+                                                                                           boolean isInCertificationRequest) throws IOException {
         Map<String, ComponentTypeArtifacts> componentTypeArtifacts = componentArtifacts.getComponentTypeArtifacts();
         //Keys are defined:
+
         //<Inner Asset TOSCA name (e.g. VFC name)> folder name: <Inner Asset TOSCA name (e.g. VFC name)>_v<version>.
+
         //E.g. "org.openecomp.resource.vf.vipr_atm_v1.0"
         Set<String> componentTypeArtifactsKeys = componentTypeArtifacts.keySet();
         for (String keyAssetName : componentTypeArtifactsKeys) {
             ComponentTypeArtifacts componentInstanceArtifacts = componentTypeArtifacts.get(keyAssetName);
             ArtifactsInfo componentArtifacts2 = componentInstanceArtifacts.getComponentArtifacts();
             String pathWithAssetName = currentPath + keyAssetName + PATH_DELIMITER;
-            Either<ZipOutputStream, ResponseFormat> writeArtifactsInfoToSpecifiedPath = writeArtifactsInfoToSpecifiedPath(mainComponent, componentArtifacts2, zipstream, pathWithAssetName, isInCertificationRequest);
-
-            if(writeArtifactsInfoToSpecifiedPath.isRight()){
+            Either<ZipOutputStream, ResponseFormat> writeArtifactsInfoToSpecifiedPath = writeArtifactsInfoToSpecifiedPath(mainComponent,
+                componentArtifacts2, zipstream, pathWithAssetName, isInCertificationRequest);
+            if (writeArtifactsInfoToSpecifiedPath.isRight()) {
                 return writeArtifactsInfoToSpecifiedPath;
             }
         }
-
         return Either.left(zipstream);
     }
 
     private Either<ZipOutputStream, ResponseFormat> writeArtifactsInfoToSpecifiedPath(final Component mainComponent,
-        final ArtifactsInfo currArtifactsInfo,
-        final ZipOutputStream zip,
-        final String path,
-        final boolean isInCertificationRequest) throws IOException {
-
-        final Map<ArtifactGroupTypeEnum, Map<String, List<ArtifactDefinition>>> artifactsInfo =
-            currArtifactsInfo.getArtifactsInfo();
+                                                                                      final ArtifactsInfo currArtifactsInfo,
+                                                                                      final ZipOutputStream zip, final String path,
+                                                                                      final boolean isInCertificationRequest) throws IOException {
+        final Map<ArtifactGroupTypeEnum, Map<String, List<ArtifactDefinition>>> artifactsInfo = currArtifactsInfo.getArtifactsInfo();
         for (final ArtifactGroupTypeEnum artifactGroupTypeEnum : artifactsInfo.keySet()) {
-            final String groupTypeFolder =
-                path + WordUtils.capitalizeFully(artifactGroupTypeEnum.getType()) + PATH_DELIMITER;
-
+            final String groupTypeFolder = path + WordUtils.capitalizeFully(artifactGroupTypeEnum.getType()) + PATH_DELIMITER;
             final Map<String, List<ArtifactDefinition>> artifactTypesMap = artifactsInfo.get(artifactGroupTypeEnum);
-
             for (final String artifactType : artifactTypesMap.keySet()) {
                 final List<ArtifactDefinition> artifactDefinitionList = artifactTypesMap.get(artifactType);
                 String artifactTypeFolder = groupTypeFolder + artifactType + PATH_DELIMITER;
-
-                if (ArtifactTypeEnum.WORKFLOW.getType().equals(artifactType) && path
-                    .contains(ARTIFACTS_PATH + RESOURCES_PATH)) {
+                if (ArtifactTypeEnum.WORKFLOW.getType().equals(artifactType) && path.contains(ARTIFACTS_PATH + RESOURCES_PATH)) {
                     // Ignore this packaging as BPMN artifacts needs to be packaged in different manner
                     continue;
                 }
@@ -1205,12 +976,11 @@ public class CsarUtils {
                     artifactTypeFolder = artifactTypeFolder
                         .replace(ArtifactTypeEnum.ONBOARDED_PACKAGE.getType(), ArtifactTypeEnum.ETSI_PACKAGE.getType());
                 }
-
                 // TODO: We should not do this but in order to keep this refactoring small enough,
+
                 // we'll leave this as is for now
-                List<ArtifactDefinition> collect =
-                    filterArtifactDefinitionToZip(mainComponent, artifactDefinitionList, isInCertificationRequest)
-                        .collect(Collectors.toList());
+                List<ArtifactDefinition> collect = filterArtifactDefinitionToZip(mainComponent, artifactDefinitionList, isInCertificationRequest)
+                    .collect(Collectors.toList());
                 for (ArtifactDefinition ad : collect) {
                     zip.putNextEntry(new ZipEntry(artifactTypeFolder + ad.getArtifactName()));
                     zip.write(ad.getPayloadData());
@@ -1220,152 +990,36 @@ public class CsarUtils {
         return Either.left(zip);
     }
 
-    private Stream<ArtifactDefinition> filterArtifactDefinitionToZip(Component mainComponent,
-        List<ArtifactDefinition> artifactDefinitionList, boolean isInCertificationRequest) {
-        return artifactDefinitionList
-            .stream()
-            .filter(shouldBeInZip(isInCertificationRequest, mainComponent))
-            .map(this::fetchPayLoadData)
-            .filter(Either::isLeft)
-            .map(e -> e.left().value());
+    private Stream<ArtifactDefinition> filterArtifactDefinitionToZip(Component mainComponent, List<ArtifactDefinition> artifactDefinitionList,
+                                                                     boolean isInCertificationRequest) {
+        return artifactDefinitionList.stream().filter(shouldBeInZip(isInCertificationRequest, mainComponent)).map(this::fetchPayLoadData)
+            .filter(Either::isLeft).map(e -> e.left().value());
     }
 
     private Predicate<ArtifactDefinition> shouldBeInZip(boolean isInCertificationRequest, Component component) {
-        return artifactDefinition ->
-            !(!isInCertificationRequest
-                && component.isService()
-                && artifactDefinition.isHeatEnvType()
-                || artifactDefinition.hasNoMandatoryEsId());
+        return artifactDefinition -> !(!isInCertificationRequest && component.isService() && artifactDefinition.isHeatEnvType() || artifactDefinition
+            .hasNoMandatoryEsId());
     }
 
     private Either<ArtifactDefinition, ActionStatus> fetchPayLoadData(ArtifactDefinition ad) {
         byte[] payloadData = ad.getPayloadData();
-        if(payloadData == null) {
-            return getFromCassandra(ad.getEsId())
-                .left().map(pd -> {
-                    ad.setPayload(pd);
-                    return ad;
-                }).right().map(as -> {
-                    log.debug(ARTIFACT_NAME_UNIQUE_ID, ad.getArtifactName(), ad.getUniqueId());
-                    log.debug("Failed to get {} payload from DB reason: {}", ad.getArtifactName(), as);
-                    return as;
-                });
+        if (payloadData == null) {
+            return getFromCassandra(ad.getEsId()).left().map(pd -> {
+                ad.setPayload(pd);
+                return ad;
+            }).right().map(as -> {
+                log.debug(ARTIFACT_NAME_UNIQUE_ID, ad.getArtifactName(), ad.getUniqueId());
+                log.debug("Failed to get {} payload from DB reason: {}", ad.getArtifactName(), as);
+                return as;
+            });
         } else {
             return Either.left(ad);
         }
     }
 
-    /************************************ Artifacts Structure ******************************************************************/
-    /**
-     * The artifacts Definition saved by their structure
-     */
-    private class ArtifactsInfo {
-        //Key is the type of artifacts(Informational/Deployment)
-        //Value is a map between an artifact type and a list of all artifacts of this type
-        private Map<ArtifactGroupTypeEnum, Map<String, List<ArtifactDefinition>>> artifactsInfoField;
-
-        public ArtifactsInfo() {
-            this.artifactsInfoField = new EnumMap<>(ArtifactGroupTypeEnum.class);
-        }
-
-        public Map<ArtifactGroupTypeEnum, Map<String, List<ArtifactDefinition>>> getArtifactsInfo() {
-            return artifactsInfoField;
-        }
-
-        public void addArtifactsToGroup(ArtifactGroupTypeEnum artifactGroup,
-                                        Map<String, List<ArtifactDefinition>> artifactsDefinition) {
-                       if (artifactsInfoField.get(artifactGroup) == null) {
-                               artifactsInfoField.put(artifactGroup, artifactsDefinition);
-                       } else {
-                               Map<String, List<ArtifactDefinition>> artifactTypeEnumListMap =
-                                               artifactsInfoField.get(artifactGroup);
-                               artifactTypeEnumListMap.putAll(artifactsDefinition);
-                               artifactsInfoField.put(artifactGroup, artifactTypeEnumListMap);
-                       }
-
-        }
-
-        public boolean isEmpty() {
-            return artifactsInfoField.isEmpty();
-        }
-
-        public boolean isNotEmpty() {
-            return !isEmpty();
-        }
-
-    }
-
-    /**
-     * The artifacts of the component and of all its composed instances
-     *
-     */
-    private class ComponentTypeArtifacts {
-        private ArtifactsInfo componentArtifacts;    //component artifacts (describes the Informational Deployment folders)
-        private Map<String, ArtifactsInfo> componentInstancesArtifacts;        //artifacts of the composed instances mapped by the resourceInstance normalized name (describes the Resources folder)
-
-        public ComponentTypeArtifacts() {
-            componentArtifacts = new ArtifactsInfo();
-            componentInstancesArtifacts = new HashMap<>();
-        }
-
-        public ArtifactsInfo getComponentArtifacts() {
-            return componentArtifacts;
-        }
-        public void setComponentArtifacts(ArtifactsInfo artifactsInfo) {
-            this.componentArtifacts = artifactsInfo;
-        }
-        public Map<String, ArtifactsInfo> getComponentInstancesArtifacts() {
-            return componentInstancesArtifacts;
-        }
-
-        public void addComponentInstancesArtifacts(String normalizedName, ArtifactsInfo artifactsInfo) {
-            componentInstancesArtifacts.put(normalizedName, artifactsInfo);
-        }
-
-    }
-
-    private class ComponentArtifacts {
-        //artifacts of the component and CI's artifacts contained in it's composition (represents Informational, Deployment & Resource folders of main component)
-        private ComponentTypeArtifacts mainTypeAndCIArtifacts;
-        //artifacts of all component types mapped by their tosca name
-        private Map<String, ComponentTypeArtifacts> componentTypeArtifacts;
-
-        public ComponentArtifacts(){
-            mainTypeAndCIArtifacts = new ComponentTypeArtifacts();
-            componentTypeArtifacts = new HashMap<>();
-        }
-
-        public ComponentTypeArtifacts getMainTypeAndCIArtifacts() {
-            return mainTypeAndCIArtifacts;
-        }
-
-        public void setMainTypeAndCIArtifacts(ComponentTypeArtifacts componentInstanceArtifacts) {
-            this.mainTypeAndCIArtifacts = componentInstanceArtifacts;
-        }
-
-        public Map<String, ComponentTypeArtifacts> getComponentTypeArtifacts() {
-            return componentTypeArtifacts;
-        }
-
-    }
-
-    private class CsarDefinition {
-        private ComponentArtifacts componentArtifacts;
-
-        // add list of tosca artifacts and meta describes CSAR zip root
-
-        public CsarDefinition(ComponentArtifacts componentArtifacts) {
-            this.componentArtifacts = componentArtifacts;
-        }
-
-        public ComponentArtifacts getComponentArtifacts() {
-            return componentArtifacts;
-        }
-    }
-
     /************************************ Artifacts Structure END******************************************************************/
 
-    private Either<CsarDefinition,ResponseFormat> collectComponentCsarDefinition(Component component){
+    private Either<CsarDefinition, ResponseFormat> collectComponentCsarDefinition(Component component) {
         ComponentArtifacts componentArtifacts = new ComponentArtifacts();
         Component updatedComponent = component;
 
@@ -1373,7 +1027,7 @@ public class CsarUtils {
         if (updatedComponent.getComponentType() == ComponentTypeEnum.SERVICE) {
             Either<Service, StorageOperationStatus> getServiceResponse = toscaOperationFacade.getToscaElement(updatedComponent.getUniqueId());
 
-            if(getServiceResponse.isRight()){
+            if (getServiceResponse.isRight()) {
                 ActionStatus actionStatus = componentsUtils.convertFromStorageResponse(getServiceResponse.right().value());
                 return Either.right(componentsUtils.getResponseFormat(actionStatus));
             }
@@ -1387,22 +1041,23 @@ public class CsarUtils {
         componentInstanceArtifacts.setComponentArtifacts(artifactsInfo);
         componentArtifacts.setMainTypeAndCIArtifacts(componentInstanceArtifacts);
 
-        Map<String,ComponentTypeArtifacts> resourceTypeArtifacts = componentArtifacts.getComponentTypeArtifacts();    //artifacts mapped by the component type(tosca name+version)
+        Map<String, ComponentTypeArtifacts> resourceTypeArtifacts = componentArtifacts
+            .getComponentTypeArtifacts();    //artifacts mapped by the component type(tosca name+version)
         //get the component instances
         List<ComponentInstance> componentInstances = updatedComponent.getComponentInstances();
-        if (componentInstances!=null){
-            for (ComponentInstance componentInstance:componentInstances){
+        if (componentInstances != null) {
+            for (ComponentInstance componentInstance : componentInstances) {
                 //call recursive to find artifacts for all the path
                 Either<Boolean, ResponseFormat> collectComponentInstanceArtifacts = collectComponentInstanceArtifacts(
-                        updatedComponent, componentInstance, resourceTypeArtifacts, componentInstanceArtifacts);
-                if (collectComponentInstanceArtifacts.isRight()){
+                    updatedComponent, componentInstance, resourceTypeArtifacts, componentInstanceArtifacts);
+                if (collectComponentInstanceArtifacts.isRight()) {
                     return Either.right(collectComponentInstanceArtifacts.right().value());
                 }
             }
         }
 
-        if(log.isDebugEnabled()){
-            printResult(componentArtifacts,updatedComponent.getName());
+        if (log.isDebugEnabled()) {
+            printResult(componentArtifacts, updatedComponent.getName());
         }
 
         return Either.left(new CsarDefinition(componentArtifacts));
@@ -1414,23 +1069,25 @@ public class CsarUtils {
         ComponentTypeArtifacts componentInstanceArtifacts = componentArtifacts.getMainTypeAndCIArtifacts();
         printArtifacts(componentInstanceArtifacts);
         result.append("Type Artifacts\n");
-        for (Map.Entry<String, ComponentTypeArtifacts> typeArtifacts:componentArtifacts.getComponentTypeArtifacts().entrySet()){
+        for (Map.Entry<String, ComponentTypeArtifacts> typeArtifacts : componentArtifacts.getComponentTypeArtifacts().entrySet()) {
             result.append("Folder " + typeArtifacts.getKey() + "\n");
             result.append(printArtifacts(typeArtifacts.getValue()));
         }
 
-        if(log.isDebugEnabled()){
+        if (log.isDebugEnabled()) {
             log.debug(result.toString());
         }
     }
 
+    /************************************ Artifacts Structure ******************************************************************/
+
     private String printArtifacts(ComponentTypeArtifacts componentInstanceArtifacts) {
         StringBuilder result = new StringBuilder();
         ArtifactsInfo artifactsInfo = componentInstanceArtifacts.getComponentArtifacts();
         Map<ArtifactGroupTypeEnum, Map<String, List<ArtifactDefinition>>> componentArtifacts = artifactsInfo.getArtifactsInfo();
         printArtifacts(componentArtifacts);
         result = result.append("Resources\n");
-        for (Map.Entry<String, ArtifactsInfo> resourceInstance:componentInstanceArtifacts.getComponentInstancesArtifacts().entrySet()){
+        for (Map.Entry<String, ArtifactsInfo> resourceInstance : componentInstanceArtifacts.getComponentInstancesArtifacts().entrySet()) {
             result.append("Folder" + resourceInstance.getKey() + "\n");
             result.append(printArtifacts(resourceInstance.getValue().getArtifactsInfo()));
         }
@@ -1440,11 +1097,11 @@ public class CsarUtils {
 
     private String printArtifacts(Map<ArtifactGroupTypeEnum, Map<String, List<ArtifactDefinition>>> componetArtifacts) {
         StringBuilder result = new StringBuilder();
-        for (Map.Entry<ArtifactGroupTypeEnum, Map<String, List<ArtifactDefinition>>> artifactGroup:componetArtifacts.entrySet()){
+        for (Map.Entry<ArtifactGroupTypeEnum, Map<String, List<ArtifactDefinition>>> artifactGroup : componetArtifacts.entrySet()) {
             result.append("    " + artifactGroup.getKey().getType());
-            for (Map.Entry<String, List<ArtifactDefinition>> groupArtifacts:artifactGroup.getValue().entrySet()){
+            for (Map.Entry<String, List<ArtifactDefinition>> groupArtifacts : artifactGroup.getValue().entrySet()) {
                 result.append("        " + groupArtifacts.getKey());
-                for (ArtifactDefinition artifact:groupArtifacts.getValue()){
+                for (ArtifactDefinition artifact : groupArtifacts.getValue()) {
                     result.append("            " + artifact.getArtifactDisplayName());
                 }
             }
@@ -1464,24 +1121,24 @@ public class CsarUtils {
         return componentArtifactsInfo;
     }
 
-    private Either<Boolean, ResponseFormat> collectComponentInstanceArtifacts(Component parentComponent,ComponentInstance componentInstance,
-            Map<String, ComponentTypeArtifacts> resourcesTypeArtifacts,ComponentTypeArtifacts instanceArtifactsLocation) {
+    private Either<Boolean, ResponseFormat> collectComponentInstanceArtifacts(Component parentComponent, ComponentInstance componentInstance,
+                                                                              Map<String, ComponentTypeArtifacts> resourcesTypeArtifacts,
+                                                                              ComponentTypeArtifacts instanceArtifactsLocation) {
         //1. get the component instance component
         String componentUid;
         if (componentInstance.getOriginType() == OriginTypeEnum.ServiceProxy) {
-                       componentUid = componentInstance.getSourceModelUid();
-               }
-               else {
-                       componentUid = componentInstance.getComponentUid();
-               }
+            componentUid = componentInstance.getSourceModelUid();
+        } else {
+            componentUid = componentInstance.getComponentUid();
+        }
         Either<Component, StorageOperationStatus> component = toscaOperationFacade.getToscaElement(componentUid);
-               if (component.isRight()) {
-            log.error("Failed to fetch resource with id {} for instance {}",componentUid, parentComponent.getUUID());
+        if (component.isRight()) {
+            log.error("Failed to fetch resource with id {} for instance {}", componentUid, parentComponent.getUUID());
             return Either.right(componentsUtils.getResponseFormat(ActionStatus.ASSET_NOT_FOUND_DURING_CSAR_CREATION,
-                    parentComponent.getComponentType().getValue(), parentComponent.getUUID(),
-                    componentInstance.getOriginType().getComponentType().getValue(), componentUid));
+                parentComponent.getComponentType().getValue(), parentComponent.getUUID(),
+                componentInstance.getOriginType().getComponentType().getValue(), componentUid));
         }
-               Component fetchedComponent = component.left().value();
+        Component fetchedComponent = component.left().value();
 
         //2. fill the artifacts for the current component parent type
         String toscaComponentName =
@@ -1498,31 +1155,31 @@ public class CsarUtils {
 
         //3. find the artifacts specific to the instance
         Map<String, List<ArtifactDefinition>> componentInstanceSpecificInformationalArtifacts =
-                getComponentInstanceSpecificArtifacts(componentInstance.getArtifacts(),
-                        componentParentArtifacts.getComponentArtifacts().getArtifactsInfo(), ArtifactGroupTypeEnum.INFORMATIONAL);
+            getComponentInstanceSpecificArtifacts(componentInstance.getArtifacts(),
+                componentParentArtifacts.getComponentArtifacts().getArtifactsInfo(), ArtifactGroupTypeEnum.INFORMATIONAL);
         Map<String, List<ArtifactDefinition>> componentInstanceSpecificDeploymentArtifacts =
-                getComponentInstanceSpecificArtifacts(componentInstance.getDeploymentArtifacts(),
-                        componentParentArtifacts.getComponentArtifacts().getArtifactsInfo(), ArtifactGroupTypeEnum.DEPLOYMENT);
+            getComponentInstanceSpecificArtifacts(componentInstance.getDeploymentArtifacts(),
+                componentParentArtifacts.getComponentArtifacts().getArtifactsInfo(), ArtifactGroupTypeEnum.DEPLOYMENT);
 
         //4. add the instances artifacts to the component type
         ArtifactsInfo artifactsInfo = new ArtifactsInfo();
-        if (!componentInstanceSpecificInformationalArtifacts.isEmpty()){
+        if (!componentInstanceSpecificInformationalArtifacts.isEmpty()) {
             artifactsInfo.addArtifactsToGroup(ArtifactGroupTypeEnum.INFORMATIONAL, componentInstanceSpecificInformationalArtifacts);
         }
-        if (!componentInstanceSpecificDeploymentArtifacts.isEmpty()){
+        if (!componentInstanceSpecificDeploymentArtifacts.isEmpty()) {
             artifactsInfo.addArtifactsToGroup(ArtifactGroupTypeEnum.DEPLOYMENT, componentInstanceSpecificDeploymentArtifacts);
         }
-        if (!artifactsInfo.isEmpty()){
+        if (!artifactsInfo.isEmpty()) {
             instanceArtifactsLocation.addComponentInstancesArtifacts(componentInstance.getNormalizedName(), artifactsInfo);
         }
 
         //5. do the same for all the component instances
         List<ComponentInstance> componentInstances = fetchedComponent.getComponentInstances();
-        if (componentInstances!=null){
-            for (ComponentInstance childComponentInstance:componentInstances){
+        if (componentInstances != null) {
+            for (ComponentInstance childComponentInstance : componentInstances) {
                 Either<Boolean, ResponseFormat> collectComponentInstanceArtifacts = collectComponentInstanceArtifacts(
-                        fetchedComponent, childComponentInstance, resourcesTypeArtifacts, componentParentArtifacts);
-                if (collectComponentInstanceArtifacts.isRight()){
+                    fetchedComponent, childComponentInstance, resourcesTypeArtifacts, componentParentArtifacts);
+                if (collectComponentInstanceArtifacts.isRight()) {
                     return collectComponentInstanceArtifacts;
                 }
             }
@@ -1538,21 +1195,24 @@ public class CsarUtils {
     public void setVersionFirstThreeOctets(String versionFirstThreeOctetes) {
         this.versionFirstThreeOctets = versionFirstThreeOctetes;
     }
+
     private Map<String, List<ArtifactDefinition>> getComponentInstanceSpecificArtifacts(Map<String, ArtifactDefinition> componentArtifacts,
-            Map<ArtifactGroupTypeEnum, Map<String, List<ArtifactDefinition>>> componentTypeArtifacts, ArtifactGroupTypeEnum artifactGroupTypeEnum) {
-        Map<String, List<ArtifactDefinition>> parentArtifacts = componentTypeArtifacts.get(artifactGroupTypeEnum);    //the artfiacts of the component itself and not the instance
+                                                                                        Map<ArtifactGroupTypeEnum, Map<String, List<ArtifactDefinition>>> componentTypeArtifacts,
+                                                                                        ArtifactGroupTypeEnum artifactGroupTypeEnum) {
+        Map<String, List<ArtifactDefinition>> parentArtifacts = componentTypeArtifacts
+            .get(artifactGroupTypeEnum);    //the artfiacts of the component itself and not the instance
 
         Map<String, List<ArtifactDefinition>> artifactsByTypeOfComponentInstance = new HashMap<>();
-        if (componentArtifacts!=null){
-            for (ArtifactDefinition artifact:componentArtifacts.values()){
+        if (componentArtifacts != null) {
+            for (ArtifactDefinition artifact : componentArtifacts.values()) {
                 List<ArtifactDefinition> parentArtifactsByType = null;
-                if (parentArtifacts!=null){
+                if (parentArtifacts != null) {
                     parentArtifactsByType = parentArtifacts.get(artifact.getArtifactType());
                 }
                 //the artifact is of instance
-                if (parentArtifactsByType == null || !parentArtifactsByType.contains(artifact)){
+                if (parentArtifactsByType == null || !parentArtifactsByType.contains(artifact)) {
                     List<ArtifactDefinition> typeArtifacts = artifactsByTypeOfComponentInstance.get(artifact.getArtifactType());
-                    if (typeArtifacts == null){
+                    if (typeArtifacts == null) {
                         typeArtifacts = new ArrayList<>();
                         artifactsByTypeOfComponentInstance.put(artifact.getArtifactType(), typeArtifacts);
                     }
@@ -1569,23 +1229,23 @@ public class CsarUtils {
         Map<String, List<ArtifactDefinition>> informationalArtifactsByType = collectGroupArtifacts(informationalArtifacts);
         Map<String, ArtifactDefinition> deploymentArtifacts = component.getDeploymentArtifacts();
         Map<String, List<ArtifactDefinition>> deploymentArtifactsByType = collectGroupArtifacts(deploymentArtifacts);
-               Map<String, ArtifactDefinition> interfaceOperationArtifacts =
-                               OperationArtifactUtil.getDistinctInterfaceOperationArtifactsByName(component);
-               Map<String, List<ArtifactDefinition>> interfaceOperationArtifactsByType = collectGroupArtifacts(
-                               interfaceOperationArtifacts);
+        Map<String, ArtifactDefinition> interfaceOperationArtifacts =
+            OperationArtifactUtil.getDistinctInterfaceOperationArtifactsByName(component);
+        Map<String, List<ArtifactDefinition>> interfaceOperationArtifactsByType = collectGroupArtifacts(
+            interfaceOperationArtifacts);
         ArtifactsInfo artifactsInfo = new ArtifactsInfo();
-        if (!informationalArtifactsByType.isEmpty()){
+        if (!informationalArtifactsByType.isEmpty()) {
             artifactsInfo.addArtifactsToGroup(ArtifactGroupTypeEnum.INFORMATIONAL, informationalArtifactsByType);
         }
-        if (!deploymentArtifactsByType.isEmpty() ){
+        if (!deploymentArtifactsByType.isEmpty(){
             artifactsInfo.addArtifactsToGroup(ArtifactGroupTypeEnum.DEPLOYMENT, deploymentArtifactsByType);
-               }
+        }
 
         return artifactsInfo;
     }
 
     private Map<String, List<ArtifactDefinition>> collectGroupArtifacts(
-            final Map<String, ArtifactDefinition> componentArtifacts) {
+        final Map<String, ArtifactDefinition> componentArtifacts) {
         final Map<String, List<ArtifactDefinition>> artifactsByType = new HashMap<>();
         for (final ArtifactDefinition artifact : componentArtifacts.values()) {
             if (artifact.getArtifactUUID() != null) {
@@ -1596,4 +1256,160 @@ public class CsarUtils {
         }
         return artifactsByType;
     }
+
+    public static class ToscaErrorException extends Exception {
+
+        ToscaErrorException(ToscaError error) {
+            super("Error while exporting component's interface (toscaError:" + error + ")");
+        }
+    }
+
+    @Getter
+    public static final class NonMetaArtifactInfo {
+
+        private final String path;
+        private final String artifactName;
+        private final String displayName;
+        private final String artifactLabel;
+        private final String artifactType;
+        private final ArtifactGroupTypeEnum artifactGroupType;
+        private final String payloadData;
+        private final String artifactChecksum;
+        private final boolean isFromCsar;
+        @Setter
+        private String artifactUniqueId;
+
+        public NonMetaArtifactInfo(final String artifactName, final String path, final String artifactType,
+                                   final ArtifactGroupTypeEnum artifactGroupType, final byte[] payloadData, final String artifactUniqueId,
+                                   final boolean isFromCsar) {
+            super();
+            this.path = path;
+            this.isFromCsar = isFromCsar;
+            this.artifactName = ValidationUtils.normalizeFileName(artifactName);
+            this.artifactType = artifactType;
+            this.artifactGroupType = artifactGroupType;
+            final int pointIndex = artifactName.lastIndexOf('.');
+            if (pointIndex > 0) {
+                displayName = artifactName.substring(0, pointIndex);
+            } else {
+                displayName = artifactName;
+            }
+            this.artifactLabel = ValidationUtils.normalizeArtifactLabel(artifactName);
+            if (payloadData == null) {
+                this.payloadData = null;
+                this.artifactChecksum = null;
+            } else {
+                this.payloadData = Base64.encodeBase64String(payloadData);
+                this.artifactChecksum = GeneralUtility.calculateMD5Base64EncodedByByteArray(payloadData);
+            }
+            this.artifactUniqueId = artifactUniqueId;
+        }
+    }
+
+    /**
+     * The artifacts Definition saved by their structure
+     */
+    private class ArtifactsInfo {
+        //Key is the type of artifacts(Informational/Deployment)
+
+        //Value is a map between an artifact type and a list of all artifacts of this type
+        private Map<ArtifactGroupTypeEnum, Map<String, List<ArtifactDefinition>>> artifactsInfoField;
+
+        public ArtifactsInfo() {
+            this.artifactsInfoField = new EnumMap<>(ArtifactGroupTypeEnum.class);
+        }
+
+        public Map<ArtifactGroupTypeEnum, Map<String, List<ArtifactDefinition>>> getArtifactsInfo() {
+            return artifactsInfoField;
+        }
+
+        public void addArtifactsToGroup(ArtifactGroupTypeEnum artifactGroup, Map<String, List<ArtifactDefinition>> artifactsDefinition) {
+            if (artifactsInfoField.get(artifactGroup) == null) {
+                artifactsInfoField.put(artifactGroup, artifactsDefinition);
+            } else {
+                Map<String, List<ArtifactDefinition>> artifactTypeEnumListMap = artifactsInfoField.get(artifactGroup);
+                artifactTypeEnumListMap.putAll(artifactsDefinition);
+                artifactsInfoField.put(artifactGroup, artifactTypeEnumListMap);
+            }
+        }
+
+        public boolean isEmpty() {
+            return artifactsInfoField.isEmpty();
+        }
+
+        public boolean isNotEmpty() {
+            return !isEmpty();
+        }
+    }
+
+    /**
+     * The artifacts of the component and of all its composed instances
+     */
+    private class ComponentTypeArtifacts {
+
+        private ArtifactsInfo componentArtifacts;    //component artifacts (describes the Informational Deployment folders)
+
+        private Map<String, ArtifactsInfo> componentInstancesArtifacts;        //artifacts of the composed instances mapped by the resourceInstance normalized name (describes the Resources folder)
+
+        public ComponentTypeArtifacts() {
+            componentArtifacts = new ArtifactsInfo();
+            componentInstancesArtifacts = new HashMap<>();
+        }
+
+        public ArtifactsInfo getComponentArtifacts() {
+            return componentArtifacts;
+        }
+
+        public void setComponentArtifacts(ArtifactsInfo artifactsInfo) {
+            this.componentArtifacts = artifactsInfo;
+        }
+
+        public Map<String, ArtifactsInfo> getComponentInstancesArtifacts() {
+            return componentInstancesArtifacts;
+        }
+
+        public void addComponentInstancesArtifacts(String normalizedName, ArtifactsInfo artifactsInfo) {
+            componentInstancesArtifacts.put(normalizedName, artifactsInfo);
+        }
+    }
+
+    private class ComponentArtifacts {
+
+        //artifacts of the component and CI's artifacts contained in it's composition (represents Informational, Deployment & Resource folders of main component)
+        private ComponentTypeArtifacts mainTypeAndCIArtifacts;
+        //artifacts of all component types mapped by their tosca name
+        private Map<String, ComponentTypeArtifacts> componentTypeArtifacts;
+
+        public ComponentArtifacts() {
+            mainTypeAndCIArtifacts = new ComponentTypeArtifacts();
+            componentTypeArtifacts = new HashMap<>();
+        }
+
+        public ComponentTypeArtifacts getMainTypeAndCIArtifacts() {
+            return mainTypeAndCIArtifacts;
+        }
+
+        public void setMainTypeAndCIArtifacts(ComponentTypeArtifacts componentInstanceArtifacts) {
+            this.mainTypeAndCIArtifacts = componentInstanceArtifacts;
+        }
+
+        public Map<String, ComponentTypeArtifacts> getComponentTypeArtifacts() {
+            return componentTypeArtifacts;
+        }
+    }
+
+    private class CsarDefinition {
+
+        private ComponentArtifacts componentArtifacts;
+
+        // add list of tosca artifacts and meta describes CSAR zip root
+        public CsarDefinition(ComponentArtifacts componentArtifacts) {
+            this.componentArtifacts = componentArtifacts;
+        }
+
+        public ComponentArtifacts getComponentArtifacts() {
+            return componentArtifacts;
+        }
+    }
 }
+
index 32b9957..94bc279 100644 (file)
@@ -17,7 +17,6 @@
  * limitations under the License.
  * ============LICENSE_END=========================================================
  */
-
 package org.openecomp.sdc.be.tosca;
 
 import io.vavr.control.Try;
@@ -28,9 +27,11 @@ import java.util.function.Function;
  */
 public final class FJToVavrHelper {
 
-    private FJToVavrHelper() {}
+    private FJToVavrHelper() {
+    }
 
     public interface Try0 {
+
         /**
          * Converts a {@link fj.data.Either} to a {@link io.vavr.control.Try}
          *
@@ -39,10 +40,7 @@ public final class FJToVavrHelper {
          * @return
          */
         static <L, R> Try<L> fromEither(fj.data.Either<L, R> e, Function<R, Throwable> onError) {
-            return e.either(
-                Try::success,
-                r -> Try.failure(onError.apply(r))
-            );
+            return e.either(Try::success, r -> Try.failure(onError.apply(r)));
         }
     }
 }
index c579a65..4c41d22 100644 (file)
@@ -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.
  * limitations under the License.
  * ============LICENSE_END=========================================================
  */
-
 package org.openecomp.sdc.be.tosca;
 
+import java.util.Map;
 import org.openecomp.sdc.be.model.Component;
 import org.openecomp.sdc.be.model.GroupInstance;
 import org.openecomp.sdc.be.tosca.model.ToscaGroupTemplate;
 
-import java.util.Map;
-
 public interface GroupExportParser {
 
-       Map<String, ToscaGroupTemplate> getGroups(Component component);
-       
-       ToscaGroupTemplate getToscaGroupTemplate(GroupInstance groupInstance, String invariantName) ;
-       
+    Map<String, ToscaGroupTemplate> getGroups(Component component);
+
+    ToscaGroupTemplate getToscaGroupTemplate(GroupInstance groupInstance, String invariantName);
 }
index bb4d363..65f3b64 100644 (file)
@@ -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.
  * limitations under the License.
  * ============LICENSE_END=========================================================
  */
-
 package org.openecomp.sdc.be.tosca;
 
+import static java.util.stream.Collectors.toList;
+import static java.util.stream.Collectors.toMap;
+import static org.apache.commons.collections.CollectionUtils.isEmpty;
+import static org.apache.commons.collections.CollectionUtils.isNotEmpty;
+import static org.apache.commons.collections.MapUtils.isEmpty;
+import static org.apache.commons.collections.MapUtils.isNotEmpty;
+import static org.apache.commons.lang.StringUtils.isNotEmpty;
+import static org.openecomp.sdc.be.model.utils.ComponentUtilities.getComponentInstanceNameByInstanceId;
+
 import fj.data.Either;
+import java.util.Collection;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+import java.util.Optional;
+import java.util.function.Predicate;
+import java.util.function.Supplier;
 import org.apache.commons.lang.StringUtils;
 import org.openecomp.sdc.be.components.impl.exceptions.SdcResourceNotFoundException;
 import org.openecomp.sdc.be.dao.janusgraph.JanusGraphOperationStatus;
@@ -43,234 +58,182 @@ import org.openecomp.sdc.be.tosca.model.VfModuleToscaMetadata;
 import org.openecomp.sdc.common.api.Constants;
 import org.openecomp.sdc.common.log.wrappers.Logger;
 import org.springframework.beans.factory.annotation.Autowired;
-
-import java.util.Collection;
-import java.util.HashMap;
-import java.util.List;
-import java.util.Map;
-import java.util.Optional;
-import java.util.function.Predicate;
-import java.util.function.Supplier;
 import org.springframework.context.event.EventListener;
 
-import static java.util.stream.Collectors.toList;
-import static java.util.stream.Collectors.toMap;
-import static org.apache.commons.collections.CollectionUtils.isEmpty;
-import static org.apache.commons.collections.CollectionUtils.isNotEmpty;
-import static org.apache.commons.collections.MapUtils.isEmpty;
-import static org.apache.commons.collections.MapUtils.isNotEmpty;
-import static org.apache.commons.lang.StringUtils.isNotEmpty;
-import static org.openecomp.sdc.be.model.utils.ComponentUtilities.getComponentInstanceNameByInstanceId;
-
 @org.springframework.stereotype.Component
 public class GroupExportParserImpl implements GroupExportParser {
 
     private static final Logger log = Logger.getLogger(GroupExportParserImpl.class);
-
+    private final PropertyConvertor propertyConvertor;
     private Map<String, DataTypeDefinition> dataTypes;
     private ApplicationDataTypeCache dataTypeCache;
-    private final PropertyConvertor propertyConvertor;
-    
-    @Autowired
-       public GroupExportParserImpl(ApplicationDataTypeCache dataTypeCache, PropertyConvertor propertyConvertor) {
-               this.dataTypeCache = dataTypeCache;
-               this.propertyConvertor = propertyConvertor;
-               this.dataTypes = getDataTypes();
-       }
-    
-    private Map<String, DataTypeDefinition> getDataTypes()  {
-               Either<Map<String, DataTypeDefinition>, JanusGraphOperationStatus> dataTypesEither = dataTypeCache.getAll();
-               if (dataTypesEither.isRight()) {
-                       log.error("Failed to retrieve all data types {}", dataTypesEither.right().value()); 
-                       throw new SdcResourceNotFoundException(); 
-               }
-               
-               return dataTypesEither.left().value();
-       }
 
-       @EventListener
-       public void onDataTypesCacheChangedEvent(
-                       ApplicationDataTypeCache.DataTypesCacheChangedEvent dataTypesCacheChangedEvent) {
-               dataTypes = dataTypesCacheChangedEvent.getNewData();
-               log.debug("Data types cache updated.");
-       }
-    
-       @Override
-       public Map<String, ToscaGroupTemplate> getGroups(Component component) {
-               List<GroupDefinition> groups = component.getGroups();
-
-               if (isEmpty(groups)) {
-                       return null;
-               }
-               
-               return groups.stream()
-                               .collect(toMap(GroupDefinition::getName,
-                                                 group -> getToscaGroupTemplate(component, group)));
-       }
-       
-       @Override
-       public ToscaGroupTemplate getToscaGroupTemplate(GroupInstance groupInstance, String componentInstanceInvariantName) {
-               
-               String groupName = groupInstance.getName();
-               if (StringUtils.isNotEmpty(componentInstanceInvariantName)) {
-                       String prefix = componentInstanceInvariantName + Constants.GROUP_POLICY_NAME_DELIMETER;
-                       if (groupName.startsWith(prefix)) {
-                               groupName = groupName.substring(prefix.length());
-                       }
-               }
-               String invariantUUID = groupInstance.getInvariantUUID();
-               String groupUUID = groupInstance.getGroupUUID();
-               String version = groupInstance.getVersion();
-               List<GroupInstanceProperty> groupInstanceProperties = groupInstance.convertToGroupInstancesProperties();
-               String groupType = groupInstance.getType();
-               String customizationUUID = groupInstance.getCustomizationUUID();
-
-               IToscaMetadata toscaMetadata = getToscaGroupTemplateMetadata(groupName, invariantUUID, groupUUID, version, groupType, customizationUUID);               
-               Map<String, Object> properties = getToscaGroupTemplateProperties(groupInstanceProperties);
-               
+    @Autowired
+    public GroupExportParserImpl(ApplicationDataTypeCache dataTypeCache, PropertyConvertor propertyConvertor) {
+        this.dataTypeCache = dataTypeCache;
+        this.propertyConvertor = propertyConvertor;
+        this.dataTypes = getDataTypes();
+    }
+
+    private Map<String, DataTypeDefinition> getDataTypes() {
+        Either<Map<String, DataTypeDefinition>, JanusGraphOperationStatus> dataTypesEither = dataTypeCache.getAll();
+        if (dataTypesEither.isRight()) {
+            log.error("Failed to retrieve all data types {}", dataTypesEither.right().value());
+            throw new SdcResourceNotFoundException();
+        }
+        return dataTypesEither.left().value();
+    }
+
+    @EventListener
+    public void onDataTypesCacheChangedEvent(ApplicationDataTypeCache.DataTypesCacheChangedEvent dataTypesCacheChangedEvent) {
+        dataTypes = dataTypesCacheChangedEvent.getNewData();
+        log.debug("Data types cache updated.");
+    }
+
+    @Override
+    public Map<String, ToscaGroupTemplate> getGroups(Component component) {
+        List<GroupDefinition> groups = component.getGroups();
+        if (isEmpty(groups)) {
+            return null;
+        }
+        return groups.stream().collect(toMap(GroupDefinition::getName, group -> getToscaGroupTemplate(component, group)));
+    }
+
+    @Override
+    public ToscaGroupTemplate getToscaGroupTemplate(GroupInstance groupInstance, String componentInstanceInvariantName) {
+        String groupName = groupInstance.getName();
+        if (StringUtils.isNotEmpty(componentInstanceInvariantName)) {
+            String prefix = componentInstanceInvariantName + Constants.GROUP_POLICY_NAME_DELIMETER;
+            if (groupName.startsWith(prefix)) {
+                groupName = groupName.substring(prefix.length());
+            }
+        }
+        String invariantUUID = groupInstance.getInvariantUUID();
+        String groupUUID = groupInstance.getGroupUUID();
+        String version = groupInstance.getVersion();
+        List<GroupInstanceProperty> groupInstanceProperties = groupInstance.convertToGroupInstancesProperties();
+        String groupType = groupInstance.getType();
+        String customizationUUID = groupInstance.getCustomizationUUID();
+        IToscaMetadata toscaMetadata = getToscaGroupTemplateMetadata(groupName, invariantUUID, groupUUID, version, groupType, customizationUUID);
+        Map<String, Object> properties = getToscaGroupTemplateProperties(groupInstanceProperties);
         return new ToscaGroupTemplate(groupType, toscaMetadata, properties);
-       }
-
-       private ToscaGroupTemplate getToscaGroupTemplate(Component component, GroupDefinition groupDefinition) {
-
-               String groupName = groupDefinition.getName();
-               String invariantUUID = groupDefinition.getInvariantUUID();
-               String groupUUID = groupDefinition.getGroupUUID();
-               String version = groupDefinition.getVersion();
-               String groupType = groupDefinition.getType();
-               List<PropertyDataDefinition> groupDefinitionProperties = groupDefinition.getProperties();
-               
-               List<String> members = getToscaGroupTemplateMembers(component, groupDefinition.getMembers());
-               IToscaMetadata toscaMetadata = getToscaGroupTemplateMetadata(groupName, invariantUUID, groupUUID, version,groupType, null);             
-               Map<String, Object> properties = getToscaGroupTemplateProperties(groupDefinitionProperties);
-               Map<String, ToscaTemplateCapability> capabilities = getToscaGroupTemplateCapabilities(groupDefinition);
-
-               return new ToscaGroupTemplate(groupType, members, toscaMetadata, properties, capabilities);
-       }
-       
-       private Map<String, ToscaTemplateCapability> getToscaGroupTemplateCapabilities(GroupDefinition group) {
-               if (isEmpty(group.getCapabilities())) {
-                       return null;
-               }
-
-               Map<String, ToscaTemplateCapability> toscaGroupTemplateCapabilities = group.getCapabilities().values()
-                               .stream()
-                               .flatMap(Collection::stream)
-                               .filter(c -> isNotEmptyProperties(c.getProperties()))
-                               .collect(toMap(c-> getCapabilityName(c, group), this::getToscaTemplateCapability));
-
-               if (isNotEmpty(toscaGroupTemplateCapabilities)) {
-                       return toscaGroupTemplateCapabilities;
-               } else {
-                       return null;
-               }
-       }
-
-       private String getCapabilityName(CapabilityDefinition capability, GroupDefinition group) {
-       if(ComponentUtilities.isNotUpdatedCapReqName(group.getNormalizedName() + ".", capability.getName(), capability.getPreviousName())){
-               return capability.getName();
-               }
-               return capability.getPreviousName();
-       }
-
-       private boolean isNotEmptyProperties(List<ComponentInstanceProperty> properties) {
-       return isNotEmpty(properties) && properties.stream()
-                               .filter(isComponentInstancePropertiesNotEmpty())
-                               .findFirst()
-                               .isPresent();
-       }
-
-       private ToscaTemplateCapability getToscaTemplateCapability(CapabilityDefinition capability) {
-               ToscaTemplateCapability toscaTemplateCapability = new ToscaTemplateCapability();
-               Map<String, Object> toscaCapabilityProperties = capability.getProperties().stream()
-                               .filter(isComponentInstancePropertiesNotEmpty())
-                               .collect(toMap(ComponentInstanceProperty::getName,
-                                                                                 this::fetchCapabilityValue));
-               if(isNotEmpty(toscaCapabilityProperties)) {
-                       toscaTemplateCapability.setProperties(toscaCapabilityProperties);
-               }
-               return toscaTemplateCapability;
-       }
-
-       private Predicate<? super ComponentInstanceProperty> isComponentInstancePropertiesNotEmpty() {
-               return c -> {
-                       return (c.getName() != null && (c.getValue() != null || c.getDefaultValue() != null));
-               };
-       }
-
-       private String fetchCapabilityValue(ComponentInstanceProperty componentInstanceProperty) {
-               if(componentInstanceProperty.getValue() != null) {
-                       return componentInstanceProperty.getValue();
-               }else {
-                       return componentInstanceProperty.getDefaultValue();
-               }
-       }
-
-       private List<String> getToscaGroupTemplateMembers(Component component, Map<String, String> members) {
-               if (members == null) {
-                       return null;
-               }
-               return members.values()
-                               .stream()
-                               .map(memberId -> getMemberNameByMemberId(component, memberId))
-                               .filter(Optional::isPresent)
-                               .map(Optional::get)
-                               .collect(toList());
-       }
-
-       private Optional<String> getMemberNameByMemberId(Component component, String memberId) {
-       return getComponentInstanceNameByInstanceId(component, memberId);
-       }
-
-       private IToscaMetadata getToscaGroupTemplateMetadata(String groupName,String invariantUUID,
-                                                                    String groupUUID,String version,String type, String customizationUUID) {
-                               
-               IToscaMetadata toscaMetadata = getToscaMetadataByType(type);
-               
-               toscaMetadata.setName(groupName);
-               toscaMetadata.setInvariantUUID(invariantUUID);
-               toscaMetadata.setUUID(groupUUID);
-               toscaMetadata.setVersion(version);
-               toscaMetadata.setCustomizationUUID(customizationUUID);
-               return toscaMetadata;
-       }
-
-       private IToscaMetadata getToscaMetadataByType(String type) {
-               IToscaMetadata toscaMetadata;
-               if (GroupUtils.isVfModule(type)) {
-                       toscaMetadata = new VfModuleToscaMetadata();
-               } else {
-                       toscaMetadata = new ToscaMetadata();
-               }
-               return toscaMetadata;
-       }
-
-       private Map<String, Object> getToscaGroupTemplateProperties(List<? extends PropertyDataDefinition> tempProperties) {
-                               
-               if (isEmpty(tempProperties)) {
-                       return null;
-               }
-                               
-               Map<String, Object> props = new HashMap<>();
-
-               tempProperties.forEach(input -> 
-                       propertyConvertor.convertAndAddValue(dataTypes, props, input, getPropertyValue(input))
-               );
-
-               if (props.isEmpty()) {
-                       return null;
-               } else {
-                       return props;
-               }       
-       }
-
-       private Supplier<String> getPropertyValue(PropertyDataDefinition propertyDataDefinition) {
-               return () -> {
-                       if (isNotEmpty(propertyDataDefinition.getValue())) {
-                               return propertyDataDefinition.getValue();
-                       } else {
-                               return propertyDataDefinition.getDefaultValue();
-                       }
-               };
-       }
+    }
+
+    private ToscaGroupTemplate getToscaGroupTemplate(Component component, GroupDefinition groupDefinition) {
+        String groupName = groupDefinition.getName();
+        String invariantUUID = groupDefinition.getInvariantUUID();
+        String groupUUID = groupDefinition.getGroupUUID();
+        String version = groupDefinition.getVersion();
+        String groupType = groupDefinition.getType();
+        List<PropertyDataDefinition> groupDefinitionProperties = groupDefinition.getProperties();
+        List<String> members = getToscaGroupTemplateMembers(component, groupDefinition.getMembers());
+        IToscaMetadata toscaMetadata = getToscaGroupTemplateMetadata(groupName, invariantUUID, groupUUID, version, groupType, null);
+        Map<String, Object> properties = getToscaGroupTemplateProperties(groupDefinitionProperties);
+        Map<String, ToscaTemplateCapability> capabilities = getToscaGroupTemplateCapabilities(groupDefinition);
+        return new ToscaGroupTemplate(groupType, members, toscaMetadata, properties, capabilities);
+    }
+
+    private Map<String, ToscaTemplateCapability> getToscaGroupTemplateCapabilities(GroupDefinition group) {
+        if (isEmpty(group.getCapabilities())) {
+            return null;
+        }
+        Map<String, ToscaTemplateCapability> toscaGroupTemplateCapabilities = group.getCapabilities().values().stream().flatMap(Collection::stream)
+            .filter(c -> isNotEmptyProperties(c.getProperties())).collect(toMap(c -> getCapabilityName(c, group), this::getToscaTemplateCapability));
+        if (isNotEmpty(toscaGroupTemplateCapabilities)) {
+            return toscaGroupTemplateCapabilities;
+        } else {
+            return null;
+        }
+    }
+
+    private String getCapabilityName(CapabilityDefinition capability, GroupDefinition group) {
+        if (ComponentUtilities.isNotUpdatedCapReqName(group.getNormalizedName() + ".", capability.getName(), capability.getPreviousName())) {
+            return capability.getName();
+        }
+        return capability.getPreviousName();
+    }
+
+    private boolean isNotEmptyProperties(List<ComponentInstanceProperty> properties) {
+        return isNotEmpty(properties) && properties.stream().filter(isComponentInstancePropertiesNotEmpty()).findFirst().isPresent();
+    }
+
+    private ToscaTemplateCapability getToscaTemplateCapability(CapabilityDefinition capability) {
+        ToscaTemplateCapability toscaTemplateCapability = new ToscaTemplateCapability();
+        Map<String, Object> toscaCapabilityProperties = capability.getProperties().stream().filter(isComponentInstancePropertiesNotEmpty())
+            .collect(toMap(ComponentInstanceProperty::getName, this::fetchCapabilityValue));
+        if (isNotEmpty(toscaCapabilityProperties)) {
+            toscaTemplateCapability.setProperties(toscaCapabilityProperties);
+        }
+        return toscaTemplateCapability;
+    }
+
+    private Predicate<? super ComponentInstanceProperty> isComponentInstancePropertiesNotEmpty() {
+        return c -> {
+            return (c.getName() != null && (c.getValue() != null || c.getDefaultValue() != null));
+        };
+    }
+
+    private String fetchCapabilityValue(ComponentInstanceProperty componentInstanceProperty) {
+        if (componentInstanceProperty.getValue() != null) {
+            return componentInstanceProperty.getValue();
+        } else {
+            return componentInstanceProperty.getDefaultValue();
+        }
+    }
+
+    private List<String> getToscaGroupTemplateMembers(Component component, Map<String, String> members) {
+        if (members == null) {
+            return null;
+        }
+        return members.values().stream().map(memberId -> getMemberNameByMemberId(component, memberId)).filter(Optional::isPresent).map(Optional::get)
+            .collect(toList());
+    }
+
+    private Optional<String> getMemberNameByMemberId(Component component, String memberId) {
+        return getComponentInstanceNameByInstanceId(component, memberId);
+    }
+
+    private IToscaMetadata getToscaGroupTemplateMetadata(String groupName, String invariantUUID, String groupUUID, String version, String type,
+                                                         String customizationUUID) {
+        IToscaMetadata toscaMetadata = getToscaMetadataByType(type);
+        toscaMetadata.setName(groupName);
+        toscaMetadata.setInvariantUUID(invariantUUID);
+        toscaMetadata.setUUID(groupUUID);
+        toscaMetadata.setVersion(version);
+        toscaMetadata.setCustomizationUUID(customizationUUID);
+        return toscaMetadata;
+    }
+
+    private IToscaMetadata getToscaMetadataByType(String type) {
+        IToscaMetadata toscaMetadata;
+        if (GroupUtils.isVfModule(type)) {
+            toscaMetadata = new VfModuleToscaMetadata();
+        } else {
+            toscaMetadata = new ToscaMetadata();
+        }
+        return toscaMetadata;
+    }
+
+    private Map<String, Object> getToscaGroupTemplateProperties(List<? extends PropertyDataDefinition> tempProperties) {
+        if (isEmpty(tempProperties)) {
+            return null;
+        }
+        Map<String, Object> props = new HashMap<>();
+        tempProperties.forEach(input -> propertyConvertor.convertAndAddValue(dataTypes, props, input, getPropertyValue(input)));
+        if (props.isEmpty()) {
+            return null;
+        } else {
+            return props;
+        }
+    }
+
+    private Supplier<String> getPropertyValue(PropertyDataDefinition propertyDataDefinition) {
+        return () -> {
+            if (isNotEmpty(propertyDataDefinition.getValue())) {
+                return propertyDataDefinition.getValue();
+            } else {
+                return propertyDataDefinition.getDefaultValue();
+            }
+        };
+    }
 }
index 8d35517..37659f1 100644 (file)
@@ -13,7 +13,6 @@
  * See the License for the specific language governing permissions and
  * limitations under the License.
  */
-
 package org.openecomp.sdc.be.tosca;
 
 import static org.openecomp.sdc.be.utils.TypeUtils.ToscaTagNamesEnum.DEFAULT;
@@ -59,17 +58,13 @@ import org.springframework.stereotype.Service;
 @Service
 public class InterfacesOperationsConverter {
 
-
+    public static final String SELF = "SELF";
     private static final String DERIVED_FROM_STANDARD_INTERFACE = "tosca.interfaces.node.lifecycle.Standard";
     private static final String DERIVED_FROM_BASE_DEFAULT = "org.openecomp.interfaces.node.lifecycle.";
-
     private static final String DEFAULT_HAS_UNDERSCORE = "_default";
     private static final String DOT = ".";
     private static final String DEFAULTP = "defaultp";
-
-    public static final String SELF = "SELF";
     private static final String LOCAL_INTERFACE_TYPE = "Local";
-
     private final PropertyConvertor propertyConvertor;
 
     @Autowired
@@ -91,18 +86,15 @@ public class InterfacesOperationsConverter {
         if (MapUtils.isEmpty(interfaces)) {
             return null;
         }
-
         Map<String, Object> toscaInterfaceTypes = new HashMap<>();
         for (InterfaceDefinition interfaceDefinition : interfaces.values()) {
-            boolean isInterfaceTypeExistInGlobalType =
-                    allInterfaceTypes.stream().anyMatch(type -> type.equalsIgnoreCase(interfaceDefinition.getType()));
+            boolean isInterfaceTypeExistInGlobalType = allInterfaceTypes.stream()
+                .anyMatch(type -> type.equalsIgnoreCase(interfaceDefinition.getType()));
             if (!isInterfaceTypeExistInGlobalType) {
                 ToscaInterfaceNodeType toscaInterfaceType = new ToscaInterfaceNodeType();
                 toscaInterfaceType.setDerived_from(DERIVED_FROM_STANDARD_INTERFACE);
-
                 final Map<String, OperationDataDefinition> operations = interfaceDefinition.getOperations();
                 Map<String, Object> toscaOperations = new HashMap<>();
-
                 for (Map.Entry<String, OperationDataDefinition> operationEntry : operations.entrySet()) {
                     toscaOperations.put(operationEntry.getValue().getName(), null);
                 }
@@ -110,22 +102,100 @@ public class InterfacesOperationsConverter {
                 Map<String, Object> interfacesAsMap = getObjectAsMap(toscaInterfaceType);
                 Map<String, Object> operationsMap = (Map<String, Object>) interfacesAsMap.remove(OPERATIONS.getElementName());
                 interfacesAsMap.putAll(operationsMap);
-
                 toscaInterfaceTypes.put(getInterfaceType(component, LOCAL_INTERFACE_TYPE), interfacesAsMap);
             }
         }
         return MapUtils.isNotEmpty(toscaInterfaceTypes) ? toscaInterfaceTypes : null;
     }
 
+    private static Object getDefaultValue(Map<String, Object> inputValueMap) {
+        Object defaultValue = null;
+        for (Map.Entry<String, Object> operationEntry : inputValueMap.entrySet()) {
+            final Object value = operationEntry.getValue();
+            if (value instanceof Map) {
+                getDefaultValue((Map<String, Object>) value);
+            }
+            final String key = operationEntry.getKey();
+            if (key.equals(DEFAULTP)) {
+                defaultValue = inputValueMap.remove(key);
+            }
+        }
+        return defaultValue;
+    }
+
+    //Remove input type and copy default value directly into the proxy node template from the node type
+    private static void handleOperationInputValue(Map<String, Object> operationsMap, String parentKey) {
+        for (Map.Entry<String, Object> operationEntry : operationsMap.entrySet()) {
+            final Object value = operationEntry.getValue();
+            final String key = operationEntry.getKey();
+            if (value instanceof Map) {
+                if (INPUTS.getElementName().equals(parentKey)) {
+                    Object defaultValue = getDefaultValue((Map<String, Object>) value);
+                    operationsMap.put(key, defaultValue);
+                } else {
+                    handleOperationInputValue((Map<String, Object>) value, key);
+                }
+            }
+        }
+    }
+
+    private static String getLastPartOfName(String toscaResourceName) {
+        return toscaResourceName.substring(toscaResourceName.lastIndexOf(DOT) + 1);
+    }
+
+    private static boolean isArtifactPresent(Map.Entry<String, OperationDataDefinition> operationEntry) {
+        final boolean isImplementationPresent = !Objects.isNull(operationEntry.getValue().getImplementation());
+        if (isImplementationPresent) {
+            return !Objects.isNull(operationEntry.getValue().getImplementation().getArtifactName());
+        }
+        return false;
+    }
+
+    private static String getInputValue(String inputValue) {
+        String toscaInputValue = inputValue;
+        if (Objects.nonNull(inputValue) && inputValue.contains(ToscaFunctions.GET_OPERATION_OUTPUT.getFunctionName())) {
+            Gson gson = new Gson();
+            Map<String, List<String>> consumptionValue = gson.fromJson(inputValue, Map.class);
+            List<String> mappedOutputValue = consumptionValue.get(ToscaFunctions.GET_OPERATION_OUTPUT.getFunctionName());
+            //Extract the interface name from the interface type
+            String interfaceType = mappedOutputValue.get(1);
+            String interfaceName = interfaceType.substring(interfaceType.lastIndexOf('.') + 1);
+            mappedOutputValue.remove(1);
+            mappedOutputValue.add(1, interfaceName);
+            toscaInputValue = gson.toJson(consumptionValue);
+        }
+        return toscaInputValue;
+    }
+
+    private static String getInterfaceType(Component component, String interfaceType) {
+        if (LOCAL_INTERFACE_TYPE.equals(interfaceType)) {
+            return DERIVED_FROM_BASE_DEFAULT + component.getComponentMetadataDefinition().getMetadataDataDefinition().getSystemName();
+        }
+        return interfaceType;
+    }
+
+    private static Map<String, Object> getObjectAsMap(Object obj) {
+        ObjectMapper objectMapper = new ObjectMapper();
+        if (obj instanceof ToscaInterfaceDefinition) {
+            //Prevent empty field serialization in interface definition
+            objectMapper.setSerializationInclusion(JsonInclude.Include.NON_NULL);
+        }
+        Map<String, Object> objectAsMap = obj instanceof Map ? (Map<String, Object>) obj : objectMapper.convertValue(obj, Map.class);
+        final String defaultEntry = DEFAULT.getElementName();
+        if (objectAsMap.containsKey(defaultEntry)) {
+            objectAsMap.put(DEFAULT_HAS_UNDERSCORE, objectAsMap.remove(defaultEntry));
+        }
+        return objectAsMap;
+    }
+
     /**
      * Adds the 'interfaces' element to the node type provided.
      *
      * @param component to work on
      * @param nodeType  to which the interfaces element will be added
      */
-    public void addInterfaceDefinitionElement(Component component, ToscaNodeType nodeType,
-                                                     Map<String, DataTypeDefinition> dataTypes,
-                                                     boolean isAssociatedComponent) {
+    public void addInterfaceDefinitionElement(Component component, ToscaNodeType nodeType, Map<String, DataTypeDefinition> dataTypes,
+                                              boolean isAssociatedComponent) {
         if (component instanceof Product) {
             return;
         }
@@ -133,60 +203,47 @@ public class InterfacesOperationsConverter {
         if (MapUtils.isEmpty(interfaces)) {
             return;
         }
-        Map<String, Object> toscaInterfaceDefinitions = getInterfacesMap(component, dataTypes,
-                isAssociatedComponent);
+        Map<String, Object> toscaInterfaceDefinitions = getInterfacesMap(component, dataTypes, isAssociatedComponent);
         if (MapUtils.isNotEmpty(toscaInterfaceDefinitions)) {
             nodeType.setInterfaces(toscaInterfaceDefinitions);
         }
     }
 
-    private Map<String, Object> getInterfacesMap(Component component,
-                                                        Map<String, DataTypeDefinition> dataTypes,
-                                                        boolean isAssociatedComponent) {
+    private Map<String, Object> getInterfacesMap(Component component, Map<String, DataTypeDefinition> dataTypes, boolean isAssociatedComponent) {
         return getInterfacesMap(component, null, component.getInterfaces(), dataTypes, isAssociatedComponent, false);
     }
 
-    public Map<String, Object> getInterfacesMap(final Component component,
-                                                final ComponentInstance componentInstance,
-                                                final Map<String, InterfaceDefinition> interfaces,
-                                                final Map<String, DataTypeDefinition> dataTypes,
-                                                final boolean isAssociatedComponent,
-                                                final boolean isServiceProxyInterface) {
+    public Map<String, Object> getInterfacesMap(final Component component, final ComponentInstance componentInstance,
+                                                final Map<String, InterfaceDefinition> interfaces, final Map<String, DataTypeDefinition> dataTypes,
+                                                final boolean isAssociatedComponent, final boolean isServiceProxyInterface) {
         if (MapUtils.isEmpty(interfaces)) {
             return null;
         }
-
         final Map<String, Object> toscaInterfaceDefinitions = new HashMap<>();
         for (InterfaceDefinition interfaceDefinition : interfaces.values()) {
-            handleInterfaceOperations(component, componentInstance, dataTypes, isAssociatedComponent,
-                isServiceProxyInterface, toscaInterfaceDefinitions, interfaceDefinition);
+            handleInterfaceOperations(component, componentInstance, dataTypes, isAssociatedComponent, isServiceProxyInterface,
+                toscaInterfaceDefinitions, interfaceDefinition);
         }
         return toscaInterfaceDefinitions;
     }
 
-    public Map<String, Object> getInterfacesMapFromComponentInstance(final Component component,
-                                                                     final ComponentInstance componentInstance,
+    public Map<String, Object> getInterfacesMapFromComponentInstance(final Component component, final ComponentInstance componentInstance,
                                                                      final Map<String, DataTypeDefinition> dataTypes,
-                                                                     final boolean isAssociatedComponent,
-                                                                     final boolean isServiceProxyInterface) {
+                                                                     final boolean isAssociatedComponent, final boolean isServiceProxyInterface) {
         final Map<String, Object> toscaInterfaceDefinitions = new HashMap<>();
         final ObjectMapper objectMapper = new ObjectMapper();
         objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
         for (final Map.Entry<String, Object> interfaceEntry : componentInstance.getInterfaces().entrySet()) {
-            final InterfaceDefinition interfaceDefinition = objectMapper
-                .convertValue(interfaceEntry.getValue(), InterfaceDefinition.class);
-            handleInterfaceOperations(component, componentInstance, dataTypes, isAssociatedComponent,
-                isServiceProxyInterface, toscaInterfaceDefinitions, interfaceDefinition);
+            final InterfaceDefinition interfaceDefinition = objectMapper.convertValue(interfaceEntry.getValue(), InterfaceDefinition.class);
+            handleInterfaceOperations(component, componentInstance, dataTypes, isAssociatedComponent, isServiceProxyInterface,
+                toscaInterfaceDefinitions, interfaceDefinition);
         }
         return toscaInterfaceDefinitions;
     }
 
-    private void handleInterfaceOperations(final Component component,
-                                           final ComponentInstance componentInstance,
-                                           final Map<String, DataTypeDefinition> dataTypes,
-                                           final boolean isAssociatedComponent,
-                                           final boolean isServiceProxyInterface,
-                                           final Map<String, Object> toscaInterfaceDefinitions,
+    private void handleInterfaceOperations(final Component component, final ComponentInstance componentInstance,
+                                           final Map<String, DataTypeDefinition> dataTypes, final boolean isAssociatedComponent,
+                                           final boolean isServiceProxyInterface, final Map<String, Object> toscaInterfaceDefinitions,
                                            final InterfaceDefinition interfaceDefinition) {
         final String interfaceType;
         if (componentInstance != null && LOCAL_INTERFACE_TYPE.equals(interfaceDefinition.getType())) {
@@ -200,19 +257,14 @@ public class InterfacesOperationsConverter {
         }
         final Map<String, OperationDataDefinition> operations = interfaceDefinition.getOperations();
         final Map<String, Object> toscaOperationMap = new HashMap<>();
-
         for (final Entry<String, OperationDataDefinition> operationEntry : operations.entrySet()) {
-            final ToscaLifecycleOperationDefinition toscaLifecycleOperationDefinition =
-                new ToscaLifecycleOperationDefinition();
-            handleInterfaceOperationImplementation(component, componentInstance, isAssociatedComponent,
-                operationEntry,
+            final ToscaLifecycleOperationDefinition toscaLifecycleOperationDefinition = new ToscaLifecycleOperationDefinition();
+            handleInterfaceOperationImplementation(component, componentInstance, isAssociatedComponent, operationEntry,
                 toscaLifecycleOperationDefinition);
             toscaLifecycleOperationDefinition.setDescription(operationEntry.getValue().getDescription());
-            fillToscaOperationInputs(operationEntry.getValue(), dataTypes, toscaLifecycleOperationDefinition,
-                isServiceProxyInterface);
+            fillToscaOperationInputs(operationEntry.getValue(), dataTypes, toscaLifecycleOperationDefinition, isServiceProxyInterface);
             toscaOperationMap.put(operationEntry.getValue().getName(), toscaLifecycleOperationDefinition);
         }
-
         toscaInterfaceDefinition.setOperations(toscaOperationMap);
         final Map<String, Object> interfaceInputMap = createInterfaceInputMap(interfaceDefinition, dataTypes);
         if (!interfaceInputMap.isEmpty()) {
@@ -222,26 +274,20 @@ public class InterfacesOperationsConverter {
         if (interfaceDefinitionAsMap.containsKey(INPUTS.getElementName())) {
             handleDefaults((Map<String, Object>) interfaceDefinitionAsMap.get(INPUTS.getElementName()));
         }
-        final Map<String, Object> operationsMap =
-            (Map<String, Object>) interfaceDefinitionAsMap.remove(OPERATIONS.getElementName());
-
+        final Map<String, Object> operationsMap = (Map<String, Object>) interfaceDefinitionAsMap.remove(OPERATIONS.getElementName());
         handleOperationInputValue(operationsMap, interfaceType);
-
         interfaceDefinitionAsMap.putAll(operationsMap);
         toscaInterfaceDefinitions.put(getLastPartOfName(interfaceType), interfaceDefinitionAsMap);
     }
 
-    private void handleInterfaceOperationImplementation(final Component component,
-                                                        final ComponentInstance componentInstance,
+    private void handleInterfaceOperationImplementation(final Component component, final ComponentInstance componentInstance,
                                                         final boolean isAssociatedComponent,
                                                         final Entry<String, OperationDataDefinition> operationEntry,
                                                         final ToscaLifecycleOperationDefinition toscaOperation) {
         final String operationArtifactPath;
-        if (isArtifactPresent(operationEntry) && StringUtils
-            .isNotEmpty(operationEntry.getValue().getImplementation().getArtifactName())) {
+        if (isArtifactPresent(operationEntry) && StringUtils.isNotEmpty(operationEntry.getValue().getImplementation().getArtifactName())) {
             operationArtifactPath = OperationArtifactUtil
-                .createOperationArtifactPath(component, componentInstance, operationEntry.getValue(),
-                    isAssociatedComponent);
+                .createOperationArtifactPath(component, componentInstance, operationEntry.getValue(), isAssociatedComponent);
             toscaOperation.setImplementation(operationArtifactPath);
         } else {
             toscaOperation.setImplementation(operationEntry.getValue().getImplementation().getArtifactName());
@@ -252,18 +298,17 @@ public class InterfacesOperationsConverter {
         if (MapUtils.isEmpty(interfaceMap)) {
             return;
         }
-        final Set<String> emptyInterfaces = interfaceMap.entrySet().stream()
-            .filter(entry -> {
-                final Object value = entry.getValue();
-                if (value instanceof ToscaInterfaceDefinition) {
-                    final ToscaInterfaceDefinition interfaceDefinition = (ToscaInterfaceDefinition) value;
-                    return MapUtils.isEmpty(interfaceDefinition.getOperations());
-                } else if (value instanceof Map) {
-                    final Map<String, Object> interfaceDefMap = (Map<String, Object>) value;
-                    return MapUtils.isEmpty(interfaceDefMap);
-                }
-                return false;
-            }).map(Entry::getKey).collect(Collectors.toSet());
+        final Set<String> emptyInterfaces = interfaceMap.entrySet().stream().filter(entry -> {
+            final Object value = entry.getValue();
+            if (value instanceof ToscaInterfaceDefinition) {
+                final ToscaInterfaceDefinition interfaceDefinition = (ToscaInterfaceDefinition) value;
+                return MapUtils.isEmpty(interfaceDefinition.getOperations());
+            } else if (value instanceof Map) {
+                final Map<String, Object> interfaceDefMap = (Map<String, Object>) value;
+                return MapUtils.isEmpty(interfaceDefMap);
+            }
+            return false;
+        }).map(Entry::getKey).collect(Collectors.toSet());
         emptyInterfaces.forEach(interfaceMap::remove);
     }
 
@@ -283,37 +328,6 @@ public class InterfacesOperationsConverter {
         return toscaInterfaceInputMap;
     }
 
-    private static Object getDefaultValue(Map<String, Object> inputValueMap) {
-        Object defaultValue = null;
-        for (Map.Entry<String, Object> operationEntry : inputValueMap.entrySet()) {
-            final Object value = operationEntry.getValue();
-            if (value instanceof Map) {
-                getDefaultValue((Map<String, Object>) value);
-            }
-            final String key = operationEntry.getKey();
-            if (key.equals(DEFAULTP)) {
-                defaultValue = inputValueMap.remove(key);
-            }
-        }
-        return defaultValue;
-    }
-
-    //Remove input type and copy default value directly into the proxy node template from the node type
-    private static void handleOperationInputValue(Map<String, Object> operationsMap, String parentKey) {
-        for (Map.Entry<String, Object> operationEntry : operationsMap.entrySet()) {
-            final Object value = operationEntry.getValue();
-            final String key = operationEntry.getKey();
-            if (value instanceof Map) {
-                if (INPUTS.getElementName().equals(parentKey)) {
-                    Object defaultValue = getDefaultValue((Map<String, Object>) value);
-                    operationsMap.put(key, defaultValue);
-                } else {
-                    handleOperationInputValue((Map<String, Object>) value, key);
-                }
-            }
-        }
-    }
-
     /*
      * workaround for : currently "defaultp" is not being converted to "default" by the relevant code in
      * ToscaExportHandler so, any string Map key named "defaultp" will have its named changed to "default"
@@ -333,87 +347,26 @@ public class InterfacesOperationsConverter {
         }
     }
 
-    private static String getLastPartOfName(String toscaResourceName) {
-        return toscaResourceName.substring(toscaResourceName.lastIndexOf(DOT) + 1);
-    }
-
-    private static boolean isArtifactPresent(Map.Entry<String, OperationDataDefinition> operationEntry) {
-        final boolean isImplementationPresent = !Objects.isNull(operationEntry.getValue().getImplementation());
-        if (isImplementationPresent) {
-            return !Objects.isNull(operationEntry.getValue().getImplementation().getArtifactName());
-        }
-        return false;
-    }
-
-    private void fillToscaOperationInputs(OperationDataDefinition operation,
-                                                 Map<String, DataTypeDefinition> dataTypes,
-                                                 ToscaLifecycleOperationDefinition toscaOperation,
-                                                 boolean isServiceProxyInterface) {
+    private void fillToscaOperationInputs(OperationDataDefinition operation, Map<String, DataTypeDefinition> dataTypes,
+                                          ToscaLifecycleOperationDefinition toscaOperation, boolean isServiceProxyInterface) {
         if (Objects.isNull(operation.getInputs()) || operation.getInputs().isEmpty()) {
             toscaOperation.setInputs(null);
             return;
         }
         Map<String, ToscaProperty> toscaInputs = new HashMap<>();
-
         for (OperationInputDefinition input : operation.getInputs().getListToscaDataDefinition()) {
             ToscaProperty toscaInput = new ToscaProperty();
             toscaInput.setDescription(input.getDescription());
             toscaInput.setType(input.getType());
             toscaInput.setRequired(input.isRequired());
             if (isServiceProxyInterface) {
-                String inputValue = Objects.nonNull(input.getValue()) ? getInputValue(input.getValue()) :
-                        getInputValue(input.getToscaDefaultValue());
+                String inputValue = Objects.nonNull(input.getValue()) ? getInputValue(input.getValue()) : getInputValue(input.getToscaDefaultValue());
                 toscaInput.setDefaultp(propertyConvertor.convertToToscaObject(input, inputValue, dataTypes, false));
             } else {
-                toscaInput.setDefaultp(propertyConvertor
-                                               .convertToToscaObject(input, getInputValue(input.getToscaDefaultValue()),
-                                                       dataTypes, false));
+                toscaInput.setDefaultp(propertyConvertor.convertToToscaObject(input, getInputValue(input.getToscaDefaultValue()), dataTypes, false));
             }
             toscaInputs.put(input.getName(), toscaInput);
         }
         toscaOperation.setInputs(toscaInputs);
     }
-
-    private static String getInputValue(String inputValue) {
-        String toscaInputValue = inputValue;
-        if (Objects.nonNull(inputValue) && inputValue.contains(ToscaFunctions.GET_OPERATION_OUTPUT.getFunctionName())) {
-            Gson gson = new Gson();
-            Map<String, List<String>> consumptionValue = gson.fromJson(inputValue, Map.class);
-            List<String> mappedOutputValue =
-                    consumptionValue.get(ToscaFunctions.GET_OPERATION_OUTPUT.getFunctionName());
-            //Extract the interface name from the interface type
-            String interfaceType = mappedOutputValue.get(1);
-            String interfaceName = interfaceType.substring(interfaceType.lastIndexOf('.') + 1);
-            mappedOutputValue.remove(1);
-            mappedOutputValue.add(1, interfaceName);
-            toscaInputValue = gson.toJson(consumptionValue);
-        }
-        return toscaInputValue;
-    }
-
-    private static String getInterfaceType(Component component, String interfaceType) {
-        if (LOCAL_INTERFACE_TYPE.equals(interfaceType)) {
-            return DERIVED_FROM_BASE_DEFAULT
-                    + component.getComponentMetadataDefinition()
-                    .getMetadataDataDefinition().getSystemName();
-        }
-
-        return interfaceType;
-    }
-
-    private static Map<String, Object> getObjectAsMap(Object obj) {
-        ObjectMapper objectMapper = new ObjectMapper();
-        if (obj instanceof ToscaInterfaceDefinition) {
-            //Prevent empty field serialization in interface definition
-            objectMapper.setSerializationInclusion(JsonInclude.Include.NON_NULL);
-        }
-        Map<String, Object> objectAsMap =
-                obj instanceof Map ? (Map<String, Object>) obj : objectMapper.convertValue(obj, Map.class);
-
-        final String defaultEntry = DEFAULT.getElementName();
-        if (objectAsMap.containsKey(defaultEntry)) {
-            objectAsMap.put(DEFAULT_HAS_UNDERSCORE, objectAsMap.remove(defaultEntry));
-        }
-        return objectAsMap;
-    }
 }
index d4a3504..e6e5ccd 100644 (file)
@@ -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.
  * limitations under the License.
  * ============LICENSE_END=========================================================
  */
-
 package org.openecomp.sdc.be.tosca;
 
+import java.util.Map;
 import org.openecomp.sdc.be.model.Component;
 import org.openecomp.sdc.be.tosca.model.ToscaPolicyTemplate;
 
-import java.util.Map;
-
 public interface PolicyExportParser {
 
-       Map<String, ToscaPolicyTemplate> getPolicies(Component component);
+    Map<String, ToscaPolicyTemplate> getPolicies(Component component);
 }
index 598f73f..d544d34 100644 (file)
@@ -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.
  * limitations under the License.
  * ============LICENSE_END=========================================================
  */
-
 package org.openecomp.sdc.be.tosca;
 
+import static org.apache.commons.collections.CollectionUtils.isEmpty;
+import static org.apache.commons.collections.CollectionUtils.isNotEmpty;
+import static org.apache.commons.collections.MapUtils.isNotEmpty;
+import static org.apache.commons.lang.StringUtils.isNotEmpty;
 
 import fj.data.Either;
+import java.util.ArrayList;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+import java.util.function.Supplier;
+import java.util.stream.Collectors;
 import org.openecomp.sdc.be.components.impl.exceptions.SdcResourceNotFoundException;
 import org.openecomp.sdc.be.dao.janusgraph.JanusGraphOperationStatus;
 import org.openecomp.sdc.be.datatypes.elements.PolicyTargetType;
@@ -37,181 +46,138 @@ import org.openecomp.sdc.be.tosca.model.ToscaMetadata;
 import org.openecomp.sdc.be.tosca.model.ToscaPolicyTemplate;
 import org.openecomp.sdc.common.log.wrappers.Logger;
 import org.springframework.beans.factory.annotation.Autowired;
-
-import java.util.ArrayList;
-import java.util.HashMap;
-import java.util.List;
-import java.util.Map;
-import java.util.function.Supplier;
-import java.util.stream.Collectors;
 import org.springframework.context.event.EventListener;
 
-import static org.apache.commons.collections.CollectionUtils.isEmpty;
-import static org.apache.commons.collections.CollectionUtils.isNotEmpty;
-import static org.apache.commons.collections.MapUtils.isNotEmpty;
-import static org.apache.commons.lang.StringUtils.isNotEmpty;
-
 @org.springframework.stereotype.Component
 public class PolicyExportParserImpl implements PolicyExportParser {
 
-       private static final Logger log = Logger.getLogger(PolicyExportParserImpl.class);
-   
-       private ApplicationDataTypeCache dataTypeCache;
-       private Map<String, DataTypeDefinition> dataTypes;
-       private PropertyConvertor propertyConvertor;
-       
-       @Autowired
-       public PolicyExportParserImpl(ApplicationDataTypeCache dataTypeCache, PropertyConvertor propertyConvertor) {
-               this.dataTypeCache = dataTypeCache;
-               this.propertyConvertor = propertyConvertor;
-               this.dataTypes = getDataTypes();
-       }
-       
-       private Map<String, DataTypeDefinition> getDataTypes()  {
-               Either<Map<String, DataTypeDefinition>, JanusGraphOperationStatus> dataTypesEither = dataTypeCache.getAll();
-               if (dataTypesEither.isRight()) {
-                       log.error("Failed to retrieve all data types {}", dataTypesEither.right().value()); 
-                       throw new SdcResourceNotFoundException(); 
-               }
-               
-               return dataTypesEither.left().value();
-       }
-
-       @EventListener
-       public void onDataTypesCacheChangedEvent(
-                       ApplicationDataTypeCache.DataTypesCacheChangedEvent dataTypesCacheChangedEvent) {
-               dataTypes = dataTypesCacheChangedEvent.getNewData();
-               log.debug("Data types cache updated.");
-       }
-       
-       @Override
-       public Map<String, ToscaPolicyTemplate> getPolicies(Component component) {
-               Map<String, ToscaPolicyTemplate> toscaPolicies = null;
-               Map<String, PolicyDefinition> policies = component.getPolicies();               
-               if (isNotEmpty(policies)) {
-
-                        toscaPolicies = policies.values().stream().collect(
-                                        Collectors.toMap(
-                                                        PolicyDefinition::getName,
-                                                        policy->getToscaPolicyTemplate(policy,component)));
-                       log.debug("policies converted");
-               }       
-               return toscaPolicies;   
-       }
-       
-       private ToscaPolicyTemplate getToscaPolicyTemplate(PolicyDefinition policyDefinition,Component component) {
-               
-                String type = policyDefinition.getPolicyTypeName();
-            IToscaMetadata metadata = getToscaPolicyTemplateMetadata(policyDefinition);
-            Map<String, Object> properties = getToscaPolicyTemplateProperties(policyDefinition);
-            List<String> targets = getToscaPolicyTemplateTargets(
-                        policyDefinition,component.getComponentInstances(),component.getGroups());
-                               
-               return new ToscaPolicyTemplate(type, metadata, properties, targets);
-       }
-       
-       private List<String> getToscaPolicyTemplateTargets(PolicyDefinition policyDefinition,
-                       List<ComponentInstance> componentInstances, List<GroupDefinition> groups) {
-
-               Map<PolicyTargetType, List<String>> targets = policyDefinition.getTargets();
-               List<String> targetNames = null;
-
-               if (targets == null || targets.isEmpty()) {
-                       return null;
-               }
-
-               List<String> componentInstancesTargets = targets.get(PolicyTargetType.COMPONENT_INSTANCES);
-               List<String> groupTargets = targets.get(PolicyTargetType.GROUPS);
-               
-               if (isNotEmpty(componentInstancesTargets) && isNotEmpty(componentInstances)) {  
-                       // get target names by Id from component instances
-                       Map<String, String> targetNamesByIdFromComponentInstances = 
-                                       getTargetNamesByIdFromComponentInstances(componentInstances);
-                       targetNames = targetNamesLazyInstantiation(targetNames);
-                       addTargetNames(componentInstancesTargets, targetNames, targetNamesByIdFromComponentInstances);
-                       
-               }
-               
-               if (isNotEmpty(groupTargets) && isNotEmpty(groups)) {
-                       // get target names by id from group definitions
-                       Map<String, String> targetNamesByIdFromGroupDefinitions = getTargetNamesByIdFromGroupDefinitions(groups);
-                       targetNames = targetNamesLazyInstantiation(targetNames);
-                       addTargetNames(groupTargets, targetNames, targetNamesByIdFromGroupDefinitions);
-                       
-               }
-
-               return targetNames;
-       }
-
-       private List<String> targetNamesLazyInstantiation(List<String> targetNames) {
-               if (targetNames == null) {
-                       targetNames = new ArrayList<>();
-               }
-               return targetNames;
-       }
-
-       private void addTargetNames(List<String> targets, List<String> targetNames,
-                       Map<String, String> targetNamesById) {
-               
-               if (!targetNamesById.isEmpty()) {
-                       
-                       for (String id : targets) {
-                               String name = targetNamesById.get(id);
-                               if (name != null) {
-                                       targetNames.add(name);
-                               }
-                       }
-               }
-       }
-
-       private Map<String, String> getTargetNamesByIdFromGroupDefinitions(List<GroupDefinition> groups) {      
-               return groups.stream().collect(
-                               Collectors.toMap(GroupDefinition::getUniqueId, GroupDefinition::getName));              
-       }
-
-       private Map<String, String> getTargetNamesByIdFromComponentInstances(List<ComponentInstance> componentInstances) {
-               return componentInstances.stream().collect(
-                               Collectors.toMap(ComponentInstance::getUniqueId,ComponentInstance::getName));
-       }
-
-       private Map<String, Object> getToscaPolicyTemplateProperties(PolicyDefinition policyDefinition) {
-               
-               List<PropertyDataDefinition> tempProperties = policyDefinition.getProperties();
-               
-               if (isEmpty(tempProperties)) {
-                       return null;
-               }
-                               
-               Map<String, Object> props = new HashMap<>();
-
-               tempProperties.forEach(input -> 
-                       propertyConvertor.convertAndAddValue(dataTypes, props, input, getPropertyValue(input))
-               );
-
-               if (props.isEmpty()) {
-                       return null;
-               } else {
-                       return props;
-               }       
-       }
-
-       private Supplier<String> getPropertyValue(PropertyDataDefinition propertyDataDefinition) {
-               return () -> {
-                       if (isNotEmpty(propertyDataDefinition.getValue())) {
-                               return propertyDataDefinition.getValue();
-                       } else {
-                               return propertyDataDefinition.getDefaultValue();
-                       }
-               };
-       }
-
-       private IToscaMetadata getToscaPolicyTemplateMetadata(PolicyDefinition policyDefinition) {
-               IToscaMetadata metadata = new ToscaMetadata();
-               metadata.setInvariantUUID(policyDefinition.getInvariantUUID());
-               metadata.setUUID(policyDefinition.getPolicyUUID());
-               metadata.setName(policyDefinition.getName());
-               metadata.setVersion(policyDefinition.getVersion());
-               return metadata;
-       }
-
+    private static final Logger log = Logger.getLogger(PolicyExportParserImpl.class);
+    private ApplicationDataTypeCache dataTypeCache;
+    private Map<String, DataTypeDefinition> dataTypes;
+    private PropertyConvertor propertyConvertor;
+
+    @Autowired
+    public PolicyExportParserImpl(ApplicationDataTypeCache dataTypeCache, PropertyConvertor propertyConvertor) {
+        this.dataTypeCache = dataTypeCache;
+        this.propertyConvertor = propertyConvertor;
+        this.dataTypes = getDataTypes();
+    }
+
+    private Map<String, DataTypeDefinition> getDataTypes() {
+        Either<Map<String, DataTypeDefinition>, JanusGraphOperationStatus> dataTypesEither = dataTypeCache.getAll();
+        if (dataTypesEither.isRight()) {
+            log.error("Failed to retrieve all data types {}", dataTypesEither.right().value());
+            throw new SdcResourceNotFoundException();
+        }
+        return dataTypesEither.left().value();
+    }
+
+    @EventListener
+    public void onDataTypesCacheChangedEvent(ApplicationDataTypeCache.DataTypesCacheChangedEvent dataTypesCacheChangedEvent) {
+        dataTypes = dataTypesCacheChangedEvent.getNewData();
+        log.debug("Data types cache updated.");
+    }
+
+    @Override
+    public Map<String, ToscaPolicyTemplate> getPolicies(Component component) {
+        Map<String, ToscaPolicyTemplate> toscaPolicies = null;
+        Map<String, PolicyDefinition> policies = component.getPolicies();
+        if (isNotEmpty(policies)) {
+            toscaPolicies = policies.values().stream()
+                .collect(Collectors.toMap(PolicyDefinition::getName, policy -> getToscaPolicyTemplate(policy, component)));
+            log.debug("policies converted");
+        }
+        return toscaPolicies;
+    }
+
+    private ToscaPolicyTemplate getToscaPolicyTemplate(PolicyDefinition policyDefinition, Component component) {
+        String type = policyDefinition.getPolicyTypeName();
+        IToscaMetadata metadata = getToscaPolicyTemplateMetadata(policyDefinition);
+        Map<String, Object> properties = getToscaPolicyTemplateProperties(policyDefinition);
+        List<String> targets = getToscaPolicyTemplateTargets(policyDefinition, component.getComponentInstances(), component.getGroups());
+        return new ToscaPolicyTemplate(type, metadata, properties, targets);
+    }
+
+    private List<String> getToscaPolicyTemplateTargets(PolicyDefinition policyDefinition, List<ComponentInstance> componentInstances,
+                                                       List<GroupDefinition> groups) {
+        Map<PolicyTargetType, List<String>> targets = policyDefinition.getTargets();
+        List<String> targetNames = null;
+        if (targets == null || targets.isEmpty()) {
+            return null;
+        }
+        List<String> componentInstancesTargets = targets.get(PolicyTargetType.COMPONENT_INSTANCES);
+        List<String> groupTargets = targets.get(PolicyTargetType.GROUPS);
+        if (isNotEmpty(componentInstancesTargets) && isNotEmpty(componentInstances)) {
+            // get target names by Id from component instances
+            Map<String, String> targetNamesByIdFromComponentInstances = getTargetNamesByIdFromComponentInstances(componentInstances);
+            targetNames = targetNamesLazyInstantiation(targetNames);
+            addTargetNames(componentInstancesTargets, targetNames, targetNamesByIdFromComponentInstances);
+        }
+        if (isNotEmpty(groupTargets) && isNotEmpty(groups)) {
+            // get target names by id from group definitions
+            Map<String, String> targetNamesByIdFromGroupDefinitions = getTargetNamesByIdFromGroupDefinitions(groups);
+            targetNames = targetNamesLazyInstantiation(targetNames);
+            addTargetNames(groupTargets, targetNames, targetNamesByIdFromGroupDefinitions);
+        }
+        return targetNames;
+    }
+
+    private List<String> targetNamesLazyInstantiation(List<String> targetNames) {
+        if (targetNames == null) {
+            targetNames = new ArrayList<>();
+        }
+        return targetNames;
+    }
+
+    private void addTargetNames(List<String> targets, List<String> targetNames, Map<String, String> targetNamesById) {
+        if (!targetNamesById.isEmpty()) {
+            for (String id : targets) {
+                String name = targetNamesById.get(id);
+                if (name != null) {
+                    targetNames.add(name);
+                }
+            }
+        }
+    }
+
+    private Map<String, String> getTargetNamesByIdFromGroupDefinitions(List<GroupDefinition> groups) {
+        return groups.stream().collect(Collectors.toMap(GroupDefinition::getUniqueId, GroupDefinition::getName));
+    }
+
+    private Map<String, String> getTargetNamesByIdFromComponentInstances(List<ComponentInstance> componentInstances) {
+        return componentInstances.stream().collect(Collectors.toMap(ComponentInstance::getUniqueId, ComponentInstance::getName));
+    }
+
+    private Map<String, Object> getToscaPolicyTemplateProperties(PolicyDefinition policyDefinition) {
+        List<PropertyDataDefinition> tempProperties = policyDefinition.getProperties();
+        if (isEmpty(tempProperties)) {
+            return null;
+        }
+        Map<String, Object> props = new HashMap<>();
+        tempProperties.forEach(input -> propertyConvertor.convertAndAddValue(dataTypes, props, input, getPropertyValue(input)));
+        if (props.isEmpty()) {
+            return null;
+        } else {
+            return props;
+        }
+    }
+
+    private Supplier<String> getPropertyValue(PropertyDataDefinition propertyDataDefinition) {
+        return () -> {
+            if (isNotEmpty(propertyDataDefinition.getValue())) {
+                return propertyDataDefinition.getValue();
+            } else {
+                return propertyDataDefinition.getDefaultValue();
+            }
+        };
+    }
+
+    private IToscaMetadata getToscaPolicyTemplateMetadata(PolicyDefinition policyDefinition) {
+        IToscaMetadata metadata = new ToscaMetadata();
+        metadata.setInvariantUUID(policyDefinition.getInvariantUUID());
+        metadata.setUUID(policyDefinition.getPolicyUUID());
+        metadata.setName(policyDefinition.getName());
+        metadata.setVersion(policyDefinition.getVersion());
+        return metadata;
+    }
 }
index 59b859d..89ff754 100644 (file)
@@ -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.
@@ -17,7 +17,6 @@
  * limitations under the License.
  * ============LICENSE_END=========================================================
  */
-
 package org.openecomp.sdc.be.tosca;
 
 import com.google.gson.JsonElement;
@@ -38,41 +37,35 @@ import org.openecomp.sdc.be.model.Component;
 import org.openecomp.sdc.be.model.DataTypeDefinition;
 import org.openecomp.sdc.be.model.PropertyDefinition;
 import org.openecomp.sdc.be.model.Resource;
-import org.openecomp.sdc.tosca.datatypes.ToscaFunctions;
 import org.openecomp.sdc.be.model.tosca.ToscaPropertyType;
 import org.openecomp.sdc.be.model.tosca.converters.DataTypePropertyConverter;
 import org.openecomp.sdc.be.model.tosca.converters.ToscaMapValueConverter;
 import org.openecomp.sdc.be.model.tosca.converters.ToscaValueBaseConverter;
 import org.openecomp.sdc.be.model.tosca.converters.ToscaValueConverter;
-import org.openecomp.sdc.be.tosca.model.ToscaSchemaDefinition;
 import org.openecomp.sdc.be.tosca.model.ToscaNodeType;
 import org.openecomp.sdc.be.tosca.model.ToscaProperty;
+import org.openecomp.sdc.be.tosca.model.ToscaSchemaDefinition;
 import org.openecomp.sdc.common.log.wrappers.Logger;
+import org.openecomp.sdc.tosca.datatypes.ToscaFunctions;
 import org.springframework.stereotype.Service;
 
 @Service
 public class PropertyConvertor {
-    private JsonParser jsonParser = new JsonParser();
-    private static final Logger log = Logger.getLogger(PropertyConvertor.class);
-    public  enum PropertyType  {
-        CAPABILITY,
-        INPUT,
-        PROPERTY
-    }
-
 
-    public Either<ToscaNodeType, ToscaError> convertProperties(Component component, ToscaNodeType toscaNodeType, Map<String, DataTypeDefinition> dataTypes) {
+    private static final Logger log = Logger.getLogger(PropertyConvertor.class);
+    private JsonParser jsonParser = new JsonParser();
 
+    public Either<ToscaNodeType, ToscaError> convertProperties(Component component, ToscaNodeType toscaNodeType,
+                                                               Map<String, DataTypeDefinition> dataTypes) {
         if (component instanceof Resource) {
             Resource resource = (Resource) component;
             List<PropertyDefinition> props = resource.getProperties();
             if (props != null) {
                 Map<String, ToscaProperty> properties = new HashMap<>();
-
                 // take only the properties of this resource
                 props.stream().filter(p -> p.getOwnerId() == null || p.getOwnerId().equals(component.getUniqueId())).forEach(property -> {
                     properties.put(property.getName(), convertProperty(dataTypes, property, PropertyType.PROPERTY));
-                 });
+                });
                 if (!properties.isEmpty()) {
                     toscaNodeType.setProperties(properties);
                 }
@@ -83,7 +76,8 @@ public class PropertyConvertor {
 
     public ToscaProperty convertProperty(Map<String, DataTypeDefinition> dataTypes, PropertyDefinition property, PropertyType propertyType) {
         ToscaProperty prop = new ToscaProperty();
-        log.trace("try to convert property {} from type {} with default value [{}]", property.getName(), property.getType(), property.getDefaultValue());
+        log.trace("try to convert property {} from type {} with default value [{}]", property.getName(), property.getType(),
+            property.getDefaultValue());
         SchemaDefinition schema = property.getSchema();
         if (schema != null && schema.getProperty() != null && schema.getProperty().getType() != null && !schema.getProperty().getType().isEmpty()) {
             final ToscaSchemaDefinition toscaSchemaDefinition = new ToscaSchemaDefinition();
@@ -92,7 +86,7 @@ public class PropertyConvertor {
             prop.setEntry_schema(toscaSchemaDefinition);
         }
         String defaultValue = property.getDefaultValue();
-        if(Objects.isNull(defaultValue)) {
+        if (Objects.isNull(defaultValue)) {
             defaultValue = property.getValue();
         }
         Object convertedObj = convertToToscaObject(property, defaultValue, dataTypes, false);
@@ -102,21 +96,21 @@ public class PropertyConvertor {
         prop.setType(property.getType());
         prop.setDescription(property.getDescription());
         prop.setRequired(property.isRequired());
-        if(propertyType.equals(PropertyType.CAPABILITY)) {
+        if (propertyType.equals(PropertyType.CAPABILITY)) {
             prop.setStatus(property.getStatus());
         }
         prop.setMetadata(property.getMetadata());
         return prop;
     }
-    
 
-    public Object convertToToscaObject(PropertyDataDefinition property, String value, Map<String, DataTypeDefinition> dataTypes, boolean preserveEmptyValue) {
+    public Object convertToToscaObject(PropertyDataDefinition property, String value, Map<String, DataTypeDefinition> dataTypes,
+                                       boolean preserveEmptyValue) {
         String propertyType = property.getType();
         String innerType = property.getSchemaType();
         log.trace("try to convert propertyType {} , value [{}], innerType {}", propertyType, value, innerType);
         if (StringUtils.isEmpty(value)) {
             value = DataTypePropertyConverter.getInstance().getDataTypePropertiesDefaultValuesRec(propertyType, dataTypes);
-            if(StringUtils.isEmpty(value)){
+            if (StringUtils.isEmpty(value)) {
                 return null;
             }
         }
@@ -124,7 +118,6 @@ public class PropertyConvertor {
             ToscaMapValueConverter mapConverterInst = ToscaMapValueConverter.getInstance();
             ToscaValueConverter innerConverter = null;
             boolean isScalar = true;
-
             ToscaPropertyType type = ToscaPropertyType.isValidType(propertyType);
             if (type == null) {
                 log.trace("isn't prederfined type, get from all data types");
@@ -132,7 +125,6 @@ public class PropertyConvertor {
                 if (innerType == null) {
                     innerType = propertyType;
                 }
-
                 if ((type = mapConverterInst.isScalarType(dataTypeDefinition)) != null) {
                     log.trace("This is scalar type. get suitable converter for type {}", type);
                     innerConverter = type.getValueConverter();
@@ -144,24 +136,19 @@ public class PropertyConvertor {
                 if (typeIfScalar == null) {
                     isScalar = false;
                 }
-
                 innerConverter = type.getValueConverter();
                 if (ToscaPropertyType.STRING == type && valueStartsWithNonJsonChar(value)) {
                     return innerConverter.convertToToscaValue(value, innerType, dataTypes);
                 }
             }
             JsonElement jsonElement = null;
-
             StringReader reader = new StringReader(value);
             JsonReader jsonReader = new JsonReader(reader);
             jsonReader.setLenient(true);
-
             jsonElement = jsonParser.parse(jsonReader);
-
             if (value.equals("")) {
                 return value;
             }
-
             if (jsonElement.isJsonPrimitive() && isScalar) {
                 log.trace("It's well defined type. convert it");
                 ToscaValueConverter converter = type.getValueConverter();
@@ -178,7 +165,7 @@ public class PropertyConvertor {
                 }
             }
             Object convertedValue;
-                if (innerConverter != null && (ToscaPropertyType.MAP == type || ToscaPropertyType.LIST == type)) {
+            if (innerConverter != null && (ToscaPropertyType.MAP == type || ToscaPropertyType.LIST == type)) {
                 convertedValue = innerConverter.convertToToscaValue(value, innerType, dataTypes);
             } else if (isScalar) {
                 // complex json for scalar type
@@ -186,33 +173,31 @@ public class PropertyConvertor {
             } else if (innerConverter != null) {
                 convertedValue = innerConverter.convertToToscaValue(value, innerType, dataTypes);
             } else {
-                convertedValue = mapConverterInst.convertDataTypeToToscaObject(
-                    innerType, dataTypes, innerConverter, isScalar, jsonElement, preserveEmptyValue);
+                convertedValue = mapConverterInst
+                    .convertDataTypeToToscaObject(innerType, dataTypes, innerConverter, isScalar, jsonElement, preserveEmptyValue);
             }
-
             return convertedValue;
-
         } catch (Exception e) {
             log.debug("convertToToscaValue failed to parse json value :", e);
             return null;
         }
-
     }
 
     private boolean valueStartsWithNonJsonChar(String value) {
         return value.startsWith("/") || value.startsWith(":");
     }
 
-    public void convertAndAddValue(Map<String, DataTypeDefinition> dataTypes,
-            Map<String, Object> props, PropertyDataDefinition prop, Supplier<String> supplier) {
+    public void convertAndAddValue(Map<String, DataTypeDefinition> dataTypes, Map<String, Object> props, PropertyDataDefinition prop,
+                                   Supplier<String> supplier) {
         Object convertedValue = convertValue(dataTypes, prop, supplier);
         if (!ToscaValueBaseConverter.isEmptyObjectValue(convertedValue)) {
             props.put(prop.getName(), convertedValue);
         }
     }
 
-    private <T extends PropertyDataDefinition> Object convertValue(Map<String, DataTypeDefinition> dataTypes,
-             T input, Supplier<String> supplier) {
+    private <T extends PropertyDataDefinition> Object convertValue(Map<String, DataTypeDefinition> dataTypes, T input, Supplier<String> supplier) {
         return convertToToscaObject(input, supplier.get(), dataTypes, false);
     }
+
+    public enum PropertyType {CAPABILITY, INPUT, PROPERTY}
 }
index c3acb43..af0fc06 100644 (file)
@@ -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.
  * limitations under the License.
  * ============LICENSE_END=========================================================
  */
-
 package org.openecomp.sdc.be.tosca;
 
 public enum ToscaError {
-
     NODE_TYPE_CAPABILITY_ERROR, NOT_SUPPORTED_TOSCA_TYPE, NODE_TYPE_REQUIREMENT_ERROR, GENERAL_ERROR
 }
index 9664ccd..988f709 100644 (file)
@@ -17,7 +17,6 @@
  * limitations under the License.
  * ============LICENSE_END=========================================================
  */
-
 package org.openecomp.sdc.be.tosca;
 
 import static org.apache.commons.collections.CollectionUtils.isNotEmpty;
@@ -142,9 +141,17 @@ import org.yaml.snakeyaml.representer.Representer;
 @org.springframework.stereotype.Component("tosca-export-handler")
 public class ToscaExportHandler {
 
+    public static final String ASSET_TOSCA_TEMPLATE = "assettoscatemplate";
     private static final Logger log = Logger.getLogger(ToscaExportHandler.class);
     private static final String INVARIANT_UUID = "invariantUUID";
-
+    private static final String TOSCA_VERSION = "tosca_simple_yaml_1_3";
+    private static final String SERVICE_NODE_TYPE_PREFIX = "org.openecomp.service.";
+    private static final String IMPORTS_FILE_KEY = "file";
+    private static final String TOSCA_INTERFACE_NAME = "-interface.yml";
+    private static final String FAILED_TO_GET_DEFAULT_IMPORTS_CONFIGURATION = "convertToToscaTemplate - failed to get Default Imports section from configuration";
+    private static final String NOT_SUPPORTED_COMPONENT_TYPE = "Not supported component type {}";
+    private static final String NATIVE_ROOT = "tosca.nodes.Root";
+    private static final YamlUtil yamlUtil = new YamlUtil();
     private ApplicationDataTypeCache dataTypeCache;
     private ToscaOperationFacade toscaOperationFacade;
     private CapabilityRequirementConverter capabilityRequirementConverter;
@@ -157,14 +164,10 @@ public class ToscaExportHandler {
     private InterfacesOperationsConverter interfacesOperationsConverter;
 
     @Autowired
-    public ToscaExportHandler(final ApplicationDataTypeCache dataTypeCache,
-                              final ToscaOperationFacade toscaOperationFacade,
-                              final CapabilityRequirementConverter capabilityRequirementConverter,
-                              final PolicyExportParser policyExportParser,
-                              final GroupExportParser groupExportParser,
-                              final PropertyConvertor propertyConvertor,
-                              final InputConverter inputConverter,
-                              final OutputConverter outputConverter,
+    public ToscaExportHandler(final ApplicationDataTypeCache dataTypeCache, final ToscaOperationFacade toscaOperationFacade,
+                              final CapabilityRequirementConverter capabilityRequirementConverter, final PolicyExportParser policyExportParser,
+                              final GroupExportParser groupExportParser, final PropertyConvertor propertyConvertor,
+                              final InputConverter inputConverter, final OutputConverter outputConverter,
                               final InterfaceLifecycleOperation interfaceLifecycleOperation,
                               final InterfacesOperationsConverter interfacesOperationsConverter) {
         this.dataTypeCache = dataTypeCache;
@@ -179,28 +182,28 @@ public class ToscaExportHandler {
         this.interfacesOperationsConverter = interfacesOperationsConverter;
     }
 
-    private static final String TOSCA_VERSION = "tosca_simple_yaml_1_3";
-    private static final String SERVICE_NODE_TYPE_PREFIX = "org.openecomp.service.";
-    private static final String IMPORTS_FILE_KEY = "file";
-    private static final String TOSCA_INTERFACE_NAME = "-interface.yml";
-    public static final String ASSET_TOSCA_TEMPLATE = "assettoscatemplate";
-    private static final String FAILED_TO_GET_DEFAULT_IMPORTS_CONFIGURATION = "convertToToscaTemplate - failed to get Default Imports section from configuration";
-    private static final String NOT_SUPPORTED_COMPONENT_TYPE = "Not supported component type {}";
-    private static final String NATIVE_ROOT = "tosca.nodes.Root";
-    private static final YamlUtil yamlUtil = new YamlUtil();
+    public static String getInterfaceFilename(String artifactName) {
+        return artifactName.substring(0, artifactName.lastIndexOf('.')) + ToscaExportHandler.TOSCA_INTERFACE_NAME;
+    }
+
+    private static void removeOperationImplementationForProxyNodeType(Map<String, InterfaceDefinition> proxyComponentInterfaces) {
+        if (MapUtils.isEmpty(proxyComponentInterfaces)) {
+            return;
+        }
+        proxyComponentInterfaces.values().stream().map(InterfaceDataDefinition::getOperations).filter(MapUtils::isNotEmpty)
+            .forEach(operations -> operations.values().forEach(operation -> operation.setImplementation(null)));
+    }
 
     public Either<ToscaRepresentation, ToscaError> exportComponent(Component component) {
         return convertToToscaTemplate(component).left().map(this::createToscaRepresentation);
     }
 
-    public Either<ToscaRepresentation, ToscaError> exportComponentInterface(final Component component,
-                                                                            final boolean isAssociatedComponent) {
+    public Either<ToscaRepresentation, ToscaError> exportComponentInterface(final Component component, final boolean isAssociatedComponent) {
         final List<Map<String, Map<String, String>>> defaultToscaImportConfig = getDefaultToscaImportConfig();
         if (CollectionUtils.isEmpty(defaultToscaImportConfig)) {
             log.debug(FAILED_TO_GET_DEFAULT_IMPORTS_CONFIGURATION);
             return Either.right(ToscaError.GENERAL_ERROR);
         }
-
         String toscaVersion = null;
         if (component instanceof Resource) {
             toscaVersion = ((Resource) component).getToscaVersion();
@@ -208,12 +211,11 @@ public class ToscaExportHandler {
         ToscaTemplate toscaTemplate = new ToscaTemplate(toscaVersion != null ? toscaVersion : TOSCA_VERSION);
         toscaTemplate.setImports(new ArrayList<>(defaultToscaImportConfig));
         final Map<String, ToscaNodeType> nodeTypes = new HashMap<>();
-        final Either<ToscaTemplate, ToscaError> toscaTemplateRes =
-            convertInterfaceNodeType(new HashMap<>(), component, toscaTemplate, nodeTypes, isAssociatedComponent);
+        final Either<ToscaTemplate, ToscaError> toscaTemplateRes = convertInterfaceNodeType(new HashMap<>(), component, toscaTemplate, nodeTypes,
+            isAssociatedComponent);
         if (toscaTemplateRes.isRight()) {
             return Either.right(toscaTemplateRes.right().value());
         }
-
         toscaTemplate = toscaTemplateRes.left().value();
         ToscaRepresentation toscaRepresentation = this.createToscaRepresentation(toscaTemplate);
         return Either.left(toscaRepresentation);
@@ -224,29 +226,22 @@ public class ToscaExportHandler {
         DumperOptions options = new DumperOptions();
         options.setAllowReadOnlyProperties(false);
         options.setPrettyFlow(true);
-
         options.setDefaultFlowStyle(FlowStyle.FLOW);
         options.setCanonical(false);
-
         representer.addClassTag(toscaTemplate.getClass(), Tag.MAP);
-
         representer.setPropertyUtils(new UnsortedPropertyUtils());
         Yaml yaml = new Yaml(representer, options);
-
         String yamlAsString = yaml.dumpAsMap(toscaTemplate);
-
         StringBuilder sb = new StringBuilder();
         sb.append(ConfigurationManager.getConfigurationManager().getConfiguration().getHeatEnvArtifactHeader());
         sb.append(yamlAsString);
         sb.append(ConfigurationManager.getConfigurationManager().getConfiguration().getHeatEnvArtifactFooter());
-
         return ToscaRepresentation.make(sb.toString().getBytes(), toscaTemplate);
     }
 
     public Either<ToscaTemplate, ToscaError> getDependencies(Component component) {
         ToscaTemplate toscaTemplate = new ToscaTemplate(null);
-        Either<ImmutablePair<ToscaTemplate, Map<String, Component>>, ToscaError> fillImports = fillImports(component,
-            toscaTemplate);
+        Either<ImmutablePair<ToscaTemplate, Map<String, Component>>, ToscaError> fillImports = fillImports(component, toscaTemplate);
         if (fillImports.isRight()) {
             return Either.right(fillImports.right().value());
         }
@@ -275,43 +270,34 @@ public class ToscaExportHandler {
             log.trace("convert component as topology template");
             return convertToscaTemplate(component, toscaTemplate);
         }
-
     }
 
     private Either<ToscaTemplate, ToscaError> convertToscaTemplate(Component component, ToscaTemplate toscaNode) {
-
-        Either<ImmutablePair<ToscaTemplate, Map<String, Component>>, ToscaError> importsRes = fillImports(component,
-            toscaNode);
+        Either<ImmutablePair<ToscaTemplate, Map<String, Component>>, ToscaError> importsRes = fillImports(component, toscaNode);
         if (importsRes.isRight()) {
             return Either.right(importsRes.right().value());
         }
         toscaNode = importsRes.left().value().left;
         Map<String, Component> componentCache = importsRes.left().value().right;
-        Either<Map<String, ToscaNodeType>, ToscaError> nodeTypesMapEither = createProxyNodeTypes(componentCache,
-            component);
+        Either<Map<String, ToscaNodeType>, ToscaError> nodeTypesMapEither = createProxyNodeTypes(componentCache, component);
         if (nodeTypesMapEither.isRight()) {
-            log.debug("Failed to fetch normative service proxy resource by tosca name, error {}",
-                nodeTypesMapEither.right().value());
+            log.debug("Failed to fetch normative service proxy resource by tosca name, error {}", nodeTypesMapEither.right().value());
             return Either.right(nodeTypesMapEither.right().value());
         }
         Map<String, ToscaNodeType> nodeTypesMap = nodeTypesMapEither.left().value();
         if (nodeTypesMap != null && !nodeTypesMap.isEmpty()) {
             toscaNode.setNode_types(nodeTypesMap);
         }
-
         createServiceSubstitutionNodeTypes(componentCache, component, toscaNode);
-
         Either<Map<String, Object>, ToscaError> proxyInterfaceTypesEither = createProxyInterfaceTypes(component);
         if (proxyInterfaceTypesEither.isRight()) {
-            log.debug("Failed to populate service proxy local interface types in tosca, error {}",
-                nodeTypesMapEither.right().value());
+            log.debug("Failed to populate service proxy local interface types in tosca, error {}", nodeTypesMapEither.right().value());
             return Either.right(proxyInterfaceTypesEither.right().value());
         }
         Map<String, Object> proxyInterfaceTypes = proxyInterfaceTypesEither.left().value();
         if (MapUtils.isNotEmpty(proxyInterfaceTypes)) {
             toscaNode.setInterface_types(proxyInterfaceTypes);
         }
-
         Either<Map<String, DataTypeDefinition>, JanusGraphOperationStatus> dataTypesEither = dataTypeCache.getAll();
         if (dataTypesEither.isRight()) {
             log.debug("Failed to retrieve all data types {}", dataTypesEither.right().value());
@@ -321,24 +307,20 @@ public class ToscaExportHandler {
         ToscaTopolgyTemplate topologyTemplate = new ToscaTopolgyTemplate();
         List<InputDefinition> inputDef = component.getInputs();
         Map<String, ToscaProperty> inputs = inputConverter.convertInputs(inputDef, dataTypes);
-
         if (!inputs.isEmpty()) {
             topologyTemplate.setInputs(inputs);
         }
-
         final Map<String, ToscaProperty> outputs;
         try {
             outputs = outputConverter.convert(component.getOutputs(), dataTypes);
         } catch (final ToscaConversionException e) {
             log.error(EcompLoggerErrorCode.SCHEMA_ERROR, ToscaExportHandler.class.getName(),
-                "Could not parse component '{}' outputs. Component unique id '{}'.",
-                new Object[]{component.getName(), component.getUniqueId(), e});
+                "Could not parse component '{}' outputs. Component unique id '{}'.", new Object[]{component.getName(), component.getUniqueId(), e});
             return Either.right(ToscaError.GENERAL_ERROR);
         }
         if (!outputs.isEmpty()) {
             topologyTemplate.setOutputs(outputs);
         }
-
         final List<ComponentInstance> componentInstances = component.getComponentInstances();
         Map<String, List<ComponentInstanceProperty>> componentInstancesProperties = component.getComponentInstancesProperties();
         Map<String, List<ComponentInstanceInterface>> componentInstanceInterfaces = component.getComponentInstancesInterfaces();
@@ -351,46 +333,39 @@ public class ToscaExportHandler {
             log.debug("node templates converted");
             topologyTemplate.setNode_templates(nodeTemplates.left().value());
         }
-        final Map<String, ToscaRelationshipTemplate> relationshipTemplatesMap =
-            new ToscaExportRelationshipTemplatesHandler().createFrom(topologyTemplate.getNode_templates());
+        final Map<String, ToscaRelationshipTemplate> relationshipTemplatesMap = new ToscaExportRelationshipTemplatesHandler()
+            .createFrom(topologyTemplate.getNode_templates());
         if (!relationshipTemplatesMap.isEmpty()) {
             topologyTemplate.setRelationshipTemplates(relationshipTemplatesMap);
         }
-
         SubstitutionMapping substitutionMapping = new SubstitutionMapping();
         convertSubstitutionMappingFilter(component, substitutionMapping);
-
         addGroupsToTopologyTemplate(component, topologyTemplate);
-
         try {
             addPoliciesToTopologyTemplate(component, topologyTemplate);
         } catch (SdcResourceNotFoundException e) {
             log.debug("Fail to add policies to topology template:", e);
             return Either.right(ToscaError.GENERAL_ERROR);
         }
-
         String toscaResourceName;
         switch (component.getComponentType()) {
             case RESOURCE:
-                toscaResourceName = ((ResourceMetadataDataDefinition) component.getComponentMetadataDefinition()
-                    .getMetadataDataDefinition()).getToscaResourceName();
+                toscaResourceName = ((ResourceMetadataDataDefinition) component.getComponentMetadataDefinition().getMetadataDataDefinition())
+                    .getToscaResourceName();
                 break;
             case SERVICE:
-                toscaResourceName = SERVICE_NODE_TYPE_PREFIX
-                    + component.getComponentMetadataDefinition().getMetadataDataDefinition().getSystemName();
+                toscaResourceName = SERVICE_NODE_TYPE_PREFIX + component.getComponentMetadataDefinition().getMetadataDataDefinition().getSystemName();
                 break;
             default:
                 log.debug(NOT_SUPPORTED_COMPONENT_TYPE, component.getComponentType());
                 return Either.right(ToscaError.NOT_SUPPORTED_TOSCA_TYPE);
         }
         substitutionMapping.setNode_type(toscaResourceName);
-        Either<SubstitutionMapping, ToscaError> capabilities = convertCapabilities(component, substitutionMapping,
-            componentCache);
+        Either<SubstitutionMapping, ToscaError> capabilities = convertCapabilities(component, substitutionMapping, componentCache);
         if (capabilities.isRight()) {
             return Either.right(capabilities.right().value());
         }
         substitutionMapping = capabilities.left().value();
-
         Either<SubstitutionMapping, ToscaError> requirements = capabilityRequirementConverter
             .convertSubstitutionMappingRequirements(componentCache, component, substitutionMapping);
         if (requirements.isRight()) {
@@ -401,25 +376,18 @@ public class ToscaExportHandler {
         if (!propertyMappingMap.isEmpty()) {
             substitutionMapping.setProperties(propertyMappingMap);
         }
-
         final Map<String, String[]> attributesMappingMap = buildSubstitutionMappingAttributesMapping(component);
         if (!attributesMappingMap.isEmpty()) {
             substitutionMapping.setAttributes(attributesMappingMap);
         }
-
         topologyTemplate.setSubstitution_mappings(substitutionMapping);
-
         toscaNode.setTopology_template(topologyTemplate);
-
         return Either.left(toscaNode);
     }
 
-    private void convertSubstitutionMappingFilter(final Component component,
-                                                  final SubstitutionMapping substitutionMapping) {
-        if (component.getSubstitutionFilter() != null
-            && (component.getSubstitutionFilter().getProperties()).getListToscaDataDefinition() != null) {
-            substitutionMapping
-                .setSubstitution_filter(convertToSubstitutionFilterComponent(component.getSubstitutionFilter()));
+    private void convertSubstitutionMappingFilter(final Component component, final SubstitutionMapping substitutionMapping) {
+        if (component.getSubstitutionFilter() != null && (component.getSubstitutionFilter().getProperties()).getListToscaDataDefinition() != null) {
+            substitutionMapping.setSubstitution_filter(convertToSubstitutionFilterComponent(component.getSubstitutionFilter()));
         }
     }
 
@@ -430,8 +398,7 @@ public class ToscaExportHandler {
         }
     }
 
-    private void addPoliciesToTopologyTemplate(Component component, ToscaTopolgyTemplate topologyTemplate)
-        throws SdcResourceNotFoundException {
+    private void addPoliciesToTopologyTemplate(Component component, ToscaTopolgyTemplate topologyTemplate) throws SdcResourceNotFoundException {
         Map<String, ToscaPolicyTemplate> policies = policyExportParser.getPolicies(component);
         if (policies != null) {
             topologyTemplate.addPolicies(policies);
@@ -442,24 +409,20 @@ public class ToscaExportHandler {
         return convertMetadata(component, false, null);
     }
 
-    private Map<String, String> convertMetadata(Component component, boolean isInstance,
-                                                ComponentInstance componentInstance) {
+    private Map<String, String> convertMetadata(Component component, boolean isInstance, ComponentInstance componentInstance) {
         Map<String, String> toscaMetadata = new LinkedHashMap<>();
         toscaMetadata.put(convertMetadataKey(JsonPresentationFields.INVARIANT_UUID), component.getInvariantUUID());
         toscaMetadata.put(JsonPresentationFields.UUID.getPresentation(), component.getUUID());
         toscaMetadata
             .put(JsonPresentationFields.NAME.getPresentation(), component.getComponentMetadataDefinition().getMetadataDataDefinition().getName());
         toscaMetadata.put(JsonPresentationFields.DESCRIPTION.getPresentation(), component.getDescription());
-
         List<CategoryDefinition> categories = component.getCategories();
         CategoryDefinition categoryDefinition = categories.get(0);
         toscaMetadata.put(JsonPresentationFields.CATEGORY.getPresentation(), categoryDefinition.getName());
-
         if (isInstance) {
             toscaMetadata.put(JsonPresentationFields.VERSION.getPresentation(), component.getVersion());
             toscaMetadata.put(JsonPresentationFields.CUSTOMIZATION_UUID.getPresentation(), componentInstance.getCustomizationUUID());
-            if (componentInstance.getSourceModelInvariant() != null
-                && !componentInstance.getSourceModelInvariant().isEmpty()) {
+            if (componentInstance.getSourceModelInvariant() != null && !componentInstance.getSourceModelInvariant().isEmpty()) {
                 toscaMetadata.put(JsonPresentationFields.VERSION.getPresentation(), componentInstance.getComponentVersion());
                 toscaMetadata.put(JsonPresentationFields.CI_SOURCE_MODEL_INVARIANT.getPresentation(), componentInstance.getSourceModelInvariant());
                 toscaMetadata.put(JsonPresentationFields.CI_SOURCE_MODEL_UUID.getPresentation(), componentInstance.getSourceModelUuid());
@@ -469,17 +432,14 @@ public class ToscaExportHandler {
                         componentInstance.getSourceModelName() + " " + OriginTypeEnum.ServiceProxy.getDisplayValue());
                 } else if (componentInstance.getOriginType() == OriginTypeEnum.ServiceSubstitution) {
                     toscaMetadata.put(JsonPresentationFields.NAME.getPresentation(),
-                        componentInstance.getSourceModelName() + " " + OriginTypeEnum.ServiceSubstitution
-                            .getDisplayValue());
+                        componentInstance.getSourceModelName() + " " + OriginTypeEnum.ServiceSubstitution.getDisplayValue());
                 }
                 toscaMetadata.put(JsonPresentationFields.DESCRIPTION.getPresentation(), componentInstance.getDescription());
             }
-
         }
         switch (component.getComponentType()) {
             case RESOURCE:
                 Resource resource = (Resource) component;
-
                 if (isInstance && (componentInstance.getOriginType() == OriginTypeEnum.ServiceProxy
                     || componentInstance.getOriginType() == OriginTypeEnum.ServiceSubstitution)) {
                     toscaMetadata.put(JsonPresentationFields.TYPE.getPresentation(), componentInstance.getOriginType().getDisplayValue());
@@ -510,13 +470,12 @@ public class ToscaExportHandler {
             default:
                 log.debug(NOT_SUPPORTED_COMPONENT_TYPE, component.getComponentType());
         }
-
         for (final String key : component.getCategorySpecificMetadata().keySet()) {
             toscaMetadata.put(key, component.getCategorySpecificMetadata().get(key));
         }
         return toscaMetadata;
     }
-    
+
     private String convertMetadataKey(JsonPresentationFields jsonPresentationField) {
         if (JsonPresentationFields.INVARIANT_UUID.equals(jsonPresentationField)) {
             return INVARIANT_UUID;
@@ -524,23 +483,17 @@ public class ToscaExportHandler {
         return jsonPresentationField.getPresentation();
     }
 
-    private Either<ImmutablePair<ToscaTemplate, Map<String, Component>>, ToscaError> fillImports(Component component,
-                                                                                                 ToscaTemplate toscaTemplate) {
-
+    private Either<ImmutablePair<ToscaTemplate, Map<String, Component>>, ToscaError> fillImports(Component component, ToscaTemplate toscaTemplate) {
         final List<Map<String, Map<String, String>>> defaultToscaImportConfig = getDefaultToscaImportConfig();
         if (CollectionUtils.isEmpty(defaultToscaImportConfig)) {
             log.debug(FAILED_TO_GET_DEFAULT_IMPORTS_CONFIGURATION);
             return Either.right(ToscaError.GENERAL_ERROR);
         }
         Map<String, Component> componentCache = new HashMap<>();
-
         if (!ModelConverter.isAtomicComponent(component)) {
             final List<Map<String, Map<String, String>>> additionalImports =
-                toscaTemplate.getImports() == null ? new ArrayList<>(defaultToscaImportConfig)
-                    : new ArrayList<>(toscaTemplate.getImports());
-
+                toscaTemplate.getImports() == null ? new ArrayList<>(defaultToscaImportConfig) : new ArrayList<>(toscaTemplate.getImports());
             List<Triple<String, String, Component>> dependecies = new ArrayList<>();
-
             Map<String, ArtifactDefinition> toscaArtifacts = component.getToscaArtifacts();
             if (isNotEmpty(toscaArtifacts)) {
                 ArtifactDefinition artifactDefinition = toscaArtifacts.get(ToscaExportHandler.ASSET_TOSCA_TEMPLATE);
@@ -549,8 +502,8 @@ public class ToscaExportHandler {
                     Map<String, String> interfaceFiles = new HashMap<>();
                     interfaceFiles.put(IMPORTS_FILE_KEY, getInterfaceFilename(artifactDefinition.getArtifactName()));
                     StringBuilder keyNameBuilder = new StringBuilder();
-                    keyNameBuilder.append(component.getComponentType().toString().toLowerCase()).append("-")
-                        .append(component.getName()).append("-interface");
+                    keyNameBuilder.append(component.getComponentType().toString().toLowerCase()).append("-").append(component.getName())
+                        .append("-interface");
                     importsListMember.put(keyNameBuilder.toString(), interfaceFiles);
                     additionalImports.add(importsListMember);
                 }
@@ -571,16 +524,13 @@ public class ToscaExportHandler {
         return ConfigurationManager.getConfigurationManager().getConfiguration().getDefaultImports();
     }
 
-    private void createDependency(final Map<String, Component> componentCache,
-                                  final List<Map<String, Map<String, String>>> imports,
-                                  final List<Triple<String, String, Component>> dependencies,
-                                  final ComponentInstance componentInstance) {
+    private void createDependency(final Map<String, Component> componentCache, final List<Map<String, Map<String, String>>> imports,
+                                  final List<Triple<String, String, Component>> dependencies, final ComponentInstance componentInstance) {
         log.debug("createDependency componentCache {}", componentCache);
         Component componentRI = componentCache.get(componentInstance.getComponentUid());
         if (componentRI == null || componentInstance.getOriginType() == OriginTypeEnum.ServiceSubstitution) {
             // all resource must be only once!
-            final Either<Component, StorageOperationStatus> resource = toscaOperationFacade
-                .getToscaFullElement(componentInstance.getComponentUid());
+            final Either<Component, StorageOperationStatus> resource = toscaOperationFacade.getToscaFullElement(componentInstance.getComponentUid());
             if ((resource.isRight()) && (log.isDebugEnabled())) {
                 log.debug("Failed to fetch resource with id {} for instance {}", componentInstance.getComponentUid(),
                     componentInstance.getUniqueId());
@@ -595,17 +545,16 @@ public class ToscaExportHandler {
     /**
      * Sets a componentCache from the given component/resource.
      */
-    private Component setComponentCache(final Map<String, Component> componentCache,
-                                   final ComponentInstance componentInstance,
-                                   final Component fetchedComponent) {
+    private Component setComponentCache(final Map<String, Component> componentCache, final ComponentInstance componentInstance,
+                                        final Component fetchedComponent) {
         componentCache.put(fetchedComponent.getUniqueId(), fetchedComponent);
         if (componentInstance.getOriginType() == OriginTypeEnum.ServiceProxy
             || componentInstance.getOriginType() == OriginTypeEnum.ServiceSubstitution) {
             final Either<Component, StorageOperationStatus> sourceService = toscaOperationFacade
                 .getToscaFullElement(componentInstance.getSourceModelUid());
             if (sourceService.isRight() && (log.isDebugEnabled())) {
-                log.debug("Failed to fetch source service with id {} for proxy {}",
-                    componentInstance.getSourceModelUid(), componentInstance.getUniqueId());
+                log.debug("Failed to fetch source service with id {} for proxy {}", componentInstance.getSourceModelUid(),
+                    componentInstance.getUniqueId());
             }
             final Component fetchedSource = sourceService.left().value();
             componentCache.put(fetchedSource.getUniqueId(), fetchedSource);
@@ -617,21 +566,17 @@ public class ToscaExportHandler {
     /**
      * Retrieves all derived_from nodes and stores it in a predictable order.
      */
-    private void addDependencies(final List<Map<String, Map<String, String>>> imports,
-                                 final List<Triple<String, String, Component>> dependencies,
+    private void addDependencies(final List<Map<String, Map<String, String>>> imports, final List<Triple<String, String, Component>> dependencies,
                                  final Component fetchedComponent) {
         final Set<Component> componentsList = new LinkedHashSet<>();
         if (fetchedComponent instanceof Resource) {
             log.debug("fetchedComponent is a resource {}", fetchedComponent);
-
-            final Optional<Map<String, String>> derivedFromMapOfIdToName = getDerivedFromMapOfIdToName(fetchedComponent,
-                componentsList);
+            final Optional<Map<String, String>> derivedFromMapOfIdToName = getDerivedFromMapOfIdToName(fetchedComponent, componentsList);
             if (derivedFromMapOfIdToName.isPresent() && !derivedFromMapOfIdToName.get().isEmpty()) {
                 derivedFromMapOfIdToName.get().entrySet().forEach(entry -> {
                     log.debug("Started entry.getValue() : {}", entry.getValue());
                     if (!NATIVE_ROOT.equals(entry.getValue())) {
-                        Either<Resource, StorageOperationStatus> resourcefetched = toscaOperationFacade
-                            .getToscaElement(entry.getKey());
+                        Either<Resource, StorageOperationStatus> resourcefetched = toscaOperationFacade.getToscaElement(entry.getKey());
                         if (resourcefetched != null && resourcefetched.isLeft()) {
                             componentsList.add(resourcefetched.left().value());
                         }
@@ -641,15 +586,13 @@ public class ToscaExportHandler {
             } else {
                 setImports(imports, dependencies, fetchedComponent);
             }
-
         }
     }
 
     /**
      * Returns all derived_from nodes found.
      */
-    private Optional<Map<String, String>> getDerivedFromMapOfIdToName(final Component fetchedComponent,
-                                                                      final Set<Component> componentsList) {
+    private Optional<Map<String, String>> getDerivedFromMapOfIdToName(final Component fetchedComponent, final Set<Component> componentsList) {
         final Resource parentResource = (Resource) fetchedComponent;
         Map<String, String> derivedFromMapOfIdToName = new HashMap<>();
         if (CollectionUtils.isNotEmpty(parentResource.getComponentInstances())) {
@@ -658,8 +601,7 @@ public class ToscaExportHandler {
                 final Either<Resource, StorageOperationStatus> resourcefetched = toscaOperationFacade
                     .getToscaElement(componentInstance.getComponentUid());
                 if (resourcefetched != null && resourcefetched.isLeft()) {
-                    final Map<String, String> derivedWithId = resourcefetched.left().value()
-                        .getDerivedFromMapOfIdToName();
+                    final Map<String, String> derivedWithId = resourcefetched.left().value().getDerivedFromMapOfIdToName();
                     if (MapUtils.isNotEmpty(derivedWithId)) {
                         derivedFromMapOfIdToName.putAll(derivedWithId);
                     }
@@ -675,14 +617,12 @@ public class ToscaExportHandler {
     /**
      * Creates a resource map and adds it to the import list.
      */
-    private void setImports(final List<Map<String, Map<String, String>>> imports,
-                            final List<Triple<String, String, Component>> dependencies,
+    private void setImports(final List<Map<String, Map<String, String>>> imports, final List<Triple<String, String, Component>> dependencies,
                             final Set<Component> componentsList) {
         componentsList.forEach(component -> setImports(imports, dependencies, component));
     }
 
-    private void setImports(final List<Map<String, Map<String, String>>> imports,
-                            final List<Triple<String, String, Component>> dependencies,
+    private void setImports(final List<Map<String, Map<String, String>>> imports, final List<Triple<String, String, Component>> dependencies,
                             final Component component) {
         final Map<String, ArtifactDefinition> toscaArtifacts = component.getToscaArtifacts();
         final ArtifactDefinition artifactDefinition = toscaArtifacts.get(ASSET_TOSCA_TEMPLATE);
@@ -695,9 +635,7 @@ public class ToscaExportHandler {
             keyNameBuilder.append("-");
             keyNameBuilder.append(component.getName());
             addImports(imports, keyNameBuilder, files);
-            dependencies
-                    .add(new ImmutableTriple<>(artifactName, artifactDefinition.getEsId(), component));
-
+            dependencies.add(new ImmutableTriple<>(artifactName, artifactDefinition.getEsId(), component));
             if (!ModelConverter.isAtomicComponent(component)) {
                 final Map<String, String> interfaceFiles = new HashMap<>();
                 interfaceFiles.put(IMPORTS_FILE_KEY, getInterfaceFilename(artifactName));
@@ -710,8 +648,7 @@ public class ToscaExportHandler {
     /**
      * Adds the found resource to the import definition list.
      */
-    private void addImports(final List<Map<String, Map<String, String>>> imports,
-                            final StringBuilder keyNameBuilder,
+    private void addImports(final List<Map<String, Map<String, String>>> imports, final StringBuilder keyNameBuilder,
                             final Map<String, String> files) {
         final String mapKey = keyNameBuilder.toString();
         if (imports.stream().allMatch(stringMapMap -> stringMapMap.get(mapKey) == null)) {
@@ -721,50 +658,35 @@ public class ToscaExportHandler {
         }
     }
 
-    public static String getInterfaceFilename(String artifactName) {
-        return artifactName.substring(0, artifactName.lastIndexOf('.')) + ToscaExportHandler.TOSCA_INTERFACE_NAME;
-    }
-
-    private Either<ToscaTemplate, ToscaError> convertNodeType(Map<String, Component> componentsCache,
-                                                              Component component, ToscaTemplate toscaNode,
+    private Either<ToscaTemplate, ToscaError> convertNodeType(Map<String, Component> componentsCache, Component component, ToscaTemplate toscaNode,
                                                               Map<String, ToscaNodeType> nodeTypes) {
         return convertInterfaceNodeType(componentsCache, component, toscaNode, nodeTypes, false);
     }
 
-    public Either<ToscaTemplate, ToscaError> convertInterfaceNodeType(Map<String, Component> componentsCache,
-                                                                      Component component, ToscaTemplate toscaNode,
-                                                                      Map<String, ToscaNodeType> nodeTypes,
+    public Either<ToscaTemplate, ToscaError> convertInterfaceNodeType(Map<String, Component> componentsCache, Component component,
+                                                                      ToscaTemplate toscaNode, Map<String, ToscaNodeType> nodeTypes,
                                                                       boolean isAssociatedComponent) {
         log.debug("start convert node type for {}", component.getUniqueId());
         ToscaNodeType toscaNodeType = createNodeType(component);
-
-        Either<Map<String, InterfaceDefinition>, StorageOperationStatus> lifecycleTypeEither =
-            interfaceLifecycleOperation.getAllInterfaceLifecycleTypes();
+        Either<Map<String, InterfaceDefinition>, StorageOperationStatus> lifecycleTypeEither = interfaceLifecycleOperation
+            .getAllInterfaceLifecycleTypes();
         if (lifecycleTypeEither.isRight()) {
             log.debug("Failed to fetch all interface types :", lifecycleTypeEither.right().value());
             return Either.right(ToscaError.GENERAL_ERROR);
         }
-        List<String> allGlobalInterfaceTypes = lifecycleTypeEither.left().value()
-            .values()
-            .stream()
-            .map(InterfaceDataDefinition::getType)
+        List<String> allGlobalInterfaceTypes = lifecycleTypeEither.left().value().values().stream().map(InterfaceDataDefinition::getType)
             .collect(Collectors.toList());
         toscaNode.setInterface_types(addInterfaceTypeElement(component, allGlobalInterfaceTypes));
-
         Either<Map<String, DataTypeDefinition>, JanusGraphOperationStatus> dataTypesEither = dataTypeCache.getAll();
         if (dataTypesEither.isRight()) {
             log.debug("Failed to fetch all data types :", dataTypesEither.right().value());
             return Either.right(ToscaError.GENERAL_ERROR);
         }
-
         Map<String, DataTypeDefinition> dataTypes = dataTypesEither.left().value();
-
         List<InputDefinition> inputDef = component.getInputs();
         Map<String, ToscaProperty> mergedProperties = new HashMap<>();
-        interfacesOperationsConverter
-            .addInterfaceDefinitionElement(component, toscaNodeType, dataTypes, isAssociatedComponent);
+        interfacesOperationsConverter.addInterfaceDefinitionElement(component, toscaNodeType, dataTypes, isAssociatedComponent);
         addInputsToProperties(dataTypes, inputDef, mergedProperties);
-
         final Map<String, ToscaAttribute> toscaAttributeMap;
         try {
             toscaAttributeMap = convertToToscaAttributes(component.getAttributes(), dataTypes);
@@ -780,17 +702,15 @@ public class ToscaExportHandler {
         if (CollectionUtils.isNotEmpty(component.getProperties())) {
             List<PropertyDefinition> properties = component.getProperties();
             Map<String, ToscaProperty> convertedProperties = properties.stream()
-                .map(propertyDefinition -> resolvePropertyValueFromInput(propertyDefinition, component.getInputs()))
-                .collect(Collectors.toMap(PropertyDataDefinition::getName,
-                    property -> propertyConvertor.convertProperty(dataTypes, property,
-                        PropertyConvertor.PropertyType.PROPERTY)));
+                .map(propertyDefinition -> resolvePropertyValueFromInput(propertyDefinition, component.getInputs())).collect(Collectors
+                    .toMap(PropertyDataDefinition::getName,
+                        property -> propertyConvertor.convertProperty(dataTypes, property, PropertyConvertor.PropertyType.PROPERTY)));
             // merge component properties and inputs properties
             mergedProperties.putAll(convertedProperties);
         }
         if (MapUtils.isNotEmpty(mergedProperties)) {
             toscaNodeType.setProperties(mergedProperties);
         }
-
         /* convert private data_types */
         List<DataTypeDefinition> privateDataTypes = component.getDataTypes();
         if (CollectionUtils.isNotEmpty(privateDataTypes)) {
@@ -1467,32 +1387,27 @@ public class ToscaExportHandler {
     private boolean isRequirementBelongToRelation(Component originComponent, RelationshipInfo reqAndRelationshipPair,
                                                   RequirementDefinition requirement, String fromInstanceId) {
         if (!StringUtils.equals(requirement.getName(), reqAndRelationshipPair.getRequirement())) {
-            log.debug("Failed to find a requirement with name {} and  reqAndRelationshipPair {}",
-                requirement.getName(), reqAndRelationshipPair.getRequirement());
+            log.debug("Failed to find a requirement with name {} and  reqAndRelationshipPair {}", requirement.getName(),
+                reqAndRelationshipPair.getRequirement());
             return false;
         }
-        return ModelConverter.isAtomicComponent(originComponent) ||
-            isRequirementBelongToOwner(reqAndRelationshipPair, requirement, fromInstanceId, originComponent);
+        return ModelConverter.isAtomicComponent(originComponent) || isRequirementBelongToOwner(reqAndRelationshipPair, requirement, fromInstanceId,
+            originComponent);
     }
 
-    private boolean isRequirementBelongToOwner(RelationshipInfo reqAndRelationshipPair,
-                                               RequirementDefinition requirement, String fromInstanceId,
+    private boolean isRequirementBelongToOwner(RelationshipInfo reqAndRelationshipPair, RequirementDefinition requirement, String fromInstanceId,
                                                Component originComponent) {
-        return StringUtils.equals(requirement.getOwnerId(), reqAndRelationshipPair.getRequirementOwnerId())
-            || (isCvfc(originComponent) && StringUtils
-            .equals(fromInstanceId, reqAndRelationshipPair.getRequirementOwnerId())
-            || StringUtils.equals(requirement.getOwnerId(), originComponent.getUniqueId()));
+        return StringUtils.equals(requirement.getOwnerId(), reqAndRelationshipPair.getRequirementOwnerId()) || (
+            isCvfc(originComponent) && StringUtils.equals(fromInstanceId, reqAndRelationshipPair.getRequirementOwnerId()) || StringUtils
+                .equals(requirement.getOwnerId(), originComponent.getUniqueId()));
     }
 
     private boolean isCvfc(Component component) {
-        return component.getComponentType() == ComponentTypeEnum.RESOURCE &&
-            ((Resource) component).getResourceType() == ResourceTypeEnum.CVFC;
+        return component.getComponentType() == ComponentTypeEnum.RESOURCE && ((Resource) component).getResourceType() == ResourceTypeEnum.CVFC;
     }
 
-    private Either<SubstitutionMapping, ToscaError> convertCapabilities(Component component,
-                                                                        SubstitutionMapping substitutionMappings,
+    private Either<SubstitutionMapping, ToscaError> convertCapabilities(Component component, SubstitutionMapping substitutionMappings,
                                                                         Map<String, Component> componentCache) {
-
         Either<SubstitutionMapping, ToscaError> result = Either.left(substitutionMappings);
         Either<Map<String, String[]>, ToscaError> toscaCapabilitiesRes = capabilityRequirementConverter
             .convertSubstitutionMappingCapabilities(componentCache, component);
@@ -1507,22 +1422,17 @@ public class ToscaExportHandler {
         return result;
     }
 
-    private Either<ToscaNodeType, ToscaError> convertCapabilities(Map<String, Component> componentsCache,
-                                                                  Component component, ToscaNodeType nodeType,
+    private Either<ToscaNodeType, ToscaError> convertCapabilities(Map<String, Component> componentsCache, Component component, ToscaNodeType nodeType,
                                                                   Map<String, DataTypeDefinition> dataTypes) {
-        Map<String, ToscaCapability> toscaCapabilities = capabilityRequirementConverter
-            .convertCapabilities(componentsCache, component,
-                dataTypes);
+        Map<String, ToscaCapability> toscaCapabilities = capabilityRequirementConverter.convertCapabilities(componentsCache, component, dataTypes);
         if (!toscaCapabilities.isEmpty()) {
             nodeType.setCapabilities(toscaCapabilities);
         }
         log.debug("Finish convert Capabilities for node type");
-
         return Either.left(nodeType);
     }
 
-    private Map<String, ToscaTemplateArtifact> convertToNodeTemplateArtifacts(
-        Map<String, ToscaArtifactDataDefinition> artifacts) {
+    private Map<String, ToscaTemplateArtifact> convertToNodeTemplateArtifacts(Map<String, ToscaArtifactDataDefinition> artifacts) {
         if (artifacts == null) {
             return null;
         }
@@ -1541,58 +1451,40 @@ public class ToscaExportHandler {
             return null;
         }
         NodeFilter nodeFilter = new NodeFilter();
-
-        ListDataDefinition<RequirementNodeFilterCapabilityDataDefinition> origCapabilities =
-            inNodeFilter.getCapabilities();
-
+        ListDataDefinition<RequirementNodeFilterCapabilityDataDefinition> origCapabilities = inNodeFilter.getCapabilities();
         ListDataDefinition<RequirementNodeFilterPropertyDataDefinition> origProperties = inNodeFilter.getProperties();
-
         List<Map<String, CapabilityFilter>> capabilitiesCopy = new ArrayList<>();
         List<Map<String, List<Object>>> propertiesCopy = new ArrayList<>();
-
         copyNodeFilterCapabilitiesTemplate(origCapabilities, capabilitiesCopy);
         copyNodeFilterProperties(origProperties, propertiesCopy);
-
         if (CollectionUtils.isNotEmpty(capabilitiesCopy)) {
             nodeFilter.setCapabilities(capabilitiesCopy);
         }
-
         if (CollectionUtils.isNotEmpty(propertiesCopy)) {
             nodeFilter.setProperties(propertiesCopy);
         }
-
         nodeFilter.setTosca_id(cloneToscaId(inNodeFilter.getTosca_id()));
-
         nodeFilter = (NodeFilter) cloneObjectFromYml(nodeFilter, NodeFilter.class);
-
         return nodeFilter;
     }
 
-    private NodeFilter convertToSubstitutionFilterComponent(
-        final SubstitutionFilterDataDefinition substitutionFilterDataDefinition) {
-
+    private NodeFilter convertToSubstitutionFilterComponent(final SubstitutionFilterDataDefinition substitutionFilterDataDefinition) {
         if (substitutionFilterDataDefinition == null) {
             return null;
         }
         NodeFilter nodeFilter = new NodeFilter();
-
-        ListDataDefinition<RequirementSubstitutionFilterPropertyDataDefinition> origProperties =
-            substitutionFilterDataDefinition.getProperties();
+        ListDataDefinition<RequirementSubstitutionFilterPropertyDataDefinition> origProperties = substitutionFilterDataDefinition.getProperties();
         List<Map<String, List<Object>>> propertiesCopy = new ArrayList<>();
-
         copySubstitutionFilterProperties(origProperties, propertiesCopy);
-
         if (CollectionUtils.isNotEmpty(propertiesCopy)) {
             nodeFilter.setProperties(propertiesCopy);
         }
         nodeFilter.setTosca_id(cloneToscaId(substitutionFilterDataDefinition.getTosca_id()));
-
         return (NodeFilter) cloneObjectFromYml(nodeFilter, NodeFilter.class);
     }
 
     private Object cloneToscaId(Object toscaId) {
-        return Objects.isNull(toscaId) ? null
-            : cloneObjectFromYml(toscaId, toscaId.getClass());
+        return Objects.isNull(toscaId) ? null : cloneObjectFromYml(toscaId, toscaId.getClass());
     }
 
     private Object cloneObjectFromYml(Object objToClone, Class classOfObj) {
@@ -1600,11 +1492,10 @@ public class ToscaExportHandler {
         return yamlUtil.yamlToObject(objectAsYml, classOfObj);
     }
 
-    private void copyNodeFilterCapabilitiesTemplate(
-        ListDataDefinition<RequirementNodeFilterCapabilityDataDefinition> origCapabilities,
-        List<Map<String, CapabilityFilter>> capabilitiesCopy) {
-        if (origCapabilities == null || origCapabilities.getListToscaDataDefinition() == null ||
-            origCapabilities.getListToscaDataDefinition().isEmpty()) {
+    private void copyNodeFilterCapabilitiesTemplate(ListDataDefinition<RequirementNodeFilterCapabilityDataDefinition> origCapabilities,
+                                                    List<Map<String, CapabilityFilter>> capabilitiesCopy) {
+        if (origCapabilities == null || origCapabilities.getListToscaDataDefinition() == null || origCapabilities.getListToscaDataDefinition()
+            .isEmpty()) {
             return;
         }
         for (RequirementNodeFilterCapabilityDataDefinition capability : origCapabilities.getListToscaDataDefinition()) {
@@ -1618,16 +1509,13 @@ public class ToscaExportHandler {
         }
     }
 
-    private void copyNodeFilterProperties(
-        ListDataDefinition<RequirementNodeFilterPropertyDataDefinition> origProperties,
-        List<Map<String, List<Object>>> propertiesCopy) {
-        if (origProperties == null || origProperties.getListToscaDataDefinition() == null ||
-            origProperties.isEmpty()) {
+    private void copyNodeFilterProperties(ListDataDefinition<RequirementNodeFilterPropertyDataDefinition> origProperties,
+                                          List<Map<String, List<Object>>> propertiesCopy) {
+        if (origProperties == null || origProperties.getListToscaDataDefinition() == null || origProperties.isEmpty()) {
             return;
         }
         Map<String, List<Object>> propertyMapCopy = new HashMap<>();
-        for (RequirementNodeFilterPropertyDataDefinition propertyDataDefinition : origProperties
-            .getListToscaDataDefinition()) {
+        for (RequirementNodeFilterPropertyDataDefinition propertyDataDefinition : origProperties.getListToscaDataDefinition()) {
             for (String propertyInfoEntry : propertyDataDefinition.getConstraints()) {
                 Map propertyValObj = new YamlUtil().yamlToObject(propertyInfoEntry, Map.class);
                 String propertyName = propertyDataDefinition.getName();
@@ -1644,23 +1532,18 @@ public class ToscaExportHandler {
                 }
             }
         }
-        propertyMapCopy.entrySet().stream().forEach(entry ->
-            addCalculatedConstraintsIntoPropertiesList(propertiesCopy, entry));
+        propertyMapCopy.entrySet().stream().forEach(entry -> addCalculatedConstraintsIntoPropertiesList(propertiesCopy, entry));
     }
 
-    private void copySubstitutionFilterProperties(
-        final ListDataDefinition<RequirementSubstitutionFilterPropertyDataDefinition> origProperties,
-        final List<Map<String, List<Object>>> propertiesCopy) {
-        if (origProperties == null || origProperties.getListToscaDataDefinition() == null ||
-            origProperties.isEmpty()) {
+    private void copySubstitutionFilterProperties(final ListDataDefinition<RequirementSubstitutionFilterPropertyDataDefinition> origProperties,
+                                                  final List<Map<String, List<Object>>> propertiesCopy) {
+        if (origProperties == null || origProperties.getListToscaDataDefinition() == null || origProperties.isEmpty()) {
             return;
         }
         final Map<String, List<Object>> propertyMapCopy = new HashMap<>();
-        for (final RequirementSubstitutionFilterPropertyDataDefinition propertyDataDefinition : origProperties
-            .getListToscaDataDefinition()) {
+        for (final RequirementSubstitutionFilterPropertyDataDefinition propertyDataDefinition : origProperties.getListToscaDataDefinition()) {
             for (final String propertyInfoEntry : propertyDataDefinition.getConstraints()) {
-                final Map<String, List<Object>> propertyValObj = new YamlUtil()
-                    .yamlToObject(propertyInfoEntry, Map.class);
+                final Map<String, List<Object>> propertyValObj = new YamlUtil().yamlToObject(propertyInfoEntry, Map.class);
                 final String propertyName = propertyDataDefinition.getName();
                 if (propertyMapCopy.containsKey(propertyName)) {
                     addPropertyConstraintValueToList(propertyName, propertyValObj, propertyMapCopy.get(propertyName));
@@ -1675,8 +1558,7 @@ public class ToscaExportHandler {
                 }
             }
         }
-        propertyMapCopy.entrySet().forEach(entry ->
-            addCalculatedConstraintsIntoPropertiesList(propertiesCopy, entry));
+        propertyMapCopy.entrySet().forEach(entry -> addCalculatedConstraintsIntoPropertiesList(propertiesCopy, entry));
     }
 
     private void addPropertyConstraintValueToList(String propertyName, Map<String, List<Object>> propertyValObj, List<Object> propsList) {
@@ -1687,84 +1569,77 @@ public class ToscaExportHandler {
         }
     }
 
-    private void addCalculatedConstraintsIntoPropertiesList(List<Map<String, List<Object>>> propertiesCopy,
-                                                            Entry<String, List<Object>> entry) {
+    private void addCalculatedConstraintsIntoPropertiesList(List<Map<String, List<Object>>> propertiesCopy, Entry<String, List<Object>> entry) {
         Map<String, List<Object>> tempMap = new HashMap<>();
         tempMap.put(entry.getKey(), entry.getValue());
         propertiesCopy.add(tempMap);
     }
 
-    private static class CustomRepresenter extends Representer {
-
-        CustomRepresenter() {
-            super();
-            this.representers.put(ToscaPropertyAssignment.class, new RepresentToscaPropertyAssignment());
-            this.representers.put(ToscaAttribute.class, new RepresentToscaAttribute());
-            // null representer is exceptional and it is stored as an instance
-            // variable.
-            this.nullRepresenter = new RepresentNull();
-
+    private Map<String, String[]> buildSubstitutionMappingPropertyMapping(final Component component) {
+        if (component == null || CollectionUtils.isEmpty(component.getInputs())) {
+            return Collections.emptyMap();
         }
+        return component.getInputs().stream().filter(input -> input.isMappedToComponentProperty()).map(PropertyDataDefinition::getName)
+            .collect(Collectors.toMap(inputName -> inputName, inputName -> new String[]{inputName}, (inputName1, inputName2) -> inputName1));
+    }
 
-        private class RepresentToscaAttribute implements Represent {
+    private Map<String, String[]> buildSubstitutionMappingAttributesMapping(final Component component) {
+        if (component == null || CollectionUtils.isEmpty(component.getOutputs())) {
+            return Collections.emptyMap();
+        }
+        return component.getOutputs().stream().map(AttributeDataDefinition::getName)
+            .collect(Collectors.toMap(outputName -> outputName, outputName -> new String[]{outputName}, (outputName1, outputName2) -> outputName1));
+    }
 
-            @Override
-            public Node representData(Object data) {
-                final ToscaAttribute toscaAttribute = (ToscaAttribute) data;
-                return represent(toscaAttribute.asToscaMap());
-            }
+    Optional<Map<String, ToscaProperty>> getProxyNodeTypeProperties(Component proxyComponent, Map<String, DataTypeDefinition> dataTypes) {
+        if (Objects.isNull(proxyComponent)) {
+            return Optional.empty();
+        }
+        Map<String, ToscaProperty> proxyProperties = new HashMap<>();
+        addInputsToProperties(dataTypes, proxyComponent.getInputs(), proxyProperties);
+        if (CollectionUtils.isNotEmpty(proxyComponent.getProperties())) {
+            proxyProperties.putAll(proxyComponent.getProperties().stream()
+                .map(propertyDefinition -> resolvePropertyValueFromInput(propertyDefinition, proxyComponent.getInputs())).collect(Collectors
+                    .toMap(PropertyDataDefinition::getName,
+                        property -> propertyConvertor.convertProperty(dataTypes, property, PropertyConvertor.PropertyType.PROPERTY))));
         }
+        return MapUtils.isNotEmpty(proxyProperties) ? Optional.of(proxyProperties) : Optional.empty();
+    }
 
-        private class RepresentToscaPropertyAssignment implements Represent {
+    void addInputsToProperties(Map<String, DataTypeDefinition> dataTypes, List<InputDefinition> componentInputs,
+                               Map<String, ToscaProperty> mergedProperties) {
+        if (CollectionUtils.isEmpty(componentInputs)) {
+            return;
+        }
+        for (InputDefinition input : componentInputs) {
+            ToscaProperty property = propertyConvertor.convertProperty(dataTypes, input, PropertyConvertor.PropertyType.INPUT);
+            mergedProperties.put(input.getName(), property);
+        }
+    }
 
-            public Node representData(Object data) {
-                final ToscaPropertyAssignment toscaOperationAssignment = (ToscaPropertyAssignment) data;
-                if (toscaOperationAssignment.getValue() instanceof String) {
-                    final String stringValue = (String) toscaOperationAssignment.getValue();
-                    if (isPropertyOrAttributeFunction(stringValue)) {
-                        return representGetAttribute(stringValue);
-                    }
+    Optional<Map<String, Object>> getProxyNodeTypeInterfaces(Component proxyComponent, Map<String, DataTypeDefinition> dataTypes) {
+        if (Objects.isNull(proxyComponent) || MapUtils.isEmpty(proxyComponent.getInterfaces())) {
+            return Optional.empty();
+        }
+        Map<String, InterfaceDefinition> proxyComponentInterfaces = proxyComponent.getInterfaces();
+        //Unset artifact path for operation implementation for proxy node types as for operations with artifacts it is
 
-                    return representScalar(Tag.STR, stringValue);
-                }
-                return represent(null);
-            }
+        // always available in the proxy node template
+        removeOperationImplementationForProxyNodeType(proxyComponentInterfaces);
+        return Optional
+            .ofNullable(interfacesOperationsConverter.getInterfacesMap(proxyComponent, null, proxyComponentInterfaces, dataTypes, false, false));
+    }
 
-            public Node representGetAttribute(final String getAttributeFunction) {
-                return represent(new Yaml().load(getAttributeFunction));
-            }
+    private static class CustomRepresenter extends Representer {
 
-            public boolean isPropertyOrAttributeFunction(final String value) {
-                try {
-                    final Yaml yaml = new Yaml();
-                    final Object yamlObj = yaml.load(value);
-                    if (!(yamlObj instanceof Map)) {
-                        return false;
-                    }
-                    final Map<String, Object> getAttributeMap = (Map) yamlObj;
-                    if (getAttributeMap.size() != 1) {
-                        return false;
-                    }
-                    final List<String> functionList = Arrays
-                        .asList(GET_ATTRIBUTE.getFunctionName(), GET_INPUT.getFunctionName(),
-                            GET_PROPERTY.getFunctionName());
-                    final Optional<String> function = getAttributeMap.keySet().stream()
-                        .filter(key -> functionList.stream().anyMatch(function1 -> function1.equals(key))).findFirst();
+        CustomRepresenter() {
+            super();
+            this.representers.put(ToscaPropertyAssignment.class, new RepresentToscaPropertyAssignment());
+            this.representers.put(ToscaAttribute.class, new RepresentToscaAttribute());
+            // null representer is exceptional and it is stored as an instance
 
-                    if (function.isEmpty()) {
-                        return false;
-                    }
-                    final String functionName = function.get();
-                    final Object getAttributeValueObj = getAttributeMap.get(functionName);
-                    if (GET_INPUT.getFunctionName().equals(functionName)) {
-                        return validateGetInputValue(getAttributeValueObj);
-                    } else {
-                        return validateGetPropertyOrAttributeValue(getAttributeValueObj);
-                    }
-                } catch (final Exception ignored) {
-                    return false;
-                }
-            }
+            // variable.
+            this.nullRepresenter = new RepresentNull();
         }
 
         public boolean validateGetInputValue(final Object valueObj) {
@@ -1774,7 +1649,6 @@ public class ToscaExportHandler {
             if (valueObj instanceof List) {
                 return ((List) valueObj).size() > 1;
             }
-
             return true;
         }
 
@@ -1782,13 +1656,11 @@ public class ToscaExportHandler {
             if (valueObj instanceof List) {
                 return ((List) valueObj).size() > 1;
             }
-
             return false;
         }
 
         @Override
-        protected NodeTuple representJavaBeanProperty(Object javaBean, Property property, Object propertyValue,
-                                                      Tag customTag) {
+        protected NodeTuple representJavaBeanProperty(Object javaBean, Property property, Object propertyValue, Tag customTag) {
             if (propertyValue == null) {
                 return null;
             }
@@ -1799,27 +1671,21 @@ public class ToscaExportHandler {
             if (javaBean instanceof ToscaRelationshipTemplate && "name".equals(property.getName())) {
                 return null;
             }
-
             removeDefaultP(propertyValue);
             NodeTuple defaultNode = super.representJavaBeanProperty(javaBean, property, propertyValue, customTag);
-
             if (javaBean instanceof ToscaTopolgyTemplate && "relationshipTemplates".equals(property.getName())) {
                 return new NodeTuple(representData("relationship_templates"), defaultNode.getValueNode());
             }
-
-            return "_defaultp_".equals(property.getName())
-                ? new NodeTuple(representData("default"), defaultNode.getValueNode()) : defaultNode;
+            return "_defaultp_".equals(property.getName()) ? new NodeTuple(representData("default"), defaultNode.getValueNode()) : defaultNode;
         }
 
         private void removeDefaultP(final Object propertyValue) {
             if (propertyValue instanceof Map) {
                 final Map mapPropertyValue = ((Map) propertyValue);
-
                 final Iterator<Entry> iter = mapPropertyValue.entrySet().iterator();
                 Object defaultValue = null;
                 while (iter.hasNext()) {
                     final Map.Entry entry = iter.next();
-
                     if ("_defaultp_".equals(entry.getKey())) {
                         defaultValue = entry.getValue();
                         iter.remove();
@@ -1839,110 +1705,83 @@ public class ToscaExportHandler {
             if (!classTags.containsKey(javaBean.getClass())) {
                 addClassTag(javaBean.getClass(), Tag.MAP);
             }
-
             return super.representJavaBean(properties, javaBean);
         }
 
-        private class RepresentNull implements Represent {
+        private class RepresentToscaAttribute implements Represent {
 
             @Override
             public Node representData(Object data) {
-                // possible values are here http://yaml.org/type/null.html
-                return representScalar(Tag.NULL, "");
+                final ToscaAttribute toscaAttribute = (ToscaAttribute) data;
+                return represent(toscaAttribute.asToscaMap());
             }
         }
-    }
 
-    private static class UnsortedPropertyUtils extends PropertyUtils {
+        private class RepresentToscaPropertyAssignment implements Represent {
 
-        @Override
-        protected Set<Property> createPropertySet(Class type, BeanAccess bAccess) {
-            Collection<Property> fields = getPropertiesMap(type, BeanAccess.FIELD).values();
-            return new LinkedHashSet<>(fields);
-        }
-    }
+            public Node representData(Object data) {
+                final ToscaPropertyAssignment toscaOperationAssignment = (ToscaPropertyAssignment) data;
+                if (toscaOperationAssignment.getValue() instanceof String) {
+                    final String stringValue = (String) toscaOperationAssignment.getValue();
+                    if (isPropertyOrAttributeFunction(stringValue)) {
+                        return representGetAttribute(stringValue);
+                    }
+                    return representScalar(Tag.STR, stringValue);
+                }
+                return represent(null);
+            }
 
-    private Map<String, String[]> buildSubstitutionMappingPropertyMapping(final Component component) {
-        if (component == null || CollectionUtils.isEmpty(component.getInputs())) {
-            return Collections.emptyMap();
-        }
-        return component.getInputs().stream().filter(input -> input.isMappedToComponentProperty())
-            .map(PropertyDataDefinition::getName)
-            .collect(
-                Collectors.toMap(
-                    inputName -> inputName,
-                    inputName -> new String[]{inputName},
-                    (inputName1, inputName2) -> inputName1)
-            );
-    }
+            public Node representGetAttribute(final String getAttributeFunction) {
+                return represent(new Yaml().load(getAttributeFunction));
+            }
 
-    private Map<String, String[]> buildSubstitutionMappingAttributesMapping(final Component component) {
-        if (component == null || CollectionUtils.isEmpty(component.getOutputs())) {
-            return Collections.emptyMap();
+            public boolean isPropertyOrAttributeFunction(final String value) {
+                try {
+                    final Yaml yaml = new Yaml();
+                    final Object yamlObj = yaml.load(value);
+                    if (!(yamlObj instanceof Map)) {
+                        return false;
+                    }
+                    final Map<String, Object> getAttributeMap = (Map) yamlObj;
+                    if (getAttributeMap.size() != 1) {
+                        return false;
+                    }
+                    final List<String> functionList = Arrays
+                        .asList(GET_ATTRIBUTE.getFunctionName(), GET_INPUT.getFunctionName(), GET_PROPERTY.getFunctionName());
+                    final Optional<String> function = getAttributeMap.keySet().stream()
+                        .filter(key -> functionList.stream().anyMatch(function1 -> function1.equals(key))).findFirst();
+                    if (function.isEmpty()) {
+                        return false;
+                    }
+                    final String functionName = function.get();
+                    final Object getAttributeValueObj = getAttributeMap.get(functionName);
+                    if (GET_INPUT.getFunctionName().equals(functionName)) {
+                        return validateGetInputValue(getAttributeValueObj);
+                    } else {
+                        return validateGetPropertyOrAttributeValue(getAttributeValueObj);
+                    }
+                } catch (final Exception ignored) {
+                    return false;
+                }
+            }
         }
-        return component.getOutputs().stream()
-            .map(AttributeDataDefinition::getName)
-            .collect(
-                Collectors.toMap(
-                    outputName -> outputName,
-                    outputName -> new String[]{outputName},
-                    (outputName1, outputName2) -> outputName1)
-            );
-    }
 
-    Optional<Map<String, ToscaProperty>> getProxyNodeTypeProperties(Component proxyComponent,
-                                                                    Map<String, DataTypeDefinition>
-                                                                        dataTypes) {
-        if (Objects.isNull(proxyComponent)) {
-            return Optional.empty();
-        }
-        Map<String, ToscaProperty> proxyProperties = new HashMap<>();
-        addInputsToProperties(dataTypes, proxyComponent.getInputs(), proxyProperties);
-        if (CollectionUtils.isNotEmpty(proxyComponent.getProperties())) {
-            proxyProperties.putAll(proxyComponent.getProperties().stream()
-                .map(propertyDefinition -> resolvePropertyValueFromInput(propertyDefinition,
-                    proxyComponent.getInputs()))
-                .collect(Collectors.toMap(PropertyDataDefinition::getName,
-                    property -> propertyConvertor.convertProperty(dataTypes, property,
-                        PropertyConvertor.PropertyType.PROPERTY))));
-        }
-        return MapUtils.isNotEmpty(proxyProperties) ? Optional.of(proxyProperties) : Optional.empty();
-    }
+        private class RepresentNull implements Represent {
 
-    void addInputsToProperties(Map<String, DataTypeDefinition> dataTypes,
-                               List<InputDefinition> componentInputs,
-                               Map<String, ToscaProperty> mergedProperties) {
-        if (CollectionUtils.isEmpty(componentInputs)) {
-            return;
-        }
-        for (InputDefinition input : componentInputs) {
-            ToscaProperty property = propertyConvertor.convertProperty(dataTypes, input,
-                PropertyConvertor.PropertyType.INPUT);
-            mergedProperties.put(input.getName(), property);
+            @Override
+            public Node representData(Object data) {
+                // possible values are here http://yaml.org/type/null.html
+                return representScalar(Tag.NULL, "");
+            }
         }
     }
 
-    Optional<Map<String, Object>> getProxyNodeTypeInterfaces(Component proxyComponent,
-                                                             Map<String, DataTypeDefinition> dataTypes) {
-        if (Objects.isNull(proxyComponent) || MapUtils.isEmpty(proxyComponent.getInterfaces())) {
-            return Optional.empty();
-        }
-        Map<String, InterfaceDefinition> proxyComponentInterfaces = proxyComponent.getInterfaces();
-        //Unset artifact path for operation implementation for proxy node types as for operations with artifacts it is
-        // always available in the proxy node template
-        removeOperationImplementationForProxyNodeType(proxyComponentInterfaces);
-        return Optional.ofNullable(interfacesOperationsConverter
-            .getInterfacesMap(proxyComponent, null, proxyComponentInterfaces, dataTypes,
-                false, false));
-    }
+    private static class UnsortedPropertyUtils extends PropertyUtils {
 
-    private static void removeOperationImplementationForProxyNodeType(
-        Map<String, InterfaceDefinition> proxyComponentInterfaces) {
-        if (MapUtils.isEmpty(proxyComponentInterfaces)) {
-            return;
+        @Override
+        protected Set<Property> createPropertySet(Class type, BeanAccess bAccess) {
+            Collection<Property> fields = getPropertiesMap(type, BeanAccess.FIELD).values();
+            return new LinkedHashSet<>(fields);
         }
-        proxyComponentInterfaces.values().stream().map(InterfaceDataDefinition::getOperations)
-            .filter(MapUtils::isNotEmpty)
-            .forEach(operations -> operations.values().forEach(operation -> operation.setImplementation(null)));
     }
 }
index c706063..4ee8ff0 100644 (file)
@@ -16,7 +16,6 @@
  *  SPDX-License-Identifier: Apache-2.0
  *  ============LICENSE_END=========================================================
  */
-
 package org.openecomp.sdc.be.tosca;
 
 import static org.apache.commons.collections.CollectionUtils.isEmpty;
@@ -47,7 +46,6 @@ public class ToscaExportRelationshipTemplatesHandler {
         if (MapUtils.isEmpty(nodeTemplateMap)) {
             return Collections.emptyMap();
         }
-
         final Map<String, ToscaRelationshipTemplate> relationshipTemplates = new HashMap<>();
         for (final Entry<String, ToscaNodeTemplate> nodeEntry : nodeTemplateMap.entrySet()) {
             final ToscaNodeTemplate nodeTemplate = nodeEntry.getValue();
@@ -56,28 +54,22 @@ public class ToscaExportRelationshipTemplatesHandler {
             }
             final AtomicInteger relationshipTemplateCount = new AtomicInteger(1);
             for (final Map<String, ToscaTemplateRequirement> requirementMap : nodeTemplate.getRequirements()) {
-                requirementMap.entrySet().stream()
-                    .filter(entry -> entry.getValue().isRelationshipComplexNotation())
-                    .forEach(requirementEntry -> {
-                        final ToscaTemplateRequirement requirement = requirementEntry.getValue();
-                        final ToscaRelationship relationship = requirement.getRelationshipAsComplexType();
-                        final ToscaRelationshipTemplate relationshipTemplate = new ToscaRelationshipTemplate();
-                        relationshipTemplate.setType(relationship.getType());
-                        relationshipTemplate.setInterfaces(relationship.getInterfaces());
-                        final String relationshipName = String.format("%s.%s",
-                            ToscaRelationshipTemplate
-                                .createRelationshipName(nodeEntry.getKey(), requirementEntry.getKey()),
+                requirementMap.entrySet().stream().filter(entry -> entry.getValue().isRelationshipComplexNotation()).forEach(requirementEntry -> {
+                    final ToscaTemplateRequirement requirement = requirementEntry.getValue();
+                    final ToscaRelationship relationship = requirement.getRelationshipAsComplexType();
+                    final ToscaRelationshipTemplate relationshipTemplate = new ToscaRelationshipTemplate();
+                    relationshipTemplate.setType(relationship.getType());
+                    relationshipTemplate.setInterfaces(relationship.getInterfaces());
+                    final String relationshipName = String
+                        .format("%s.%s", ToscaRelationshipTemplate.createRelationshipName(nodeEntry.getKey(), requirementEntry.getKey()),
                             relationshipTemplateCount);
-
-                        requirement.setRelationship(relationshipName);
-                        relationshipTemplate.setName(relationshipName);
-                        relationshipTemplates.put(relationshipName, relationshipTemplate);
-                        relationshipTemplateCount.incrementAndGet();
-                    });
+                    requirement.setRelationship(relationshipName);
+                    relationshipTemplate.setName(relationshipName);
+                    relationshipTemplates.put(relationshipName, relationshipTemplate);
+                    relationshipTemplateCount.incrementAndGet();
+                });
             }
         }
-
         return relationshipTemplates;
     }
-
 }
index 1ca9557..07463f8 100644 (file)
@@ -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.
  * limitations under the License.
  * ============LICENSE_END=========================================================
  */
-
 package org.openecomp.sdc.be.tosca;
 
 import io.vavr.control.Option;
+import java.util.List;
 import lombok.Getter;
 import org.apache.commons.lang3.tuple.Triple;
 import org.openecomp.sdc.be.model.Component;
-
-import java.util.List;
 import org.openecomp.sdc.be.tosca.model.ToscaTemplate;
 
 public class ToscaRepresentation {
 
     @Getter
     private final byte[] mainYaml;
-
     @Getter
     private final Option<List<Triple<String, String, Component>>> dependencies;
 
index 38e6061..0f13395 100644 (file)
@@ -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.
  * limitations under the License.
  * ============LICENSE_END=========================================================
  */
-
 package org.openecomp.sdc.be.tosca;
 
-import org.openecomp.sdc.be.datatypes.components.ResourceMetadataDataDefinition;
-import org.openecomp.sdc.be.datatypes.enums.ComponentTypeEnum;
-import org.openecomp.sdc.be.datatypes.enums.ResourceTypeEnum;
-import org.openecomp.sdc.be.model.Component;
-
 import java.lang.reflect.Field;
 import java.util.ArrayList;
 import java.util.Arrays;
 import java.util.HashMap;
 import java.util.List;
 import java.util.Map;
+import org.openecomp.sdc.be.datatypes.components.ResourceMetadataDataDefinition;
+import org.openecomp.sdc.be.datatypes.enums.ComponentTypeEnum;
+import org.openecomp.sdc.be.datatypes.enums.ResourceTypeEnum;
+import org.openecomp.sdc.be.model.Component;
+
 public class ToscaUtils {
 
-    private ToscaUtils() {}
+    private ToscaUtils() {
+    }
 
     public static boolean isNotComplexVfc(Component component) {
         if (ComponentTypeEnum.RESOURCE == component.getComponentType()) {
-            ResourceTypeEnum resourceType = ((ResourceMetadataDataDefinition) component.getComponentMetadataDefinition().getMetadataDataDefinition()).getResourceType();
-            if (ResourceTypeEnum.CVFC == resourceType ) {
+            ResourceTypeEnum resourceType = ((ResourceMetadataDataDefinition) component.getComponentMetadataDefinition().getMetadataDataDefinition())
+                .getResourceType();
+            if (ResourceTypeEnum.CVFC == resourceType) {
                 return false;
             }
-            if (component.getComponentMetadataDefinition()!=null && component.getComponentMetadataDefinition().getMetadataDataDefinition()!=null
-                    && component.getComponentMetadataDefinition().getMetadataDataDefinition().getDescription()!=null){
-                if(component.getComponentMetadataDefinition().getMetadataDataDefinition().getDescription().equalsIgnoreCase("Nested VF in service")){
+            if (component.getComponentMetadataDefinition() != null && component.getComponentMetadataDefinition().getMetadataDataDefinition() != null
+                && component.getComponentMetadataDefinition().getMetadataDataDefinition().getDescription() != null) {
+                if (component.getComponentMetadataDefinition().getMetadataDataDefinition().getDescription()
+                    .equalsIgnoreCase("Nested VF in service")) {
                     return false;
                 }
             }
@@ -54,9 +56,7 @@ public class ToscaUtils {
     public static Map<String, Object> objectToMap(Object objectToConvert, Class<?> clazz) throws IllegalAccessException {
         Map<String, Object> map = new HashMap<>();
         List<Field> fields = new ArrayList<>();
-
         fields = getAllFields(fields, clazz);
-
         for (Field field : fields) {
             field.setAccessible(true);
             map.put(field.getName(), field.get(objectToConvert));
@@ -79,13 +79,13 @@ public class ToscaUtils {
         private String owner = "";
 
         SubstitutionEntry(String fullName, String sourceName, String owner) {
-            if(fullName != null) {
+            if (fullName != null) {
                 this.fullName = fullName;
             }
-            if(sourceName != null) {
+            if (sourceName != null) {
                 this.sourceName = sourceName;
             }
-            if(owner != null) {
+            if (owner != null) {
                 this.owner = owner;
             }
         }
@@ -114,5 +114,4 @@ public class ToscaUtils {
             this.owner = owner;
         }
     }
-
 }
index 916895f..55ae728 100644 (file)
  * limitations under the License.
  * ============LICENSE_END=========================================================
  */
-
 package org.openecomp.sdc.be.tosca;
 
-import fj.data.Either;
 import io.vavr.control.Try;
 import java.util.function.Function;
 import java.util.zip.ZipEntry;
@@ -31,11 +29,25 @@ import java.util.zip.ZipOutputStream;
  */
 public interface ZipWriter {
 
+    /**
+     * Builds a ZipWriter that outputs the data on a {@link java.util.zip.ZipOutputStream}
+     *
+     * @param zos the target {@link java.util.zip.ZipOutputStream}
+     */
+    static ZipWriter live(ZipOutputStream zos) {
+        return (entryName, payload) -> Try.of(() -> {
+            zos.putNextEntry(new ZipEntry(entryName));
+            zos.write(payload);
+            // We can return null as a Void is expected;
+            return null;
+        });
+    }
+
     /**
      * Writes an entry provided with its name and its payload
      *
      * @param entryName The entry's name to use in the zip file
-     * @param payload The payload to write for this entry
+     * @param payload   The payload to write for this entry
      */
     Try<Void> write(String entryName, byte[] payload);
 
@@ -43,7 +55,7 @@ public interface ZipWriter {
      * Writes an entry provided with its name and its payload
      *
      * @param entryName The entry's name to use in the zip file
-     * @param payload The payload to write for this entry
+     * @param payload   The payload to write for this entry
      */
     default Try<Void> write(String entryName, String payload) {
         return write(entryName, payload.getBytes());
@@ -61,18 +73,4 @@ public interface ZipWriter {
     default Function<byte[], Try<Void>> write(String entryName) {
         return payload -> write(entryName, payload);
     }
-
-    /**
-     * Builds a ZipWriter that outputs the data on a {@link java.util.zip.ZipOutputStream}
-     * @param zos the target {@link java.util.zip.ZipOutputStream}
-     */
-    static ZipWriter live(ZipOutputStream zos) {
-        return (entryName, payload) -> Try.of(() -> {
-            zos.putNextEntry(new ZipEntry(entryName));
-            zos.write(payload);
-            // We can return null as a Void is expected;
-            return null;
-        });
-    }
 }
-
index c3c9607..1dec236 100644 (file)
@@ -16,7 +16,6 @@
  *  SPDX-License-Identifier: Apache-2.0
  *  ============LICENSE_END=========================================================
  */
-
 package org.openecomp.sdc.be.tosca.builder;
 
 import java.util.HashMap;
@@ -56,7 +55,6 @@ public class ToscaRelationshipBuilder {
                         toscaProperty.setValue(propertyAssignmentUi.getValue());
                         inputMap.put(propertyAssignmentUi.getName(), toscaProperty);
                     });
-
                     toscaOperationAssignment.setInputs(inputMap);
                 }
                 operationDefinitionMap.put(operationUi.getOperationType(), toscaOperationAssignment);
@@ -67,5 +65,4 @@ public class ToscaRelationshipBuilder {
         toscaRelationship.setInterfaces(interfaceMap);
         return toscaRelationship;
     }
-
 }
index 2d37a35..80a943f 100644 (file)
@@ -16,7 +16,6 @@
  *  SPDX-License-Identifier: Apache-2.0
  *  ============LICENSE_END=========================================================
  */
-
 package org.openecomp.sdc.be.tosca.exception;
 
 public class ToscaConversionException extends Exception {
index 0197c3d..579cfc5 100644 (file)
  * See the License for the specific language governing permissions and
  * limitations under the License.
  */
-
 package org.openecomp.sdc.be.tosca.model;
 
+import java.util.ArrayList;
+import java.util.List;
+import java.util.Map;
 import lombok.Getter;
 import lombok.Setter;
 import lombok.ToString;
 import org.apache.commons.collections.CollectionUtils;
 
-import java.util.ArrayList;
-import java.util.List;
-import java.util.Map;
-
 @Getter
 @Setter
 @ToString
@@ -33,7 +31,7 @@ public class CapabilityFilter {
     private List<Map<String, List<Object>>> properties;
 
     public void addProperty(Map<String, List<Object>> property) {
-        if(CollectionUtils.isEmpty(properties)) {
+        if (CollectionUtils.isEmpty(properties)) {
             this.properties = new ArrayList<>();
         }
         this.properties.add(property);
index 1bb865f..e24316c 100644 (file)
@@ -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.
@@ -17,7 +17,6 @@
  * limitations under the License.
  * ============LICENSE_END=========================================================
  */
-
 package org.openecomp.sdc.be.tosca.model;
 
 public interface IToscaMetadata {
index f5511ed..6cad788 100644 (file)
@@ -23,7 +23,8 @@ import lombok.Setter;
 @Getter
 @Setter
 public class NodeFilter {
+
     private Object tosca_id;
     private List<Map<String, List<Object>>> properties;
     private List<Map<String, CapabilityFilter>> capabilities;
-}
\ No newline at end of file
+}
index 7b70a0b..9e3380f 100644 (file)
@@ -17,7 +17,6 @@
  * limitations under the License.
  * ============LICENSE_END=========================================================
  */
-
 package org.openecomp.sdc.be.tosca.model;
 
 import java.util.Map;
index 455e1bd..5aee23d 100644 (file)
@@ -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.
  * limitations under the License.
  * ============LICENSE_END=========================================================
  */
-
 package org.openecomp.sdc.be.tosca.model;
 
 import java.util.HashMap;
 import java.util.Map;
 
 public class ToscaAnnotation {
-    private String type;
-
-    private Map<String ,Object> properties ;
 
-    public void setDescription(String description) {
-        this.description = description;
-    }
+    private String type;
+    private Map<String, Object> properties;
+    private String description;
 
     public String getDescription() {
         return description;
     }
 
-    private String description;
+    public void setDescription(String description) {
+        this.description = description;
+    }
 
     public String getType() {
         return type;
@@ -45,23 +43,19 @@ public class ToscaAnnotation {
     public void setType(String type) {
         this.type = type;
     }
-    
-    public void addProperty(String name, Object property){
-        if ( properties == null ){
+
+    public void addProperty(String name, Object property) {
+        if (properties == null) {
             properties = new HashMap<>();
         }
         properties.put(name, property);
     }
 
-    public void setProperties(Map<String, Object> properties) {
-        this.properties = properties;
-    }
-
     public Map<String, Object> getProperties() {
         return properties;
     }
 
-
-
-
+    public void setProperties(Map<String, Object> properties) {
+        this.properties = properties;
+    }
 }
index ea56e60..769f32c 100644 (file)
@@ -16,7 +16,6 @@
  *  SPDX-License-Identifier: Apache-2.0
  *  ============LICENSE_END=========================================================
  */
-
 package org.openecomp.sdc.be.tosca.model;
 
 import java.util.LinkedHashMap;
@@ -86,8 +85,6 @@ public class ToscaAttribute {
         if (getStatus() != null) {
             toscaAttributeAsMap.put(ToscaTagNamesEnum.STATUS.getElementName(), getStatus());
         }
-
         return toscaAttributeAsMap;
     }
-
 }
index d26fd04..8a748ed 100644 (file)
@@ -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.
@@ -17,7 +17,6 @@
  * limitations under the License.
  * ============LICENSE_END=========================================================
  */
-
 package org.openecomp.sdc.be.tosca.model;
 
 import java.util.List;
@@ -27,13 +26,13 @@ public class ToscaCapability {
 
     private String type;
     private String description;
-
     private List<Object> occurrences;
-
     private List<String> valid_source_types;
-
     private Map<String, ToscaProperty> properties;
 
+    public ToscaCapability() {
+    }
+
     public List<String> getValid_source_types() {
         return valid_source_types;
     }
@@ -42,9 +41,6 @@ public class ToscaCapability {
         this.valid_source_types = valid_source_types;
     }
 
-    public ToscaCapability() {
-    }
-
     public String getType() {
         return type;
     }
@@ -76,5 +72,4 @@ public class ToscaCapability {
     public void setProperties(Map<String, ToscaProperty> properties) {
         this.properties = properties;
     }
-
 }
index 8a4ec7c..a84ef02 100644 (file)
@@ -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.
@@ -17,7 +17,6 @@
  * limitations under the License.
  * ============LICENSE_END=========================================================
  */
-
 package org.openecomp.sdc.be.tosca.model;
 
 import java.util.Map;
index 605d41e..c7763e6 100644 (file)
@@ -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.
  * limitations under the License.
  * ============LICENSE_END=========================================================
  */
-
 package org.openecomp.sdc.be.tosca.model;
 
 import java.util.List;
 import java.util.Map;
 
 public class ToscaGroupTemplate {
+
     private String type;
     private List<String> members;
     private IToscaMetadata metadata;
     private Map<String, Object> properties;
     private Map<String, ToscaTemplateCapability> capabilities;
-    
-    public ToscaGroupTemplate(String type, List<String> members, IToscaMetadata metadata, Map<String, Object> properties, Map<String, ToscaTemplateCapability> capabilities) {
-               this.type = type;
-               this.members = members;
-               this.metadata = metadata;
-               this.properties = properties;
-               this.capabilities = capabilities;
-       }
-    
+
+    public ToscaGroupTemplate(String type, List<String> members, IToscaMetadata metadata, Map<String, Object> properties,
+                              Map<String, ToscaTemplateCapability> capabilities) {
+        this.type = type;
+        this.members = members;
+        this.metadata = metadata;
+        this.properties = properties;
+        this.capabilities = capabilities;
+    }
+
     public ToscaGroupTemplate(String type, IToscaMetadata metadata, Map<String, Object> properties) {
-               this.type = type;
-               this.metadata = metadata;
-               this.properties = properties;
-       }
-    
-    
+        this.type = type;
+        this.metadata = metadata;
+        this.properties = properties;
+    }
 
-       public String getType() {
+    public String getType() {
         return type;
     }
 
@@ -77,13 +76,12 @@ public class ToscaGroupTemplate {
     public void setProperties(Map<String, Object> properties) {
         this.properties = properties;
     }
-    
-       public Map<String, ToscaTemplateCapability> getCapabilities() {
-               return capabilities;
-       }
 
-       public void setCapabilities(Map<String, ToscaTemplateCapability> capabilities) {
-               this.capabilities = capabilities;
-       }
+    public Map<String, ToscaTemplateCapability> getCapabilities() {
+        return capabilities;
+    }
 
+    public void setCapabilities(Map<String, ToscaTemplateCapability> capabilities) {
+        this.capabilities = capabilities;
+    }
 }
index c4eba4f..a06f67c 100644 (file)
@@ -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.
  * limitations under the License.
  * ============LICENSE_END=========================================================
  */
-
 package org.openecomp.sdc.be.tosca.model;
 
 import java.util.HashMap;
 import java.util.Map;
 
 public class ToscaInput extends ToscaProperty {
-    private  Map<String,ToscaAnnotation> annotations;
+
+    private Map<String, ToscaAnnotation> annotations;
 
     //copy constructor
-    public ToscaInput(ToscaProperty toscaProperty){
+    public ToscaInput(ToscaProperty toscaProperty) {
         super(toscaProperty);
     }
 
-
     public Map<String, ToscaAnnotation> getAnnotations() {
         return annotations;
     }
@@ -39,12 +38,11 @@ public class ToscaInput extends ToscaProperty {
     public void setAnnotations(Map<String, ToscaAnnotation> annotations) {
         this.annotations = annotations;
     }
-    public void addAnnotation(String name, ToscaAnnotation annotaion){
-        if ( annotations == null ){
+
+    public void addAnnotation(String name, ToscaAnnotation annotaion) {
+        if (annotations == null) {
             annotations = new HashMap<>();
         }
         annotations.put(name, annotaion);
-
-
     }
 }
index 89e0b07..d76c2d2 100644 (file)
@@ -22,54 +22,50 @@ import java.util.Objects;
  * @author KATYR
  * @since March 26, 2018
  */
-
 public class ToscaInterfaceNodeType {
 
-  private String derived_from;
-  private String description;
-  private Map<String, Object> operations;
-
-
-  public String getDerived_from() {
-    return derived_from;
-  }
+    private String derived_from;
+    private String description;
+    private Map<String, Object> operations;
 
-  public void setDerived_from(String derived_from) {
-    this.derived_from = derived_from;
-  }
-
-  public String getDescription() {
-    return description;
-  }
+    public String getDerived_from() {
+        return derived_from;
+    }
 
-  public void setDescription(String description) {
-    this.description = description;
-  }
+    public void setDerived_from(String derived_from) {
+        this.derived_from = derived_from;
+    }
 
-  @Override
-  public boolean equals(Object o) {
-    if (this == o) {
-      return true;
+    public String getDescription() {
+        return description;
     }
-    if (o == null || getClass() != o.getClass()) {
-      return false;
+
+    public void setDescription(String description) {
+        this.description = description;
     }
-    ToscaInterfaceNodeType that = (ToscaInterfaceNodeType) o;
-    return Objects.equals(derived_from, that.derived_from) &&
-        Objects.equals(description, that.description);
-  }
 
-  @Override
-  public int hashCode() {
+    @Override
+    public boolean equals(Object o) {
+        if (this == o) {
+            return true;
+        }
+        if (o == null || getClass() != o.getClass()) {
+            return false;
+        }
+        ToscaInterfaceNodeType that = (ToscaInterfaceNodeType) o;
+        return Objects.equals(derived_from, that.derived_from) && Objects.equals(description, that.description);
+    }
 
-    return Objects.hash(derived_from, description);
-  }
+    @Override
+    public int hashCode() {
+        return Objects.hash(derived_from, description);
+    }
 
-  public Map<String, Object> getOperations() {
-    return operations;
-  }
+    public Map<String, Object> getOperations() {
+        return operations;
+    }
 
-  public void setOperations(Map<String, Object> operations) {
-    this.operations = operations;
-  }
+    public void setOperations(Map<String, Object> operations) {
+        this.operations = operations;
+    }
 }
index f801ac0..f35cab2 100644 (file)
@@ -13,7 +13,6 @@
  * See the License for the specific language governing permissions and
  * limitations under the License.
  */
-
 package org.openecomp.sdc.be.tosca.model;
 
 import java.util.Map;
@@ -23,14 +22,12 @@ import java.util.Objects;
  * @author KATYR
  * @since March 26, 2018
  */
-
 public class ToscaLifecycleOperationDefinition {
 
     private String description;
     private String implementation;
     private Map<String, ToscaProperty> inputs;
 
-
     public String getImplementation() {
         return implementation;
     }
@@ -47,7 +44,6 @@ public class ToscaLifecycleOperationDefinition {
         this.inputs = inputs;
     }
 
-
     @Override
     public boolean equals(Object o) {
         if (this == o) {
@@ -62,7 +58,6 @@ public class ToscaLifecycleOperationDefinition {
 
     @Override
     public int hashCode() {
-
         return Objects.hash(implementation, inputs);
     }
 
index f496994..97dab36 100644 (file)
@@ -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.
  * limitations under the License.
  * ============LICENSE_END=========================================================
  */
-
 package org.openecomp.sdc.be.tosca.model;
 
 public class ToscaMetadata implements IToscaMetadata {
+
     private String invariantUUID;
     private String UUID;
     private String customizationUUID;
@@ -45,7 +45,6 @@ public class ToscaMetadata implements IToscaMetadata {
     private String sourceModelUuid;
     private String serviceFunction;
 
-
     public String getName() {
         return name;
     }
@@ -141,6 +140,10 @@ public class ToscaMetadata implements IToscaMetadata {
         return serviceRole;
     }
 
+    public void setServiceRole(String serviceRole) {
+        this.serviceRole = serviceRole;
+    }
+
     public String getServiceFunction() {
         return serviceFunction;
     }
@@ -149,16 +152,12 @@ public class ToscaMetadata implements IToscaMetadata {
         this.serviceFunction = serviceFunction;
     }
 
-    public void setInstantiationType(String instantiationType) {
-        this.instantiationType = instantiationType;
-    }
-
     public String getInstantiationType() {
         return instantiationType;
     }
 
-    public void setServiceRole(String serviceRole) {
-        this.serviceRole = serviceRole;
+    public void setInstantiationType(String instantiationType) {
+        this.instantiationType = instantiationType;
     }
 
     public Boolean isEcompGeneratedNaming() {
@@ -166,7 +165,7 @@ public class ToscaMetadata implements IToscaMetadata {
     }
 
     public void setEcompGeneratedNaming(Boolean ecompGeneratedNaming) {
-       this.ecompGeneratedNaming = ecompGeneratedNaming == null ? null : ecompGeneratedNaming.toString();
+        this.ecompGeneratedNaming = ecompGeneratedNaming == null ? null : ecompGeneratedNaming.toString();
     }
 
     public String isNamingPolicy() {
@@ -182,7 +181,7 @@ public class ToscaMetadata implements IToscaMetadata {
     }
 
     public void setServiceEcompNaming(Boolean serviceEcompNaming) {
-       this.serviceEcompNaming = serviceEcompNaming == null ? null : serviceEcompNaming.toString();
+        this.serviceEcompNaming = serviceEcompNaming == null ? null : serviceEcompNaming.toString();
     }
 
     public String getVersion() {
index 50a8f3d..e65d9a2 100644 (file)
  * limitations under the License.
  * ============LICENSE_END=========================================================
  */
-
 package org.openecomp.sdc.be.tosca.model;
 
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
 import lombok.Getter;
 import lombok.NoArgsConstructor;
 import lombok.Setter;
 import org.apache.commons.collections.CollectionUtils;
 import org.apache.commons.collections.MapUtils;
 
-import java.util.HashMap;
-import java.util.List;
-import java.util.Map;
-
 @Getter
 @Setter
 @NoArgsConstructor
@@ -54,7 +52,6 @@ public class ToscaNodeTemplate {
         if (MapUtils.isEmpty(this.interfaces)) {
             this.interfaces = new HashMap<>();
         }
-
         this.interfaces.put(interfaceName, interfaceDataDefinition);
     }
 }
index c43486f..cc3c57c 100644 (file)
@@ -17,7 +17,6 @@
  * limitations under the License.
  * ============LICENSE_END=========================================================
  */
-
 package org.openecomp.sdc.be.tosca.model;
 
 import java.util.List;
@@ -34,12 +33,9 @@ public class ToscaNodeType {
     private ToscaMetadata metadata;
     private String derived_from;
     private String description;
-
     private Map<String, ToscaProperty> properties;
     private Map<String, Object> interfaces;
     private Map<String, ToscaCapability> capabilities;
-
     private List<Map<String, ToscaRequirement>> requirements;
     private Map<String, ToscaAttribute> attributes;
-
 }
index 2aba850..d7f918d 100644 (file)
@@ -16,7 +16,6 @@
  *  SPDX-License-Identifier: Apache-2.0
  *  ============LICENSE_END=========================================================
  */
-
 package org.openecomp.sdc.be.tosca.model;
 
 import java.util.Map;
@@ -30,5 +29,4 @@ public class ToscaOperationAssignment {
     private String description;
     private String implementation;
     private Map<String, ToscaPropertyAssignment> inputs;
-
 }
index 826c7fc..90e2374 100644 (file)
@@ -16,7 +16,6 @@
  *  SPDX-License-Identifier: Apache-2.0
  *  ============LICENSE_END=========================================================
  */
-
 package org.openecomp.sdc.be.tosca.model;
 
 public class ToscaOutput extends ToscaProperty {
@@ -28,5 +27,4 @@ public class ToscaOutput extends ToscaProperty {
         this.setDescription(toscaAttribute.getStatus());
         this.setValue(toscaAttribute.getValue());
     }
-
 }
index 5d8f200..18f2b7f 100644 (file)
@@ -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.
  * limitations under the License.
  * ============LICENSE_END=========================================================
  */
-
 package org.openecomp.sdc.be.tosca.model;
 
 import java.util.List;
 import java.util.Map;
 
 public class ToscaPolicyTemplate {
-       private String type;
+
+    private String type;
     private IToscaMetadata metadata;
     private Map<String, Object> properties;
     private List<String> targets;
-    
+
     public ToscaPolicyTemplate(String type, IToscaMetadata metadata, Map<String, Object> properties, List<String> targets) {
-               this.type = type;
-               this.metadata = metadata;
-               this.properties = properties;
-               this.targets = targets;
-       }
+        this.type = type;
+        this.metadata = metadata;
+        this.properties = properties;
+        this.targets = targets;
+    }
 
-       public String getType() {
+    public String getType() {
         return type;
     }
 
@@ -60,14 +60,11 @@ public class ToscaPolicyTemplate {
         this.properties = properties;
     }
 
-       public List<String> getTargets() {
-               return targets;
-       }
+    public List<String> getTargets() {
+        return targets;
+    }
 
-       public void setTargets(List<String> targets) {
-               this.targets = targets;
-       }
-    
-    
-    
+    public void setTargets(List<String> targets) {
+        this.targets = targets;
+    }
 }
index fb5c544..f6e74c9 100644 (file)
@@ -17,7 +17,6 @@
  * limitations under the License.
  * ============LICENSE_END=========================================================
  */
-
 package org.openecomp.sdc.be.tosca.model;
 
 import java.util.List;
@@ -73,5 +72,4 @@ public class ToscaProperty {
     public void setDefaultp(Object defaultp) {
         this._defaultp_ = defaultp;
     }
-
 }
index f42b655..44eb209 100644 (file)
@@ -16,7 +16,6 @@
  *  SPDX-License-Identifier: Apache-2.0
  *  ============LICENSE_END=========================================================
  */
-
 package org.openecomp.sdc.be.tosca.model;
 
 import lombok.Getter;
@@ -27,5 +26,4 @@ import lombok.Setter;
 public class ToscaPropertyAssignment {
 
     private Object value;
-
 }
index 2faceb3..ab11373 100644 (file)
@@ -16,7 +16,6 @@
  *  SPDX-License-Identifier: Apache-2.0
  *  ============LICENSE_END=========================================================
  */
-
 package org.openecomp.sdc.be.tosca.model;
 
 import org.openecomp.sdc.be.model.tosca.constraints.ConstraintType;
@@ -27,5 +26,4 @@ import org.openecomp.sdc.be.model.tosca.constraints.ConstraintType;
 public interface ToscaPropertyConstraint {
 
     ConstraintType getConstraintType();
-
 }
index a07f681..e7bade9 100644 (file)
@@ -16,7 +16,6 @@
  *  SPDX-License-Identifier: Apache-2.0
  *  ============LICENSE_END=========================================================
  */
-
 package org.openecomp.sdc.be.tosca.model;
 
 import java.util.List;
@@ -45,7 +44,6 @@ public class ToscaPropertyConstraintValidValues implements ToscaPropertyConstrai
         if ("validValues".equals(attributeName)) {
             return "valid_values";
         }
-
         return attributeName;
     }
 
index 49286ca..91b9869 100644 (file)
@@ -16,7 +16,6 @@
  *  SPDX-License-Identifier: Apache-2.0
  *  ============LICENSE_END=========================================================
  */
-
 package org.openecomp.sdc.be.tosca.model;
 
 import java.util.Map;
index f42effa..1ef3cfd 100644 (file)
@@ -16,7 +16,6 @@
  *  SPDX-License-Identifier: Apache-2.0
  *  ============LICENSE_END=========================================================
  */
-
 package org.openecomp.sdc.be.tosca.model;
 
 import java.util.Map;
index c8e0527..79cbb5d 100644 (file)
@@ -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.
@@ -17,7 +17,6 @@
  * limitations under the License.
  * ============LICENSE_END=========================================================
  */
-
 package org.openecomp.sdc.be.tosca.model;
 
 import java.util.List;
@@ -29,5 +28,4 @@ import lombok.Setter;
 public class ToscaRequirement extends ToscaTemplateRequirement {
 
     private List<Object> occurrences;
-
 }
index d02e9da..a88f82c 100644 (file)
@@ -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.
@@ -17,7 +17,6 @@
  * limitations under the License.
  * ============LICENSE_END=========================================================
  */
-
 package org.openecomp.sdc.be.tosca.model;
 
 import lombok.Getter;
@@ -26,6 +25,7 @@ import lombok.Setter;
 @Getter
 @Setter
 public class ToscaSchemaDefinition {
+
     private String type;
     private String description;
 }
index 7fc60d1..f60b22c 100644 (file)
@@ -17,7 +17,6 @@
  * limitations under the License.
  * ============LICENSE_END=========================================================
  */
-
 package org.openecomp.sdc.be.tosca.model;
 
 import java.util.List;
@@ -43,6 +42,4 @@ public class ToscaTemplate {
     public ToscaTemplate(final String toscaDefinitionsVersion) {
         this.tosca_definitions_version = toscaDefinitionsVersion;
     }
-
 }
-
index 58432ba..894a806 100644 (file)
@@ -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.
@@ -17,7 +17,6 @@
  * limitations under the License.
  * ============LICENSE_END=========================================================
  */
-
 package org.openecomp.sdc.be.tosca.model;
 
 import lombok.Getter;
@@ -29,5 +28,4 @@ public class ToscaTemplateArtifact {
 
     private String file;
     private String type;
-
 }
index 4ec457a..2375af7 100644 (file)
@@ -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.
  * limitations under the License.
  * ============LICENSE_END=========================================================
  */
-
 package org.openecomp.sdc.be.tosca.model;
 
 import java.util.List;
 import java.util.Map;
 
 public class ToscaTemplateCapability {
+
     private List<String> validSourceTypes;
     private Map<String, Object> properties;
 
@@ -42,5 +42,4 @@ public class ToscaTemplateCapability {
     public void setProperties(Map<String, Object> properties) {
         this.properties = properties;
     }
-
 }
index 85d01e1..ffbf28b 100644 (file)
@@ -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.
@@ -17,7 +17,6 @@
  * limitations under the License.
  * ============LICENSE_END=========================================================
  */
-
 package org.openecomp.sdc.be.tosca.model;
 
 import lombok.Getter;
@@ -27,6 +26,7 @@ import org.openecomp.sdc.exception.InvalidArgumentException;
 @Getter
 @Setter
 public class ToscaTemplateRequirement {
+
     private String capability;
     private String node;
     private Object relationship;
@@ -49,22 +49,22 @@ public class ToscaTemplateRequirement {
             return;
         }
         if (!(relationship instanceof ToscaRelationship) && !(relationship instanceof String)) {
-            throw new InvalidArgumentException(String.format("relationship %s type not expected. "
-                + "Supported types are %s and %s", relationship.getClass(), ToscaRelationship.class, String.class));
+            throw new InvalidArgumentException(String
+                .format("relationship %s type not expected. " + "Supported types are %s and %s", relationship.getClass(), ToscaRelationship.class,
+                    String.class));
         }
         this.relationship = relationship;
     }
 
     /**
      * Checks if the relationship entry is a complex type ({@link ToscaRelationship}).
-     *
-     * The relationship can be a simple notation (string) (see Tosca 1.3, Section 3.7.3.2.2), or a multi-line grammar
-     * notation (complex) (see Tosca 1.3, Section 3.7.3.2.3).
+     * <p>
+     * The relationship can be a simple notation (string) (see Tosca 1.3, Section 3.7.3.2.2), or a multi-line grammar notation (complex) (see Tosca
+     * 1.3, Section 3.7.3.2.3).
      *
      * @return {@code true} if the relationship is a complex type, {@code false} otherwise
      */
     public boolean isRelationshipComplexNotation() {
         return relationship instanceof ToscaRelationship;
     }
-
 }
index 3cecbc2..a2dc509 100644 (file)
@@ -17,7 +17,6 @@
  * limitations under the License.
  * ============LICENSE_END=========================================================
  */
-
 package org.openecomp.sdc.be.tosca.model;
 
 import java.util.HashMap;
index 198e233..2c67f3e 100644 (file)
@@ -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.
@@ -17,7 +17,6 @@
  * limitations under the License.
  * ============LICENSE_END=========================================================
  */
-
 package org.openecomp.sdc.be.tosca.model;
 
 public class VfModuleToscaMetadata implements IToscaMetadata {
@@ -71,5 +70,4 @@ public class VfModuleToscaMetadata implements IToscaMetadata {
     public void setCustomizationUUID(String customizationUUID) {
         this.vfModuleModelCustomizationUUID = customizationUUID;
     }
-
 }
index 1d40de3..b668ae7 100644 (file)
@@ -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.
  * limitations under the License.
  * ============LICENSE_END=========================================================
  */
-
 package org.openecomp.sdc.be.tosca.utils;
 
 import fj.data.Either;
+import java.util.ArrayList;
+import java.util.Collection;
+import java.util.Collections;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+import java.util.Objects;
+import java.util.Optional;
 import org.apache.commons.collections.MapUtils;
 import org.openecomp.sdc.be.datatypes.elements.ForwardingPathDataDefinition;
 import org.openecomp.sdc.be.datatypes.elements.ForwardingPathElementDataDefinition;
@@ -33,39 +40,26 @@ import org.openecomp.sdc.be.tosca.CapabilityRequirementConverter;
 import org.openecomp.sdc.be.tosca.model.ToscaNodeTemplate;
 import org.openecomp.sdc.be.tosca.model.ToscaTemplateRequirement;
 
-import java.util.ArrayList;
-import java.util.Collection;
-import java.util.Collections;
-import java.util.HashMap;
-import java.util.List;
-import java.util.Map;
-import java.util.Objects;
-import java.util.Optional;
-
 /**
  * @author KATYR
  * @since November 19, 2017
  */
-
 public class ForwardingPathToscaUtil {
-    public static final String FORWARDS_TO_TOSCA_NAME =
-            "org.openecomp.relationships.ForwardsTo";
+
+    public static final String FORWARDS_TO_TOSCA_NAME = "org.openecomp.relationships.ForwardsTo";
     public static final String PROTOCOL = "protocol";
     public static final String PORTS_RANGE = "target_range";
     public static final String FORWARDER = "forwarder";
 
-    public static void addForwardingPaths(Service service, Map<String, ToscaNodeTemplate>
-            nodeTemplates, CapabilityRequirementConverter capabiltyRequirementConvertor, Map<String, Component> originComponents, ToscaOperationFacade toscaOperationFacade) {
+    public static void addForwardingPaths(Service service, Map<String, ToscaNodeTemplate> nodeTemplates,
+                                          CapabilityRequirementConverter capabiltyRequirementConvertor, Map<String, Component> originComponents,
+                                          ToscaOperationFacade toscaOperationFacade) {
         for (String forwardingPathName : service.getForwardingPaths().keySet()) {
-            ToscaNodeTemplate forwardingPathNodeTemplate =
-                    new ToscaNodeTemplate();
-            final ForwardingPathDataDefinition path =
-                    service.getForwardingPaths().get(forwardingPathName);
+            ToscaNodeTemplate forwardingPathNodeTemplate = new ToscaNodeTemplate();
+            final ForwardingPathDataDefinition path = service.getForwardingPaths().get(forwardingPathName);
             forwardingPathNodeTemplate.setType(path.getToscaResourceName());
-
             if (Objects.nonNull(path.getDescription())) {
-                forwardingPathNodeTemplate.setDescription(path
-                        .getDescription());
+                forwardingPathNodeTemplate.setDescription(path.getDescription());
             }
             Map<String, Object> props = new HashMap<>();
             if (Objects.nonNull(path.getDestinationPortNumber())) {
@@ -77,31 +71,29 @@ public class ForwardingPathToscaUtil {
             if (MapUtils.isNotEmpty(props)) {
                 forwardingPathNodeTemplate.setProperties(props);
             }
-
-            final List<ForwardingPathElementDataDefinition> pathElements =
-                    path.getPathElements()
-                            .getListToscaDataDefinition();
-            forwardingPathNodeTemplate.setRequirements(convertPathElementsToRequirements(pathElements,
-                    service, capabiltyRequirementConvertor, originComponents, toscaOperationFacade));
-
+            final List<ForwardingPathElementDataDefinition> pathElements = path.getPathElements().getListToscaDataDefinition();
+            forwardingPathNodeTemplate.setRequirements(
+                convertPathElementsToRequirements(pathElements, service, capabiltyRequirementConvertor, originComponents, toscaOperationFacade));
             nodeTemplates.put(path.getName(), forwardingPathNodeTemplate);
         }
-
     }
 
     private static List<Map<String, ToscaTemplateRequirement>> convertPathElementsToRequirements(
-            List<ForwardingPathElementDataDefinition> pathElements, Service service, CapabilityRequirementConverter capabiltyRequirementConvertor, Map<String, Component> originComponents, ToscaOperationFacade toscaOperationFacade) {
+        List<ForwardingPathElementDataDefinition> pathElements, Service service, CapabilityRequirementConverter capabiltyRequirementConvertor,
+        Map<String, Component> originComponents, ToscaOperationFacade toscaOperationFacade) {
         List<Map<String, ToscaTemplateRequirement>> toscaRequirements = new ArrayList<>();
-        for (int i = 0; i <= pathElements.size() -1 ; i++) {
-                final ForwardingPathElementDataDefinition element = pathElements.get(i);
-                toscaRequirements.add(handleSingleReq(fetchCPName(service, element.getFromNode(), element.getFromCP(), capabiltyRequirementConvertor, originComponents, toscaOperationFacade), fetchNodeName(service, element.getFromNode())));
-                if ( i == pathElements.size() -1) {
-                    toscaRequirements.add(handleSingleReq(fetchCPName(service, element.getToNode(), element.getToCP(), capabiltyRequirementConvertor, originComponents, toscaOperationFacade), fetchNodeName(service, element
-                            .getToNode())));
-                }
-       }
+        for (int i = 0; i <= pathElements.size() - 1; i++) {
+            final ForwardingPathElementDataDefinition element = pathElements.get(i);
+            toscaRequirements.add(handleSingleReq(
+                fetchCPName(service, element.getFromNode(), element.getFromCP(), capabiltyRequirementConvertor, originComponents,
+                    toscaOperationFacade), fetchNodeName(service, element.getFromNode())));
+            if (i == pathElements.size() - 1) {
+                toscaRequirements.add(handleSingleReq(
+                    fetchCPName(service, element.getToNode(), element.getToCP(), capabiltyRequirementConvertor, originComponents,
+                        toscaOperationFacade), fetchNodeName(service, element.getToNode())));
+            }
+        }
         return toscaRequirements;
-
     }
 
     private static String fetchNodeName(Service service, String nodeId) {
@@ -112,40 +104,38 @@ public class ForwardingPathToscaUtil {
         }
     }
 
-
-    private static Map<String, ToscaTemplateRequirement> handleSingleReq(
-            String fromCP, String fromNode) {
+    private static Map<String, ToscaTemplateRequirement> handleSingleReq(String fromCP, String fromNode) {
         Map<String, ToscaTemplateRequirement> toscaReqMap = new HashMap<>();
         ToscaTemplateRequirement firstReq = new ToscaTemplateRequirement();
         firstReq.setRelationship(FORWARDS_TO_TOSCA_NAME); //todo
         firstReq.setCapability(fromCP);
         firstReq.setNode(fromNode);
         toscaReqMap.put(FORWARDER, firstReq);
-
         return toscaReqMap;
     }
 
     /**
      * @todo handle errors.
      */
-    private static String fetchCPName(Service service, String nodeID, String cpName, CapabilityRequirementConverter capabiltyRequirementConvertor, Map<String, Component> originComponents, ToscaOperationFacade toscaOperationFacade) {
+    private static String fetchCPName(Service service, String nodeID, String cpName, CapabilityRequirementConverter capabiltyRequirementConvertor,
+                                      Map<String, Component> originComponents, ToscaOperationFacade toscaOperationFacade) {
         Optional<ComponentInstance> componentInstance = service.getComponentInstanceByName(nodeID);
         ComponentInstance componentInstanceVal = componentInstance.get();
         String name = componentInstanceVal.getNormalizedName();
         Component component = originComponents.get(componentInstanceVal.getComponentUid());
-        if(componentInstanceVal.getIsProxy()){
+        if (componentInstanceVal.getIsProxy()) {
             component = originComponents.get(componentInstanceVal.getSourceModelUid());
             if (component == null) {
                 component = toscaOperationFacade.getToscaFullElement(componentInstanceVal.getSourceModelUid()).left().value();
             }
-
         }
         CapabilityDefinition capability = componentInstanceVal.getCapabilities().values().stream().flatMap(Collection::stream)
-                .filter(capabilityDefinition -> capabilityDefinition.getName().equals(cpName)).findAny().get();
+            .filter(capabilityDefinition -> capabilityDefinition.getName().equals(cpName)).findAny().get();
         List<String> path = capability.getPath();
         List<String> reducedPath = new ArrayList<>(path);
         reducedPath.remove(reducedPath.size() - 1);
-        Either<String, Boolean> stringBooleanEither = capabiltyRequirementConvertor.buildSubstitutedName(originComponents, component, reducedPath, capability.getName(), null);
+        Either<String, Boolean> stringBooleanEither = capabiltyRequirementConvertor
+            .buildSubstitutedName(originComponents, component, reducedPath, capability.getName(), null);
         return name + "." + stringBooleanEither.left().value();
     }
 }
index 475627b..55de9e5 100644 (file)
@@ -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.
  * limitations under the License.
  * ============LICENSE_END=========================================================
  */
-
 package org.openecomp.sdc.be.tosca.utils;
 
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
 import org.openecomp.sdc.be.datatypes.elements.Annotation;
 import org.openecomp.sdc.be.model.DataTypeDefinition;
 import org.openecomp.sdc.be.model.InputDefinition;
@@ -29,16 +31,13 @@ import org.openecomp.sdc.be.tosca.model.ToscaAnnotation;
 import org.openecomp.sdc.be.tosca.model.ToscaInput;
 import org.openecomp.sdc.be.tosca.model.ToscaProperty;
 import org.openecomp.sdc.common.log.wrappers.Logger;
-
-import java.util.HashMap;
-import java.util.List;
-import java.util.Map;
 import org.springframework.beans.factory.annotation.Autowired;
 
 @org.springframework.stereotype.Component
 public class InputConverter {
-    private PropertyConvertor propertyConvertor;
+
     private static final Logger log = Logger.getLogger(ToscaExportHandler.class);
+    private PropertyConvertor propertyConvertor;
 
     @Autowired
     public InputConverter(PropertyConvertor propertyConvertor) {
@@ -56,15 +55,13 @@ public class InputConverter {
      *              type
      *              description
      *              list of properties */
-    public Map<String, ToscaProperty>  convertInputs( List<InputDefinition> inputDef,Map<String, DataTypeDefinition> dataTypes) {
+    public Map<String, ToscaProperty> convertInputs(List<InputDefinition> inputDef, Map<String, DataTypeDefinition> dataTypes) {
         log.debug("convert inputs to to tosca  ");
-
         Map<String, ToscaProperty> inputs = new HashMap<>();
         if (inputDef != null) {
             inputDef.forEach(i -> {
                 //Extract input the same as property
-                ToscaProperty toscaProperty = propertyConvertor.convertProperty(dataTypes, i,
-                    PropertyConvertor.PropertyType.INPUT);
+                ToscaProperty toscaProperty = propertyConvertor.convertProperty(dataTypes, i, PropertyConvertor.PropertyType.INPUT);
                 //now that we have Tosca property we create new object called tosca input which drives from it
                 ToscaInput toscaInput = new ToscaInput(toscaProperty);
                 List<Annotation> annotations = i.getAnnotations();
@@ -88,7 +85,7 @@ public class InputConverter {
                 if (inputAnnotation.getProperties() != null) {
                     Map<String, Object> properties = new HashMap<>();
                     inputAnnotation.getProperties().forEach(k -> {
-                        propertyConvertor.convertAndAddValue(dataTypes,properties,k, k::getValue);
+                        propertyConvertor.convertAndAddValue(dataTypes, properties, k, k::getValue);
                     });
                     annotation.setProperties(properties);
                 }
@@ -97,6 +94,3 @@ public class InputConverter {
         }
     }
 }
-
-
-
index eda8cef..d2c0693 100644 (file)
  *  SPDX-License-Identifier: Apache-2.0
  *  ============LICENSE_END=========================================================
  */
-
 package org.openecomp.sdc.be.tosca.utils;
 
 public class InterfaceTypesNameUtil {
 
     private InterfaceTypesNameUtil() {
-
     }
 
     /**
-     * Build the short name of an interface_type by grabbing the final name in its path. E.g.
-     * "tosca.interfaces.relationship.Configure" will be shortened to "Configure".
+     * Build the short name of an interface_type by grabbing the final name in its path. E.g. "tosca.interfaces.relationship.Configure" will be
+     * shortened to "Configure".
      *
      * @param interfaceName the full interface name
      * @return the shortened name of the interface
@@ -39,5 +37,4 @@ public class InterfaceTypesNameUtil {
         final int index = interfaceName.lastIndexOf('.');
         return index > 0 && interfaceName.length() > index + 1 ? interfaceName.substring(index + 1) : interfaceName;
     }
-
 }
index 3ad5022..cd1a1c6 100644 (file)
@@ -13,7 +13,6 @@
  * See the License for the specific language governing permissions and
  * limitations under the License.
  */
-
 package org.openecomp.sdc.be.tosca.utils;
 
 import java.util.ArrayList;
@@ -30,7 +29,6 @@ import org.openecomp.sdc.be.ui.model.UINodeFilter;
 
 public class NodeFilterConverter {
 
-
     public Map<String, UINodeFilter> convertDataMapToUI(Map<String, CINodeFilterDataDefinition> inMap) {
         return inMap.entrySet().stream().collect(Collectors.toMap(Map.Entry::getKey, o -> convertToUi(o.getValue())));
     }
@@ -38,39 +36,29 @@ public class NodeFilterConverter {
     public UINodeFilter convertToUi(final CINodeFilterDataDefinition inNodeFilter) {
         final UINodeFilter uiNodeFilter = new UINodeFilter();
         final ConstraintConvertor constraintConvertor = new ConstraintConvertor();
-        final ListDataDefinition<RequirementNodeFilterPropertyDataDefinition> nodeFilterProperties =
-            inNodeFilter.getProperties();
+        final ListDataDefinition<RequirementNodeFilterPropertyDataDefinition> nodeFilterProperties = inNodeFilter.getProperties();
         if (nodeFilterProperties != null && !nodeFilterProperties.isEmpty()) {
-            final List<UIConstraint> propertiesConstraint = nodeFilterProperties.getListToscaDataDefinition()
-                .stream()
-                .map(property -> property.getConstraints().iterator().next())
-                .map(constraintConvertor::convert)
-                .collect(Collectors.toList());
+            final List<UIConstraint> propertiesConstraint = nodeFilterProperties.getListToscaDataDefinition().stream()
+                .map(property -> property.getConstraints().iterator().next()).map(constraintConvertor::convert).collect(Collectors.toList());
             uiNodeFilter.setProperties(propertiesConstraint);
         }
-        final ListDataDefinition<RequirementNodeFilterCapabilityDataDefinition> nodeFilterCapabilities =
-            inNodeFilter.getCapabilities();
+        final ListDataDefinition<RequirementNodeFilterCapabilityDataDefinition> nodeFilterCapabilities = inNodeFilter.getCapabilities();
         if (nodeFilterCapabilities != null && !nodeFilterCapabilities.isEmpty()) {
             final List<UIConstraint> capabilitiesConstraint = new ArrayList<>();
-            nodeFilterCapabilities.getListToscaDataDefinition()
-                .forEach(requirementNodeFilterCapabilityDataDefinition ->
-                    convertCapabilityConstraint(requirementNodeFilterCapabilityDataDefinition, capabilitiesConstraint ));
-
+            nodeFilterCapabilities.getListToscaDataDefinition().forEach(
+                requirementNodeFilterCapabilityDataDefinition -> convertCapabilityConstraint(requirementNodeFilterCapabilityDataDefinition,
+                    capabilitiesConstraint));
             uiNodeFilter.setCapabilities(capabilitiesConstraint);
         }
-
         return uiNodeFilter;
     }
 
-    private void convertCapabilityConstraint(
-        final RequirementNodeFilterCapabilityDataDefinition requirementNodeFilterCapabilityDataDefinition,
-        final List<UIConstraint> capabilitiesConstraint) {
-
+    private void convertCapabilityConstraint(final RequirementNodeFilterCapabilityDataDefinition requirementNodeFilterCapabilityDataDefinition,
+                                             final List<UIConstraint> capabilitiesConstraint) {
         final UIConstraint uiConstraint = new UIConstraint();
         final ConstraintConvertor constraintConvertor = new ConstraintConvertor();
         uiConstraint.setCapabilityName(requirementNodeFilterCapabilityDataDefinition.getName());
-        requirementNodeFilterCapabilityDataDefinition.getProperties().getListToscaDataDefinition()
-            .forEach(property -> capabilitiesConstraint.add(constraintConvertor
-                .getUiConstraint(property.getConstraints().iterator().next(), uiConstraint)));
+        requirementNodeFilterCapabilityDataDefinition.getProperties().getListToscaDataDefinition().forEach(
+            property -> capabilitiesConstraint.add(constraintConvertor.getUiConstraint(property.getConstraints().iterator().next(), uiConstraint)));
     }
 }
index f6a7691..3a8bf43 100644 (file)
@@ -13,7 +13,6 @@
  * See the License for the specific language governing permissions and
  * limitations under the License.
  */
-
 package org.openecomp.sdc.be.tosca.utils;
 
 import java.io.File;
@@ -49,31 +48,28 @@ public class OperationArtifactUtil {
     }
 
     /**
-     * This method assumes that operation.getImplementation() is not NULL  ( it should be verified by the caller
-     * method)
+     * This method assumes that operation.getImplementation() is not NULL  ( it should be verified by the caller method)
      *
      * @param operation the specific operation name
      * @return the full path including file name for operation's artifacts
      */
-    public static String createOperationArtifactPath(Component component, ComponentInstance componentInstance,
-                                                     OperationDataDefinition operation, boolean isAssociatedComponent) {
+    public static String createOperationArtifactPath(Component component, ComponentInstance componentInstance, OperationDataDefinition operation,
+                                                     boolean isAssociatedComponent) {
         if (!(component instanceof Resource || component instanceof Service)) {
             return null;
         }
-
         if (isAssociatedComponent) {
             // Service Proxy is only in Node Template interface
             if (componentInstance != null) {
-                return createOperationArtifactPathInService(componentInstance.getToscaComponentName()
-                    + "_v" + componentInstance.getComponentVersion(), operation);
+                return createOperationArtifactPathInService(
+                    componentInstance.getToscaComponentName() + "_v" + componentInstance.getComponentVersion(), operation);
             }
             // Resource Instance is part of Node Type interface
             else {
-                ResourceMetadataDataDefinition resourceMetadataDataDefinition =
-                    (ResourceMetadataDataDefinition) component.getComponentMetadataDefinition()
-                        .getMetadataDataDefinition();
-                return createOperationArtifactPathInService(resourceMetadataDataDefinition.getToscaResourceName()
-                    + "_v" + component.getVersion(), operation);
+                ResourceMetadataDataDefinition resourceMetadataDataDefinition = (ResourceMetadataDataDefinition) component
+                    .getComponentMetadataDefinition().getMetadataDataDefinition();
+                return createOperationArtifactPathInService(resourceMetadataDataDefinition.getToscaResourceName() + "_v" + component.getVersion(),
+                    operation);
             }
         }
         return createOperationArtifactPathInComponent(operation);
@@ -82,40 +78,34 @@ public class OperationArtifactUtil {
     private static String createOperationArtifactPathInComponent(OperationDataDefinition operation) {
         final String implementationArtifactName = operation.getImplementation().getArtifactName();
         if (artifactNameIsALiteralValue(implementationArtifactName)) {
-            return implementationArtifactName.substring(1, implementationArtifactName.length()-1);
+            return implementationArtifactName.substring(1, implementationArtifactName.length() - 1);
         } else {
-            return CsarUtils.ARTIFACTS + File.separator + WordUtils
-                .capitalizeFully(ArtifactGroupTypeEnum.DEPLOYMENT.name())
-                + File.separator + ArtifactTypeEnum.WORKFLOW.getType() + File.separator + BPMN_ARTIFACT_PATH
-                + File.separator + implementationArtifactName;
+            return CsarUtils.ARTIFACTS + File.separator + WordUtils.capitalizeFully(ArtifactGroupTypeEnum.DEPLOYMENT.name()) + File.separator
+                + ArtifactTypeEnum.WORKFLOW.getType() + File.separator + BPMN_ARTIFACT_PATH + File.separator + implementationArtifactName;
         }
     }
 
     public static boolean artifactNameIsALiteralValue(final String artifactName) {
-        return (artifactName.startsWith(Constants.QUOTE) || artifactName.startsWith(Constants.ESCAPED_DOUBLE_QUOTE))
-            && (artifactName.endsWith(Constants.QUOTE) || artifactName.endsWith(Constants.ESCAPED_DOUBLE_QUOTE));
+        return (artifactName.startsWith(Constants.QUOTE) || artifactName.startsWith(Constants.ESCAPED_DOUBLE_QUOTE)) && (
+            artifactName.endsWith(Constants.QUOTE) || artifactName.endsWith(Constants.ESCAPED_DOUBLE_QUOTE));
     }
 
-    private static String createOperationArtifactPathInService(String toscaComponentName,
-                                                               OperationDataDefinition operation) {
-        return CsarUtils.ARTIFACTS + File.separator + toscaComponentName + File.separator +
-            WordUtils.capitalizeFully(ArtifactGroupTypeEnum.DEPLOYMENT.name()) + File.separator +
-            ArtifactTypeEnum.WORKFLOW.getType() + File.separator + BPMN_ARTIFACT_PATH + File.separator +
-            operation.getImplementation().getArtifactName();
+    private static String createOperationArtifactPathInService(String toscaComponentName, OperationDataDefinition operation) {
+        return CsarUtils.ARTIFACTS + File.separator + toscaComponentName + File.separator + WordUtils
+            .capitalizeFully(ArtifactGroupTypeEnum.DEPLOYMENT.name()) + File.separator + ArtifactTypeEnum.WORKFLOW.getType() + File.separator
+            + BPMN_ARTIFACT_PATH + File.separator + operation.getImplementation().getArtifactName();
     }
 
-    public static Map<String, ArtifactDefinition> getDistinctInterfaceOperationArtifactsByName(
-        Component originComponent) {
+    public static Map<String, ArtifactDefinition> getDistinctInterfaceOperationArtifactsByName(Component originComponent) {
         Map<String, ArtifactDefinition> distinctInterfaceArtifactsByName = new HashMap<>();
         Map<String, InterfaceDefinition> interfaces = originComponent.getInterfaces();
         if (MapUtils.isEmpty(interfaces)) {
             return distinctInterfaceArtifactsByName;
         }
         Map<String, ArtifactDefinition> interfaceArtifacts = interfaces.values().stream()
-            .flatMap(interfaceDefinition -> interfaceDefinition.getOperationsMap().values().stream())
-            .map(Operation::getImplementationArtifact).filter(Objects::nonNull)
-            .collect(Collectors.toMap(ArtifactDataDefinition::getUniqueId,
-                artifactDefinition -> artifactDefinition, (a1, a2) -> a1));
+            .flatMap(interfaceDefinition -> interfaceDefinition.getOperationsMap().values().stream()).map(Operation::getImplementationArtifact)
+            .filter(Objects::nonNull)
+            .collect(Collectors.toMap(ArtifactDataDefinition::getUniqueId, artifactDefinition -> artifactDefinition, (a1, a2) -> a1));
         if (MapUtils.isNotEmpty(interfaceArtifacts)) {
             Set<String> artifactNameSet = new HashSet<>();
             for (Map.Entry<String, ArtifactDefinition> interfaceArtifactEntry : interfaceArtifacts.entrySet()) {
@@ -123,13 +113,10 @@ public class OperationArtifactUtil {
                 if (artifactNameSet.contains(artifactName)) {
                     continue;
                 }
-                distinctInterfaceArtifactsByName.put(interfaceArtifactEntry.getKey(),
-                    interfaceArtifactEntry.getValue());
+                distinctInterfaceArtifactsByName.put(interfaceArtifactEntry.getKey(), interfaceArtifactEntry.getValue());
                 artifactNameSet.add(artifactName);
             }
-
         }
         return distinctInterfaceArtifactsByName;
     }
-
 }
index 1e7fc81..8f92034 100644 (file)
@@ -16,7 +16,6 @@
  *  SPDX-License-Identifier: Apache-2.0
  *  ============LICENSE_END=========================================================
  */
-
 package org.openecomp.sdc.be.tosca.utils;
 
 import java.util.Collections;
@@ -45,8 +44,8 @@ public class OutputConverter {
         this.attributeConverterProvider = attributeConverterProvider;
     }
 
-    public Map<String, ToscaProperty> convert(final List<OutputDefinition> outputDefinitionList,
-                                              final Map<String, DataTypeDefinition> dataTypes) throws ToscaConversionException {
+    public Map<String, ToscaProperty> convert(final List<OutputDefinition> outputDefinitionList, final Map<String, DataTypeDefinition> dataTypes)
+        throws ToscaConversionException {
         final AttributeConverter attributeConverter = this.attributeConverterProvider.getObject(dataTypes);
         final Map<String, ToscaProperty> outputMap = new HashMap<>();
         if (CollectionUtils.isEmpty(outputDefinitionList)) {
@@ -60,6 +59,3 @@ public class OutputConverter {
         return outputMap;
     }
 }
-
-
-
index d43ba43..c083099 100644 (file)
@@ -16,7 +16,6 @@
  *  SPDX-License-Identifier: Apache-2.0
  *  ============LICENSE_END=========================================================
  */
-
 package org.openecomp.sdc.be.tosca.utils;
 
 import java.util.Collections;
@@ -40,47 +39,35 @@ public class SubstitutionFilterConverter {
         if (!uiPropertyFilters.isEmpty()) {
             uiNodeFilter.setProperties(uiPropertyFilters);
         }
-
-        final List<UIConstraint> uiCapabilityFilters =
-            extractCapabilitiesFilter(inSubstitutionFilter, constraintConvertor);
+        final List<UIConstraint> uiCapabilityFilters = extractCapabilitiesFilter(inSubstitutionFilter, constraintConvertor);
         if (!uiCapabilityFilters.isEmpty()) {
             uiNodeFilter.setCapabilities(uiCapabilityFilters);
         }
-
         return uiNodeFilter;
     }
 
     private List<UIConstraint> extractPropertyFilter(final SubstitutionFilterDataDefinition substitutionFilter,
                                                      final ConstraintConvertor constraintConvertor) {
-        final ListDataDefinition<RequirementSubstitutionFilterPropertyDataDefinition> substitutionFilterProperties =
-            substitutionFilter.getProperties();
-        if (substitutionFilterProperties != null && !substitutionFilterProperties.isEmpty()
-            && CollectionUtils.isNotEmpty(substitutionFilterProperties.getListToscaDataDefinition())) {
-            return substitutionFilterProperties.getListToscaDataDefinition()
-                .stream()
-                .map(property -> property.getConstraints().iterator().next())
-                .map(constraintConvertor::convert)
-                .collect(Collectors.toList());
+        final ListDataDefinition<RequirementSubstitutionFilterPropertyDataDefinition> substitutionFilterProperties = substitutionFilter
+            .getProperties();
+        if (substitutionFilterProperties != null && !substitutionFilterProperties.isEmpty() && CollectionUtils
+            .isNotEmpty(substitutionFilterProperties.getListToscaDataDefinition())) {
+            return substitutionFilterProperties.getListToscaDataDefinition().stream().map(property -> property.getConstraints().iterator().next())
+                .map(constraintConvertor::convert).collect(Collectors.toList());
         }
-
         return Collections.emptyList();
     }
 
     private List<UIConstraint> extractCapabilitiesFilter(final SubstitutionFilterDataDefinition substitutionFilter,
                                                          final ConstraintConvertor constraintConvertor) {
-        final ListDataDefinition<RequirementSubstitutionFilterCapabilityDataDefinition> substitutionFilterCapabilities =
-            substitutionFilter.getCapabilities();
-        if (substitutionFilterCapabilities != null && !substitutionFilterCapabilities.isEmpty()
-            && CollectionUtils.isNotEmpty(substitutionFilterCapabilities.getListToscaDataDefinition())) {
-            return substitutionFilterCapabilities
-                .getListToscaDataDefinition()
-                .stream()
+        final ListDataDefinition<RequirementSubstitutionFilterCapabilityDataDefinition> substitutionFilterCapabilities = substitutionFilter
+            .getCapabilities();
+        if (substitutionFilterCapabilities != null && !substitutionFilterCapabilities.isEmpty() && CollectionUtils
+            .isNotEmpty(substitutionFilterCapabilities.getListToscaDataDefinition())) {
+            return substitutionFilterCapabilities.getListToscaDataDefinition().stream()
                 .map(capabilities -> capabilities.getProperties().getListToscaDataDefinition().iterator().next())
-                .map(property -> property.getConstraints().iterator().next())
-                .map(constraintConvertor::convert)
-                .collect(Collectors.toList());
+                .map(property -> property.getConstraints().iterator().next()).map(constraintConvertor::convert).collect(Collectors.toList());
         }
-
         return Collections.emptyList();
     }
 }
index 5e97ac6..51b3653 100644 (file)
  * See the License for the specific language governing permissions and
  * limitations under the License.
  */
-
 package org.openecomp.sdc.be.types;
 
 public class ServiceConsumptionData {
-  private String inputId;
-  private String source;
-  private String value;
-  private String type;
-
-  public String getInputId() {
-    return inputId;
-  }
-
-  public void setInputId(String inputId) {
-    this.inputId = inputId;
-  }
-
-  public String getSource() {
-    return source;
-  }
-
-  public void setSource(String source) {
-    this.source = source;
-  }
-
-  public String getValue() {
-    return value;
-  }
-
-  public void setValue(String value) {
-    this.value = value;
-  }
-
-  public String getType() {
-    return type;
-  }
-
-  public void setType(String type) {
-    this.type = type;
-  }
+
+    private String inputId;
+    private String source;
+    private String value;
+    private String type;
+
+    public String getInputId() {
+        return inputId;
+    }
+
+    public void setInputId(String inputId) {
+        this.inputId = inputId;
+    }
+
+    public String getSource() {
+        return source;
+    }
+
+    public void setSource(String source) {
+        this.source = source;
+    }
+
+    public String getValue() {
+        return value;
+    }
+
+    public void setValue(String value) {
+        this.value = value;
+    }
+
+    public String getType() {
+        return type;
+    }
+
+    public void setType(String type) {
+        this.type = type;
+    }
 }
index 9e297b7..bd6ae1e 100644 (file)
  * See the License for the specific language governing permissions and
  * limitations under the License.
  */
-
 package org.openecomp.sdc.be.types;
 
 import java.util.HashMap;
 import java.util.Map;
 
-public enum  ServiceConsumptionSource {
-  SERVICE_INPUT("ServiceInput"),
-  STATIC("Static");
-
-
-  private static Map<String, ServiceConsumptionSource> sourceToValue;
+public enum ServiceConsumptionSource {
+    SERVICE_INPUT("ServiceInput"), STATIC("Static");
+    private static Map<String, ServiceConsumptionSource> sourceToValue;
 
-  static {
-    sourceToValue = new HashMap<>();
-    for(ServiceConsumptionSource sourceName : ServiceConsumptionSource.values()) {
-      sourceToValue.put(sourceName.source, sourceName);
+    static {
+        sourceToValue = new HashMap<>();
+        for (ServiceConsumptionSource sourceName : ServiceConsumptionSource.values()) {
+            sourceToValue.put(sourceName.source, sourceName);
+        }
     }
-  }
 
-  private String source;
+    private String source;
 
-  ServiceConsumptionSource(String source) {
-    this.source = source;
-  }
+    ServiceConsumptionSource(String source) {
+        this.source = source;
+    }
 
-  public static ServiceConsumptionSource getSourceValue(String source) {
-    return sourceToValue.get(source);
-  }
+    public static ServiceConsumptionSource getSourceValue(String source) {
+        return sourceToValue.get(source);
+    }
 
-  public String getSource() {
-    return source;
-  }
+    public String getSource() {
+        return source;
+    }
 }
index c15c063..4274532 100644 (file)
@@ -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.
@@ -17,7 +17,6 @@
  * limitations under the License.
  * ============LICENSE_END=========================================================
  */
-
 package org.openecomp.sdc.be.user;
 
 /*
@@ -36,7 +35,3 @@ public enum Role {
         return null;
     }
 }
-
-
-
-
index f5b33be..4aa852c 100644 (file)
@@ -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.
  * limitations under the License.
  * ============LICENSE_END=========================================================
  */
-
 package org.openecomp.sdc.be.user;
 
 public enum UserAdminAction {
-
     ADD_USER, UPDATE_USER, DELET_USER
-
 }
index 589fdd8..758ac07 100644 (file)
@@ -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.
@@ -17,7 +17,6 @@
  * limitations under the License.
  * ============LICENSE_END=========================================================
  */
-
 package org.openecomp.sdc.be.user;
 
 import java.util.regex.Matcher;
@@ -25,11 +24,17 @@ import java.util.regex.Pattern;
 
 public class UserAdminValidator {
 
+    private static final String EMAIL_PATTERN = "^[_A-Za-z0-9-\\+]+(\\.[_A-Za-z0-9-]+)*@" + "[A-Za-z0-9-]+(\\.[A-Za-z0-9]+)*(\\.[A-Za-z]{2,})$";
+    private static final String USER_ID_PATTERN = "\\w{1,25}";
+    private static UserAdminValidator userAdminValidator = null;
     private Pattern emailPat;
     private Pattern userIdPat;
     private Matcher matcher;
 
-    private static UserAdminValidator userAdminValidator = null;
+    private UserAdminValidator() {
+        emailPat = Pattern.compile(EMAIL_PATTERN);
+        userIdPat = Pattern.compile(USER_ID_PATTERN);
+    }
 
     public static synchronized UserAdminValidator getInstance() {
         if (userAdminValidator == null) {
@@ -38,15 +43,6 @@ public class UserAdminValidator {
         return userAdminValidator;
     }
 
-    private static final String EMAIL_PATTERN = "^[_A-Za-z0-9-\\+]+(\\.[_A-Za-z0-9-]+)*@" + "[A-Za-z0-9-]+(\\.[A-Za-z0-9]+)*(\\.[A-Za-z]{2,})$";
-
-    private static final String USER_ID_PATTERN = "\\w{1,25}";
-
-    private UserAdminValidator() {
-        emailPat = Pattern.compile(EMAIL_PATTERN);
-        userIdPat = Pattern.compile(USER_ID_PATTERN);
-    }
-
     public boolean validateEmail(final String hex) {
         matcher = emailPat.matcher(hex);
         return matcher.matches();
index e1cac1c..f904400 100644 (file)
@@ -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.
  * limitations under the License.
  * ============LICENSE_END=========================================================
  */
-
 package org.openecomp.sdc.be.user;
 
+import static org.openecomp.sdc.be.resources.data.auditing.AuditingActionEnum.ADD_USER;
+import static org.openecomp.sdc.be.resources.data.auditing.AuditingActionEnum.GET_USERS_LIST;
+import static org.openecomp.sdc.be.resources.data.auditing.AuditingActionEnum.UPDATE_USER;
+
 import fj.data.Either;
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.HashSet;
+import java.util.List;
+import java.util.Objects;
+import java.util.stream.Collectors;
 import org.apache.commons.collections.CollectionUtils;
 import org.apache.commons.lang3.StringUtils;
 import org.apache.tinkerpop.gremlin.structure.Edge;
@@ -41,17 +50,6 @@ import org.openecomp.sdc.common.log.wrappers.Logger;
 import org.openecomp.sdc.common.util.ThreadLocalsHolder;
 import org.openecomp.sdc.exception.ResponseFormat;
 
-import java.util.ArrayList;
-import java.util.Arrays;
-import java.util.HashSet;
-import java.util.List;
-import java.util.Objects;
-import java.util.stream.Collectors;
-
-import static org.openecomp.sdc.be.resources.data.auditing.AuditingActionEnum.ADD_USER;
-import static org.openecomp.sdc.be.resources.data.auditing.AuditingActionEnum.GET_USERS_LIST;
-import static org.openecomp.sdc.be.resources.data.auditing.AuditingActionEnum.UPDATE_USER;
-
 @org.springframework.stereotype.Component
 public class UserBusinessLogic {
 
@@ -59,7 +57,6 @@ public class UserBusinessLogic {
     private static final String IN_CERTIFICATION_CHECKED_OUT = "in-certification/checked-out";
     private static final String UNKNOWN = "UNKNOWN";
     private static UserAdminValidator userAdminValidator = UserAdminValidator.getInstance();
-
     private final UserAdminOperation userAdminOperation;
     private final ComponentsUtils componentsUtils;
     private final UserOperation facadeUserOperation;
@@ -91,7 +88,7 @@ public class UserBusinessLogic {
             handleUserAccessAuditing(userId, ActionStatus.USER_NOT_FOUND);
             throw new ByActionStatusComponentException(ActionStatus.USER_NOT_FOUND, userId);
         }
-        if (Objects.isNull(userContext.getUserRoles())){
+        if (Objects.isNull(userContext.getUserRoles())) {
             userContext.setUserRoles(new HashSet<>());
         }
         return convertUserContextToUser(userContext);
@@ -110,11 +107,11 @@ public class UserBusinessLogic {
 
     public boolean hasActiveUser(String userId) {
         UserContext userContext = ThreadLocalsHolder.getUserContext();
-        if (Objects.isNull(userContext) || Objects.isNull(userContext.getUserId()) ) {
+        if (Objects.isNull(userContext) || Objects.isNull(userContext.getUserId())) {
             handleUserAccessAuditing(userId, ActionStatus.USER_NOT_FOUND);
             return false;
         }
-        if (Objects.isNull(userContext.getUserRoles()) || userContext.getUserRoles().isEmpty()){
+        if (Objects.isNull(userContext.getUserRoles()) || userContext.getUserRoles().isEmpty()) {
             handleUserAccessAuditing(userId, ActionStatus.USER_INACTIVE);
             return false;
         }
@@ -122,25 +119,20 @@ public class UserBusinessLogic {
     }
 
     public User createUser(String modifierUserId, User newUser) {
-
         User modifier = getValidModifier(modifierUserId, newUser.getUserId(), AuditingActionEnum.ADD_USER);
-
         // verify user not exist
         String newUserId = newUser.getUserId();
         Either<User, ActionStatus> eitherUserInDB = verifyNewUser(newUserId);
         newUser.setStatus(UserStatusEnum.ACTIVE);
-
         validateEmail(newUser);
-
         validateRole(newUser);
-
         // handle last login if user is import
         if (newUser.getLastLoginTime() == null) {
             newUser.setLastLoginTime(0L);
         }
-
         User createdUser;
-        if (ActionStatus.USER_INACTIVE.equals(eitherUserInDB.right().value())) { // user inactive - update state                                                                                  // exist
+        if (ActionStatus.USER_INACTIVE.equals(eitherUserInDB.right()
+            .value())) { // user inactive - update state                                                                                  // exist
             newUser.setLastLoginTime(0L);
             createdUser = userAdminOperation.updateUserData(newUser);
         } else { // user does not exist - create new user
@@ -199,37 +191,32 @@ public class UserBusinessLogic {
                 componentsUtils.auditAdminUserActionAndThrowException(ADD_USER, null, null, null, status, newUserId);
             }
         }
-
         return eitherUserInDB;
     }
 
     private Either<User, ActionStatus> getUserData(String newUserId) {
         if (newUserId == null) {
-            log.error(EcompLoggerErrorCode.DATA_ERROR, "", "","Create user - new user id is missing");
+            log.error(EcompLoggerErrorCode.DATA_ERROR, "", "", "Create user - new user id is missing");
             throw new ByActionStatusComponentException(ActionStatus.MISSING_INFORMATION);
         }
-
         return userAdminOperation.getUserData(newUserId, false);
     }
 
     public User updateUserRole(String modifierUserId, String userIdToUpdate, String userRole) {
-
         User modifier = getValidModifier(modifierUserId, userIdToUpdate, UPDATE_USER);
         User userToUpdate = getUser(userIdToUpdate, false);
         validateChangeRoleToAllowedRoles(userRole);
-
         List<Edge> userPendingTasks = userAdminOperation.getUserPendingTasksList(userToUpdate, getChangeRoleStateLimitations(userToUpdate));
         if (!userPendingTasks.isEmpty()) {
             log.debug("updateUserRole method - User cannot be updated, user have pending projects userId {}", userIdToUpdate);
             String userInfo = userToUpdate.getFirstName() + " " + userToUpdate.getLastName() + '(' + userToUpdate.getUserId() + ')';
-            componentsUtils.auditAdminUserActionAndThrowException(UPDATE_USER, modifier, userToUpdate, null, ActionStatus.CANNOT_UPDATE_USER_WITH_ACTIVE_ELEMENTS, userInfo, IN_CERTIFICATION_CHECKED_OUT);
+            componentsUtils.auditAdminUserActionAndThrowException(UPDATE_USER, modifier, userToUpdate, null,
+                ActionStatus.CANNOT_UPDATE_USER_WITH_ACTIVE_ELEMENTS, userInfo, IN_CERTIFICATION_CHECKED_OUT);
         }
-
         Role newRole = Role.valueOf(userRole);
         User newUser = new User();
         newUser.setRole(newRole.name());
         newUser.setUserId(userIdToUpdate);
-
         User updatedUser = userAdminOperation.updateUserData(newUser);
         handleAuditing(modifier, userToUpdate, updatedUser, componentsUtils.getResponseFormat(ActionStatus.OK), UPDATE_USER);
         getFacadeUserOperation().updateUserCache(UserOperationEnum.CHANGE_ROLE, updatedUser.getUserId(), updatedUser.getRole());
@@ -238,7 +225,7 @@ public class UserBusinessLogic {
 
     private void validateChangeRoleToAllowedRoles(String userRole) {
         List<String> allowedRoles = Arrays.asList(UserRoleEnum.DESIGNER.getName(), UserRoleEnum.ADMIN.getName());
-        if (!allowedRoles.contains(userRole)){
+        if (!allowedRoles.contains(userRole)) {
             throw new ByActionStatusComponentException(ActionStatus.INVALID_ROLE, userRole);
         }
     }
@@ -248,13 +235,11 @@ public class UserBusinessLogic {
             log.error(EcompLoggerErrorCode.DATA_ERROR, "", "", "user modifier is missing");
             throw new ByActionStatusComponentException(ActionStatus.MISSING_INFORMATION);
         }
-
         User modifier = getUser(modifierUserId, false);
         if (!modifier.getRole().equals(UserRoleEnum.ADMIN.getName())) {
             log.debug("user is not admin. Id = {}", modifier.getUserId());
             componentsUtils.auditAdminUserActionAndThrowException(actionEnum, modifier, null, null, ActionStatus.RESTRICTED_OPERATION);
         }
-
         if (modifier.getUserId().equals(userIdHandle)) {
             log.debug("admin user cannot act on self. Id = {}", modifier.getUserId());
             componentsUtils.auditAdminUserActionAndThrowException(actionEnum, modifier, null, null, ActionStatus.UPDATE_USER_ADMIN_CONFLICT);
@@ -302,10 +287,7 @@ public class UserBusinessLogic {
             handleGetUsersListAuditing(user, responseFormat, rolesStr);
             return Either.right(responseFormat);
         }
-        List<User> users = response.left().value()
-                .stream()
-                .filter(u-> StringUtils.isNotEmpty(u.getUserId()))
-                .collect(Collectors.toList());
+        List<User> users = response.left().value().stream().filter(u -> StringUtils.isNotEmpty(u.getUserId())).collect(Collectors.toList());
         return Either.left(users);
     }
 
@@ -331,27 +313,21 @@ public class UserBusinessLogic {
             log.debug("authorize method -  user id is missing");
             throw new ByActionStatusComponentException(ActionStatus.MISSING_INFORMATION);
         }
-
         User user = getUser(userId, false);
-
         String firstName = authUser.getFirstName();
         if (firstName != null && !firstName.isEmpty() && !firstName.equals(user.getFirstName())) {
             user.setFirstName(firstName);
         }
-
         String lastName = authUser.getLastName();
         if (lastName != null && !lastName.isEmpty() && !lastName.equals(user.getLastName())) {
             user.setLastName(lastName);
         }
-
         String email = authUser.getEmail();
         if (email != null && !email.isEmpty() && !email.equals(user.getEmail())) {
             user.setEmail(email);
         }
-
         // last login time stamp handle
         user.setLastLoginTime();
-
         User updatedUser = userAdminOperation.updateUserData(user);
         Long lastLoginTime = user.getLastLoginTime();
         if (lastLoginTime != null) {
@@ -359,7 +335,6 @@ public class UserBusinessLogic {
         } else {
             updatedUser.setLastLoginTime(0L);
         }
-
         handleUserAccessAuditing(updatedUser.getUserId(), ActionStatus.OK);
         ASDCKpiApi.countUsersAuthorizations();
         return updatedUser;
@@ -369,11 +344,8 @@ public class UserBusinessLogic {
      * The method updates user credentials only, the role is neglected The role updated through updateRole method
      */
     public Either<User, ResponseFormat> updateUserCredentials(User updatedUserCred) {
-
         ResponseFormat responseFormat;
-
         String userId = updatedUserCred.getUserId();
-
         if (userId == null) {
             updatedUserCred.setUserId(UNKNOWN);
             log.debug("updateUserCredentials method - user header is missing");
@@ -381,23 +353,19 @@ public class UserBusinessLogic {
             handleUserAccessAuditing(updatedUserCred, responseFormat);
             return Either.right(responseFormat);
         }
-
         User user = getUser(userId, false);
         String firstName = updatedUserCred.getFirstName();
         if (firstName != null && !firstName.isEmpty() && !firstName.equals(user.getFirstName())) {
             user.setFirstName(firstName);
         }
-
         String lastName = updatedUserCred.getLastName();
         if (lastName != null && !lastName.isEmpty() && !lastName.equals(user.getLastName())) {
             user.setLastName(lastName);
         }
-
         String email = updatedUserCred.getEmail();
         if (email != null && !email.isEmpty() && !email.equals(user.getEmail())) {
             user.setEmail(email);
         }
-
         if (updatedUserCred.getLastLoginTime() != null && user.getLastLoginTime() != null) {
             if (updatedUserCred.getLastLoginTime() > user.getLastLoginTime()) {
                 user.setLastLoginTime(updatedUserCred.getLastLoginTime());
@@ -405,7 +373,6 @@ public class UserBusinessLogic {
         } else if (updatedUserCred.getLastLoginTime() != null && user.getLastLoginTime() == null) {
             user.setLastLoginTime(updatedUserCred.getLastLoginTime());
         }
-
         User updatedUser = userAdminOperation.updateUserData(user);
         responseFormat = componentsUtils.getResponseFormat(ActionStatus.OK);
         handleUserAccessAuditing(updatedUser, responseFormat);
@@ -432,5 +399,4 @@ public class UserBusinessLogic {
     public UserOperation getFacadeUserOperation() {
         return facadeUserOperation;
     }
-
 }
index 38b4339..345501d 100644 (file)
  * limitations under the License.
  * ============LICENSE_END=========================================================
  */
-
 package org.openecomp.sdc.be.user;
 
 import fj.data.Either;
+import java.util.ArrayList;
+import java.util.List;
 import org.apache.commons.collections.CollectionUtils;
 import org.openecomp.sdc.be.components.lifecycle.LifecycleBusinessLogic;
 import org.openecomp.sdc.be.components.lifecycle.LifecycleChangeInfoWithAction;
@@ -37,14 +38,10 @@ import org.openecomp.sdc.common.log.enums.EcompLoggerErrorCode;
 import org.openecomp.sdc.common.log.wrappers.Logger;
 import org.openecomp.sdc.exception.ResponseFormat;
 
-import java.util.ArrayList;
-import java.util.List;
-
 @org.springframework.stereotype.Component
 public class UserBusinessLogicExt {
 
     private static final Logger log = Logger.getLogger(UserBusinessLogicExt.class);
-
     private final UserBusinessLogic userBusinessLogic;
     private final UserAdminOperation userAdminOperation;
     private final LifecycleBusinessLogic lifecycleBusinessLogic;
@@ -58,30 +55,27 @@ public class UserBusinessLogicExt {
         this.componentsUtils = componentsUtils;
     }
 
-
     public User deActivateUser(String modifierUserId, String userIdToDeactivate) {
-
         User modifier = userBusinessLogic.getValidModifier(modifierUserId, userIdToDeactivate, AuditingActionEnum.DELETE_USER);
-
         User userToDeactivate = userBusinessLogic.getUser(userIdToDeactivate, false);
         if (userToDeactivate.getStatus() == UserStatusEnum.INACTIVE) {
             log.debug("deActivateUser method - User already inactive", userIdToDeactivate);
-            componentsUtils.auditAdminUserActionAndThrowException(AuditingActionEnum.DELETE_USER, modifier, userToDeactivate, null, ActionStatus.USER_NOT_FOUND, userIdToDeactivate);
+            componentsUtils
+                .auditAdminUserActionAndThrowException(AuditingActionEnum.DELETE_USER, modifier, userToDeactivate, null, ActionStatus.USER_NOT_FOUND,
+                    userIdToDeactivate);
         }
-
         handleTasksInProgress(userToDeactivate);
-
         userAdminOperation.deActivateUser(userToDeactivate);
         componentsUtils.auditUserAccess(userToDeactivate, ActionStatus.OK);
         handleAuditing(modifier, userToDeactivate, null, componentsUtils.getResponseFormat(ActionStatus.OK), AuditingActionEnum.DELETE_USER);
-        userBusinessLogic.getFacadeUserOperation().updateUserCache(UserOperationEnum.DEACTIVATE, userToDeactivate.getUserId(), userToDeactivate.getRole());
+        userBusinessLogic.getFacadeUserOperation()
+            .updateUserCache(UserOperationEnum.DEACTIVATE, userToDeactivate.getUserId(), userToDeactivate.getRole());
         return userToDeactivate;
     }
 
     private void handleTasksInProgress(User userToDeactivate) {
         String userIdToDeactivate = userToDeactivate.getUserId();
-        List<Component> userPendingTasks = userAdminOperation
-                .getUserActiveComponents(userToDeactivate, getDeactivateUserStateLimitations());
+        List<Component> userPendingTasks = userAdminOperation.getUserActiveComponents(userToDeactivate, getDeactivateUserStateLimitations());
         if (userPendingTasks.isEmpty()) {
             return;
         }
@@ -95,17 +89,19 @@ public class UserBusinessLogicExt {
                 log.debug("Erroneous component state when deactivating user for component {} state is {}", componentId, currentState);
                 continue;
             }
-            Either<? extends Component, ResponseFormat> result = lifecycleBusinessLogic.changeComponentState(component.getComponentType(), componentId, userToDeactivate,
-                    transition, changeInfo, false, true);
+            Either<? extends Component, ResponseFormat> result = lifecycleBusinessLogic
+                .changeComponentState(component.getComponentType(), componentId, userToDeactivate, transition, changeInfo, false, true);
             if (result.isRight()) {
                 failedComponents.add(component.getName());
             }
         }
         if (CollectionUtils.isNotEmpty(failedComponents)) {
             String componentList = failedComponents.toString();
-            log.error(EcompLoggerErrorCode.DATA_ERROR, "", "", "User cannot be deleted, {} has the following pending projects that cannot be committed: {}", userIdToDeactivate, componentList);
+            log.error(EcompLoggerErrorCode.DATA_ERROR, "", "",
+                "User cannot be deleted, {} has the following pending projects that cannot be committed: {}", userIdToDeactivate, componentList);
             String userInfo = userToDeactivate.getFirstName() + " " + userToDeactivate.getLastName() + '(' + userToDeactivate.getUserId() + ')';
-            componentsUtils.auditAdminUserActionAndThrowException(AuditingActionEnum.DELETE_USER, null, userToDeactivate, null, ActionStatus.CANNOT_DELETE_USER_WITH_ACTIVE_ELEMENTS, userInfo, componentList);
+            componentsUtils.auditAdminUserActionAndThrowException(AuditingActionEnum.DELETE_USER, null, userToDeactivate, null,
+                ActionStatus.CANNOT_DELETE_USER_WITH_ACTIVE_ELEMENTS, userInfo, componentList);
         }
     }
 
@@ -126,5 +122,4 @@ public class UserBusinessLogicExt {
     private void handleAuditing(User modifier, User userBefor, User userAfter, ResponseFormat responseFormat, AuditingActionEnum actionName) {
         componentsUtils.auditAdminUserAction(actionName, modifier, userBefor, userAfter, responseFormat);
     }
-
 }
index 73943f6..f108a76 100644 (file)
@@ -17,7 +17,6 @@
  * limitations under the License.
  * ============LICENSE_END=========================================================
  */
-
 package org.openecomp.sdc.be.user;
 
 import lombok.AllArgsConstructor;
@@ -31,6 +30,7 @@ import org.openecomp.sdc.be.catalog.api.ITypeMessage;
 @AllArgsConstructor
 @ToString
 public class UserMessage implements ITypeMessage {
+
     private UserOperationEnum operation;
     private String userId;
     private String role;
index c4cc62d..e54a562 100644 (file)
@@ -17,7 +17,6 @@
  * limitations under the License.
  * ============LICENSE_END=========================================================
  */
-
 package org.openecomp.sdc.be.user;
 
 public enum UserOperationEnum {
index 4be9158..0ff6bd6 100644 (file)
@@ -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.
  * limitations under the License.
  * ============LICENSE_END=========================================================
  */
-
 package org.openecomp.sdc.be.view;
 
 import com.fasterxml.jackson.annotation.JsonAutoDetect;
 
 @JsonAutoDetect(getterVisibility = JsonAutoDetect.Visibility.NONE, isGetterVisibility = JsonAutoDetect.Visibility.NONE)
 public abstract class Mixin {
+
 }
index d7f07ba..0f8cbf4 100644 (file)
@@ -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.
  * limitations under the License.
  * ============LICENSE_END=========================================================
  */
-
 package org.openecomp.sdc.be.view;
 
 import com.fasterxml.jackson.databind.ObjectMapper;
 import com.fasterxml.jackson.databind.SerializationFeature;
-
-import javax.ws.rs.Produces;
-import javax.ws.rs.core.MediaType;
-import javax.ws.rs.core.MultivaluedMap;
-import javax.ws.rs.ext.MessageBodyWriter;
-import javax.ws.rs.ext.Provider;
 import java.io.IOException;
 import java.io.OutputStream;
 import java.lang.annotation.Annotation;
@@ -36,9 +29,15 @@ import java.util.List;
 import java.util.Objects;
 import java.util.stream.Collectors;
 import java.util.stream.Stream;
+import javax.ws.rs.Produces;
+import javax.ws.rs.core.MediaType;
+import javax.ws.rs.core.MultivaluedMap;
+import javax.ws.rs.ext.MessageBodyWriter;
+import javax.ws.rs.ext.Provider;
 
 /**
- * A class that is then responsible for converting a message payload with a dedicated mixin from an instance of a specific Java type into a json representation.
+ * A class that is then responsible for converting a message payload with a dedicated mixin from an instance of a specific Java type into a json
+ * representation.
  */
 @Provider
 @Produces(MediaType.APPLICATION_JSON)
@@ -55,7 +54,8 @@ public class MixinModelWriter implements MessageBodyWriter<Object> {
     }
 
     @Override
-    public void writeTo(Object object, Class<?> type, Type genericType, Annotation[] annotations, MediaType mediaType, MultivaluedMap<String, Object> httpHeaders, OutputStream entityStream) throws IOException {
+    public void writeTo(Object object, Class<?> type, Type genericType, Annotation[] annotations, MediaType mediaType,
+                        MultivaluedMap<String, Object> httpHeaders, OutputStream entityStream) throws IOException {
         ObjectMapper objectMapper = new ObjectMapper();
         objectMapper.configure(SerializationFeature.FAIL_ON_EMPTY_BEANS, false);
         List<MixinSourceTarget> mixinSourceTargets = getMixinSourceTarget(annotations);
@@ -64,19 +64,14 @@ public class MixinModelWriter implements MessageBodyWriter<Object> {
     }
 
     private List<MixinSourceTarget> getMixinSourceTarget(Annotation[] annotations) {
-        return Stream.of(annotations)
-                .filter(annotation -> annotation.annotationType().equals(ResponseView.class))
-                .map(annotation -> (ResponseView) annotation)
-                .flatMap(responseView -> Stream.of(responseView.mixin()))
-                .map(mixinClass -> new MixinSourceTarget(mixinClass, mixinClass.getAnnotation(MixinTarget.class).target()))
-                .collect(Collectors.toList());
+        return Stream.of(annotations).filter(annotation -> annotation.annotationType().equals(ResponseView.class))
+            .map(annotation -> (ResponseView) annotation).flatMap(responseView -> Stream.of(responseView.mixin()))
+            .map(mixinClass -> new MixinSourceTarget(mixinClass, mixinClass.getAnnotation(MixinTarget.class).target())).collect(Collectors.toList());
     }
 
     private boolean hasResponseViewAndMixinTargetAnnotations(Annotation[] annotations) {
-        return Stream.of(annotations)
-                .filter(annotation -> annotation.annotationType().equals(ResponseView.class))
-                .map(annotation -> (ResponseView) annotation)
-                .flatMap(responseView -> Stream.of(responseView.mixin()))
-                .anyMatch(mixinClass -> Objects.nonNull(mixinClass.getAnnotation(MixinTarget.class)));
+        return Stream.of(annotations).filter(annotation -> annotation.annotationType().equals(ResponseView.class))
+            .map(annotation -> (ResponseView) annotation).flatMap(responseView -> Stream.of(responseView.mixin()))
+            .anyMatch(mixinClass -> Objects.nonNull(mixinClass.getAnnotation(MixinTarget.class)));
     }
 }
index 35ae05b..4df20e9 100644 (file)
@@ -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.
@@ -17,7 +17,6 @@
  * limitations under the License.
  * ============LICENSE_END=========================================================
  */
-
 package org.openecomp.sdc.be.view;
 
 /**
index 823a6f7..4f91957 100644 (file)
@@ -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.
@@ -17,7 +17,6 @@
  * limitations under the License.
  * ============LICENSE_END=========================================================
  */
-
 package org.openecomp.sdc.be.view;
 
 import java.lang.annotation.ElementType;
@@ -30,10 +29,9 @@ import java.lang.annotation.Target;
 @Target(ElementType.TYPE)
 @Inherited
 public @interface MixinTarget {
+
     /**
-     *
      * @return the class which is the target for the mixin. (i.e the class to be serialized into a json response)
      */
     Class<?> target();
-
 }
index 00006e0..b9e365c 100644 (file)
@@ -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.
@@ -17,7 +17,6 @@
  * limitations under the License.
  * ============LICENSE_END=========================================================
  */
-
 package org.openecomp.sdc.be.view;
 
 import java.lang.annotation.ElementType;
@@ -28,10 +27,10 @@ import java.lang.annotation.Target;
 @Retention(RetentionPolicy.RUNTIME)
 @Target(ElementType.METHOD)
 public @interface ResponseView {
+
     /**
-     * The mixins that will be used when converting the resource's response into a specific view of that response.
-     * A number of mixins can be declared, each of which corresponds to a different object.
+     * The mixins that will be used when converting the resource's response into a specific view of that response. A number of mixins can be declared,
+     * each of which corresponds to a different object.
      */
     public Class<? extends Mixin>[] mixin();
 }
-
index 52a1023..570cabe 100644 (file)
@@ -40,8 +40,10 @@ import org.springframework.context.annotation.ComponentScan;
 import org.springframework.context.annotation.Configuration;
 import org.springframework.core.annotation.Order;
 
+// @formatter:off
 @Configuration
-@ComponentScan({"org.openecomp.sdc.be.user",
+@ComponentScan({
+    "org.openecomp.sdc.be.user",
     "org.openecomp.sdc.be.facade.operations",
     "org.openecomp.sdc.be.impl",
     "org.openecomp.sdc.be.auditing.impl",
@@ -63,8 +65,8 @@ import org.springframework.core.annotation.Order;
     "org.openecomp.sdc.be.servlets",
     "org.openecomp.sdc.be.filters",
     "org.openecomp.sdc.be.plugins",
-    "org.openecomp.sdc.be.togglz"
-})
+    "org.openecomp.sdc.be.togglz"})
+// @formatter:on
 public class CatalogBESpringConfig {
 
     private static final int BEFORE_TRANSACTION_MANAGER = 0;
@@ -97,7 +99,9 @@ public class CatalogBESpringConfig {
     }
 
     @Bean
-    public RoleAuthorizationHandler roleAuthorizationHandler() {return new RoleAuthorizationHandler();}
+    public RoleAuthorizationHandler roleAuthorizationHandler() {
+        return new RoleAuthorizationHandler();
+    }
 
     @Bean
     public CloseableHttpClient httpClientConnectionManager() {
@@ -106,13 +110,19 @@ public class CatalogBESpringConfig {
     }
 
     @Bean
-    public PortalConfiguration portalConfiguration() throws CipherUtilException {return new PortalConfiguration();}
+    public PortalConfiguration portalConfiguration() throws CipherUtilException {
+        return new PortalConfiguration();
+    }
 
     @Bean
-    public FilterConfiguration filterConfiguration() {return new FilterConfiguration(configuration());}
+    public FilterConfiguration filterConfiguration() {
+        return new FilterConfiguration(configuration());
+    }
 
     @Bean
-    public ThreadLocalUtils threadLocalUtils() {return new ThreadLocalUtils();}
+    public ThreadLocalUtils threadLocalUtils() {
+        return new ThreadLocalUtils();
+    }
 
     @Bean
     public PortalClient portalClient() throws CipherUtilException {
@@ -120,8 +130,7 @@ public class CatalogBESpringConfig {
     }
 
     @Bean
-    public org.openecomp.sdc.be.config.Configuration configuration(){
+    public org.openecomp.sdc.be.config.Configuration configuration() {
         return ConfigurationManager.getConfigurationManager().getConfiguration();
     }
-
 }
index f2544aa..176f05a 100644 (file)
@@ -17,7 +17,6 @@
  * limitations under the License.
  * ============LICENSE_END=========================================================
  */
-
 package org.openecomp.sdc.config;
 
 import org.apache.http.client.HttpRequestRetryHandler;
@@ -46,28 +45,19 @@ public class HttpClientFactory {
     private static final int DEFAULT_MAX_CONNECTION_PER_ROUTE = 5;
     private static final int VALIDATE_CONNECTION_AFTER_INACTIVITY_MS = 10000;
     private static final int CONNECT_TIMEOUT_MS = 15000;
-
     private static final Logger log = Logger.getLogger(HttpClientFactory.class);
     private static final UserTokenHandler userTokenHandler = context -> null;
 
-    private HttpClientConnectionManager createConnectionManager(){
+    private HttpClientConnectionManager createConnectionManager() {
         SSLConnectionSocketFactory sslsf = getSslConnectionSocketFactory();
-
         Registry<ConnectionSocketFactory> registry = RegistryBuilder.<ConnectionSocketFactory>create()
-                .register(Constants.HTTP, PlainConnectionSocketFactory.getSocketFactory())
-                .register(Constants.HTTPS, sslsf).build();
-
+            .register(Constants.HTTP, PlainConnectionSocketFactory.getSocketFactory()).register(Constants.HTTPS, sslsf).build();
         PoolingHttpClientConnectionManager manager = new PoolingHttpClientConnectionManager(registry);
-
         manager.setMaxTotal(DEFAULT_CONNECTION_POOL_SIZE);
         manager.setDefaultMaxPerRoute(DEFAULT_MAX_CONNECTION_PER_ROUTE);
         manager.setValidateAfterInactivity(VALIDATE_CONNECTION_AFTER_INACTIVITY_MS);
-
-        SocketConfig socketConfig = SocketConfig.custom()
-                .setSoTimeout(CONNECT_TIMEOUT_MS)
-                .build();
+        SocketConfig socketConfig = SocketConfig.custom().setSoTimeout(CONNECT_TIMEOUT_MS).build();
         manager.setDefaultSocketConfig(socketConfig);
-
         return manager;
     }
 
@@ -75,7 +65,6 @@ public class HttpClientFactory {
         return new SSLConnectionSocketFactory(SSLContexts.createSystemDefault());
     }
 
-
     /*
     The difference between this client factory and the one in common api,
     is that this one returns an apache httpclient instance, rather than a custom created custom.
@@ -87,24 +76,16 @@ public class HttpClientFactory {
         HttpClientConfig httpClientConfig = new HttpClientConfig(new Timeouts(connectTimeoutMs, readTimeoutMs));
         HttpClientConfigImmutable immutableHttpClientConfig = new HttpClientConfigImmutable(httpClientConfig);
         RequestConfig requestConfig = createClientTimeoutConfiguration(immutableHttpClientConfig);
-        return HttpClients.custom()
-                .setConnectionManager(connManager)
-                .setDefaultRequestConfig(requestConfig)
-                .setUserTokenHandler(userTokenHandler)
-                .setRetryHandler(resolveRetryHandler(immutableHttpClientConfig))
-                .build();
+        return HttpClients.custom().setConnectionManager(connManager).setDefaultRequestConfig(requestConfig).setUserTokenHandler(userTokenHandler)
+            .setRetryHandler(resolveRetryHandler(immutableHttpClientConfig)).build();
     }
 
-    private  RequestConfig createClientTimeoutConfiguration(HttpClientConfigImmutable config) {
-        return RequestConfig.custom()
-                .setConnectTimeout(config.getConnectTimeoutMs())
-                .setSocketTimeout(config.getReadTimeoutMs())
-                .setConnectionRequestTimeout(config.getConnectPoolTimeoutMs())
-                .build();
+    private RequestConfig createClientTimeoutConfiguration(HttpClientConfigImmutable config) {
+        return RequestConfig.custom().setConnectTimeout(config.getConnectTimeoutMs()).setSocketTimeout(config.getReadTimeoutMs())
+            .setConnectionRequestTimeout(config.getConnectPoolTimeoutMs()).build();
     }
 
     private HttpRequestRetryHandler resolveRetryHandler(HttpClientConfigImmutable config) {
         return config.getNumOfRetries() > 0 ? config.getRetryHandler() : null;
     }
-
 }
index 8b5f7ed..62c4d90 100644 (file)
  * limitations under the License.
  * ============LICENSE_END=========================================================
  */
-
 package org.openecomp.sdc.config;
 
 import com.fasterxml.jackson.databind.DeserializationFeature;
 import com.fasterxml.jackson.databind.ObjectMapper;
-
 import javax.ws.rs.ext.ContextResolver;
 import javax.ws.rs.ext.Provider;
 
@@ -39,9 +37,8 @@ public class ObjectMapperProvider implements ContextResolver<ObjectMapper> {
     }
 
     private ObjectMapper createObjectMapper() {
-        return new ObjectMapper()
-                .disable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES)
-                .enable(DeserializationFeature.ACCEPT_SINGLE_VALUE_AS_ARRAY);
+        return new ObjectMapper().disable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES)
+            .enable(DeserializationFeature.ACCEPT_SINGLE_VALUE_AS_ARRAY);
     }
 
     @Override
index e6d12c9..6ada300 100644 (file)
  * See the License for the specific language governing permissions and
  * limitations under the License.
  */
-
 package org.openecomp.sdc.externalupload.utils;
 
 import com.fasterxml.jackson.databind.ObjectMapper;
 import com.google.common.collect.ImmutableSet;
-import org.apache.commons.beanutils.BeanUtils;
-
 import java.lang.reflect.Field;
 import java.util.ArrayList;
 import java.util.Arrays;
@@ -29,72 +26,64 @@ import java.util.Map;
 import java.util.Objects;
 import java.util.Optional;
 import java.util.Set;
+import org.apache.commons.beanutils.BeanUtils;
 
 public class ServiceUtils {
 
-  private static ImmutableSet<Class> collectionClasses = ImmutableSet.of(Map.class, List.class, Set.class);
-  private static ImmutableSet<Class> primitiveTypesClasses = ImmutableSet.of(String.class, Integer.class, Double.class, Float.class);
+    private static ImmutableSet<Class> collectionClasses = ImmutableSet.of(Map.class, List.class, Set.class);
+    private static ImmutableSet<Class> primitiveTypesClasses = ImmutableSet.of(String.class, Integer.class, Double.class, Float.class);
 
-  private ServiceUtils() {}
-
-  public static <T> Optional<T> createObjectUsingSetters(Object objectCandidate,
-                                                         Class<T> classToCreate)
-      throws Exception {
-    if (Objects.isNull(objectCandidate)) {
-      return Optional.empty();
+    private ServiceUtils() {
     }
 
-    Map<String, Object> objectAsMap = getObjectAsMap(objectCandidate);
-    T result = classToCreate.newInstance();
-
-    List<Field> declaredFields = getAllFields(classToCreate);
-    for( Field field : declaredFields){
-      if(isComplexClass(field)){
-        Optional<?> objectUsingSetters =
-            createObjectUsingSetters(objectAsMap.get(field.getName()), field.getType());
-        if( objectUsingSetters.isPresent()){
-          objectAsMap.remove(field.getName());
-          objectAsMap.put(field.getName(), objectUsingSetters.get());
+    public static <T> Optional<T> createObjectUsingSetters(Object objectCandidate, Class<T> classToCreate) throws Exception {
+        if (Objects.isNull(objectCandidate)) {
+            return Optional.empty();
         }
-      }
+        Map<String, Object> objectAsMap = getObjectAsMap(objectCandidate);
+        T result = classToCreate.newInstance();
+        List<Field> declaredFields = getAllFields(classToCreate);
+        for (Field field : declaredFields) {
+            if (isComplexClass(field)) {
+                Optional<?> objectUsingSetters = createObjectUsingSetters(objectAsMap.get(field.getName()), field.getType());
+                if (objectUsingSetters.isPresent()) {
+                    objectAsMap.remove(field.getName());
+                    objectAsMap.put(field.getName(), objectUsingSetters.get());
+                }
+            }
+        }
+        BeanUtils.populate(result, objectAsMap);
+        return Optional.of(result);
     }
-    BeanUtils.populate(result, objectAsMap);
-
-    return Optional.of(result);
-  }
 
-  private static <T> List<Field> getAllFields(Class<T> clazz) {
-    List<Field> fields = new ArrayList<>();
-    for(Class<?> c = clazz; c != null; c = c.getSuperclass()) {
-      fields.addAll(Arrays.asList(c.getDeclaredFields()));
+    private static <T> List<Field> getAllFields(Class<T> clazz) {
+        List<Field> fields = new ArrayList<>();
+        for (Class<?> c = clazz; c != null; c = c.getSuperclass()) {
+            fields.addAll(Arrays.asList(c.getDeclaredFields()));
+        }
+        return fields;
     }
 
-    return fields;
-  }
-
-  private static boolean isComplexClass(Field field) {
-    return !isCollectionClass(field)
-        && !isPrimitiveClass(field)
-        && !field.getType().equals(Object.class);
-  }
-
-  private static boolean isCollectionClass(Field field) {
-    return collectionClasses.contains(field.getType());
-  }
+    private static boolean isComplexClass(Field field) {
+        return !isCollectionClass(field) && !isPrimitiveClass(field) && !field.getType().equals(Object.class);
+    }
 
-  private static boolean isPrimitiveClass(Field field) {
-    return primitiveTypesClasses.contains(field.getType());
-  }
+    private static boolean isCollectionClass(Field field) {
+        return collectionClasses.contains(field.getType());
+    }
 
-  public static Map<String, Object> getObjectAsMap(Object obj) {
-    return new ObjectMapper().convertValue(obj, Map.class);
-  }
+    private static boolean isPrimitiveClass(Field field) {
+        return primitiveTypesClasses.contains(field.getType());
+    }
 
-  public static Set<String> getClassFieldNames(Class<? extends Object> classType) {
-    Set<String> fieldNames = new HashSet<>();
-    List<Field> allFields = getAllFields(classType);
-    allFields.forEach(field -> fieldNames.add(field.getName()));
+    public static Map<String, Object> getObjectAsMap(Object obj) {
+        return new ObjectMapper().convertValue(obj, Map.class);
+    }
 
-    return fieldNames;
-  }
-}
\ No newline at end of file
+    public static Set<String> getClassFieldNames(Class<? extends Object> classType) {
+        Set<String> fieldNames = new HashSet<>();
+        List<Field> allFields = getAllFields(classType);
+        allFields.forEach(field -> fieldNames.add(field.getName()));
+        return fieldNames;
+    }
+}