From 0953785bfd6a3af5e506f8a55a8520c0fb7ef358 Mon Sep 17 00:00:00 2001 From: Talio Date: Thu, 31 Jan 2019 18:00:36 +0200 Subject: Add property mapping feature to ONAP Add service property assignment Change-Id: I29748ce12bacab06b8bc27f8875b39d80ffe5af7 Issue-ID: SDC-1988 Signed-off-by: Talio --- catalog-be/pom.xml | 30 ++ .../be/components/impl/PropertyBusinessLogic.java | 398 ++++++++++++++------- .../property/ComponentPropertyDeclarator.java | 153 ++++++++ .../property/DefaultPropertyDeclarator.java | 50 ++- .../property/PropertyDeclarationOrchestrator.java | 14 +- .../sdc/be/servlets/BeGenericServlet.java | 179 ++++++++- .../sdc/be/servlets/ComponentInstanceServlet.java | 2 +- .../sdc/be/servlets/ComponentPropertyServlet.java | 390 ++++++++++++++++++++ .../openecomp/sdc/be/servlets/PropertyServlet.java | 369 ------------------- .../sdc/be/servlets/TypesFetchServlet.java | 6 - .../be/tosca/CapabilityRequirementConverter.java | 4 +- .../openecomp/sdc/be/tosca/PropertyConvertor.java | 64 ++-- .../openecomp/sdc/be/tosca/ToscaExportHandler.java | 245 ++++++++++--- .../sdc/be/tosca/model/ToscaNodeTemplate.java | 17 + .../sdc/be/tosca/utils/InputConverter.java | 3 +- .../tosca/utils/InterfacesOperationsToscaUtil.java | 63 +++- .../sdc/externalupload/utils/ServiceUtils.java | 89 +++++ .../be/components/PropertyBusinessLogicTest.java | 149 ++++++-- .../InterfaceOperationValidationTest.java | 2 +- .../sdc/be/servlets/PropertyServletTest.java | 116 ------ .../sdc/be/tosca/PropertyConvertorTest.java | 10 +- .../sdc/be/tosca/ToscaExportHandlerTest.java | 13 +- .../utils/InterfacesOperationsToscaUtilTest.java | 10 +- .../test/utils/InterfaceOperationTestUtils.java | 3 +- 24 files changed, 1595 insertions(+), 784 deletions(-) create mode 100644 catalog-be/src/main/java/org/openecomp/sdc/be/components/property/ComponentPropertyDeclarator.java create mode 100644 catalog-be/src/main/java/org/openecomp/sdc/be/servlets/ComponentPropertyServlet.java delete mode 100644 catalog-be/src/main/java/org/openecomp/sdc/be/servlets/PropertyServlet.java create mode 100644 catalog-be/src/main/java/org/openecomp/sdc/externalupload/utils/ServiceUtils.java delete mode 100644 catalog-be/src/test/java/org/openecomp/sdc/be/servlets/PropertyServletTest.java (limited to 'catalog-be') diff --git a/catalog-be/pom.xml b/catalog-be/pom.xml index 8bbe456c9d..4c0cbbfae0 100644 --- a/catalog-be/pom.xml +++ b/catalog-be/pom.xml @@ -588,6 +588,36 @@ io.netty netty-handler + + org.onap.sdc.common + onap-tosca-datatype + ${project.version} + + + org.apache.commons + commons-collections4 + 4.1 + + + org.openecomp.sdc.be + catalog-model + ${project.version} + + + org.onap.sdc.common + onap-tosca-datatype + ${project.version} + + + org.apache.commons + commons-collections4 + 4.1 + + + org.openecomp.sdc.be + catalog-model + ${project.version} + diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/PropertyBusinessLogic.java b/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/PropertyBusinessLogic.java index 5f40606177..f49f531e28 100644 --- a/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/PropertyBusinessLogic.java +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/PropertyBusinessLogic.java @@ -7,9 +7,9 @@ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -22,19 +22,27 @@ package org.openecomp.sdc.be.components.impl; import com.google.gson.JsonElement; import fj.data.Either; +import java.util.Map.Entry; import org.apache.commons.collections.CollectionUtils; +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; import org.openecomp.sdc.be.dao.titan.TitanOperationStatus; +import org.openecomp.sdc.be.datatypes.elements.ListDataDefinition; +import org.openecomp.sdc.be.datatypes.elements.OperationDataDefinition; +import org.openecomp.sdc.be.datatypes.elements.OperationInputDefinition; import org.openecomp.sdc.be.datatypes.elements.PropertyDataDefinition; import org.openecomp.sdc.be.datatypes.elements.SchemaDefinition; import org.openecomp.sdc.be.datatypes.enums.NodeTypeEnum; import org.openecomp.sdc.be.impl.WebAppContextWrapper; +import org.openecomp.sdc.be.model.Component; +import org.openecomp.sdc.be.model.ComponentInstanceInterface; +import org.openecomp.sdc.be.model.ComponentParametersView; import org.openecomp.sdc.be.model.DataTypeDefinition; import org.openecomp.sdc.be.model.IComplexDefaultValue; +import org.openecomp.sdc.be.model.InterfaceDefinition; import org.openecomp.sdc.be.model.PropertyDefinition; -import org.openecomp.sdc.be.model.Resource; import org.openecomp.sdc.be.model.operations.api.IElementOperation; import org.openecomp.sdc.be.model.operations.api.StorageOperationStatus; import org.openecomp.sdc.be.model.operations.utils.ComponentValidationUtils; @@ -45,17 +53,13 @@ import org.openecomp.sdc.be.resources.data.EntryData; 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.Component; import org.springframework.web.context.WebApplicationContext; import javax.servlet.ServletContext; -import java.util.HashMap; -import java.util.List; -import java.util.Map; -import java.util.Map.Entry; +import java.util.*; import java.util.function.Supplier; -@Component("propertyBusinessLogic") +@org.springframework.stereotype.Component("propertyBusinessLogic") public class PropertyBusinessLogic extends BaseBusinessLogic { private static final String CREATE_PROPERTY = "CreateProperty"; @@ -77,262 +81,368 @@ public class PropertyBusinessLogic extends BaseBusinessLogic { } /** - * Create new property on resource in graph + * Create new property on component in graph * - * @param resourceId + * @param componentId * @param propertyName * @param newPropertyDefinition * @param userId * @return either properties or response format */ - public Either, ResponseFormat> createProperty(String resourceId, String propertyName, PropertyDefinition newPropertyDefinition, String userId) { + public Either, ResponseFormat> addPropertyToComponent(String componentId, + String propertyName, + PropertyDefinition newPropertyDefinition, + String userId) { Either, ResponseFormat> result = null; validateUserExists(userId, "create Property", false); - StorageOperationStatus lockResult = graphLockOperation.lockComponent(resourceId, NodeTypeEnum.Resource); + Either 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_PROPERTY, NodeTypeEnum.Resource.name().toLowerCase(), resourceId); - log.info("Failed to lock component {}. Error - {}", resourceId, lockResult); + 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 { - // Get the resource from DB - Either status = toscaOperationFacade.getToscaElement(resourceId); - if (status.isRight()) { - result = Either.right(componentsUtils.getResponseFormat(ActionStatus.RESOURCE_NOT_FOUND, "")); - return result; - } - Resource resource = status.left().value(); - - // verify that resource is checked-out and the user is the last - // updater - if (!ComponentValidationUtils.canWorkOnResource(resource, userId)) { + if (!ComponentValidationUtils.canWorkOnComponent(component, userId)) { result = Either.right(componentsUtils.getResponseFormat(ActionStatus.RESTRICTED_OPERATION)); return result; } - // verify property not exist in resource - List resourceProperties = resource.getProperties(); + List properties = component.getProperties(); - if (resourceProperties != null && isPropertyExist(resourceProperties, resourceId, propertyName, newPropertyDefinition.getType())) { - result = Either.right(componentsUtils.getResponseFormat(ActionStatus.PROPERTY_ALREADY_EXIST, propertyName)); - return result; + if(CollectionUtils.isEmpty(properties)) { + properties = new ArrayList<>(); } - Either, ResponseFormat> allDataTypes = getAllDataTypes(applicationDataTypeCache); - if (allDataTypes.isRight()) { - result = Either.right(allDataTypes.right().value()); + if(isPropertyExistInComponent(properties, propertyName)) { + + result = + Either.right(componentsUtils.getResponseFormat(ActionStatus + .PROPERTY_ALREADY_EXIST, propertyName)); return result; - } - Map dataTypes = allDataTypes.left().value(); + } else { - // validate property default values - Either defaultValuesValidation = validatePropertyDefaultValue(newPropertyDefinition, dataTypes); - if (defaultValuesValidation.isRight()) { - result = Either.right(defaultValuesValidation.right().value()); - return result; - } - convertProperty(newPropertyDefinition, allDataTypes); + Either, ResponseFormat> allDataTypes = getAllDataTypes(applicationDataTypeCache); + if (allDataTypes.isRight()) { + result = Either.right(allDataTypes.right().value()); + return result; + } + Map dataTypes = allDataTypes.left().value(); - // add the new property to resource on graph - // need to get StorageOpaerationStatus and convert to ActionStatus - // from componentsUtils - Either either = toscaOperationFacade.addPropertyToResource(propertyName, newPropertyDefinition, resource); - if (either.isRight()) { - result = Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(either.right().value()), resource.getName())); - return result; + // validate property default values + Either defaultValuesValidation = validatePropertyDefaultValue(newPropertyDefinition, dataTypes); + if (defaultValuesValidation.isRight()) { + result = Either.right(defaultValuesValidation.right().value()); + return result; + } + // convert property + ToscaPropertyType type = getType(newPropertyDefinition.getType()); + if (type != null) { + PropertyValueConverter converter = type.getConverter(); + // get inner type + String innerType = null; + if (newPropertyDefinition != null) { + SchemaDefinition schema = newPropertyDefinition.getSchema(); + if (schema != null) { + PropertyDataDefinition prop = schema.getProperty(); + if (prop != null) { + innerType = prop.getType(); + } + } + String convertedValue = null; + if (newPropertyDefinition.getDefaultValue() != null) { + convertedValue = converter.convert( + (String) newPropertyDefinition.getDefaultValue(), innerType, allDataTypes.left().value()); + newPropertyDefinition.setDefaultValue(convertedValue); + } + } + } + Either 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)); + return result; + } } - PropertyDefinition createdPropertyDefinition = either.left().value(); - EntryData property = new EntryData<>(propertyName, createdPropertyDefinition); - result = Either.left(property); + result = Either.left(new EntryData<>(propertyName, newPropertyDefinition)); return result; } finally { commitOrRollback(result); // unlock component - graphLockOperation.unlockComponent(resourceId, NodeTypeEnum.Resource); + graphLockOperation.unlockComponent(componentId, nodeType); } } - private void convertProperty(PropertyDefinition newPropertyDefinition, Either, ResponseFormat> allDataTypes) { - ToscaPropertyType type = getType(newPropertyDefinition.getType()); - if (type != null) { - String innerType = null; - SchemaDefinition schema = newPropertyDefinition.getSchema(); - if (schema != null && schema.getProperty() != null) { - innerType = schema.getProperty().getType(); - } - if (newPropertyDefinition.getDefaultValue() != null) { - newPropertyDefinition.setDefaultValue( - type.getConverter().convert( - newPropertyDefinition.getDefaultValue(), innerType, allDataTypes.left().value())); - } - } - } - /** - * Get property of resource + * Get property of component * - * @param resourceId + * @param componentId * @param propertyId * @param userId * @return either properties or response format */ - public Either, ResponseFormat> getProperty(String resourceId, String propertyId, String userId) { + + public Either, ResponseFormat> getComponentProperty(String componentId, String propertyId, String userId) { validateUserExists(userId, "create Component Instance", false); // Get the resource from DB - Either status = toscaOperationFacade.getToscaElement(resourceId); + Either status = + toscaOperationFacade.getToscaElement(componentId); if (status.isRight()) { return Either.right(componentsUtils.getResponseFormat(ActionStatus.RESOURCE_NOT_FOUND, "")); } - Resource resource = status.left().value(); - - // verify property exist in resource - List properties = resource.getProperties(); - if (properties == null) { + Component component = status.left().value(); + List properties = component.getProperties(); + if(CollectionUtils.isEmpty(properties)) { return Either.right(componentsUtils.getResponseFormat(ActionStatus.PROPERTY_NOT_FOUND, "")); } - for (PropertyDefinition property : properties) { - if (property.getUniqueId().equals(propertyId) ) { - Map propMap = new HashMap<>(); - propMap.put(property.getName(), property); - return Either.left(propMap.entrySet().iterator().next()); + + 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, ResponseFormat> getPropertiesList(String componentId, + String userId) { + validateUserExists(userId, "create Component Instance", false); + + // Get the resource from DB + ComponentParametersView filter = new ComponentParametersView(true); + filter.setIgnoreProperties(false); + Either status = + toscaOperationFacade.getToscaElement(componentId); + if (status.isRight()) { + return Either.right(componentsUtils.getResponseFormat(ActionStatus.RESOURCE_NOT_FOUND, "")); + } + Component component = status.left().value(); + List properties = component.getProperties(); + + return Either.left(properties); + } + + /** - * delete property of resource from graph + * delete property of component from graph * - * @param resourceId + * @param componentId * @param propertyId * @param userId * @return either properties or response format */ - public Either, ResponseFormat> deleteProperty(String resourceId, String propertyId, String userId) { - Either, ResponseFormat> result = null; + public Either, ResponseFormat> deletePropertyFromComponent(String componentId, String propertyId, String userId) { + + Either, ResponseFormat> result = null; validateUserExists(userId, "delete Property", false); - StorageOperationStatus lockResult = graphLockOperation.lockComponent(resourceId, NodeTypeEnum.Resource); + // Get the resource from DB + Either getComponentRes = toscaOperationFacade.getToscaElement(componentId); + if (getComponentRes.isRight()) { + result = Either.right(componentsUtils.getResponseFormat(ActionStatus.RESOURCE_NOT_FOUND, "")); + return result; + } + Component component = getComponentRes.left().value(); + NodeTypeEnum nodeType = component.getComponentType().getNodeType(); + StorageOperationStatus lockResult = graphLockOperation.lockComponent(componentId, nodeType); if (!lockResult.equals(StorageOperationStatus.OK)) { - BeEcompErrorManager.getInstance().logBeFailedLockObjectError(CREATE_PROPERTY, NodeTypeEnum.Resource.name().toLowerCase(), resourceId); + BeEcompErrorManager.getInstance().logBeFailedLockObjectError(CREATE_PROPERTY, nodeType.name().toLowerCase(), + componentId); result = Either.right(componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR)); return result; } try { - - // Get the resource from DB - Either getResourceRes = toscaOperationFacade.getToscaElement(resourceId); - if (getResourceRes.isRight()) { - result = Either.right(componentsUtils.getResponseFormat(ActionStatus.RESOURCE_NOT_FOUND, "")); - return result; - } - Resource resource = getResourceRes.left().value(); - // verify that resource is checked-out and the user is the last // updater - if (!ComponentValidationUtils.canWorkOnResource(resource, userId)) { + if (!ComponentValidationUtils.canWorkOnComponent(component, userId)) { result = Either.right(componentsUtils.getResponseFormat(ActionStatus.RESTRICTED_OPERATION)); return result; } // verify property exist in resource - Either, ResponseFormat> statusGetProperty = getProperty(resourceId, propertyId, userId); + Either, ResponseFormat> statusGetProperty = + getComponentProperty(componentId, propertyId, userId); if (statusGetProperty.isRight()) { result = Either.right(statusGetProperty.right().value()); return result; } - StorageOperationStatus status = toscaOperationFacade.deletePropertyOfResource(resource, statusGetProperty.left().value().getKey()); + Map.Entry 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)); + } + + StorageOperationStatus status = + toscaOperationFacade.deletePropertyOfComponent(component, propertyDefinitionEntry.getKey()); if (status != StorageOperationStatus.OK) { - result = Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(status), resource.getName())); + result = Either.right(componentsUtils.getResponseFormat(componentsUtils + .convertFromStorageResponse(status), component.getName())); return result; } - result = Either.left(statusGetProperty.left().value()); + result = Either.left(propertyDefinitionEntry); return result; } finally { commitOrRollback(result); // unlock component - graphLockOperation.unlockComponent(resourceId, NodeTypeEnum.Resource); + graphLockOperation.unlockComponent(componentId, nodeType); + } + } + + public boolean isPropertyUsedByOperation(Component component, + PropertyDefinition propertyDefinitionEntry) { + + // Component's own interfaces + Map interfaces = component.getInterfaces(); + if(MapUtils.isNotEmpty(interfaces)){ + for(Map.Entry 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, StorageOperationStatus> componentList = toscaOperationFacade.getParentComponents(component.getUniqueId()); + if(componentList.isLeft()){ + for (Component parentComponent : componentList.left().value()) { + if(isPropertyUsedInCIInterfaces(parentComponent.getComponentInstancesInterfaces(), propertyDefinitionEntry)){ + return true; + } + } + } + + return false; + } + + private boolean isPropertyUsedInCIInterfaces(Map> componentInstanceInterfaces, PropertyDefinition propertyDefinitionEntry){ + if(MapUtils.isNotEmpty(componentInstanceInterfaces)){ + for (Entry> interfaceEntry : componentInstanceInterfaces.entrySet()) { + for (ComponentInstanceInterface instanceInterface : interfaceEntry.getValue()) { + if (isPropertyExistInOperationInterface(propertyDefinitionEntry, instanceInterface)) { + return true; + } + } + } } + return false; + } + + private boolean isPropertyExistInOperationInterface(PropertyDefinition propertyDefinition, + InterfaceDefinition interfaceDefinition) { + Map operations = + interfaceDefinition.getOperations(); + for(Map.Entry operationEntry : operations + .entrySet()) { + Optional inputWithDeletedPropertyCandidate = + getInputWithDeclaredProperty(propertyDefinition, operationEntry); + + if(inputWithDeletedPropertyCandidate.isPresent()) { + return true; + } + } + return false; + } + + private Optional getInputWithDeclaredProperty(PropertyDefinition propertyDefinition, + Map.Entry operationEntry) { + ListDataDefinition inputs = + operationEntry.getValue().getInputs(); + List operationInputsList = + Objects.isNull(inputs) ? null : inputs.getListToscaDataDefinition(); + + if(CollectionUtils.isEmpty(operationInputsList)) { + return Optional.empty(); + } + + return operationInputsList.stream().filter(input -> input.getInputId().equals(propertyDefinition.getUniqueId())).findAny(); } /** * update property * - * @param resourceId + * @param componentId * @param propertyId * @param newPropertyDefinition * @param userId * @return either properties or response format */ - public Either, ResponseFormat> updateProperty(String resourceId, String propertyId, PropertyDefinition newPropertyDefinition, String userId) { + + public Either, ResponseFormat> updateComponentProperty(String componentId, + String propertyId, + PropertyDefinition newPropertyDefinition, + String userId) { Either, ResponseFormat> result = null; - Either status = toscaOperationFacade.getToscaElement(resourceId); + Either status = toscaOperationFacade.getToscaElement( + componentId); if (status.isRight()) { return Either.right(componentsUtils.getResponseFormat(ActionStatus.RESOURCE_NOT_FOUND, "")); } - Resource resource = status.left().value(); + Component component = status.left().value(); + NodeTypeEnum nodeType = component.getComponentType().getNodeType(); - if (!ComponentValidationUtils.canWorkOnResource(resource, userId)) { + if (!ComponentValidationUtils.canWorkOnComponent(component, userId)) { return Either.right(componentsUtils.getResponseFormat(ActionStatus.RESTRICTED_OPERATION)); } - StorageOperationStatus lockResult = graphLockOperation.lockComponent(resourceId, NodeTypeEnum.Resource); + StorageOperationStatus lockResult = graphLockOperation.lockComponent(componentId, nodeType); if (!lockResult.equals(StorageOperationStatus.OK)) { - BeEcompErrorManager.getInstance().logBeFailedLockObjectError(CREATE_PROPERTY, NodeTypeEnum.Resource.name().toLowerCase(), resourceId); + BeEcompErrorManager.getInstance().logBeFailedLockObjectError(CREATE_PROPERTY, nodeType.name().toLowerCase(), + componentId); result = Either.right(componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR)); return result; } try { - Either, ResponseFormat> statusGetProperty = getProperty(resourceId, propertyId, userId); + Either, ResponseFormat> statusGetProperty = + getComponentProperty(componentId, propertyId, userId); if (statusGetProperty.isRight()) { result = Either.right(statusGetProperty.right().value()); return result; } String propertyName = statusGetProperty.left().value().getKey(); - Either, ResponseFormat> allDataTypes = getAllDataTypes(applicationDataTypeCache); - if (allDataTypes.isRight()) { - result = Either.right(allDataTypes.right().value()); - return result; - } - Map dataTypes = allDataTypes.left().value(); - - Either defaultValuesValidation = validatePropertyDefaultValue(newPropertyDefinition, dataTypes); - if (defaultValuesValidation.isRight()) { - result = Either.right(defaultValuesValidation.right().value()); - return result; - } - - Either either = handleProperty(newPropertyDefinition, dataTypes); - if (either.isRight()) { - log.debug("Problem while updating property with id {}. Reason - {}", propertyId, either.right().value()); - result = Either.right(componentsUtils.getResponseFormatByResource(componentsUtils.convertFromStorageResponse(either.right().value()), resource.getName())); - return result; - } - - - either = toscaOperationFacade.updatePropertyOfResource(resource, newPropertyDefinition); + Either either = + toscaOperationFacade.updatePropertyOfComponent(component, newPropertyDefinition); if (either.isRight()) { - result = Either.right(componentsUtils.getResponseFormatByResource(componentsUtils.convertFromStorageResponse(either.right().value()), resource.getName())); + result = Either.right(componentsUtils.getResponseFormatByResource(componentsUtils.convertFromStorageResponse(either.right().value()), component.getName())); return result; } @@ -342,18 +452,30 @@ public class PropertyBusinessLogic extends BaseBusinessLogic { } finally { commitOrRollback(result); - graphLockOperation.unlockComponent(resourceId, NodeTypeEnum.Resource); + graphLockOperation.unlockComponent(componentId, nodeType); } } + private boolean isPropertyExistInComponent(List properties, String propertyName) { + if(CollectionUtils.isEmpty(properties)) { + return false; + } + + Optional propertyCandidate = + properties.stream().filter(property -> property.getName().equals(propertyName)) + .findAny(); + + return propertyCandidate.isPresent(); + } + private boolean isPropertyExist(List properties, String resourceUid, String propertyName, String propertyType) { boolean result = false; if (!CollectionUtils.isEmpty(properties)) { for (PropertyDefinition propertyDefinition : properties) { if ( propertyDefinition.getName().equals(propertyName) && - (propertyDefinition.getParentUniqueId().equals(resourceUid) || !propertyDefinition.getType().equals(propertyType)) ) { + (propertyDefinition.getParentUniqueId().equals(resourceUid) || !propertyDefinition.getType().equals(propertyType)) ) { result = true; break; } diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/components/property/ComponentPropertyDeclarator.java b/catalog-be/src/main/java/org/openecomp/sdc/be/components/property/ComponentPropertyDeclarator.java new file mode 100644 index 0000000000..7f49e389ef --- /dev/null +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/components/property/ComponentPropertyDeclarator.java @@ -0,0 +1,153 @@ +/* + * Copyright © 2016-2018 European Support Limited + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.openecomp.sdc.be.components.property; + +import fj.data.Either; +import org.apache.commons.collections.CollectionUtils; +import org.openecomp.sdc.be.components.impl.PropertyBusinessLogic; +import org.openecomp.sdc.be.datatypes.elements.GetInputValueDataDefinition; +import org.openecomp.sdc.be.datatypes.elements.PropertyDataDefinition; +import org.openecomp.sdc.be.impl.ComponentsUtils; +import org.openecomp.sdc.be.model.Component; +import org.openecomp.sdc.be.model.ComponentInstanceProperty; +import org.openecomp.sdc.be.model.InputDefinition; +import org.openecomp.sdc.be.model.PropertyDefinition; +import org.openecomp.sdc.be.model.jsontitan.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 { + + private ToscaOperationFacade toscaOperationFacade; + PropertyBusinessLogic propertyBL; + + + public ComponentPropertyDeclarator(ComponentsUtils componentsUtils, + PropertyOperation propertyOperation, + ToscaOperationFacade toscaOperationFacade, + PropertyBusinessLogic propertyBL) { + super(componentsUtils, propertyOperation); + this.toscaOperationFacade = toscaOperationFacade; + this.propertyBL = propertyBL; + } + + @Override + PropertyDataDefinition createDeclaredProperty(PropertyDataDefinition prop) { + return new PropertyDataDefinition(prop); + } + + @Override + Either updatePropertiesValues(Component component, + String propertiesOwnerId, + List properties) { + if(CollectionUtils.isNotEmpty(properties)) { + for(PropertyDataDefinition property : properties) { + Either + storageStatus = toscaOperationFacade + .updatePropertyOfComponent(component, new PropertyDefinition(property)); + if(storageStatus.isRight()) { + return Either.right(storageStatus.right().value()); + } + } + } + return Either.left(properties); + } + + @Override + Optional resolvePropertiesOwner(Component component, String propertiesOwnerId) { + return Optional.of( component); + } + + @Override + void addPropertiesListToInput(PropertyDataDefinition declaredProp, + InputDefinition input) { + + List 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); + } + + @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 propertyToUpdateCandidate = + getDeclaredPropertyByInputId(component, input.getUniqueId()); + + if(propertyToUpdateCandidate.isPresent()) { + PropertyDefinition propertyToUpdate = propertyToUpdateCandidate.get(); + return unDeclareInput(component, input, propertyToUpdate); + } + + + return StorageOperationStatus.OK; + } + + private StorageOperationStatus unDeclareInput(Component component, + InputDefinition input, + PropertyDefinition propertyToUpdate) { + prepareValueBeforeDelete(input, propertyToUpdate, Collections.emptyList()); + propertyToUpdate.setValue(input.getDefaultValue()); + Either status = toscaOperationFacade + .updatePropertyOfComponent(component, propertyToUpdate); + if(status.isRight()) { + return status.right().value(); + } + + return StorageOperationStatus.OK; + } + + private Optional getDeclaredPropertyByInputId(Component component, + String inputId) { + List properties = component.getProperties(); + + if(CollectionUtils.isEmpty(properties)) { + return Optional.empty(); + } + + for(PropertyDefinition propertyDefinition : properties) { + List getInputValues = propertyDefinition.getGetInputValues(); + if(CollectionUtils.isEmpty(getInputValues)) { + continue; + } + + Optional getInputCandidate = + getInputValues.stream().filter(getInput -> getInput.getInputId().equals(inputId)) + .findAny(); + + if(getInputCandidate.isPresent()) { + return Optional.of(propertyDefinition); + } + } + + return Optional.empty(); + } +} diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/components/property/DefaultPropertyDeclarator.java b/catalog-be/src/main/java/org/openecomp/sdc/be/components/property/DefaultPropertyDeclarator.java index a5ba0003d2..437ae2d67d 100644 --- a/catalog-be/src/main/java/org/openecomp/sdc/be/components/property/DefaultPropertyDeclarator.java +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/components/property/DefaultPropertyDeclarator.java @@ -87,20 +87,44 @@ public abstract class DefaultPropertyDeclarator propertiesToCreate, ComponentInstancePropInput propInput) { @@ -131,14 +155,20 @@ public abstract class DefaultPropertyDeclarator propertyDeclarators; - public PropertyDeclarationOrchestrator(ComponentInstanceInputPropertyDeclarator componentInstanceInputPropertyDeclarator, ComponentInstancePropertyDeclarator componentInstancePropertyDeclarator, PolicyPropertyDeclarator policyPropertyDeclarator, GroupPropertyDeclarator groupPropertyDeclarator) { + public PropertyDeclarationOrchestrator( + ComponentInstanceInputPropertyDeclarator componentInstanceInputPropertyDeclarator, + ComponentInstancePropertyDeclarator componentInstancePropertyDeclarator, + PolicyPropertyDeclarator policyPropertyDeclarator, + GroupPropertyDeclarator groupPropertyDeclarator, + ComponentPropertyDeclarator servicePropertyDeclarator) { this.componentInstanceInputPropertyDeclarator = componentInstanceInputPropertyDeclarator; this.componentInstancePropertyDeclarator = componentInstancePropertyDeclarator; this.policyPropertyDeclarator = policyPropertyDeclarator; this.groupPropertyDeclarator = groupPropertyDeclarator; - propertyDeclarators = Arrays.asList(componentInstanceInputPropertyDeclarator, componentInstancePropertyDeclarator, policyPropertyDeclarator, groupPropertyDeclarator); + this.servicePropertyDeclarator = servicePropertyDeclarator; + propertyDeclarators = Arrays.asList(componentInstanceInputPropertyDeclarator, componentInstancePropertyDeclarator, policyPropertyDeclarator, groupPropertyDeclarator, servicePropertyDeclarator); } public Either, StorageOperationStatus> declarePropertiesToInputs(Component component, ComponentInstInputsMap componentInstInputsMap) { @@ -64,6 +71,9 @@ public class PropertyDeclarationOrchestrator { if (isNotEmpty(componentInstInputsMap.getGroupProperties())) { return groupPropertyDeclarator; } + if(isNotEmpty(componentInstInputsMap.getServiceProperties())) { + return servicePropertyDeclarator; + } throw new IllegalStateException("there are no properties selected for declaration"); } diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/servlets/BeGenericServlet.java b/catalog-be/src/main/java/org/openecomp/sdc/be/servlets/BeGenericServlet.java index 5b8d6dcc17..4502012bd9 100644 --- a/catalog-be/src/main/java/org/openecomp/sdc/be/servlets/BeGenericServlet.java +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/servlets/BeGenericServlet.java @@ -23,8 +23,27 @@ package org.openecomp.sdc.be.servlets; import com.fasterxml.jackson.databind.DeserializationFeature; import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.databind.module.SimpleModule; +import com.google.gson.Gson; +import com.google.gson.GsonBuilder; +import com.google.gson.reflect.TypeToken; import fj.data.Either; -import org.openecomp.sdc.be.components.impl.*; +import org.json.simple.JSONArray; +import org.json.simple.JSONObject; +import org.json.simple.parser.JSONParser; +import org.json.simple.parser.ParseException; +import org.openecomp.sdc.be.components.impl.ArtifactsBusinessLogic; +import org.openecomp.sdc.be.components.impl.ComponentBusinessLogic; +import org.openecomp.sdc.be.components.impl.ComponentInstanceBusinessLogic; +import org.openecomp.sdc.be.components.impl.ElementBusinessLogic; +import org.openecomp.sdc.be.components.impl.GroupBusinessLogic; +import org.openecomp.sdc.be.components.impl.InterfaceOperationBusinessLogic; +import org.openecomp.sdc.be.components.impl.MonitoringBusinessLogic; +import org.openecomp.sdc.be.components.impl.PolicyBusinessLogic; +import org.openecomp.sdc.be.components.impl.PolicyTypeBusinessLogic; +import org.openecomp.sdc.be.components.impl.ProductBusinessLogic; +import org.openecomp.sdc.be.components.impl.PropertyBusinessLogic; +import org.openecomp.sdc.be.components.impl.ResourceBusinessLogic; +import org.openecomp.sdc.be.components.impl.ServiceBusinessLogic; import org.openecomp.sdc.be.components.lifecycle.LifecycleBusinessLogic; import org.openecomp.sdc.be.components.scheduledtasks.ComponentsCleanBusinessLogic; import org.openecomp.sdc.be.components.upgrade.UpgradeBusinessLogic; @@ -35,8 +54,11 @@ import org.openecomp.sdc.be.ecomp.converters.AssetMetadataConverter; import org.openecomp.sdc.be.impl.ComponentsUtils; import org.openecomp.sdc.be.impl.WebAppContextWrapper; import org.openecomp.sdc.be.model.PropertyConstraint; +import org.openecomp.sdc.be.model.PropertyDefinition; 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; +import org.openecomp.sdc.be.model.operations.impl.UniqueIdBuilder; import org.openecomp.sdc.be.resources.data.auditing.AuditingActionEnum; import org.openecomp.sdc.be.user.UserBusinessLogic; import org.openecomp.sdc.common.api.Constants; @@ -51,8 +73,12 @@ 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.lang.reflect.Type; +import java.util.HashMap; +import java.util.Iterator; import java.util.Map; import java.util.Map.Entry; +import java.util.Set; import java.util.function.Supplier; public class BeGenericServlet extends BasicServlet { @@ -79,8 +105,8 @@ public class BeGenericServlet extends BasicServlet { private static Response buildOkResponseStatic(Object entity) { return Response.status(Response.Status.OK) - .entity(entity) - .build(); + .entity(entity) + .build(); } protected Response buildOkResponse(ResponseFormat errorResponseWrapper, Object entity) { @@ -215,8 +241,8 @@ public class BeGenericServlet extends BasicServlet { protected String getContentDispositionValue(String artifactFileName) { return new StringBuilder().append("attachment; filename=\"").append(artifactFileName).append("\"").toString(); } - - + + protected ComponentBusinessLogic getComponentBL(ComponentTypeEnum componentTypeEnum, ServletContext context) { ComponentBusinessLogic businessLogic; @@ -243,8 +269,8 @@ public class BeGenericServlet extends BasicServlet { void convertJsonToObjectOfClass(String json, Wrapper policyWrapper, Class clazz, Wrapper errorWrapper) { T object = null; ObjectMapper mapper = new ObjectMapper() - .configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false) - .configure(DeserializationFeature.ACCEPT_SINGLE_VALUE_AS_ARRAY, true); + .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); @@ -266,4 +292,143 @@ public class BeGenericServlet extends BasicServlet { errorWrapper.setInnerElement(buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.INVALID_CONTENT))); } } + + protected Either, ActionStatus> getPropertyModel(String componentId, + String data) { + JSONParser parser = new JSONParser(); + JSONObject root; + try { + Map 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(); + JSONObject value = (JSONObject) next.getValue(); + String jsonString = value.toJSONString(); + Either convertJsonToObject = convertJsonToObject(jsonString, PropertyDefinition.class); + if (convertJsonToObject.isRight()) { + return Either.right(convertJsonToObject.right().value()); + } + PropertyDefinition propertyDefinition = convertJsonToObject.left().value(); + String uniqueId = UniqueIdBuilder.buildPropertyUniqueId(componentId, (String) propertyName); + propertyDefinition.setUniqueId(uniqueId); + properties.put(propertyName, propertyDefinition); + } + + return Either.left(properties); + } catch (ParseException e) { + log.info("Property conetnt is invalid - {}", data); + return Either.right(ActionStatus.INVALID_CONTENT); + } + } + + protected Either, ActionStatus> getPropertiesListForUpdate(String data) { + + Map properties = new HashMap<>(); + JSONParser parser = new JSONParser(); + JSONArray jsonArray; + + try { + jsonArray = (JSONArray) parser.parse(data); + for (Object jsonElement : jsonArray) { + String propertyAsString = jsonElement.toString(); + Either 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 property) { + JSONObject root = new JSONObject(); + String propertyName = property.getKey(); + PropertyDefinition propertyDefinition = property.getValue(); + JSONObject propertyDefinitionO = getPropertyDefinitionJSONObject(propertyDefinition); + root.put(propertyName, propertyDefinitionO); + propertyDefinition.getType(); + return root.toString(); + } + + private JSONObject getPropertyDefinitionJSONObject(PropertyDefinition propertyDefinition) { + + Either either = convertObjectToJson(propertyDefinition); + if (either.isRight()) { + return new JSONObject(); + } + String value = either.left().value(); + try { + JSONObject root = (JSONObject) new JSONParser().parse(value); + return root; + } catch (ParseException e) { + log.info("failed to convert input to json"); + log.debug("failed to convert to json", e); + return new JSONObject(); + } + + } + + protected Either convertJsonToObject(String data, Class clazz) { + T t = null; + Type constraintType = new TypeToken() { + }.getType(); + 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); + if (t == null) { + log.info("object is null after converting from json"); + return Either.right(ActionStatus.INVALID_CONTENT); + } + } catch (Exception e) { + // INVALID JSON + log.info("failed to convert from json"); + log.debug("failed to convert from json", e); + return Either.right(ActionStatus.INVALID_CONTENT); + } + return Either.left(t); + } + + private Either convertObjectToJson(PropertyDefinition propertyDefinition) { + Type constraintType = new TypeToken() { + }.getType(); + Gson gson = new GsonBuilder().registerTypeAdapter(constraintType, new PropertyOperation.PropertyConstraintSerialiser()).create(); + try { + log.trace("convert object to json. propertyDefinition= {}", propertyDefinition); + String json = gson.toJson(propertyDefinition); + if (json == null) { + log.info("object is null after converting to json"); + return Either.right(ActionStatus.INVALID_CONTENT); + } + return Either.left(json); + } catch (Exception e) { + // INVALID JSON + log.info("failed to convert to json"); + log.debug("failed to convert fto json", e); + return Either.right(ActionStatus.INVALID_CONTENT); + } + + } + + protected PropertyBusinessLogic getPropertyBL(ServletContext context) { + WebAppContextWrapper webApplicationContextWrapper = (WebAppContextWrapper) context.getAttribute(Constants.WEB_APPLICATION_CONTEXT_WRAPPER_ATTR); + WebApplicationContext webApplicationContext = webApplicationContextWrapper.getWebAppContext(context); + PropertyBusinessLogic propertytBl = webApplicationContext.getBean(PropertyBusinessLogic.class); + return propertytBl; + } } diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/servlets/ComponentInstanceServlet.java b/catalog-be/src/main/java/org/openecomp/sdc/be/servlets/ComponentInstanceServlet.java index 042303e2c3..b5e28148da 100644 --- a/catalog-be/src/main/java/org/openecomp/sdc/be/servlets/ComponentInstanceServlet.java +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/servlets/ComponentInstanceServlet.java @@ -1139,7 +1139,7 @@ public class ComponentInstanceServlet extends AbstractValidationsServlet { return Either.left(requirementCapabilityRelDef); } - private Either convertJsonToObject(String data, Class clazz) { + public Either convertJsonToObject(String data, Class clazz) { try { log.trace("convert json to object. json=\n {}", data); T t; diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/servlets/ComponentPropertyServlet.java b/catalog-be/src/main/java/org/openecomp/sdc/be/servlets/ComponentPropertyServlet.java new file mode 100644 index 0000000000..0edce61bae --- /dev/null +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/servlets/ComponentPropertyServlet.java @@ -0,0 +1,390 @@ +/* + * Copyright © 2016-2018 European Support Limited + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.openecomp.sdc.be.servlets; + +import com.jcabi.aspects.Loggable; +import fj.data.Either; +import io.swagger.annotations.Api; +import io.swagger.annotations.ApiOperation; +import io.swagger.annotations.ApiParam; +import io.swagger.annotations.ApiResponse; +import io.swagger.annotations.ApiResponses; +import org.openecomp.sdc.be.components.impl.PropertyBusinessLogic; +import org.openecomp.sdc.be.config.BeEcompErrorManager; +import org.openecomp.sdc.be.dao.api.ActionStatus; +import org.openecomp.sdc.be.model.PropertyDefinition; +import org.openecomp.sdc.be.model.User; +import org.openecomp.sdc.be.resources.data.EntryData; +import org.openecomp.sdc.common.api.Constants; +import org.openecomp.sdc.exception.ResponseFormat; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import javax.inject.Singleton; +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.Map; + +@Loggable(prepend = true, value = Loggable.DEBUG, trim = false) +@Path("/v1/catalog") +@Api(value = "Component Property Servlet", description = "Property Servlet - used to create properties in Service and Resource") +@Singleton +public class ComponentPropertyServlet extends BeGenericServlet { + + private static final Logger log = LoggerFactory.getLogger(ComponentPropertyServlet.class); + + @POST + @Path("services/{serviceId}/properties") + @Consumes(MediaType.APPLICATION_JSON) + @Produces(MediaType.APPLICATION_JSON) + @ApiOperation(value = "Create Service Property", httpMethod = "POST", notes = "Returns created service property", response = Response.class) + @ApiResponses(value = { @ApiResponse(code = 201, message = "Service property created"), + @ApiResponse(code = 403, message = "Restricted operation"), @ApiResponse(code = 400, message = "Invalid content / Missing content"), + @ApiResponse(code = 409, message = "Service property already exist") }) + public Response createPropertyInService(@ApiParam(value = "service id to update with new property", required = true) @PathParam("serviceId") final String serviceId, + @ApiParam(value = "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); + } + + @POST + @Path("resources/{resourceId}/properties") + @Consumes(MediaType.APPLICATION_JSON) + @Produces(MediaType.APPLICATION_JSON) + @ApiOperation(value = "Create Resource Property", httpMethod = "POST", notes = "Returns created service property", response = Response.class) + @ApiResponses(value = { @ApiResponse(code = 201, message = "Resource property created"), + @ApiResponse(code = 403, message = "Restricted operation"), @ApiResponse(code = 400, message = "Invalid content / Missing content"), + @ApiResponse(code = 409, message = "Resource property already exist") }) + public Response createPropertyInResource(@ApiParam(value = "Resource id to update with new property", required = true) @PathParam("resourceId") final String resourceId, + @ApiParam(value = "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) + @ApiOperation(value = "Get Service Property", httpMethod = "GET", notes = "Returns property of service", response = Response.class) + @ApiResponses(value = { @ApiResponse(code = 200, message = "property"), @ApiResponse(code = 403, message = "Restricted operation"), @ApiResponse(code = 400, message = "Invalid content / Missing content"), + @ApiResponse(code = 404, message = "Service property not found") }) + public Response getPropertyInService(@ApiParam(value = "service id of property", required = true) + @PathParam("serviceId") final String serviceId, @ApiParam(value = "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); + } + + @GET + @Path("resources/{resourceId}/properties/{propertyId}") + @Consumes(MediaType.APPLICATION_JSON) + @Produces(MediaType.APPLICATION_JSON) + @ApiOperation(value = "Get Resource Property", httpMethod = "GET", notes = "Returns property of resource", response = Response.class) + @ApiResponses(value = { @ApiResponse(code = 200, message = "property"), @ApiResponse(code = 403, message = "Restricted operation"), @ApiResponse(code = 400, message = "Invalid content / Missing content"), + @ApiResponse(code = 404, message = "Resource property not found") }) + public Response getPropertyInResource(@ApiParam(value = "resource id of property", required = true) + @PathParam("resourceId") final String resourceId, @ApiParam(value = "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); + } + + @GET + @Path("services/{serviceId}/properties") + @Consumes(MediaType.APPLICATION_JSON) + @Produces(MediaType.APPLICATION_JSON) + @ApiOperation(value = "Get Service Property", httpMethod = "GET", notes = "Returns property list of service", response = Response.class) + @ApiResponses(value = { @ApiResponse(code = 200, message = "property"), @ApiResponse(code = 403, message = "Restricted operation"), @ApiResponse(code = 400, message = "Invalid content / Missing content"), + @ApiResponse(code = 404, message = "Service property not found") }) + public Response getPropertyListInService(@ApiParam(value = "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); + } + + @GET + @Path("resources/{resourceId}/properties") + @Consumes(MediaType.APPLICATION_JSON) + @Produces(MediaType.APPLICATION_JSON) + @ApiOperation(value = "Get Resource Property", httpMethod = "GET", notes = "Returns property list of resource", response = Response.class) + @ApiResponses(value = { @ApiResponse(code = 200, message = "property"), @ApiResponse(code = 403, message = "Restricted operation"), @ApiResponse(code = 400, message = "Invalid content / Missing content"), + @ApiResponse(code = 404, message = "Resource property not found") }) + public Response getPropertyListInResource(@ApiParam(value = "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); + } + + @DELETE + @Path("services/{serviceId}/properties/{propertyId}") + @Consumes(MediaType.APPLICATION_JSON) + @Produces(MediaType.APPLICATION_JSON) + @ApiOperation(value = "Delete Service Property", httpMethod = "DELETE", notes = "Returns deleted property", response = Response.class) + @ApiResponses(value = { @ApiResponse(code = 204, message = "deleted property"), @ApiResponse(code = 403, message = "Restricted operation"), @ApiResponse(code = 400, message = "Invalid content / Missing content"), + @ApiResponse(code = 404, message = "Service property not found") }) + public Response deletePropertyInService(@ApiParam(value = "service id of property", required = true) @PathParam("serviceId") final String serviceId, + @ApiParam(value = "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); + } + + @DELETE + @Path("resources/{resourceId}/properties/{propertyId}") + @Consumes(MediaType.APPLICATION_JSON) + @Produces(MediaType.APPLICATION_JSON) + @ApiOperation(value = "Delete Resource Property", httpMethod = "DELETE", notes = "Returns deleted property", response = Response.class) + @ApiResponses(value = { @ApiResponse(code = 204, message = "deleted property"), @ApiResponse(code = 403, message = "Restricted operation"), @ApiResponse(code = 400, message = "Invalid content / Missing content"), + @ApiResponse(code = 404, message = "Resource property not found") }) + public Response deletePropertyInResource(@ApiParam(value = "resource id of property", required = true) @PathParam("resourceId") final String resourceId, + @ApiParam(value = "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); + } + + @PUT + @Path("services/{serviceId}/properties") + @Consumes(MediaType.APPLICATION_JSON) + @Produces(MediaType.APPLICATION_JSON) + @ApiOperation(value = "Update Service Property", httpMethod = "PUT", notes = "Returns updated property", response = Response.class) + @ApiResponses(value = { @ApiResponse(code = 200, message = "Service property updated"), + @ApiResponse(code = 403, message = "Restricted operation"), @ApiResponse(code = 400, message = "Invalid content / Missing content") }) + public Response updatePropertyInService(@ApiParam(value = "service id to update with new property", required = true) @PathParam("serviceId") final String serviceId, + @ApiParam(value = "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); + } + + @PUT + @Path("resources/{resourceId}/properties") + @Consumes(MediaType.APPLICATION_JSON) + @Produces(MediaType.APPLICATION_JSON) + @ApiOperation(value = "Update Resource Property", httpMethod = "PUT", notes = "Returns updated property", response = Response.class) + @ApiResponses(value = { @ApiResponse(code = 200, message = "Resource property updated"), + @ApiResponse(code = 403, message = "Restricted operation"), @ApiResponse(code = 400, message = "Invalid content / Missing content") }) + public Response updatePropertyInResource(@ApiParam(value = "resource id to update with new property", required = true) @PathParam("resourceId") final String resourceId, + @ApiParam(value = "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) { + 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{ + Either, ActionStatus> propertyDefinition = + getPropertyModel(componentId, data); + if (propertyDefinition.isRight()) { + ResponseFormat responseFormat = getComponentsUtils().getResponseFormat(propertyDefinition.right().value()); + return buildErrorResponse(responseFormat); + } + + Map 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 entry = properties.entrySet().iterator().next(); + PropertyDefinition newPropertyDefinition = entry.getValue(); + newPropertyDefinition.setParentUniqueId(componentId); + String propertyName = newPropertyDefinition.getName(); + + PropertyBusinessLogic propertyBL = getPropertyBL(context); + Either, ResponseFormat> addPropertyEither = + propertyBL.addPropertyToComponent(componentId, propertyName, newPropertyDefinition, userId); + + if(addPropertyEither.isRight()) { + return buildErrorResponse(addPropertyEither.right().value()); + } + + 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); + } + } + + + private Response updateProperty(String componentId, String data, HttpServletRequest request, String userId) { + 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 { + // convert json to PropertyDefinition + + Either, ActionStatus> propertiesListEither = + getPropertiesListForUpdate(data); + if (propertiesListEither.isRight()) { + ResponseFormat responseFormat = + getComponentsUtils().getResponseFormat(propertiesListEither.right().value()); + return buildErrorResponse(responseFormat); + } + Map properties = propertiesListEither.left().value(); + if (properties == null) { + log.info("Property content is invalid - {}", data); + ResponseFormat responseFormat = + getComponentsUtils().getResponseFormat(ActionStatus.INVALID_CONTENT); + return buildErrorResponse(responseFormat); + } + + // update property + + PropertyBusinessLogic businessLogic = getPropertyBL(context); + for(PropertyDefinition propertyDefinition : properties.values()) { + Either, ResponseFormat> status = + businessLogic.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 property = status.left().value(); + PropertyDefinition updatedPropertyDefinition = property.getValue(); + + log.debug("Property id {} updated successfully ", updatedPropertyDefinition.getUniqueId()); + } + + ResponseFormat responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.OK); + 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) { + ServletContext context = request.getSession().getServletContext(); + + String url = request.getMethod() + " " + request.getRequestURI(); + log.debug("Start handle request of {} modifier id is {}", url, userId); + + try { + PropertyBusinessLogic propertyBL = getPropertyBL(context); + Either, ResponseFormat> retrievedPropertyEither = + propertyBL.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) { + ServletContext context = request.getSession().getServletContext(); + + String url = request.getMethod() + " " + request.getRequestURI(); + log.debug("Start handle request of {} modifier id is {}", url, userId); + + try { + PropertyBusinessLogic propertyBL = getPropertyBL(context); + Either, ResponseFormat> propertiesListEither = + propertyBL.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) { + ServletContext context = request.getSession().getServletContext(); + + String url = request.getMethod() + " " + request.getRequestURI(); + log.debug("Start handle request of {} modifier id is {}", url, userId); + + try { + + // delete the property + PropertyBusinessLogic businessLogic = getPropertyBL(context); + Either, ResponseFormat> status = + businessLogic.deletePropertyFromComponent(componentId, propertyId, userId); + if (status.isRight()) { + log.debug("Failed to delete Property. Reason - ", status.right().value()); + return buildErrorResponse(status.right().value()); + } + Map.Entry 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); + + } + } + +} diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/servlets/PropertyServlet.java b/catalog-be/src/main/java/org/openecomp/sdc/be/servlets/PropertyServlet.java deleted file mode 100644 index 12d788dd45..0000000000 --- a/catalog-be/src/main/java/org/openecomp/sdc/be/servlets/PropertyServlet.java +++ /dev/null @@ -1,369 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * SDC - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - */ - -package org.openecomp.sdc.be.servlets; - -import com.google.gson.Gson; -import com.google.gson.GsonBuilder; -import com.google.gson.reflect.TypeToken; -import com.jcabi.aspects.Loggable; -import fj.data.Either; -import io.swagger.annotations.*; -import org.json.simple.JSONObject; -import org.json.simple.parser.JSONParser; -import org.json.simple.parser.ParseException; -import org.openecomp.sdc.be.components.impl.PropertyBusinessLogic; -import org.openecomp.sdc.be.config.BeEcompErrorManager; -import org.openecomp.sdc.be.dao.api.ActionStatus; -import org.openecomp.sdc.be.impl.WebAppContextWrapper; -import org.openecomp.sdc.be.model.PropertyConstraint; -import org.openecomp.sdc.be.model.PropertyDefinition; -import org.openecomp.sdc.be.model.User; -import org.openecomp.sdc.be.model.operations.impl.PropertyOperation.PropertyConstraintDeserialiser; -import org.openecomp.sdc.be.model.operations.impl.PropertyOperation.PropertyConstraintSerialiser; -import org.openecomp.sdc.be.model.operations.impl.UniqueIdBuilder; -import org.openecomp.sdc.be.resources.data.EntryData; -import org.openecomp.sdc.common.api.Constants; -import org.openecomp.sdc.common.log.wrappers.Logger; -import org.openecomp.sdc.exception.ResponseFormat; -import org.springframework.web.context.WebApplicationContext; - -import javax.inject.Singleton; -import javax.servlet.ServletContext; -import javax.servlet.http.HttpServletRequest; -import javax.ws.rs.*; -import javax.ws.rs.core.Context; -import javax.ws.rs.core.MediaType; -import javax.ws.rs.core.Response; -import java.lang.reflect.Type; -import java.util.HashMap; -import java.util.Iterator; -import java.util.Map; -import java.util.Map.Entry; -import java.util.Set; - -@Loggable(prepend = true, value = Loggable.DEBUG, trim = false) -@Path("/v1/catalog") -@Api(value = "Resource Property Servlet", description = "Resource Property Servlet") -@Singleton -public class PropertyServlet extends BeGenericServlet { - - private static final Logger log = Logger.getLogger(PropertyServlet.class.getName()); - - @POST - @Path("resources/{resourceId}/properties") - @Consumes(MediaType.APPLICATION_JSON) - @Produces(MediaType.APPLICATION_JSON) - @ApiOperation(value = "Create Resource Property", httpMethod = "POST", notes = "Returns created resource property", response = Response.class) - @ApiResponses(value = { @ApiResponse(code = 201, message = "Resource property created"), @ApiResponse(code = 403, message = "Restricted operation"), @ApiResponse(code = 400, message = "Invalid content / Missing content"), - @ApiResponse(code = 409, message = "Resource property already exist") }) - public Response createProperty(@ApiParam(value = "resource id to update with new property", required = true) @PathParam("resourceId") final String resourceId, @ApiParam(value = "Resource property to be created", required = true) String data, - @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 {} modifier id is {} data is {}", url, userId, data); - - try { - // convert json to PropertyDefinition - Either, ActionStatus> either = getPropertyModel(resourceId, data); - if (either.isRight()) { - ResponseFormat responseFormat = getComponentsUtils().getResponseFormat(either.right().value()); - return buildErrorResponse(responseFormat); - } - Map properties = either.left().value(); - if (properties == null || properties.size() != 1) { - log.info("Property conetnt is invalid - {}", data); - ResponseFormat responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.INVALID_CONTENT); - return buildErrorResponse(responseFormat); - } - Entry entry = properties.entrySet().iterator().next(); - String propertyName = entry.getKey(); - PropertyDefinition newPropertyDefinition = entry.getValue(); - - // create the new property - PropertyBusinessLogic businessLogic = getPropertyBL(context); - Either, ResponseFormat> status = businessLogic.createProperty(resourceId, propertyName, newPropertyDefinition, userId); - if (status.isRight()) { - log.info("Failed to create Property. Reason - ", status.right().value()); - return buildErrorResponse(status.right().value()); - } - EntryData property = status.left().value(); - String name = property.getKey(); - PropertyDefinition propertyDefinition = property.getValue(); - - log.debug("Property {} created successfully with id {}", name, propertyDefinition.getUniqueId()); - ResponseFormat responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.CREATED); - return buildOkResponse(responseFormat, propertyToJson(property)); - - } 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 - @Path("resources/{resourceId}/properties/{propertyId}") - @Consumes(MediaType.APPLICATION_JSON) - @Produces(MediaType.APPLICATION_JSON) - @ApiOperation(value = "Create Resource Property", httpMethod = "GET", notes = "Returns property of resource", response = Response.class) - @ApiResponses(value = { @ApiResponse(code = 200, message = "property"), @ApiResponse(code = 403, message = "Restricted operation"), @ApiResponse(code = 400, message = "Invalid content / Missing content"), - @ApiResponse(code = 404, message = "Resource property not found") }) - public Response getProperty(@ApiParam(value = "resource id of property", required = true) @PathParam("resourceId") final String resourceId, @ApiParam(value = "proerty id to get", required = true) @PathParam("propertyId") final String propertyId, - @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 {}, modifier id is {}", url, userId); - - try { - - // - PropertyBusinessLogic businessLogic = getPropertyBL(context); - Either, ResponseFormat> status = businessLogic.getProperty(resourceId, propertyId, userId); - - if (status.isRight()) { - log.info("Failed to get Property. Reason - ", status.right().value()); - return buildErrorResponse(status.right().value()); - } - Entry property = status.left().value(); - ResponseFormat responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.OK); - return buildOkResponse(responseFormat, propertyToJson(property)); - } catch (Exception e) { - BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Get Property"); - log.debug("get property failed with exception", e); - ResponseFormat responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR); - return buildErrorResponse(responseFormat); - - } - } - - @DELETE - @Path("resources/{resourceId}/properties/{propertyId}") - @Consumes(MediaType.APPLICATION_JSON) - @Produces(MediaType.APPLICATION_JSON) - @ApiOperation(value = "Create Resource Property", httpMethod = "DELETE", notes = "Returns deleted property", response = Response.class) - @ApiResponses(value = { @ApiResponse(code = 204, message = "deleted property"), @ApiResponse(code = 403, message = "Restricted operation"), @ApiResponse(code = 400, message = "Invalid content / Missing content"), - @ApiResponse(code = 404, message = "Resource property not found") }) - public Response deleteProperty(@ApiParam(value = "resource id of property", required = true) @PathParam("resourceId") final String resourceId, - @ApiParam(value = "Property id to delete", required = true) @PathParam("propertyId") final String propertyId, @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 {} modifier id is {}", url, userId); - - try { - - // delete the property - PropertyBusinessLogic businessLogic = getPropertyBL(context); - Either, ResponseFormat> status = businessLogic.deleteProperty(resourceId, propertyId, userId); - if (status.isRight()) { - log.debug("Failed to delete Property. Reason - ", status.right().value()); - return buildErrorResponse(status.right().value()); - } - Entry 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); - - } - } - - @PUT - @Path("resources/{resourceId}/properties/{propertyId}") - @Consumes(MediaType.APPLICATION_JSON) - @Produces(MediaType.APPLICATION_JSON) - @ApiOperation(value = "Update Resource Property", httpMethod = "PUT", notes = "Returns updated property", response = Response.class) - @ApiResponses(value = { @ApiResponse(code = 200, message = "Resource property updated"), @ApiResponse(code = 403, message = "Restricted operation"), @ApiResponse(code = 400, message = "Invalid content / Missing content") }) - public Response updateProperty(@ApiParam(value = "resource id to update with new property", required = true) @PathParam("resourceId") final String resourceId, - @ApiParam(value = "proerty id to update", required = true) @PathParam("propertyId") final String propertyId, @ApiParam(value = "Resource property to update", required = true) String data, @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); - - // get modifier id - User modifier = new User(); - modifier.setUserId(userId); - log.debug("modifier id is {}", userId); - - try { - // convert json to PropertyDefinition - Either, ActionStatus> either = getPropertyModel(resourceId, data); - if (either.isRight()) { - ResponseFormat responseFormat = getComponentsUtils().getResponseFormat(either.right().value()); - return buildErrorResponse(responseFormat); - } - Map properties = either.left().value(); - if (properties == null || properties.size() != 1) { - log.info("Property conetnt is invalid - {}", data); - ResponseFormat responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.INVALID_CONTENT); - return buildErrorResponse(responseFormat); - } - Entry entry = properties.entrySet().iterator().next(); - PropertyDefinition newPropertyDefinition = entry.getValue(); - - // update property - PropertyBusinessLogic businessLogic = getPropertyBL(context); - Either, ResponseFormat> status = businessLogic.updateProperty(resourceId, propertyId, newPropertyDefinition, userId); - if (status.isRight()) { - log.info("Failed to update Property. Reason - ", status.right().value()); - return buildErrorResponse(status.right().value()); - } - EntryData property = status.left().value(); - PropertyDefinition propertyDefinition = property.getValue(); - - log.debug("Property id {} updated successfully ", propertyDefinition.getUniqueId()); - ResponseFormat responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.OK); - return buildOkResponse(responseFormat, propertyToJson(property)); - - } 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 Either, ActionStatus> getPropertyModel(String resourceId, String data) { - JSONParser parser = new JSONParser(); - JSONObject root; - try { - Map 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(); - JSONObject value = (JSONObject) next.getValue(); - String jsonString = value.toJSONString(); - Either convertJsonToObject = convertJsonToObject(jsonString, PropertyDefinition.class); - if (convertJsonToObject.isRight()) { - return Either.right(convertJsonToObject.right().value()); - } - PropertyDefinition propertyDefinition = convertJsonToObject.left().value(); - String uniqueId = UniqueIdBuilder.buildPropertyUniqueId(resourceId, (String) propertyName); - propertyDefinition.setUniqueId(uniqueId); - properties.put(propertyName, propertyDefinition); - } - - return Either.left(properties); - } catch (ParseException e) { - log.info("Property conetnt is invalid - {}", data); - return Either.right(ActionStatus.INVALID_CONTENT); - } - } - - private String propertyToJson(Map.Entry property) { - JSONObject root = new JSONObject(); - String propertyName = property.getKey(); - PropertyDefinition propertyDefinition = property.getValue(); - JSONObject propertyDefinitionO = getPropertyDefinitionJSONObject(propertyDefinition); - root.put(propertyName, propertyDefinitionO); - propertyDefinition.getType(); - return root.toString(); - } - - private JSONObject getPropertyDefinitionJSONObject(PropertyDefinition propertyDefinition) { - - Either either = convertObjectToJson(propertyDefinition); - if (either.isRight()) { - return new JSONObject(); - } - String value = either.left().value(); - try { - return (JSONObject) new JSONParser().parse(value); - } catch (ParseException e) { - log.info("failed to convert input to json"); - log.debug("failed to convert to json", e); - return new JSONObject(); - } - - } - - private Either convertJsonToObject(String data, Class clazz) { - T t = null; - Type constraintType = new TypeToken() { - }.getType(); - Gson gson = new GsonBuilder().registerTypeAdapter(constraintType, new PropertyConstraintDeserialiser()).create(); - try { - log.trace("convert json to object. json=\n {}", data); - t = gson.fromJson(data, clazz); - if (t == null) { - log.info("object is null after converting from json"); - return Either.right(ActionStatus.INVALID_CONTENT); - } - } catch (Exception e) { - // INVALID JSON - log.info("failed to convert from json"); - log.debug("failed to convert from json", e); - return Either.right(ActionStatus.INVALID_CONTENT); - } - return Either.left(t); - } - - private Either convertObjectToJson(PropertyDefinition propertyDefinition) { - Type constraintType = new TypeToken() { - }.getType(); - Gson gson = new GsonBuilder().registerTypeAdapter(constraintType, new PropertyConstraintSerialiser()).create(); - try { - log.trace("convert object to json. propertyDefinition= {}", propertyDefinition); - String json = gson.toJson(propertyDefinition); - if (json == null) { - log.info("object is null after converting to json"); - return Either.right(ActionStatus.INVALID_CONTENT); - } - return Either.left(json); - } catch (Exception e) { - // INVALID JSON - log.info("failed to convert to json"); - log.debug("failed to convert fto json", e); - return Either.right(ActionStatus.INVALID_CONTENT); - } - - } - - private PropertyBusinessLogic getPropertyBL(ServletContext context) { - WebAppContextWrapper webApplicationContextWrapper = (WebAppContextWrapper) context.getAttribute(Constants.WEB_APPLICATION_CONTEXT_WRAPPER_ATTR); - WebApplicationContext webApplicationContext = webApplicationContextWrapper.getWebAppContext(context); - return webApplicationContext.getBean(PropertyBusinessLogic.class); - } - -} diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/servlets/TypesFetchServlet.java b/catalog-be/src/main/java/org/openecomp/sdc/be/servlets/TypesFetchServlet.java index ddb405779d..00b04a4ffc 100644 --- a/catalog-be/src/main/java/org/openecomp/sdc/be/servlets/TypesFetchServlet.java +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/servlets/TypesFetchServlet.java @@ -105,12 +105,6 @@ public class TypesFetchServlet extends AbstractValidationsServlet { } } - private PropertyBusinessLogic getPropertyBL(ServletContext context) { - WebAppContextWrapper webApplicationContextWrapper = (WebAppContextWrapper) context.getAttribute(Constants.WEB_APPLICATION_CONTEXT_WRAPPER_ATTR); - WebApplicationContext webApplicationContext = webApplicationContextWrapper.getWebAppContext(context); - return webApplicationContext.getBean(PropertyBusinessLogic.class); - } - @GET @Path("interfaceLifecycleTypes") @Consumes(MediaType.APPLICATION_JSON) diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/tosca/CapabilityRequirementConverter.java b/catalog-be/src/main/java/org/openecomp/sdc/be/tosca/CapabilityRequirementConverter.java index 6a06c943a0..04119fed7b 100644 --- a/catalog-be/src/main/java/org/openecomp/sdc/be/tosca/CapabilityRequirementConverter.java +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/tosca/CapabilityRequirementConverter.java @@ -488,7 +488,7 @@ public class CapabilityRequirementConverter { if (isNotEmpty(properties)) { Map toscaProperties = new HashMap<>(); for (PropertyDefinition property : properties) { - ToscaProperty toscaProperty = PropertyConvertor.getInstance().convertProperty(dataTypes, property, true); + ToscaProperty toscaProperty = PropertyConvertor.getInstance().convertProperty(dataTypes, property, PropertyConvertor.PropertyType.CAPABILITY); toscaProperties.put(property.getName(), toscaProperty); } toscaCapability.setProperties(toscaProperties); @@ -520,7 +520,7 @@ public class CapabilityRequirementConverter { if (isNotEmpty(properties)) { Map toscaProperties = new HashMap<>(); for (PropertyDefinition property : properties) { - ToscaProperty toscaProperty = PropertyConvertor.getInstance().convertProperty(dataTypes, property, true); + ToscaProperty toscaProperty = PropertyConvertor.getInstance().convertProperty(dataTypes, property, PropertyConvertor.PropertyType.CAPABILITY); toscaProperties.put(property.getName(), toscaProperty); } toscaCapability.setProperties(toscaProperties); diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/tosca/PropertyConvertor.java b/catalog-be/src/main/java/org/openecomp/sdc/be/tosca/PropertyConvertor.java index d128d5349f..04c7c69daa 100644 --- a/catalog-be/src/main/java/org/openecomp/sdc/be/tosca/PropertyConvertor.java +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/tosca/PropertyConvertor.java @@ -20,11 +20,13 @@ package org.openecomp.sdc.be.tosca; -import com.google.gson.Gson; -import com.google.gson.JsonElement; -import com.google.gson.JsonParser; -import com.google.gson.stream.JsonReader; -import fj.data.Either; +import java.io.StringReader; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.Objects; +import java.util.function.Supplier; + import org.apache.commons.lang3.StringUtils; import org.openecomp.sdc.be.datatypes.elements.PropertyDataDefinition; import org.openecomp.sdc.be.datatypes.elements.SchemaDefinition; @@ -35,6 +37,7 @@ import org.openecomp.sdc.be.model.Resource; 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.ToscaStringConvertor; 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.EntrySchema; @@ -42,18 +45,24 @@ import org.openecomp.sdc.be.tosca.model.ToscaNodeType; import org.openecomp.sdc.be.tosca.model.ToscaProperty; import org.openecomp.sdc.common.log.wrappers.Logger; -import java.io.StringReader; -import java.util.HashMap; -import java.util.List; -import java.util.Map; -import java.util.function.Supplier; +import com.google.gson.Gson; +import com.google.gson.JsonElement; +import com.google.gson.JsonParser; +import com.google.gson.stream.JsonReader; + +import fj.data.Either; public class PropertyConvertor { private static PropertyConvertor instance; private JsonParser jsonParser = new JsonParser(); private static final Logger log = Logger.getLogger(PropertyConvertor.class); + public enum PropertyType { + CAPABILITY, + INPUT, + PROPERTY + } Gson gson = new Gson(); - protected PropertyConvertor() { + public PropertyConvertor() { } @@ -74,7 +83,7 @@ public class PropertyConvertor { // 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, false)); + properties.put(property.getName(), convertProperty(dataTypes, property, PropertyType.PROPERTY)); }); if (!properties.isEmpty()) { toscaNodeType.setProperties(properties); @@ -84,7 +93,7 @@ public class PropertyConvertor { return Either.left(toscaNodeType); } - public ToscaProperty convertProperty(Map dataTypes, PropertyDataDefinition property, boolean isCapabiltyProperty) { + public ToscaProperty convertProperty(Map dataTypes, PropertyDefinition property, PropertyType propertyType) { ToscaProperty prop = new ToscaProperty(); String innerType = null; @@ -96,22 +105,35 @@ public class PropertyConvertor { eschema.setDescription(schema.getProperty().getDescription()); prop.setEntry_schema(eschema); } - return getToscaProperty(dataTypes, property, isCapabiltyProperty, prop, innerType); + return getToscaProperty(dataTypes, property, prop, innerType, propertyType); } - private ToscaProperty getToscaProperty(Map dataTypes, PropertyDataDefinition property, boolean isCapabiltyProperty, ToscaProperty prop, String innerType) { + private ToscaProperty getToscaProperty(Map dataTypes, + PropertyDataDefinition property, + ToscaProperty prop, + String innerType, + PropertyType propertyType) { log.trace("try to convert property {} from type {} with default value [{}]", property.getName(), property.getType(), property.getDefaultValue()); - Object convertedObj = convertToToscaObject(property.getType(), property.getDefaultValue(), innerType, dataTypes, false); + String defaultValue = property.getDefaultValue(); + if(Objects.isNull(defaultValue)) { + defaultValue = property.getValue(); + } + Object convertedObj = + convertToToscaObject(property.getType(), defaultValue, innerType, dataTypes, false); if (convertedObj != null) { prop.setDefaultp(convertedObj); } prop.setType(property.getType()); prop.setDescription(property.getDescription()); - if (isCapabiltyProperty) { - prop.setStatus(property.getStatus()); - } prop.setRequired(property.isRequired()); + switch (propertyType) { + case CAPABILITY: + prop.setStatus(property.getStatus()); + break; + default: + break; + } return prop; } @@ -198,9 +220,9 @@ public class PropertyConvertor { } private boolean valueStartsWithNonJsonChar(String value) { - return value.startsWith("/") || value.startsWith(":") || value.startsWith("#"); + return value.startsWith("/") || value.startsWith(":"); } - + public void convertAndAddValue(Map dataTypes, Map props, PropertyDataDefinition prop, Supplier supplier) { Object convertedValue = convertValue(dataTypes, prop, supplier); diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/tosca/ToscaExportHandler.java b/catalog-be/src/main/java/org/openecomp/sdc/be/tosca/ToscaExportHandler.java index d0286d72d9..ecead12478 100644 --- a/catalog-be/src/main/java/org/openecomp/sdc/be/tosca/ToscaExportHandler.java +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/tosca/ToscaExportHandler.java @@ -20,10 +20,11 @@ package org.openecomp.sdc.be.tosca; -import static org.openecomp.sdc.be.tosca.utils.InterfacesOperationsToscaUtil.addInterfaceDefinitionElement; -import static org.openecomp.sdc.be.tosca.utils.InterfacesOperationsToscaUtil.addInterfaceTypeElement; - +import com.fasterxml.jackson.databind.ObjectMapper; +import com.fasterxml.jackson.databind.SerializationFeature; import fj.data.Either; +import org.apache.commons.collections.CollectionUtils; +import org.apache.commons.collections.MapUtils; import org.apache.commons.lang.StringUtils; import org.apache.commons.lang3.tuple.ImmutablePair; import org.apache.commons.lang3.tuple.ImmutableTriple; @@ -32,48 +33,24 @@ import org.openecomp.sdc.be.components.impl.exceptions.SdcResourceNotFoundExcept import org.openecomp.sdc.be.config.ConfigurationManager; import org.openecomp.sdc.be.dao.titan.TitanOperationStatus; import org.openecomp.sdc.be.datatypes.components.ResourceMetadataDataDefinition; +import org.openecomp.sdc.be.datatypes.elements.PropertyDataDefinition; import org.openecomp.sdc.be.datatypes.enums.ComponentTypeEnum; import org.openecomp.sdc.be.datatypes.enums.OriginTypeEnum; import org.openecomp.sdc.be.datatypes.enums.ResourceTypeEnum; -import org.openecomp.sdc.be.model.ArtifactDefinition; -import org.openecomp.sdc.be.model.CapabilityDefinition; -import org.openecomp.sdc.be.model.Component; -import org.openecomp.sdc.be.model.ComponentInstance; -import org.openecomp.sdc.be.model.ComponentInstanceInput; -import org.openecomp.sdc.be.model.ComponentInstanceProperty; -import org.openecomp.sdc.be.model.ComponentParametersView; -import org.openecomp.sdc.be.model.DataTypeDefinition; -import org.openecomp.sdc.be.model.GroupInstance; -import org.openecomp.sdc.be.model.InputDefinition; -import org.openecomp.sdc.be.model.InterfaceDefinition; -import org.openecomp.sdc.be.model.PropertyDefinition; -import org.openecomp.sdc.be.model.RelationshipInfo; -import org.openecomp.sdc.be.model.RequirementCapabilityRelDef; -import org.openecomp.sdc.be.model.RequirementDefinition; -import org.openecomp.sdc.be.model.Resource; -import org.openecomp.sdc.be.model.Service; +import org.openecomp.sdc.be.model.*; import org.openecomp.sdc.be.model.cache.ApplicationDataTypeCache; import org.openecomp.sdc.be.model.category.CategoryDefinition; import org.openecomp.sdc.be.model.jsontitan.operations.ToscaOperationFacade; import org.openecomp.sdc.be.model.jsontitan.utils.ModelConverter; -import org.openecomp.sdc.be.model.operations.api.IInterfaceLifecycleOperation; import org.openecomp.sdc.be.model.operations.api.StorageOperationStatus; import org.openecomp.sdc.be.model.operations.impl.InterfaceLifecycleOperation; -import org.openecomp.sdc.be.tosca.model.SubstitutionMapping; -import org.openecomp.sdc.be.tosca.model.ToscaCapability; -import org.openecomp.sdc.be.tosca.model.ToscaGroupTemplate; -import org.openecomp.sdc.be.tosca.model.ToscaMetadata; -import org.openecomp.sdc.be.tosca.model.ToscaNodeTemplate; -import org.openecomp.sdc.be.tosca.model.ToscaNodeType; -import org.openecomp.sdc.be.tosca.model.ToscaPolicyTemplate; -import org.openecomp.sdc.be.tosca.model.ToscaProperty; -import org.openecomp.sdc.be.tosca.model.ToscaTemplate; -import org.openecomp.sdc.be.tosca.model.ToscaTemplateRequirement; -import org.openecomp.sdc.be.tosca.model.ToscaTopolgyTemplate; +import org.openecomp.sdc.be.model.tosca.converters.ToscaValueBaseConverter; +import org.openecomp.sdc.be.tosca.model.*; import org.openecomp.sdc.be.tosca.utils.ForwardingPathToscaUtil; import org.openecomp.sdc.be.tosca.utils.InputConverter; +import org.openecomp.sdc.be.tosca.utils.InterfacesOperationsToscaUtil; import org.openecomp.sdc.common.log.wrappers.Logger; -import org.openecomp.sdc.exception.ResponseFormat; +import org.openecomp.sdc.externalupload.utils.ServiceUtils; import org.springframework.beans.factory.annotation.Autowired; import org.yaml.snakeyaml.DumperOptions; import org.yaml.snakeyaml.DumperOptions.FlowStyle; @@ -89,15 +66,8 @@ import org.yaml.snakeyaml.representer.Represent; import org.yaml.snakeyaml.representer.Representer; import java.beans.IntrospectionException; -import java.util.ArrayList; -import java.util.Collection; -import java.util.HashMap; -import java.util.LinkedHashSet; -import java.util.List; -import java.util.Map; +import java.util.*; import java.util.Map.Entry; -import java.util.Optional; -import java.util.Set; import java.util.function.Supplier; import java.util.stream.Collectors; @@ -105,6 +75,8 @@ 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 static org.openecomp.sdc.be.tosca.utils.InterfacesOperationsToscaUtil.addInterfaceDefinitionElement; +import static org.openecomp.sdc.be.tosca.utils.InterfacesOperationsToscaUtil.addInterfaceTypeElement; @org.springframework.stereotype.Component("tosca-export-handler") public class ToscaExportHandler { @@ -145,6 +117,8 @@ public class ToscaExportHandler { private static final List>> DEFAULT_IMPORTS = ConfigurationManager .getConfigurationManager().getConfiguration().getDefaultImports(); + public ToscaExportHandler(){} + public Either exportComponent(Component component) { Either toscaTemplateRes = convertToToscaTemplate(component); @@ -274,12 +248,16 @@ public class ToscaExportHandler { } List componentInstances = component.getComponentInstances(); - Map> componentInstancesProperties = component - .getComponentInstancesProperties(); + Map> componentInstancesProperties = + component.getComponentInstancesProperties(); + Map> componentInstanceInterfaces = + component.getComponentInstancesInterfaces(); if (componentInstances != null && !componentInstances.isEmpty()) { - Either, ToscaError> nodeTemplates = convertNodeTemplates(component, - componentInstances, componentInstancesProperties, componentCache, dataTypes, topologyTemplate); + Either, ToscaError> nodeTemplates = + convertNodeTemplates(component, componentInstances, + componentInstancesProperties, componentInstanceInterfaces, + componentCache, dataTypes, topologyTemplate); if (nodeTemplates.isRight()) { return Either.right(nodeTemplates.right().value()); } @@ -335,7 +313,27 @@ public class ToscaExportHandler { return Either.left(toscaNode); } - private void addGroupsToTopologyTemplate(Component component, ToscaTopolgyTemplate topologyTemplate) { + private Either fillInputs(Component component, + ToscaTopolgyTemplate topologyTemplate, Map dataTypes) { + if (log.isDebugEnabled()) { + log.debug("fillInputs for component {}", component.getUniqueId()); + } + List inputDef = component.getInputs(); + Map inputs = new HashMap<>(); + + if (inputDef != null) { + inputDef.forEach(i -> { + ToscaProperty property = propertyConvertor.convertProperty(dataTypes, i, PropertyConvertor.PropertyType.INPUT); + inputs.put(i.getName(), property); + }); + if (!inputs.isEmpty()) { + topologyTemplate.setInputs(inputs); + } + } + return Either.left(topologyTemplate); + } + + private void addGroupsToTopologyTemplate(Component component, ToscaTopolgyTemplate topologyTemplate) { Map groups = groupExportParser.getGroups(component); @@ -436,8 +434,6 @@ public class ToscaExportHandler { Map componentCache = new HashMap<>(); if (!ModelConverter.isAtomicComponent(component)) { - List componentInstances = component.getComponentInstances(); - List>> additionalImports = toscaTemplate.getImports() == null ? new ArrayList<>(DEFAULT_IMPORTS) : new ArrayList<>(toscaTemplate.getImports()); @@ -457,6 +453,7 @@ public class ToscaExportHandler { additionalImports.add(importsListMember); } } + List componentInstances = component.getComponentInstances(); if (componentInstances != null && !componentInstances.isEmpty()) { componentInstances.forEach(ci -> createDependency(componentCache, additionalImports, dependecies, ci)); } @@ -582,20 +579,35 @@ public class ToscaExportHandler { Map dataTypes = dataTypesEither.left().value(); List inputDef = component.getInputs(); - Map inputs = new HashMap<>(); - addInterfaceDefinitionElement(component, toscaNodeType, isAssociatedResourceComponent); + Map mergedProperties = new HashMap<>(); + addInterfaceDefinitionElement(component, toscaNodeType, dataTypes, isAssociatedResourceComponent); if (inputDef != null) { - inputDef.forEach(i -> { - ToscaProperty property = propertyConvertor.convertProperty(dataTypes, i, false); - inputs.put(i.getName(), property); - }); - if (!inputs.isEmpty()) { - toscaNodeType.setProperties(inputs); - } + addInputsToProperties(dataTypes, inputDef, mergedProperties); + } + + if(CollectionUtils.isNotEmpty(component.getProperties())) { + List properties = component.getProperties(); + mergedProperties = properties.stream().collect(Collectors.toMap( + PropertyDataDefinition::getName, + property -> propertyConvertor.convertProperty(dataTypes, property, PropertyConvertor.PropertyType.PROPERTY))); } + if (!mergedProperties.isEmpty()) { + toscaNodeType.setProperties(mergedProperties); + } + // Extracted to method for code reuse return convertReqCapAndTypeName(componentsCache, component, toscaNode, nodeTypes, toscaNodeType, dataTypes); } + private void addInputsToProperties(Map dataTypes, + List inputDef, + Map mergedProperties) { + for(InputDefinition input : inputDef) { + ToscaProperty property = propertyConvertor.convertProperty(dataTypes, input, PropertyConvertor.PropertyType.INPUT); + mergedProperties.put(input.getName(), property); + } + } + + private Either convertReqCapAndTypeName(Map componentsCache, Component component, ToscaTemplate toscaNode, Map nodeTypes, ToscaNodeType toscaNodeType, Map dataTypes) { @@ -635,9 +647,11 @@ public class ToscaExportHandler { return Either.left(toscaNode); } - private Either, ToscaError> convertNodeTemplates(Component component, + protected Either, ToscaError> convertNodeTemplates( + Component component, List componentInstances, Map> componentInstancesProperties, + Map> componentInstanceInterfaces, Map componentCache, Map dataTypes, ToscaTopolgyTemplate topologyTemplate) { @@ -704,7 +718,11 @@ public class ToscaExportHandler { addComponentInstanceInputs(dataTypes, componentInstancesInputs, instanceUniqueId, props); } - if (!props.isEmpty()) { + //M3[00001] - NODE TEMPLATE INTERFACES - START + handleInstanceInterfaces(componentInstanceInterfaces, componentInstance, dataTypes, nodeTemplate, + instanceUniqueId, component); + //M3[00001] - NODE TEMPLATE INTERFACES - END + if (props != null && !props.isEmpty()) { nodeTemplate.setProperties(props); } @@ -749,6 +767,70 @@ public class ToscaExportHandler { return convertNodeTemplatesRes; } + private void handleInstanceInterfaces( + Map> componentInstanceInterfaces, + ComponentInstance componentInstance, Map dataTypes, ToscaNodeTemplate nodeTemplate, + String instanceUniqueId, + Component parentComponent) { + + Map interfaces; + + // we need to handle service proxy interfaces + if(isComponentOfTypeServiceProxy(componentInstance)) { + if(MapUtils.isEmpty(componentInstanceInterfaces) + || !componentInstanceInterfaces.containsKey(instanceUniqueId)) { + interfaces = null; + } else { + List currServiceInterfaces = + componentInstanceInterfaces.get(instanceUniqueId); + + Map tmpInterfaces = new HashMap<>(); + currServiceInterfaces.forEach(instInterface -> tmpInterfaces.put(instInterface + .getUniqueId(), instInterface)); + + interfaces = InterfacesOperationsToscaUtil + .getInterfacesMap(parentComponent, tmpInterfaces, dataTypes, true, true); + } + } else { + interfaces = + getComponentInstanceInterfaceInstances(componentInstanceInterfaces, + componentInstance, instanceUniqueId); + } + nodeTemplate.setInterfaces(interfaces); + } + + private boolean isComponentOfTypeServiceProxy(ComponentInstance componentInstance) { + return Objects.nonNull(componentInstance.getOriginType()) + && componentInstance.getOriginType().getValue().equals("Service Proxy"); + } + + //M3[00001] - NODE TEMPLATE INTERFACES - START + private Map getComponentInstanceInterfaceInstances(Map> componentInstancesInterfaces, + ComponentInstance componentInstance, + String instanceUniqueId) { + if(MapUtils.isEmpty(componentInstancesInterfaces)) { + return null; + } + + List componentInstanceInterfaces = + componentInstancesInterfaces.get(instanceUniqueId); + + if(CollectionUtils.isEmpty(componentInstanceInterfaces)) { + return null; + } + + Map interfaces = new HashMap<>(); + for(ComponentInstanceInterface componentInstanceInterface : componentInstanceInterfaces) { + interfaces.put(componentInstanceInterface.getInterfaceId(), + removeOperationsKeyFromInterface(componentInstanceInterface.getInterfaceInstanceDataDefinition())); + } + + componentInstance.setInterfaces(interfaces); + + return interfaces; + } + //M3[00001] - NODE TEMPLATE INTERFACES - END + private void addComponentInstanceInputs(Map dataTypes, Map> componentInstancesInputs, String instanceUniqueId, Map props) { @@ -791,6 +873,34 @@ public class ToscaExportHandler { } } + /** + * @param dataTypes + * @param componentInstance + * @param props + * @param prop + * @param supplier + */ + private void convertAndAddValue(Map dataTypes, ComponentInstance componentInstance, + Map props, PropertyDefinition prop, Supplier supplier) { + Object convertedValue = convertValue(dataTypes, componentInstance, prop, supplier); + if (!ToscaValueBaseConverter.isEmptyObjectValue(convertedValue)) { + props.put(prop.getName(), convertedValue); + } + } + + private Object convertValue(Map dataTypes, + ComponentInstance componentInstance, T input, Supplier supplier) { + log.debug("Convert property or input value {} for instance {}", input.getName(), + componentInstance.getUniqueId()); + String propertyType = input.getType(); + String innerType = null; + if (input.getSchema() != null && input.getSchema().getProperty() != null) { + innerType = input.getSchema().getProperty().getType(); + } + return propertyConvertor.convertToToscaObject(propertyType, supplier.get(), innerType, + dataTypes, true); + } + private ToscaNodeType createNodeType(Component component) { ToscaNodeType toscaNodeType = new ToscaNodeType(); if (ModelConverter.isAtomicComponent(component)) { @@ -1128,5 +1238,22 @@ public class ToscaExportHandler { } } + private Object removeOperationsKeyFromInterface(Object interfaceInstanceDataDefinition) { + ObjectMapper objectMapper = new ObjectMapper(); + objectMapper.configure(SerializationFeature.WRITE_NULL_MAP_VALUES, false); + + Map interfaceAsMap = ServiceUtils.getObjectAsMap(interfaceInstanceDataDefinition); + Map operations = (Map) interfaceAsMap.remove("operations"); + interfaceAsMap.remove("empty"); + + if(MapUtils.isNotEmpty(operations)) { + interfaceAsMap.putAll(operations); + } + + Object interfaceObject = objectMapper.convertValue(interfaceAsMap, Object.class); + + return interfaceObject; + + } } diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/tosca/model/ToscaNodeTemplate.java b/catalog-be/src/main/java/org/openecomp/sdc/be/tosca/model/ToscaNodeTemplate.java index c27944e8ee..b67a2cf233 100644 --- a/catalog-be/src/main/java/org/openecomp/sdc/be/tosca/model/ToscaNodeTemplate.java +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/tosca/model/ToscaNodeTemplate.java @@ -20,6 +20,9 @@ package org.openecomp.sdc.be.tosca.model; +import org.apache.commons.collections.MapUtils; + +import java.util.HashMap; import java.util.List; import java.util.Map; @@ -30,6 +33,7 @@ public class ToscaNodeTemplate { private Map properties; private List> requirements; private Map capabilities; + private Map interfaces; public String getType() { return type; @@ -78,4 +82,17 @@ public class ToscaNodeTemplate { public void setDescription(String description) { this.description = description; } + + public void setInterfaces( + Map interfaces) { + this.interfaces = interfaces; + } + + public void addInterface(String interfaceName, Object interfaceDataDefinition) { + if (MapUtils.isEmpty(this.interfaces)) { + this.interfaces = new HashMap<>(); + } + + this.interfaces.put(interfaceName, interfaceDataDefinition); + } } diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/tosca/utils/InputConverter.java b/catalog-be/src/main/java/org/openecomp/sdc/be/tosca/utils/InputConverter.java index f6619b9aaa..c7e4d9b635 100644 --- a/catalog-be/src/main/java/org/openecomp/sdc/be/tosca/utils/InputConverter.java +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/tosca/utils/InputConverter.java @@ -42,7 +42,8 @@ public class InputConverter { if (inputDef != null) { inputDef.forEach(i -> { //Extract input the same as property - ToscaProperty toscaProperty = propertyConvertor.convertProperty(dataTypes, i, false); + 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 annotations = i.getAnnotations(); diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/tosca/utils/InterfacesOperationsToscaUtil.java b/catalog-be/src/main/java/org/openecomp/sdc/be/tosca/utils/InterfacesOperationsToscaUtil.java index 106aa58133..a72f57d61c 100644 --- a/catalog-be/src/main/java/org/openecomp/sdc/be/tosca/utils/InterfacesOperationsToscaUtil.java +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/tosca/utils/InterfacesOperationsToscaUtil.java @@ -30,6 +30,7 @@ import org.apache.commons.collections.MapUtils; import org.openecomp.sdc.be.datatypes.elements.OperationDataDefinition; import org.openecomp.sdc.be.datatypes.elements.OperationInputDefinition; import org.openecomp.sdc.be.model.Component; +import org.openecomp.sdc.be.model.DataTypeDefinition; import org.openecomp.sdc.be.model.InterfaceDefinition; import org.openecomp.sdc.be.model.Product; import org.openecomp.sdc.be.tosca.model.ToscaInterfaceDefinition; @@ -103,6 +104,7 @@ public class InterfacesOperationsToscaUtil { * @param nodeType to which the interfaces element will be added */ public static void addInterfaceDefinitionElement(Component component, ToscaNodeType nodeType, + Map dataTypes, boolean isAssociatedResourceComponent) { if (component instanceof Product) { return; @@ -111,6 +113,28 @@ public class InterfacesOperationsToscaUtil { if (MapUtils.isEmpty(interfaces)) { return; } + Map toscaInterfaceDefinitions = getInterfacesMap(component, dataTypes, + isAssociatedResourceComponent); + if (MapUtils.isNotEmpty(toscaInterfaceDefinitions)) { + nodeType.setInterfaces(toscaInterfaceDefinitions); + } + } + + private static Map getInterfacesMap(Component component, + Map dataTypes, + boolean isAssociatedResourceComponent) { + return getInterfacesMap(component, component.getInterfaces(), dataTypes, isAssociatedResourceComponent, false); + } + + public static Map getInterfacesMap(Component component, + Map interfaces, + Map dataTypes, + boolean isAssociatedResourceComponent, + boolean isServiceProxyInterface) { + if(MapUtils.isEmpty(interfaces)) { + return null; + } + Map toscaInterfaceDefinitions = new HashMap<>(); for (InterfaceDefinition interfaceDefinition : interfaces.values()) { ToscaInterfaceDefinition toscaInterfaceDefinition = new ToscaInterfaceDefinition(); @@ -137,13 +161,46 @@ public class InterfacesOperationsToscaUtil { toscaInterfaceDefinition.setOperations(toscaOperations); Map interfaceDefAsMap = getObjectAsMap(toscaInterfaceDefinition); Map operationsMap = (Map) interfaceDefAsMap.remove(OPERATIONS_KEY); - handleDefaults(operationsMap); + if (isServiceProxyInterface) { + handleServiceProxyOperationInputValue(operationsMap, interfaceType); + } else { + handleDefaults(operationsMap); + } interfaceDefAsMap.putAll(operationsMap); toscaInterfaceDefinitions.put(getLastPartOfName(interfaceType), interfaceDefAsMap); } - if (MapUtils.isNotEmpty(toscaInterfaceDefinitions)) { - nodeType.setInterfaces(toscaInterfaceDefinitions); + + return toscaInterfaceDefinitions; + } + + private static void handleServiceProxyOperationInputValue(Map operationsMap, String parentKey) { + for (Map.Entry operationEntry : operationsMap.entrySet()) { + final Object value = operationEntry.getValue(); + final String key = operationEntry.getKey(); + if (value instanceof Map) { + if ("inputs".equals(parentKey)) { + Object defaultValue = getDefaultValue((Map) value); + operationsMap.put(key, defaultValue); + } else { + handleServiceProxyOperationInputValue((Map) value, key); + } + } + } + } + + private static Object getDefaultValue(Map inputValueMap) { + Object defaultValue = null; + for (Map.Entry operationEntry : inputValueMap.entrySet()) { + final Object value = operationEntry.getValue(); + if (value instanceof Map) { + getDefaultValue((Map) value); + } + final String key = operationEntry.getKey(); + if (key.equals(DEFAULTP)) { + defaultValue = inputValueMap.remove(key); + } } + return defaultValue; } /* diff --git a/catalog-be/src/main/java/org/openecomp/sdc/externalupload/utils/ServiceUtils.java b/catalog-be/src/main/java/org/openecomp/sdc/externalupload/utils/ServiceUtils.java new file mode 100644 index 0000000000..ba6f9c233c --- /dev/null +++ b/catalog-be/src/main/java/org/openecomp/sdc/externalupload/utils/ServiceUtils.java @@ -0,0 +1,89 @@ +/* + * Copyright © 2016-2018 European Support Limited + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.openecomp.sdc.externalupload.utils; + +import com.fasterxml.jackson.databind.ObjectMapper; +import org.apache.commons.beanutils.BeanUtils; + +import java.lang.reflect.Field; +import java.util.*; + +public class ServiceUtils { + private static final char[] CHARS = new char[]{ + '0', '1', '2', '3', '4', '5', '6', '7', + '8', '9', 'A', 'B', 'C', 'D', 'E', 'F' + }; + private static final String TYPE = "type"; + private static final String NODE = "node"; + + public static Optional createObjectUsingSetters(Object objectCandidate, + Class classToCreate) + throws Exception { + if (Objects.isNull(objectCandidate)) { + return Optional.empty(); + } + + Map objectAsMap = getObjectAsMap(objectCandidate); + T result = classToCreate.newInstance(); + + List 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); + } + + private static List getAllFields(Class clazz) { + List fields = new ArrayList<>(); + for(Class c = clazz; c != null; c = c.getSuperclass()) { + fields.addAll(Arrays.asList(c.getDeclaredFields())); + } + + return fields; + } + + private static boolean isComplexClass(Field field) { + return !field.getType().equals(Map.class) + && !field.getType().equals(String.class) + && !field.getType().equals(Integer.class) + && !field.getType().equals(Float.class) + && !field.getType().equals(Double.class) + && !field.getType().equals(Set.class) + && !field.getType().equals(Object.class) + && !field.getType().equals(List.class); + } + public static Map getObjectAsMap(Object obj) { + return new ObjectMapper().convertValue(obj, Map.class); + } + + public static Set getClassFieldNames(Class classType) { + Set fieldNames = new HashSet<>(); + List allFields = getAllFields(classType); + allFields.forEach(field -> fieldNames.add(field.getName())); + + return fieldNames; + } +} \ No newline at end of file diff --git a/catalog-be/src/test/java/org/openecomp/sdc/be/components/PropertyBusinessLogicTest.java b/catalog-be/src/test/java/org/openecomp/sdc/be/components/PropertyBusinessLogicTest.java index f55f461ce9..4f2bb78079 100644 --- a/catalog-be/src/test/java/org/openecomp/sdc/be/components/PropertyBusinessLogicTest.java +++ b/catalog-be/src/test/java/org/openecomp/sdc/be/components/PropertyBusinessLogicTest.java @@ -23,19 +23,15 @@ package org.openecomp.sdc.be.components; import fj.data.Either; import org.junit.Before; import org.junit.Test; -import org.junit.runner.RunWith; import org.mockito.InjectMocks; import org.mockito.Mock; import org.mockito.Mockito; import org.mockito.MockitoAnnotations; -import org.mockito.junit.MockitoJUnitRunner; -import org.openecomp.sdc.be.components.impl.BaseBusinessLogic; import org.openecomp.sdc.be.components.impl.PropertyBusinessLogic; import org.openecomp.sdc.be.components.validation.UserValidations; import org.openecomp.sdc.be.config.ConfigurationManager; import org.openecomp.sdc.be.dao.api.ActionStatus; import org.openecomp.sdc.be.dao.jsongraph.TitanDao; -import org.openecomp.sdc.be.datatypes.enums.NodeTypeEnum; import org.openecomp.sdc.be.impl.ComponentsUtils; import org.openecomp.sdc.be.impl.WebAppContextWrapper; import org.openecomp.sdc.be.model.*; @@ -50,27 +46,18 @@ import org.openecomp.sdc.common.api.Constants; import org.openecomp.sdc.common.impl.ExternalConfiguration; import org.openecomp.sdc.common.impl.FSConfigurationSource; import org.openecomp.sdc.exception.ResponseFormat; +import org.openecomp.sdc.test.utils.InterfaceOperationTestUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.web.context.WebApplicationContext; + import javax.servlet.ServletContext; import java.lang.reflect.Field; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.List; -import java.util.Map; -import static org.assertj.core.api.Assertions.assertThat; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertTrue; -import static org.junit.runner.Request.method; -import static org.mockito.ArgumentMatchers.anyString; -import static org.mockito.ArgumentMatchers.eq; +import java.util.*; + +import static org.junit.Assert.*; +import static org.mockito.ArgumentMatchers.*; import static org.mockito.Mockito.when; -import static org.mockito.ArgumentMatchers.any; -import static org.mockito.ArgumentMatchers.anyBoolean; -import static org.mockito.ArgumentMatchers.anyString; -import static org.mockito.ArgumentMatchers.eq; -import static org.mockito.Mockito.*; public class PropertyBusinessLogicTest { @@ -89,20 +76,22 @@ public class PropertyBusinessLogicTest { private ComponentsUtils componentsUtils; @Mock private ToscaOperationFacade toscaOperationFacade; - @Mock private UserValidations userValidations; - @Mock IGraphLockOperation graphLockOperation; + @Mock + TitanDao titanDao; @InjectMocks private PropertyBusinessLogic bl = new PropertyBusinessLogic(); private User user = null; private String resourceId = "resourceforproperty.0.1"; - - @Mock - TitanDao titanDao; + private String serviceId = "serviceForProperty.0.1"; + private static final String interfaceType = "interfaceType"; + private static final String operationType = "operationType"; + private static final String operationId = "operationId"; + private static final String operationId2 = "operationId2"; @Before public void setup() { @@ -144,7 +133,7 @@ public class PropertyBusinessLogicTest { resource.setUniqueId(resourceId); Mockito.when(toscaOperationFacade.getToscaElement(resourceId)).thenReturn(Either.left(resource)); - Either, ResponseFormat> nonExistingProperty = bl.getProperty(resourceId, "NonExistingProperty", user.getUserId()); + Either, ResponseFormat> nonExistingProperty = bl.getComponentProperty(resourceId, "NonExistingProperty", user.getUserId()); assertTrue(nonExistingProperty.isRight()); Mockito.verify(componentsUtils).getResponseFormat(ActionStatus.PROPERTY_NOT_FOUND, ""); } @@ -158,7 +147,7 @@ public class PropertyBusinessLogicTest { resource.setUniqueId(resourceId); Mockito.when(toscaOperationFacade.getToscaElement(resourceId)).thenReturn(Either.left(resource)); - Either, ResponseFormat> notFoundProperty = bl.getProperty(resourceId, "invalidId", user.getUserId()); + Either, ResponseFormat> notFoundProperty = bl.getComponentProperty(resourceId, "invalidId", user.getUserId()); assertTrue(notFoundProperty.isRight()); Mockito.verify(componentsUtils).getResponseFormat(ActionStatus.PROPERTY_NOT_FOUND, ""); } @@ -171,11 +160,105 @@ public class PropertyBusinessLogicTest { resource.setProperties(Arrays.asList(property1)); Mockito.when(toscaOperationFacade.getToscaElement(resourceId)).thenReturn(Either.left(resource)); - Either, ResponseFormat> foundProperty = bl.getProperty(resourceId, property1.getUniqueId(), user.getUserId()); + Either, ResponseFormat> foundProperty = bl.getComponentProperty(resourceId, property1.getUniqueId(), user.getUserId()); assertTrue(foundProperty.isLeft()); assertEquals(foundProperty.left().value().getValue().getUniqueId(), property1.getUniqueId()); } + @Test + public void testGetPropertyFromService() { + Service service = new Service(); + service.setUniqueId(serviceId); + + PropertyDefinition property1 = createPropertyObject("someProperty", null); + service.setProperties(Arrays.asList(property1)); + + Mockito.when(toscaOperationFacade.getToscaElement(serviceId)).thenReturn(Either.left(service)); + Either, ResponseFormat> serviceProperty = + bl.getComponentProperty(serviceId, property1.getUniqueId(), user.getUserId()); + + assertTrue(serviceProperty.isLeft()); + assertEquals(serviceProperty.left().value().getValue().getUniqueId(), property1.getUniqueId()); + } + + @Test + public void testPropertyNotFoundOnService() { + Service service = new Service(); + service.setUniqueId(serviceId); + + PropertyDefinition property1 = createPropertyObject("someProperty", null); + service.setProperties(Arrays.asList(property1)); + + Mockito.when(toscaOperationFacade.getToscaElement(serviceId)).thenReturn(Either.left(service)); + Either, ResponseFormat> serviceProperty = + bl.getComponentProperty(serviceId, "notExistingPropId", user.getUserId()); + + assertTrue(serviceProperty.isRight()); + } + + @Test + public void isPropertyUsedByComponentInterface(){ + Service service = new Service(); + service.setUniqueId(serviceId); + service.setInterfaces(InterfaceOperationTestUtils.createMockInterfaceDefinitionMap(interfaceType, operationId, operationType)); + + PropertyDefinition propDef1 = new PropertyDefinition(); + propDef1.setUniqueId("ComponentInput1_uniqueId"); + assertTrue(bl.isPropertyUsedByOperation(service, propDef1)); + + PropertyDefinition propDef2 = new PropertyDefinition(); + propDef1.setUniqueId("inputId2"); + Mockito.when(toscaOperationFacade.getParentComponents(serviceId)).thenReturn(Either.left(new ArrayList<>())); + assertFalse(bl.isPropertyUsedByOperation(service, propDef2)); + } + + @Test + public void isPropertyUsedByComponentInstanceInterface(){ + Map newInterfaceDefinition = InterfaceOperationTestUtils.createMockInterfaceDefinitionMap(interfaceType, operationId, operationType); + ComponentInstanceInterface componentInstanceInterface = new ComponentInstanceInterface(interfaceType, newInterfaceDefinition.get(interfaceType)); + + Map> componentInstanceInterfaces = new HashMap<>(); + componentInstanceInterfaces.put("Test", Arrays.asList(componentInstanceInterface)); + + Service service = new Service(); + service.setUniqueId(serviceId); + service.setComponentInstancesInterfaces(componentInstanceInterfaces); + + PropertyDefinition propDef1 = new PropertyDefinition(); + propDef1.setUniqueId("ComponentInput1_uniqueId"); + assertTrue(bl.isPropertyUsedByOperation(service, propDef1)); + + PropertyDefinition propDef2 = new PropertyDefinition(); + propDef1.setUniqueId("inputId2"); + Mockito.when(toscaOperationFacade.getParentComponents(serviceId)).thenReturn(Either.left(new ArrayList<>())); + assertFalse(bl.isPropertyUsedByOperation(service, propDef2)); + } + + @Test + public void isPropertyUsedByComponentParentComponentInstanceInterface(){ + Map newInterfaceDefinition = InterfaceOperationTestUtils.createMockInterfaceDefinitionMap(interfaceType, operationId, operationType); + ComponentInstanceInterface componentInstanceInterface = new ComponentInstanceInterface(interfaceType, newInterfaceDefinition.get(interfaceType)); + + Map> componentInstanceInterfaces = new HashMap<>(); + componentInstanceInterfaces.put("Test", Arrays.asList(componentInstanceInterface)); + + Service parentService = new Service(); + parentService.setComponentInstancesInterfaces(componentInstanceInterfaces); + Service childService = new Service(); + childService.setUniqueId(serviceId); + + PropertyDefinition propDef1 = new PropertyDefinition(); + propDef1.setUniqueId("ComponentInput1_uniqueId"); + Mockito.when(toscaOperationFacade.getParentComponents(serviceId)).thenReturn(Either.left(Arrays.asList(parentService))); + assertTrue(bl.isPropertyUsedByOperation(childService, propDef1)); + + PropertyDefinition propDef2 = new PropertyDefinition(); + propDef1.setUniqueId("inputId2"); + Mockito.when(toscaOperationFacade.getParentComponents(serviceId)).thenReturn(Either.left(new ArrayList<>())); + assertFalse(bl.isPropertyUsedByOperation(childService, propDef2)); + } + + private PropertyDefinition createPropertyObject(String propertyName, String resourceId) { PropertyDefinition pd = new PropertyDefinition(); pd.setConstraints(null); @@ -193,7 +276,8 @@ public class PropertyBusinessLogicTest { public void deleteProperty_CONNECTION_FAILURE() { StorageOperationStatus lockResult = StorageOperationStatus.CONNECTION_FAILURE; when(graphLockOperation.lockComponent(any(), any())).thenReturn(lockResult); - assertTrue(bl.deleteProperty("resourceforproperty.0.1", "someProperty","i726").isRight()); + when(toscaOperationFacade.getToscaElement(anyString())).thenReturn(Either.left(new Resource())); + assertTrue(bl.deletePropertyFromComponent("resourceforproperty.0.1", "someProperty","i726").isRight()); } @Test @@ -229,7 +313,7 @@ public class PropertyBusinessLogicTest { when(toscaOperationFacade.getToscaElement("RES01")).thenReturn(toscastatus); - assertTrue(bl.deleteProperty("RES01", "someProperty","i726").isRight()); + assertTrue(bl.deletePropertyFromComponent("RES01", "someProperty","i726").isRight()); } @Test @@ -265,7 +349,7 @@ public class PropertyBusinessLogicTest { when(toscaOperationFacade.getToscaElement("RES01")).thenReturn(toscastatus); - assertTrue(bl.deleteProperty("RES01", "someProperty","i726").isRight()); + assertTrue(bl.deletePropertyFromComponent("RES01", "someProperty","i726").isRight()); } @Test @@ -299,8 +383,9 @@ public class PropertyBusinessLogicTest { Either toscastatus=Either.left(resource); when(toscaOperationFacade.getToscaElement("RES01")).thenReturn(toscastatus); - when(toscaOperationFacade.deletePropertyOfResource(anyObject(),anyString())).thenReturn(StorageOperationStatus.OK); + when(toscaOperationFacade.deletePropertyOfComponent(anyObject(),anyString())).thenReturn(StorageOperationStatus.OK); + when(toscaOperationFacade.getParentComponents(anyString())).thenReturn(Either.left(new ArrayList<>())); - assertTrue(bl.deleteProperty("RES01", "PROP","USR01").isRight()); + assertTrue(bl.deletePropertyFromComponent("RES01", "PROP","USR01").isRight()); } } diff --git a/catalog-be/src/test/java/org/openecomp/sdc/be/components/validation/InterfaceOperationValidationTest.java b/catalog-be/src/test/java/org/openecomp/sdc/be/components/validation/InterfaceOperationValidationTest.java index e2d83aef29..fe1e384546 100644 --- a/catalog-be/src/test/java/org/openecomp/sdc/be/components/validation/InterfaceOperationValidationTest.java +++ b/catalog-be/src/test/java/org/openecomp/sdc/be/components/validation/InterfaceOperationValidationTest.java @@ -337,7 +337,7 @@ public class InterfaceOperationValidationTest { .validateInterfaceOperations(inputInterfaceDefinition, component, component.getInterfaces().get(interfaceType1), InterfaceOperationTestUtils.createMockInterfaceTypeMap( - interfaceType1, operationType1), false).isRight()); + interfaceType1, operationType1 ), false).isRight()); } @Test diff --git a/catalog-be/src/test/java/org/openecomp/sdc/be/servlets/PropertyServletTest.java b/catalog-be/src/test/java/org/openecomp/sdc/be/servlets/PropertyServletTest.java deleted file mode 100644 index fe147b19a9..0000000000 --- a/catalog-be/src/test/java/org/openecomp/sdc/be/servlets/PropertyServletTest.java +++ /dev/null @@ -1,116 +0,0 @@ -package org.openecomp.sdc.be.servlets; - -import java.util.Map; - -import javax.servlet.ServletContext; -import javax.servlet.http.HttpServletRequest; -import javax.ws.rs.core.Response; - -import org.codehaus.jettison.json.JSONObject; -import org.junit.Test; -import org.openecomp.sdc.be.components.impl.PropertyBusinessLogic; -import org.openecomp.sdc.be.dao.api.ActionStatus; -import org.openecomp.sdc.be.model.PropertyDefinition; - -import fj.data.Either; - -public class PropertyServletTest { - - private PropertyServlet createTestSubject() { - return new PropertyServlet(); - } - - - @Test - public void testCreateProperty() throws Exception { - PropertyServlet testSubject; - String resourceId = ""; - String data = ""; - HttpServletRequest request = null; - String userId = ""; - Response result; - - // default test - testSubject = createTestSubject(); - } - - - @Test - public void testGetProperty() throws Exception { - PropertyServlet testSubject; - String resourceId = ""; - String propertyId = ""; - HttpServletRequest request = null; - String userId = ""; - Response result; - - // default test - testSubject = createTestSubject(); - } - - - @Test - public void testDeleteProperty() throws Exception { - PropertyServlet testSubject; - String resourceId = ""; - String propertyId = ""; - HttpServletRequest request = null; - String userId = ""; - Response result; - - // default test - testSubject = createTestSubject(); - } - - - @Test - public void testUpdateProperty() throws Exception { - PropertyServlet testSubject; - String resourceId = ""; - String propertyId = ""; - String data = ""; - HttpServletRequest request = null; - String userId = ""; - Response result; - - // default test - testSubject = createTestSubject(); - } - - - @Test - public void testGetPropertyModel() throws Exception { - PropertyServlet testSubject; - String resourceId = ""; - String data = ""; - Either, ActionStatus> result; - - // default test - testSubject = createTestSubject(); - } - - - - - - @Test - public void testGetPropertyDefinitionJSONObject() throws Exception { - PropertyServlet testSubject; - PropertyDefinition propertyDefinition = null; - JSONObject result; - - // default test - testSubject = createTestSubject(); - } - - - @Test - public void testGetPropertyBL() throws Exception { - PropertyServlet testSubject; - ServletContext context = null; - PropertyBusinessLogic result; - - // default test - testSubject = createTestSubject(); - } -} \ No newline at end of file diff --git a/catalog-be/src/test/java/org/openecomp/sdc/be/tosca/PropertyConvertorTest.java b/catalog-be/src/test/java/org/openecomp/sdc/be/tosca/PropertyConvertorTest.java index a06ba84b4e..35b8ed0278 100644 --- a/catalog-be/src/test/java/org/openecomp/sdc/be/tosca/PropertyConvertorTest.java +++ b/catalog-be/src/test/java/org/openecomp/sdc/be/tosca/PropertyConvertorTest.java @@ -37,12 +37,12 @@ public class PropertyConvertorTest { property.setSchema(schema); - PropertyConvertor.getInstance().convertProperty(dataTypes, property, true); + PropertyConvertor.getInstance().convertProperty(dataTypes, property, PropertyConvertor.PropertyType.PROPERTY); } @Test public void convertPropertyWhenValueAndDefaultNull() { - ToscaProperty prop = PropertyConvertor.getInstance().convertProperty(dataTypes, property, false); + ToscaProperty prop = PropertyConvertor.getInstance().convertProperty(dataTypes, property, PropertyConvertor.PropertyType.PROPERTY); assertNotNull(prop); assertNull(prop.getDefaultp()); } @@ -51,7 +51,7 @@ public class PropertyConvertorTest { public void convertPropertyWhenValueNullAndDefaultNotEmpty() { final String def = "1"; property.setDefaultValue(def); - ToscaProperty result = PropertyConvertor.getInstance().convertProperty(dataTypes, property, false); + ToscaProperty result = PropertyConvertor.getInstance().convertProperty(dataTypes, property, PropertyConvertor.PropertyType.PROPERTY); assertNotNull(result); assertEquals(Integer.valueOf(def), result.getDefaultp()); } @@ -129,7 +129,7 @@ public class PropertyConvertorTest { .setDefaultValue("::") .setType(ToscaPropertyType.STRING.getType()) .build(); - ToscaProperty toscaProperty = PropertyConvertor.getInstance().convertProperty(Collections.emptyMap(), property1, false); + ToscaProperty toscaProperty = PropertyConvertor.getInstance().convertProperty(Collections.emptyMap(), property1, PropertyConvertor.PropertyType.PROPERTY); assertThat(toscaProperty.getDefaultp()).isEqualTo("::"); } @@ -139,7 +139,7 @@ public class PropertyConvertorTest { .setDefaultValue("/") .setType(ToscaPropertyType.STRING.getType()) .build(); - ToscaProperty toscaProperty = PropertyConvertor.getInstance().convertProperty(Collections.emptyMap(), property1, false); + ToscaProperty toscaProperty = PropertyConvertor.getInstance().convertProperty(Collections.emptyMap(), property1, PropertyConvertor.PropertyType.PROPERTY); assertThat(toscaProperty.getDefaultp()).isEqualTo("/"); } diff --git a/catalog-be/src/test/java/org/openecomp/sdc/be/tosca/ToscaExportHandlerTest.java b/catalog-be/src/test/java/org/openecomp/sdc/be/tosca/ToscaExportHandlerTest.java index 592d27ec5d..a61ea0410a 100644 --- a/catalog-be/src/test/java/org/openecomp/sdc/be/tosca/ToscaExportHandlerTest.java +++ b/catalog-be/src/test/java/org/openecomp/sdc/be/tosca/ToscaExportHandlerTest.java @@ -498,6 +498,7 @@ public class ToscaExportHandlerTest extends BeConfDependentTest { Component component = getNewService(); List componentInstances = new ArrayList<>(); Map> componentInstancesProperties = new HashMap<>(); + Map> componentInstancesInterfaces = new HashMap<>(); Map componentCache = new HashMap<>(); Map dataTypes = new HashMap<>(); ToscaTopolgyTemplate topologyTemplate = new ToscaTopolgyTemplate(); @@ -542,6 +543,7 @@ public class ToscaExportHandlerTest extends BeConfDependentTest { componentCache.put("uid", component); componentInstancesProperties.put("id", new ArrayList<>()); + componentInstancesInterfaces.put("id", new ArrayList<>()); componentInstancesInputs.put("id", new ArrayList<>()); Mockito.when(capabiltyRequirementConvertor.getOriginComponent(Mockito.any(Map.class), @@ -553,7 +555,7 @@ public class ToscaExportHandlerTest extends BeConfDependentTest { // default test result = Deencapsulation.invoke(testSubject, "convertNodeTemplates", component, componentInstances, - componentInstancesProperties, componentCache, dataTypes, topologyTemplate); + componentInstancesProperties, componentInstancesInterfaces, componentCache, dataTypes, topologyTemplate); } @Test @@ -561,6 +563,7 @@ public class ToscaExportHandlerTest extends BeConfDependentTest { Component component = getNewResource(); List componentInstances = new ArrayList<>(); Map> componentInstancesProperties = new HashMap<>(); + Map> componentInstancesInterfaces = new HashMap<>(); Map componentCache = new HashMap<>(); Map dataTypes = new HashMap<>(); ToscaTopolgyTemplate topologyTemplate = new ToscaTopolgyTemplate(); @@ -597,7 +600,7 @@ public class ToscaExportHandlerTest extends BeConfDependentTest { // default test result = Deencapsulation.invoke(testSubject, "convertNodeTemplates", component, componentInstances, - componentInstancesProperties, componentCache, dataTypes, topologyTemplate); + componentInstancesProperties, componentInstancesInterfaces, componentCache, dataTypes, topologyTemplate); } @Test @@ -605,6 +608,7 @@ public class ToscaExportHandlerTest extends BeConfDependentTest { Component component = getNewResource(); List componentInstances = new ArrayList<>(); Map> componentInstancesProperties = new HashMap<>(); + Map> componentInstancesInterfaces = new HashMap<>(); Map componentCache = new HashMap<>(); Map dataTypes = new HashMap<>(); ToscaTopolgyTemplate topologyTemplate = new ToscaTopolgyTemplate(); @@ -637,7 +641,7 @@ public class ToscaExportHandlerTest extends BeConfDependentTest { // default test result = Deencapsulation.invoke(testSubject, "convertNodeTemplates", component, componentInstances, - componentInstancesProperties, componentCache, dataTypes, topologyTemplate); + componentInstancesProperties, componentInstancesInterfaces, componentCache, dataTypes, topologyTemplate); } @Test @@ -645,6 +649,7 @@ public class ToscaExportHandlerTest extends BeConfDependentTest { Component component = new Resource(); List componentInstances = new ArrayList<>(); Map> componentInstancesProperties = new HashMap<>(); + Map> componentInstancesInterfaces = new HashMap<>(); Map componentCache = new HashMap<>(); Map dataTypes = new HashMap<>(); ToscaTopolgyTemplate topologyTemplate = new ToscaTopolgyTemplate(); @@ -677,7 +682,7 @@ public class ToscaExportHandlerTest extends BeConfDependentTest { // default test result = Deencapsulation.invoke(testSubject, "convertNodeTemplates", component, componentInstances, - componentInstancesProperties, componentCache, dataTypes, topologyTemplate); + componentInstancesProperties, componentInstancesInterfaces, componentCache, dataTypes, topologyTemplate); } @Test diff --git a/catalog-be/src/test/java/org/openecomp/sdc/be/tosca/utils/InterfacesOperationsToscaUtilTest.java b/catalog-be/src/test/java/org/openecomp/sdc/be/tosca/utils/InterfacesOperationsToscaUtilTest.java index 156d280a6e..fc017c8483 100644 --- a/catalog-be/src/test/java/org/openecomp/sdc/be/tosca/utils/InterfacesOperationsToscaUtilTest.java +++ b/catalog-be/src/test/java/org/openecomp/sdc/be/tosca/utils/InterfacesOperationsToscaUtilTest.java @@ -122,7 +122,7 @@ public class InterfacesOperationsToscaUtilTest { component.setInterfaces(new HashMap<>()); component.getInterfaces().put(interfaceType, addedInterface); ToscaNodeType nodeType = new ToscaNodeType(); - addInterfaceDefinitionElement(component, nodeType, false); + addInterfaceDefinitionElement(component, nodeType, null, false); ToscaExportHandler handler = new ToscaExportHandler(null,null,null,null,null,null, null); ToscaTemplate template = new ToscaTemplate(NODE_TYPE_NAME); @@ -153,7 +153,7 @@ public class InterfacesOperationsToscaUtilTest { component.setInterfaces(new HashMap<>()); component.getInterfaces().put(interfaceType, addedInterface); ToscaNodeType nodeType = new ToscaNodeType(); - addInterfaceDefinitionElement(component, nodeType, false); + addInterfaceDefinitionElement(component, nodeType, null, false); ToscaExportHandler handler = new ToscaExportHandler(null,null,null,null,null,null, null); ToscaTemplate template = new ToscaTemplate("testService"); @@ -183,7 +183,7 @@ public class InterfacesOperationsToscaUtilTest { component.setInterfaces(new HashMap<>()); component.getInterfaces().put(interfaceType, addedInterface); ToscaNodeType nodeType = new ToscaNodeType(); - addInterfaceDefinitionElement(component, nodeType, false); + addInterfaceDefinitionElement(component, nodeType, null, false); ToscaExportHandler handler = new ToscaExportHandler(null,null,null,null,null,null, null); ToscaTemplate template = new ToscaTemplate("test"); @@ -218,7 +218,7 @@ public class InterfacesOperationsToscaUtilTest { component.setInterfaces(new HashMap<>()); component.getInterfaces().put(addedInterfaceType, addedInterface); ToscaNodeType nodeType = new ToscaNodeType(); - addInterfaceDefinitionElement(component, nodeType, false); + addInterfaceDefinitionElement(component, nodeType, null, false); ToscaExportHandler handler = new ToscaExportHandler(null,null,null,null,null,null, null); ToscaTemplate template = new ToscaTemplate("test"); @@ -266,7 +266,7 @@ public class InterfacesOperationsToscaUtilTest { component.getInterfaces().put(secondInterfaceType, secondInterface); ToscaNodeType nodeType = new ToscaNodeType(); - addInterfaceDefinitionElement(component, nodeType, false); + addInterfaceDefinitionElement(component, nodeType, null,false); ToscaExportHandler handler = new ToscaExportHandler(null,null,null,null,null,null, null); ToscaTemplate template = new ToscaTemplate("test"); diff --git a/catalog-be/src/test/java/org/openecomp/sdc/test/utils/InterfaceOperationTestUtils.java b/catalog-be/src/test/java/org/openecomp/sdc/test/utils/InterfaceOperationTestUtils.java index 1cc5b56ca9..25c0d651c6 100644 --- a/catalog-be/src/test/java/org/openecomp/sdc/test/utils/InterfaceOperationTestUtils.java +++ b/catalog-be/src/test/java/org/openecomp/sdc/test/utils/InterfaceOperationTestUtils.java @@ -103,7 +103,7 @@ public class InterfaceOperationTestUtils { } public static Map createMockInterfaceTypeMap(String interfaceType, - String operationType) { + String operationType) { Map operationMap = createMockOperationTypeMap(operationType); Map interfaceDefinitionMap = new HashMap<>(); interfaceDefinitionMap.put(interfaceType, @@ -118,5 +118,4 @@ public class InterfaceOperationTestUtils { operationMap.put(operationType, operation); return operationMap; } - } -- cgit 1.2.3-korg