}
public Either<Map<String, EnumMap<ArtifactsBusinessLogic.ArtifactOperationEnum, List<ArtifactDefinition>>>, ResponseFormat> findNodeTypesArtifactsToHandle(
- Map<String, NodeTypeInfo> nodeTypesInfo, CsarInfo csarInfo, Service oldResource) {
+ Map<String, NodeTypeInfo> nodeTypesInfo, CsarInfo csarInfo, Service oldResource) {
Map<String, EnumMap<ArtifactsBusinessLogic.ArtifactOperationEnum, List<ArtifactDefinition>>> nodeTypesArtifactsToHandle = new HashMap<>();
Either<Map<String, EnumMap<ArtifactsBusinessLogic.ArtifactOperationEnum, List<ArtifactDefinition>>>, ResponseFormat> nodeTypesArtifactsToHandleRes = Either
- .left(nodeTypesArtifactsToHandle);
+ .left(nodeTypesArtifactsToHandle);
try {
Map<String, List<ArtifactDefinition>> extractedVfcsArtifacts = CsarUtils.extractVfcsArtifactsFromCsar(csarInfo.getCsar());
Map<String, ImmutablePair<String, String>> extractedVfcToscaNames = extractVfcToscaNames(nodeTypesInfo, oldResource.getName(), csarInfo);
log.debug("Going to fetch node types for resource with name {} during import csar with UUID {}. ", oldResource.getName(),
- csarInfo.getCsarUUID());
+ csarInfo.getCsarUUID());
extractedVfcToscaNames.forEach(
- (namespace, vfcToscaNames) -> findAddNodeTypeArtifactsToHandle(csarInfo, nodeTypesArtifactsToHandle, oldResource,
- extractedVfcsArtifacts, namespace, vfcToscaNames));
+ (namespace, vfcToscaNames) -> findAddNodeTypeArtifactsToHandle(csarInfo, nodeTypesArtifactsToHandle, oldResource,
+ extractedVfcsArtifacts, namespace, vfcToscaNames));
} catch (Exception e) {
ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR);
nodeTypesArtifactsToHandleRes = Either.right(responseFormat);
while (nodesNameEntry.hasNext()) {
Map.Entry<String, Object> nodeType = nodesNameEntry.next();
ImmutablePair<String, String> toscaResourceName = buildNestedToscaResourceName(ResourceTypeEnum.VFC.name(), vfResourceName,
- nodeType.getKey());
+ nodeType.getKey());
vfcToscaNames.put(nodeType.getKey(), toscaResourceName);
}
}
Yaml yaml = new Yaml(options);
Map<String, Object> node = new HashMap<>();
node.put(buildNestedToscaResourceName(nodeResourceType, csarInfo.getVfResourceName(), nodeNameValue.getKey()).getLeft(),
- nodeNameValue.getValue());
+ nodeNameValue.getValue());
mapToConvert.put(TypeUtils.ToscaTagNamesEnum.NODE_TYPES.getElementName(), node);
return yaml.dumpAsMap(mapToConvert);
}
}
StringBuilder previousToscaResourceName = new StringBuilder(toscaResourceName);
return new ImmutablePair<>(toscaResourceName.append(actualName.toLowerCase()).toString(),
- previousToscaResourceName.append(actualName.substring(actualName.split("\\.")[1].length() + 1).toLowerCase()).toString());
+ previousToscaResourceName.append(actualName.substring(actualName.split("\\.")[1].length() + 1).toLowerCase()).toString());
} catch (Exception e) {
componentsUtils.getResponseFormat(ActionStatus.INVALID_TOSCA_TEMPLATE);
log.debug("Exception occured when buildNestedToscaResourceName, error is:{}", e.getMessage(), e);
private void extractNodeTypes(Map<String, Object> nodes, Map<String, Object> mappedToscaTemplate) {
Either<Map<String, Object>, ImportUtils.ResultStatusEnum> eitherNodeTypes = ImportUtils
- .findFirstToscaMapElement(mappedToscaTemplate, TypeUtils.ToscaTagNamesEnum.NODE_TYPES);
+ .findFirstToscaMapElement(mappedToscaTemplate, TypeUtils.ToscaTagNamesEnum.NODE_TYPES);
if (eitherNodeTypes.isLeft()) {
nodes.putAll(eitherNodeTypes.left().value());
}
List<ArtifactDefinition> artifactsToDelete = new ArrayList<>();
// delete all informational artifacts
artifactsToDelete.addAll(
- curNodeType.getArtifacts().values().stream().filter(a -> a.getArtifactGroupType() == ArtifactGroupTypeEnum.INFORMATIONAL)
- .collect(toList()));
+ curNodeType.getArtifacts().values().stream().filter(a -> a.getArtifactGroupType() == ArtifactGroupTypeEnum.INFORMATIONAL)
+ .collect(toList()));
// delete all deployment artifacts
artifactsToDelete.addAll(curNodeType.getDeploymentArtifacts().values());
if (!artifactsToDelete.isEmpty()) {
throw new ComponentException(componentsUtils.convertFromStorageResponse(status), csarInfo.getCsarUUID());
} else if (org.apache.commons.lang.StringUtils.isNotEmpty(currVfcToscaName)) {
return (Resource) toscaOperationFacade.getLatestByToscaResourceName(currVfcToscaName, resource.getModel()).left()
- .on(st -> findVfcResource(csarInfo, resource, previousVfcToscaName, null, st));
+ .on(st -> findVfcResource(csarInfo, resource, previousVfcToscaName, null, st));
}
return null;
}
List<ArtifactDefinition> artifactsToUpdate = new ArrayList<>();
List<ArtifactDefinition> artifactsToDelete = new ArrayList<>();
processExistingNodeTypeArtifacts(extractedArtifacts, artifactsToUpload, artifactsToUpdate, artifactsToDelete,
- collectExistingArtifacts(curNodeType));
+ collectExistingArtifacts(curNodeType));
nodeTypeArtifactsToHandle = putFoundArtifacts(artifactsToUpload, artifactsToUpdate, artifactsToDelete);
} catch (Exception e) {
log.debug("Exception occured when findNodeTypeArtifactsToHandle, error is:{}", e.getMessage(), e);
}
if (MapUtils.isNotEmpty(curNodeType.getArtifacts())) {
existingArtifacts.putAll(
- curNodeType.getArtifacts().entrySet().stream().filter(e -> e.getValue().getArtifactGroupType() == ArtifactGroupTypeEnum.INFORMATIONAL)
- .collect(toMap(Map.Entry::getKey, Map.Entry::getValue)));
+ curNodeType.getArtifacts().entrySet().stream().filter(e -> e.getValue().getArtifactGroupType() == ArtifactGroupTypeEnum.INFORMATIONAL)
+ .collect(toMap(Map.Entry::getKey, Map.Entry::getValue)));
}
return existingArtifacts;
}
protected EnumMap<ArtifactsBusinessLogic.ArtifactOperationEnum, List<ArtifactDefinition>> putFoundArtifacts(
- List<ArtifactDefinition> artifactsToUpload, List<ArtifactDefinition> artifactsToUpdate, List<ArtifactDefinition> artifactsToDelete) {
+ List<ArtifactDefinition> artifactsToUpload, List<ArtifactDefinition> artifactsToUpdate, List<ArtifactDefinition> artifactsToDelete) {
EnumMap<ArtifactsBusinessLogic.ArtifactOperationEnum, List<ArtifactDefinition>> nodeTypeArtifactsToHandle = null;
if (!artifactsToUpload.isEmpty() || !artifactsToUpdate.isEmpty() || !artifactsToDelete.isEmpty()) {
nodeTypeArtifactsToHandle = new EnumMap<>(ArtifactsBusinessLogic.ArtifactOperationEnum.class);
protected void processNodeTypeArtifact(List<ArtifactDefinition> artifactsToUpload, List<ArtifactDefinition> artifactsToUpdate,
Map<String, ArtifactDefinition> existingArtifacts, ArtifactDefinition currNewArtifact) {
Optional<ArtifactDefinition> foundArtifact = existingArtifacts.values().stream()
- .filter(a -> a.getArtifactName().equals(currNewArtifact.getArtifactName())).findFirst();
+ .filter(a -> a.getArtifactName().equals(currNewArtifact.getArtifactName())).findFirst();
if (foundArtifact.isPresent()) {
if (foundArtifact.get().getArtifactType().equals(currNewArtifact.getArtifactType())) {
updateFoundArtifact(artifactsToUpdate, currNewArtifact, foundArtifact.get());
} else {
log.debug("Can't upload two artifact with the same name {}.", currNewArtifact.getArtifactName());
throw new ComponentException(ActionStatus.ARTIFACT_ALREADY_EXIST_IN_DIFFERENT_TYPE_IN_CSAR, currNewArtifact.getArtifactName(),
- currNewArtifact.getArtifactType(), foundArtifact.get().getArtifactType());
+ currNewArtifact.getArtifactType(), foundArtifact.get().getArtifactType());
}
}
}
public void addNonMetaCreatedArtifactsToSupportRollback(ArtifactOperationInfo operation, List<ArtifactDefinition> createdArtifacts,
Either<Either<ArtifactDefinition, Operation>, ResponseFormat> eitherNonMetaArtifacts) {
if (ArtifactsBusinessLogic.ArtifactOperationEnum.isCreateOrLink(operation.getArtifactOperationEnum()) && createdArtifacts != null
- && eitherNonMetaArtifacts.isLeft()) {
+ && eitherNonMetaArtifacts.isLeft()) {
Either<ArtifactDefinition, Operation> eitherResult = eitherNonMetaArtifacts.left().value();
if (eitherResult.isLeft()) {
createdArtifacts.add(eitherResult.left().value());
resourceSystemName = resource.getSystemName();
}
resource
- .setToscaResourceName(CommonBeUtils.generateToscaResourceName(resource.getResourceType().name().toLowerCase(), resourceSystemName));
+ .setToscaResourceName(CommonBeUtils.generateToscaResourceName(resource.getResourceType().name().toLowerCase(), resourceSystemName));
}
// Generate invariant UUID - must be here and not in operation since it
InterfaceDefinition interfaceDefinition = intItr.next();
String intType = interfaceDefinition.getUniqueId();
Either<InterfaceDefinition, StorageOperationStatus> eitherCapTypeFound = interfaceTypeOperation.getInterface(
- UniqueIdBuilder.buildInterfaceTypeUid(resource.getModel(), intType));
+ UniqueIdBuilder.buildInterfaceTypeUid(resource.getModel(), intType));
if (eitherCapTypeFound.isRight()) {
if (eitherCapTypeFound.right().value() == StorageOperationStatus.NOT_FOUND) {
BeEcompErrorManager.getInstance()
- .logBeGraphObjectMissingError("Create Resource - validateLifecycleTypesCreate", "Interface", intType);
+ .logBeGraphObjectMissingError("Create Resource - validateLifecycleTypesCreate", "Interface", intType);
log.debug("Lifecycle Type: {} is required by resource: {} but does not exist in the DB", intType, resource.getName());
BeEcompErrorManager.getInstance().logBeDaoSystemError("Create Resource - validateLifecycleTypesCreate");
log.debug("request to data model failed with error: {}", eitherCapTypeFound.right().value().name());
log.debug("validate capability Types Exist - capabilities section");
for (Map.Entry<String, List<CapabilityDefinition>> typeEntry : resource.getCapabilities().entrySet()) {
eitherResult = validateCapabilityTypeExists(user, capabilityTypeOperation, resource, actionEnum, eitherResult, typeEntry,
- inTransaction);
+ inTransaction);
if (eitherResult.isRight()) {
return Either.right(eitherResult.right().value());
}
log.debug("validate capability Types Exist - requirements section");
for (String type : resource.getRequirements().keySet()) {
eitherResult = validateCapabilityTypeExists(user, capabilityTypeOperation, resource, resource.getRequirements().get(type), actionEnum,
- eitherResult, type, inTransaction);
+ eitherResult, type, inTransaction);
if (eitherResult.isRight()) {
return Either.right(eitherResult.right().value());
}
Map.Entry<String, List<CapabilityDefinition>> typeEntry,
boolean inTransaction) {
Either<CapabilityTypeDefinition, StorageOperationStatus> eitherCapTypeFound = capabilityTypeOperation
- .getCapabilityType(UniqueIdBuilder.buildCapabilityTypeUid(resource.getModel(), typeEntry.getKey()), inTransaction);
+ .getCapabilityType(UniqueIdBuilder.buildCapabilityTypeUid(resource.getModel(), typeEntry.getKey()), inTransaction);
if (eitherCapTypeFound.isRight()) {
if (eitherCapTypeFound.right().value() == StorageOperationStatus.NOT_FOUND) {
BeEcompErrorManager.getInstance()
- .logBeGraphObjectMissingError(CREATE_RESOURCE_VALIDATE_CAPABILITY_TYPES, "Capability Type", typeEntry.getKey());
+ .logBeGraphObjectMissingError(CREATE_RESOURCE_VALIDATE_CAPABILITY_TYPES, "Capability Type", typeEntry.getKey());
log.debug("Capability Type: {} is required by resource: {} but does not exist in the DB", typeEntry.getKey(), resource.getName());
BeEcompErrorManager.getInstance().logBeDaoSystemError(CREATE_RESOURCE_VALIDATE_CAPABILITY_TYPES);
}
boolean inTransaction) {
try {
Either<CapabilityTypeDefinition, StorageOperationStatus> eitherCapTypeFound = capabilityTypeOperation
- .getCapabilityType(UniqueIdBuilder.buildCapabilityTypeUid(resource.getModel(), type), inTransaction);
+ .getCapabilityType(UniqueIdBuilder.buildCapabilityTypeUid(resource.getModel(), type), inTransaction);
if (eitherCapTypeFound.isRight()) {
if (eitherCapTypeFound.right().value() == StorageOperationStatus.NOT_FOUND) {
BeEcompErrorManager.getInstance()
- .logBeGraphObjectMissingError(CREATE_RESOURCE_VALIDATE_CAPABILITY_TYPES, "Capability Type", type);
+ .logBeGraphObjectMissingError(CREATE_RESOURCE_VALIDATE_CAPABILITY_TYPES, "Capability Type", type);
log.debug("Capability Type: {} is required by resource: {} but does not exist in the DB", type, resource.getName());
BeEcompErrorManager.getInstance().logBeDaoSystemError(CREATE_RESOURCE_VALIDATE_CAPABILITY_TYPES);
}
BeEcompErrorManager.getInstance().logBeDaoSystemError("Create Resource - validateDerivedFromExist");
log.debug("request to data model failed with error: {}", storageStatus);
ResponseFormat responseFormat = componentsUtils
- .getResponseFormatByResource(componentsUtils.convertFromStorageResponse(storageStatus), resource);
+ .getResponseFormatByResource(componentsUtils.convertFromStorageResponse(storageStatus), resource);
log.trace("audit before sending response");
componentsUtils.auditResource(responseFormat, user, resource, actionEnum);
throw new ComponentException(componentsUtils.convertFromStorageResponse(storageStatus));
if (!ValidationUtils.validateResourceVendorModelNumberLength(resourceVendorModelNumber)) {
log.info("resource vendor model number exceeds limit.");
ResponseFormat errorResponse = componentsUtils.getResponseFormat(ActionStatus.RESOURCE_VENDOR_MODEL_NUMBER_EXCEEDS_LIMIT,
- "" + ValidationUtils.RESOURCE_VENDOR_MODEL_NUMBER_MAX_LENGTH);
+ "" + ValidationUtils.RESOURCE_VENDOR_MODEL_NUMBER_MAX_LENGTH);
componentsUtils.auditResource(errorResponse, user, resource, actionEnum);
throw new ComponentException(ActionStatus.RESOURCE_VENDOR_MODEL_NUMBER_EXCEEDS_LIMIT,
- "" + ValidationUtils.RESOURCE_VENDOR_MODEL_NUMBER_MAX_LENGTH);
+ "" + ValidationUtils.RESOURCE_VENDOR_MODEL_NUMBER_MAX_LENGTH);
}
// resource vendor model number is currently validated as vendor
if (!ValidationUtils.validateVendorReleaseLength(vendorRelease)) {
log.info("vendor release exceds limit.");
ResponseFormat errorResponse = componentsUtils
- .getResponseFormat(ActionStatus.VENDOR_RELEASE_EXCEEDS_LIMIT, "" + ValidationUtils.VENDOR_RELEASE_MAX_LENGTH);
+ .getResponseFormat(ActionStatus.VENDOR_RELEASE_EXCEEDS_LIMIT, "" + ValidationUtils.VENDOR_RELEASE_MAX_LENGTH);
componentsUtils.auditResource(errorResponse, user, resource, actionEnum);
throw new ComponentException(ActionStatus.VENDOR_RELEASE_EXCEEDS_LIMIT, "" + ValidationUtils.VENDOR_RELEASE_MAX_LENGTH);
}
if (CollectionUtils.isEmpty(categories)) {
log.debug(CATEGORY_IS_EMPTY);
ResponseFormat responseFormat = componentsUtils
- .getResponseFormat(ActionStatus.COMPONENT_MISSING_CATEGORY, ComponentTypeEnum.RESOURCE.getValue());
+ .getResponseFormat(ActionStatus.COMPONENT_MISSING_CATEGORY, ComponentTypeEnum.RESOURCE.getValue());
componentsUtils.auditResource(responseFormat, user, resource, actionEnum);
throw new ComponentException(ActionStatus.COMPONENT_MISSING_CATEGORY, ComponentTypeEnum.RESOURCE.getValue());
}
if (StringUtils.isEmpty(category.getName())) {
log.debug(CATEGORY_IS_EMPTY);
ResponseFormat responseFormat = componentsUtils
- .getResponseFormat(ActionStatus.COMPONENT_MISSING_CATEGORY, ComponentTypeEnum.RESOURCE.getValue());
+ .getResponseFormat(ActionStatus.COMPONENT_MISSING_CATEGORY, ComponentTypeEnum.RESOURCE.getValue());
componentsUtils.auditResource(responseFormat, user, resource, actionEnum);
throw new ComponentException(ActionStatus.COMPONENT_MISSING_CATEGORY, ComponentTypeEnum.RESOURCE.getValue());
}
if (StringUtils.isEmpty(subcategory.getName())) {
log.debug(CATEGORY_IS_EMPTY);
ResponseFormat responseFormat = componentsUtils
- .getResponseFormat(ActionStatus.COMPONENT_MISSING_SUBCATEGORY, ComponentTypeEnum.RESOURCE.getValue());
+ .getResponseFormat(ActionStatus.COMPONENT_MISSING_SUBCATEGORY, ComponentTypeEnum.RESOURCE.getValue());
componentsUtils.auditResource(responseFormat, user, resource, actionEnum);
throw new ComponentException(ActionStatus.COMPONENT_MISSING_SUBCATEGORY, ComponentTypeEnum.RESOURCE.getValue());
}
try {
log.debug("validating resource category {} against valid categories list", category);
Either<List<CategoryDefinition>, ActionStatus> categories = serviceBusinessLogic.elementDao
- .getAllCategories(NodeTypeEnum.ResourceNewCategory, inTransaction);
+ .getAllCategories(NodeTypeEnum.ResourceNewCategory, inTransaction);
if (categories.isRight()) {
log.debug("failed to retrieve resource categories from Titan");
responseFormat = componentsUtils.getResponseFormat(categories.right().value());
}
List<CategoryDefinition> categoryList = categories.left().value();
Optional<CategoryDefinition> foundCategory = categoryList.stream().filter(cat -> cat.getName().equals(category.getName()))
- .findFirst();
+ .findFirst();
if (!foundCategory.isPresent()) {
log.debug("Category {} is not part of resource category group. Resource category valid values are {}", category, categoryList);
failOnInvalidCategory(user, resource, actionEnum);
}
Optional<SubCategoryDefinition> foundSubcategory = foundCategory.get().getSubcategories().stream()
- .filter(subcat -> subcat.getName().equals(subcategory.getName())).findFirst();
+ .filter(subcat -> subcat.getName().equals(subcategory.getName())).findFirst();
if (!foundSubcategory.isPresent()) {
log.debug("SubCategory {} is not part of resource category group. Resource subcategory valid values are {}", subcategory,
- foundCategory.get().getSubcategories());
+ foundCategory.get().getSubcategories());
failOnInvalidCategory(user, resource, actionEnum);
}
} catch (Exception e) {
if (!ValidationUtils.validateVendorNameLength(vendorName)) {
log.info("vendor name exceds limit.");
ResponseFormat errorResponse = componentsUtils
- .getResponseFormat(ActionStatus.VENDOR_NAME_EXCEEDS_LIMIT, "" + ValidationUtils.VENDOR_NAME_MAX_LENGTH);
+ .getResponseFormat(ActionStatus.VENDOR_NAME_EXCEEDS_LIMIT, "" + ValidationUtils.VENDOR_NAME_MAX_LENGTH);
componentsUtils.auditResource(errorResponse, user, resource, actionEnum);
throw new ComponentException(ActionStatus.VENDOR_NAME_EXCEEDS_LIMIT, "" + ValidationUtils.VENDOR_NAME_MAX_LENGTH);
}
}
if (validRegDef == null) {
ResponseFormat responseFormat = componentsUtils
- .getResponseFormat(ActionStatus.INVALID_NODE_TEMPLATE, yamlName, uploadComponentInstanceInfo.getName(),
- uploadComponentInstanceInfo.getType());
+ .getResponseFormat(ActionStatus.INVALID_NODE_TEMPLATE, yamlName, uploadComponentInstanceInfo.getName(),
+ uploadComponentInstanceInfo.getType());
return Either.right(responseFormat);
}
return Either.left(validRegDef);
return null;
}
Optional<CapabilityDefinition> capByName = capMap.get(validReq.getCapability()).stream()
- .filter(p -> p.getName().equals(uploadReqInfo.getCapabilityName())).findAny();
+ .filter(p -> p.getName().equals(uploadReqInfo.getCapabilityName())).findAny();
if (!capByName.isPresent()) {
return null;
}
UploadCapInfo uploadedCapability) {
List<ComponentInstanceProperty> validProperties = new ArrayList<>();
Map<String, PropertyDefinition> defaultProperties = defaultCapability.getProperties().stream()
- .collect(toMap(PropertyDefinition::getName, Function.identity()));
+ .collect(toMap(PropertyDefinition::getName, Function.identity()));
List<UploadPropInfo> uploadedProperties = uploadedCapability.getProperties();
for (UploadPropInfo property : uploadedProperties) {
String propertyName = property.getName().toLowerCase();
artifactMap = new HashMap<>();
}
Map<String, Object> deploymentResourceArtifacts = ConfigurationManager.getConfigurationManager().getConfiguration()
- .getDeploymentResourceArtifacts();
+ .getDeploymentResourceArtifacts();
if (deploymentResourceArtifacts != null) {
Map<String, ArtifactDefinition> finalArtifactMap = artifactMap;
deploymentResourceArtifacts.forEach((k, v) -> processDeploymentResourceArtifacts(user, resource, finalArtifactMap, k, v));
if (shouldCreateArtifact) {
if (serviceBusinessLogic.artifactsBusinessLogic != null) {
ArtifactDefinition artifactDefinition = serviceBusinessLogic.artifactsBusinessLogic
- .createArtifactPlaceHolderInfo(resource.getUniqueId(), k, (Map<String, Object>) v, user, ArtifactGroupTypeEnum.DEPLOYMENT);
+ .createArtifactPlaceHolderInfo(resource.getUniqueId(), k, (Map<String, Object>) v, user, ArtifactGroupTypeEnum.DEPLOYMENT);
if (artifactDefinition != null && !artifactMap.containsKey(artifactDefinition.getArtifactLabel())) {
artifactMap.put(artifactDefinition.getArtifactLabel(), artifactDefinition);
}
private void validateDerivedFromNotEmpty(User user, Resource resource, AuditingActionEnum actionEnum) {
log.debug("validate resource derivedFrom field");
if ((resource.getDerivedFrom() == null) || (resource.getDerivedFrom().isEmpty()) || (resource.getDerivedFrom().get(0)) == null || (resource
- .getDerivedFrom().get(0).trim().isEmpty())) {
+ .getDerivedFrom().get(0).trim().isEmpty())) {
log.info("derived from (template) field is missing for the resource");
ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.MISSING_DERIVED_FROM_TEMPLATE);
componentsUtils.auditResource(responseFormat, user, resource, actionEnum);
Either<Service, StorageOperationStatus> updatedResource = toscaOperationFacade.getToscaElement(service.getUniqueId());
if (updatedResource.isRight()) {
throw new ComponentException(componentsUtils
- .getResponseFormatByComponent(componentsUtils.convertFromStorageResponse(updatedResource.right().value()), service,
- ComponentTypeEnum.SERVICE));
+ .getResponseFormatByComponent(componentsUtils.convertFromStorageResponse(updatedResource.right().value()), service,
+ ComponentTypeEnum.SERVICE));
}
return updatedResource.left().value();
}
final Either<Service, StorageOperationStatus> updatedResource = toscaOperationFacade.getToscaElement(service.getUniqueId());
if (updatedResource.isRight()) {
throw new ComponentException(
- componentsUtils.getResponseFormatByComponent(componentsUtils.convertFromStorageResponse(updatedResource.right().value()), service,
- ComponentTypeEnum.SERVICE));
+ componentsUtils.getResponseFormatByComponent(componentsUtils.convertFromStorageResponse(updatedResource.right().value()), service,
+ ComponentTypeEnum.SERVICE));
}
return updatedResource.left().value();
}
public Service createSubstitutionFilterOnService(Service service,
ListDataDefinition<SubstitutionFilterPropertyDataDefinition> substitutionFilterProperties)
- throws BusinessLogicException {
+ throws BusinessLogicException {
if (substitutionFilterProperties == null || substitutionFilterProperties.isEmpty()) {
return service;
}
Either<Service, StorageOperationStatus> updatedResource = toscaOperationFacade.getToscaElement(service.getUniqueId());
if (updatedResource.isRight()) {
throw new ComponentException(componentsUtils
- .getResponseFormatByComponent(componentsUtils.convertFromStorageResponse(updatedResource.right().value()), service,
- ComponentTypeEnum.SERVICE));
+ .getResponseFormatByComponent(componentsUtils.convertFromStorageResponse(updatedResource.right().value()), service,
+ ComponentTypeEnum.SERVICE));
}
return updatedResource.left().value();
}
public Service createServiceTransaction(Service service, User user, boolean isNormative, AuditingActionEnum auditingAction) {
if (!AuditingActionEnum.UPDATE_SERVICE_TOSCA_TEMPLATE.equals(auditingAction) &&
- !AuditingActionEnum.UPDATE_SERVICE_TOSCA_MODEL.equals(auditingAction)) {
+ !AuditingActionEnum.UPDATE_SERVICE_TOSCA_MODEL.equals(auditingAction)) {
// validate resource name uniqueness
log.debug("validate resource name");
Either<Boolean, StorageOperationStatus> eitherValidation = toscaOperationFacade
- .validateComponentNameExists(service.getName(), null, service.getComponentType());
+ .validateComponentNameExists(service.getName(), null, service.getComponentType());
if (eitherValidation.isRight()) {
log.debug("Failed to validate component name {}. Status is {}. ", service.getName(), eitherValidation.right().value());
ResponseFormat errorResponse = componentsUtils
- .getResponseFormat(componentsUtils.convertFromStorageResponse(eitherValidation.right().value()));
+ .getResponseFormat(componentsUtils.convertFromStorageResponse(eitherValidation.right().value()));
throw new ComponentException(errorResponse);
}
if (eitherValidation.left().value()) {
log.debug("resource with name: {}, already exists", service.getName());
ResponseFormat errorResponse = componentsUtils
- .getResponseFormat(ActionStatus.COMPONENT_NAME_ALREADY_EXIST, ComponentTypeEnum.RESOURCE.getValue(), service.getName());
+ .getResponseFormat(ActionStatus.COMPONENT_NAME_ALREADY_EXIST, ComponentTypeEnum.RESOURCE.getValue(), service.getName());
throw new ComponentException(errorResponse);
}
}
createArtifactsPlaceHolderData(service, user);
// enrich object
if (!isNormative && !AuditingActionEnum.UPDATE_SERVICE_TOSCA_TEMPLATE.equals(auditingAction) &&
- !AuditingActionEnum.UPDATE_SERVICE_TOSCA_MODEL.equals(auditingAction)) {
+ !AuditingActionEnum.UPDATE_SERVICE_TOSCA_MODEL.equals(auditingAction)) {
log.debug("enrich resource with creator, version and state");
service.setLifecycleState(LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT);
service.setVersion(INITIAL_VERSION);
service.setHighestVersion(true);
}
if (AuditingActionEnum.UPDATE_SERVICE_TOSCA_TEMPLATE.equals(auditingAction) ||
- AuditingActionEnum.UPDATE_SERVICE_TOSCA_MODEL.equals(auditingAction)) {
- toscaOperationFacade.deleteService(service.getInvariantUUID(), false);
+ AuditingActionEnum.UPDATE_SERVICE_TOSCA_MODEL.equals(auditingAction)) {
+ toscaOperationFacade.deleteService(service.getInvariantUUID(), true);
}
return toscaOperationFacade.createToscaComponent(service).left().on(r -> throwComponentExceptionByResource(r, service));
}
public Service throwComponentExceptionByResource(StorageOperationStatus status, Service service) {
ResponseFormat responseFormat = componentsUtils
- .getResponseFormatByComponent(componentsUtils.convertFromStorageResponse(status), service, ComponentTypeEnum.SERVICE);
+ .getResponseFormatByComponent(componentsUtils.convertFromStorageResponse(status), service, ComponentTypeEnum.SERVICE);
throw new ComponentException(responseFormat);
}
List<String> exludeResourceCategory = ConfigurationManager.getConfigurationManager().getConfiguration().getExcludeResourceCategory();
List<String> exludeResourceType = ConfigurationManager.getConfigurationManager().getConfiguration().getExcludeResourceType();
Map<String, Object> informationalResourceArtifacts = ConfigurationManager.getConfigurationManager().getConfiguration()
- .getInformationalResourceArtifacts();
+ .getInformationalResourceArtifacts();
List<CategoryDefinition> categories = service.getCategories();
boolean isCreateArtifact = true;
if (exludeResourceCategory != null) {
Map<String, Object> artifactInfoMap = (Map<String, Object>) informationalResourceArtifacts.get(informationalResourceArtifactName);
if (serviceBusinessLogic.artifactsBusinessLogic != null) {
ArtifactDefinition artifactDefinition = serviceBusinessLogic.artifactsBusinessLogic
- .createArtifactPlaceHolderInfo(resourceUniqueId, informationalResourceArtifactName, artifactInfoMap, user,
- ArtifactGroupTypeEnum.INFORMATIONAL);
+ .createArtifactPlaceHolderInfo(resourceUniqueId, informationalResourceArtifactName, artifactInfoMap, user,
+ ArtifactGroupTypeEnum.INFORMATIONAL);
artifactMap.put(artifactDefinition.getArtifactLabel(), artifactDefinition);
}
}
private Resource nodeFullCertification(String uniqueId, User user, LifecycleChangeInfoWithAction lifecycleChangeInfo, boolean inTransaction,
boolean needLock) {
Either<Resource, ResponseFormat> resourceResponse = lifecycleBusinessLogic
- .changeState(uniqueId, user, LifeCycleTransitionEnum.CERTIFY, lifecycleChangeInfo, inTransaction, needLock);
+ .changeState(uniqueId, user, LifeCycleTransitionEnum.CERTIFY, lifecycleChangeInfo, inTransaction, needLock);
if (resourceResponse.isRight()) {
throw new ByResponseFormatComponentException(resourceResponse.right().value());
}
validateDerivedFromExist(null, updateInfoResource, null);
} else {
Either<Boolean, ResponseFormat> validateDerivedFromExtending = validateDerivedFromExtending(null, currentResource, updateInfoResource,
- null);
+ null);
if (validateDerivedFromExtending.isRight() || !validateDerivedFromExtending.left().value()) {
log.debug("Derived from cannot be updated if it doesnt inherits directly or extends inheritance");
return validateDerivedFromExtending;
String currentTemplateName = currentResource.getDerivedFrom().get(0);
String updatedTemplateName = updateInfoResource.getDerivedFrom().get(0);
Either<Boolean, StorageOperationStatus> dataModelResponse = toscaOperationFacade
- .validateToscaResourceNameExtends(currentTemplateName, updatedTemplateName, currentResource.getModel());
+ .validateToscaResourceNameExtends(currentTemplateName, updatedTemplateName, currentResource.getModel());
if (dataModelResponse.isRight()) {
StorageOperationStatus storageStatus = dataModelResponse.right().value();
BeEcompErrorManager.getInstance().logBeDaoSystemError("Create/Update Resource - validateDerivingFromExtendingType");
ResponseFormat responseFormat = componentsUtils
- .getResponseFormatByResource(componentsUtils.convertFromStorageResponse(storageStatus), currentResource);
+ .getResponseFormatByResource(componentsUtils.convertFromStorageResponse(storageStatus), currentResource);
log.trace("audit before sending response");
componentsUtils.auditResource(responseFormat, user, currentResource, actionEnum);
return Either.right(responseFormat);
return true;
}
return currentResource.getResourceType().equals(ResourceTypeEnum.VF) && resourceNameUpdated
- .equals(addCvfcSuffixToResourceName(resourceNameCurrent));
+ .equals(addCvfcSuffixToResourceName(resourceNameCurrent));
}
public Resource prepareResourceForUpdate(Resource oldResource, Resource newResource, User user, boolean inTransaction, boolean needLock) {
if (!ComponentValidationUtils.canWorkOnResource(oldResource, user.getUserId())) {
// checkout
return lifecycleBusinessLogic
- .changeState(oldResource.getUniqueId(), user, LifeCycleTransitionEnum.CHECKOUT, new LifecycleChangeInfoWithAction("update by import"),
- inTransaction, needLock).left().on(response -> failOnChangeState(response, user, oldResource, newResource));
+ .changeState(oldResource.getUniqueId(), user, LifeCycleTransitionEnum.CHECKOUT, new LifecycleChangeInfoWithAction("update by import"),
+ inTransaction, needLock).left().on(response -> failOnChangeState(response, user, oldResource, newResource));
}
return oldResource;
}
if (response.getRequestError() != null) {
log.info("resource {} cannot be updated. reason={}", oldResource.getUniqueId(), response.getFormattedMessage());
componentsUtils.auditResource(response, user, newResource, AuditingActionEnum.IMPORT_RESOURCE,
- ResourceVersionInfo.newBuilder().state(oldResource.getLifecycleState().name()).version(oldResource.getVersion()).build());
+ ResourceVersionInfo.newBuilder().state(oldResource.getLifecycleState().name()).version(oldResource.getVersion()).build());
}
throw new ComponentException(response);
}
Either<Resource, StorageOperationStatus> updatedResource = toscaOperationFacade.getToscaElement(resource.getUniqueId());
if (updatedResource.isRight()) {
throw new ComponentException(
- componentsUtils.getResponseFormatByResource(componentsUtils.convertFromStorageResponse(updatedResource.right().value()), resource));
+ componentsUtils.getResponseFormatByResource(componentsUtils.convertFromStorageResponse(updatedResource.right().value()), resource));
}
return updatedResource.left().value();
}
}
if (isNotEmpty(groupsToUpdate)) {
groupBusinessLogic.updateGroups(resource, groupsToUpdate, true).left()
- .on(serviceBusinessLogic::throwComponentException);
+ .on(serviceBusinessLogic::throwComponentException);
}
}
List<GroupDefinition> groupsToUpdate, List<GroupDefinition> groupsToCreate) {
for (GroupDefinition group : groupsAsList) {
Optional<GroupDefinition> op = groupsFromResource.stream().filter(p -> p.getInvariantName().equalsIgnoreCase(group.getInvariantName()))
- .findAny();
+ .findAny();
if (op.isPresent()) {
GroupDefinition groupToUpdate = op.get();
groupToUpdate.setMembers(group.getMembers());
if (CollectionUtils.isEmpty(componentInstances)) {
String membersAstString = compInstancesNames.stream().collect(joining(","));
log.debug("The members: {}, in group: {}, cannot be found in component {}. There are no component instances.", membersAstString,
- groupName, component.getNormalizedName());
+ groupName, component.getNormalizedName());
throw new ComponentException(componentsUtils
- .getResponseFormat(ActionStatus.GROUP_INVALID_COMPONENT_INSTANCE, membersAstString, groupName, component.getNormalizedName(),
- getComponentTypeForResponse(component)));
+ .getResponseFormat(ActionStatus.GROUP_INVALID_COMPONENT_INSTANCE, membersAstString, groupName, component.getNormalizedName(),
+ getComponentTypeForResponse(component)));
}
// Find all component instances with the member names
Map<String, String> memberNames = componentInstances.stream().collect(toMap(ComponentInstance::getName, ComponentInstance::getUniqueId));
memberNames.putAll(groups.keySet().stream().collect(toMap(g -> g, g -> "")));
Map<String, String> relevantInstances = memberNames.entrySet().stream().filter(n -> compInstancesNames.contains(n.getKey()))
- .collect(toMap(Map.Entry::getKey, Map.Entry::getValue));
+ .collect(toMap(Map.Entry::getKey, Map.Entry::getValue));
if (relevantInstances == null || relevantInstances.size() != compInstancesNames.size()) {
List<String> foundMembers = new ArrayList<>();
if (relevantInstances != null) {
String membersAstString = compInstancesNames.stream().collect(joining(","));
log.debug("The members: {}, in group: {}, cannot be found in component: {}", membersAstString, groupName, component.getNormalizedName());
throw new ComponentException(componentsUtils
- .getResponseFormat(ActionStatus.GROUP_INVALID_COMPONENT_INSTANCE, membersAstString, groupName, component.getNormalizedName(),
- getComponentTypeForResponse(component)));
+ .getResponseFormat(ActionStatus.GROUP_INVALID_COMPONENT_INSTANCE, membersAstString, groupName, component.getNormalizedName(),
+ getComponentTypeForResponse(component)));
}
updatedGroupDefinition.setMembers(relevantInstances);
}
boolean forceCertificationAllowed, CsarInfo csarInfo, String nodeName,
boolean isNested) {
LifecycleChangeInfoWithAction lifecycleChangeInfo = new LifecycleChangeInfoWithAction(CERTIFICATION_ON_IMPORT,
- LifecycleChangeInfoWithAction.LifecycleChanceActionEnum.CREATE_FROM_CSAR);
+ LifecycleChangeInfoWithAction.LifecycleChanceActionEnum.CREATE_FROM_CSAR);
Function<Resource, Boolean> validator = resource -> validateResourceCreationFromNodeType(resource, creator);
return resourceImportManager
- .importCertifiedResource(nodeTypeYaml, resourceMetaData, creator, validator, lifecycleChangeInfo, isInTransaction, true, needLock,
- nodeTypeArtifactsToHandle, nodeTypesNewCreatedArtifacts, forceCertificationAllowed, csarInfo, nodeName, isNested, null);
+ .importCertifiedResource(nodeTypeYaml, resourceMetaData, creator, validator, lifecycleChangeInfo, isInTransaction, true, needLock,
+ nodeTypeArtifactsToHandle, nodeTypesNewCreatedArtifacts, forceCertificationAllowed, csarInfo, nodeName, isNested, null);
}
public ImmutablePair<Resource, ActionStatus> createNodeTypeResourceFromYaml(String yamlName, Map.Entry<String, Object> nodeNameValue, User user,
String singleVfcYaml = buildNodeTypeYaml(nodeNameValue, mapToConvert, resourceMetaData.getResourceType(), csarInfo);
user = serviceBusinessLogic.validateUser(user, "CheckIn Resource", resourceVf, AuditingActionEnum.CHECKIN_RESOURCE, true);
return createResourceFromNodeType(singleVfcYaml, resourceMetaData, user, true, needLock, nodeTypeArtifactsToHandle,
- nodeTypesNewCreatedArtifacts, forceCertificationAllowed, csarInfo, nodeNameValue.getKey(), isNested);
+ nodeTypesNewCreatedArtifacts, forceCertificationAllowed, csarInfo, nodeNameValue.getKey(), isNested);
}
protected UploadResourceInfo fillResourceMetadata(String yamlName, Service resourceVf, String nodeName, User user) {
Either<Resource, ResponseFormat> result = null;
try {
if (resource.getLifecycleState() != LifecycleStateEnum.CERTIFIED && forceCertificationAllowed && lifecycleBusinessLogic
- .isFirstCertification(resource.getVersion())) {
+ .isFirstCertification(resource.getVersion())) {
nodeForceCertification(resource, user, lifecycleChangeInfo, inTransaction, needLock);
}
if (resource.getLifecycleState() == LifecycleStateEnum.CERTIFIED) {
Either<ArtifactDefinition, Operation> eitherPopulated = serviceBusinessLogic
- .populateToscaArtifacts(resource, user, false, inTransaction, needLock);
+ .populateToscaArtifacts(resource, user, false, inTransaction, needLock);
return resource;
}
return nodeFullCertification(resource.getUniqueId(), user, lifecycleChangeInfo, inTransaction, needLock);
Either<Resource, StorageOperationStatus> updatedResource = toscaOperationFacade.getToscaElement(resource.getUniqueId());
if (updatedResource.isRight()) {
throw new ComponentException(
- componentsUtils.getResponseFormatByResource(componentsUtils.convertFromStorageResponse(updatedResource.right().value()), resource));
+ componentsUtils.getResponseFormatByResource(componentsUtils.convertFromStorageResponse(updatedResource.right().value()), resource));
}
return updatedResource.left().value();
}
List<String> exludeResourceCategory = ConfigurationManager.getConfigurationManager().getConfiguration().getExcludeResourceCategory();
List<String> exludeResourceType = ConfigurationManager.getConfigurationManager().getConfiguration().getExcludeResourceType();
Map<String, Object> informationalResourceArtifacts = ConfigurationManager.getConfigurationManager().getConfiguration()
- .getInformationalResourceArtifacts();
+ .getInformationalResourceArtifacts();
List<CategoryDefinition> categories = resource.getCategories();
boolean isCreateArtifact = true;
if (exludeResourceCategory != null) {
Map<String, Object> artifactInfoMap = (Map<String, Object>) informationalResourceArtifacts.get(informationalResourceArtifactName);
if (serviceBusinessLogic.artifactsBusinessLogic != null) {
ArtifactDefinition artifactDefinition = serviceBusinessLogic.artifactsBusinessLogic
- .createArtifactPlaceHolderInfo(resourceUniqueId, informationalResourceArtifactName, artifactInfoMap, user,
- ArtifactGroupTypeEnum.INFORMATIONAL);
+ .createArtifactPlaceHolderInfo(resourceUniqueId, informationalResourceArtifactName, artifactInfoMap, user,
+ ArtifactGroupTypeEnum.INFORMATIONAL);
artifactMap.put(artifactDefinition.getArtifactLabel(), artifactDefinition);
}
}
List<InputDefinition> inputs = service.getInputs();
if (MapUtils.isNotEmpty(groups)) {
groups.values().stream().filter(g -> isNotEmpty(g.getProperties())).flatMap(g -> g.getProperties().stream())
- .forEach(p -> handleGetInputs(p, inputs));
+ .forEach(p -> handleGetInputs(p, inputs));
}
}
List<InputDefinition> inputs = resource.getInputs();
if (MapUtils.isNotEmpty(groups)) {
groups.values().stream().filter(g -> isNotEmpty(g.getProperties())).flatMap(g -> g.getProperties().stream())
- .forEach(p -> handleGetInputs(p, inputs));
+ .forEach(p -> handleGetInputs(p, inputs));
}
}
if (inputs == null || inputs.isEmpty()) {
log.debug("Failed to add property {} to group. Inputs list is empty ", property);
serviceBusinessLogic.rollbackWithException(ActionStatus.INPUTS_NOT_FOUND,
- property.getGetInputValues().stream().map(GetInputValueDataDefinition::getInputName).collect(toList()).toString());
+ property.getGetInputValues().stream().map(GetInputValueDataDefinition::getInputName).collect(toList()).toString());
}
ListIterator<GetInputValueDataDefinition> getInputValuesIter = property.getGetInputValues().listIterator();
while (getInputValuesIter.hasNext()) {
Map<String, List<ComponentInstanceProperty>> instProperties) {
try {
Either<Map<String, List<ComponentInstanceProperty>>, StorageOperationStatus> addPropToInst = toscaOperationFacade
- .associateComponentInstancePropertiesToComponent(instProperties, resource.getUniqueId());
+ .associateComponentInstancePropertiesToComponent(instProperties, resource.getUniqueId());
if (addPropToInst.isRight()) {
log.debug("failed to associate properties of resource {} status is {}", resource.getUniqueId(), addPropToInst.right().value());
throw new ComponentException(
- componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(addPropToInst.right().value()), yamlName));
+ componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(addPropToInst.right().value()), yamlName));
}
} catch (Exception e) {
log.debug("Exception occured when findNodeTypeArtifactsToHandle, error is:{}", e.getMessage());
Map<String, List<ComponentInstanceInput>> instInputs) {
if (MapUtils.isNotEmpty(instInputs)) {
Either<Map<String, List<ComponentInstanceInput>>, StorageOperationStatus> addInputToInst = toscaOperationFacade
- .associateComponentInstanceInputsToComponent(instInputs, resource.getUniqueId());
+ .associateComponentInstanceInputsToComponent(instInputs, resource.getUniqueId());
if (addInputToInst.isRight()) {
log.debug("failed to associate inputs value of resource {} status is {}", resource.getUniqueId(), addInputToInst.right().value());
throw new ComponentException(
- componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(addInputToInst.right().value()), yamlName));
+ componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(addInputToInst.right().value()), yamlName));
}
}
}
public void associateComponentInstanceInterfacesToComponent(
- String yamlName,
- Service service,
- Map<String, Map<String, InterfaceDefinition>> instInterfaces
+ String yamlName,
+ Service service,
+ Map<String, Map<String, InterfaceDefinition>> instInterfaces
) {
if (MapUtils.isNotEmpty(instInterfaces)) {
Either<Map<String, MapInterfaceDataDefinition>, StorageOperationStatus> addInterfaceToInst =
- toscaOperationFacade
- .associateComponentInstanceInterfacesToComponent(
- instInterfaces,
- service.getUniqueId()
- );
+ toscaOperationFacade
+ .associateComponentInstanceInterfacesToComponent(
+ instInterfaces,
+ service.getUniqueId()
+ );
if (addInterfaceToInst.isRight()) {
log.error("failed to associate interfaces value of service {}, status is {}", service.getUniqueId(),
- addInterfaceToInst.right().value());
+ addInterfaceToInst.right().value());
throw new ComponentException(
- componentsUtils.getResponseFormat(
- componentsUtils.convertFromStorageResponse(
- addInterfaceToInst.right().value()
- ),
- yamlName
- )
+ componentsUtils.getResponseFormat(
+ componentsUtils.convertFromStorageResponse(
+ addInterfaceToInst.right().value()
+ ),
+ yamlName
+ )
);
}
}
public void associateComponentInstanceInputsToComponent(String yamlName, Service service, Map<String, List<ComponentInstanceInput>> instInputs) {
if (MapUtils.isNotEmpty(instInputs)) {
Either<Map<String, List<ComponentInstanceInput>>, StorageOperationStatus> addInputToInst = toscaOperationFacade
- .associateComponentInstanceInputsToComponent(instInputs, service.getUniqueId());
+ .associateComponentInstanceInputsToComponent(instInputs, service.getUniqueId());
if (addInputToInst.isRight()) {
log.debug("failed to associate inputs value of resource {} status is {}", service.getUniqueId(), addInputToInst.right().value());
throw new ComponentException(
- componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(addInputToInst.right().value()), yamlName));
+ componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(addInputToInst.right().value()), yamlName));
}
}
}
log.trace("************* Going to associate all resource node filters {}", yamlName);
if (MapUtils.isNotEmpty(nodeFilter)) {
StorageOperationStatus status = componentNodeFilterBusinessLogic.associateNodeFilterToComponentInstance(service.getUniqueId(),
- nodeFilter);
+ nodeFilter);
if (status != StorageOperationStatus.OK) {
throw new ComponentException(
- componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(status), yamlName));
+ componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(status), yamlName));
}
}
}
public void associateComponentInstancePropertiesToComponent(String yamlName, Service service,
Map<String, List<ComponentInstanceProperty>> instProperties) {
Either<Map<String, List<ComponentInstanceProperty>>, StorageOperationStatus> addPropToInst = toscaOperationFacade
- .associateComponentInstancePropertiesToComponent(instProperties, service.getUniqueId());
+ .associateComponentInstancePropertiesToComponent(instProperties, service.getUniqueId());
if (addPropToInst.isRight()) {
throw new ComponentException(
- componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(addPropToInst.right().value()), yamlName));
+ componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(addPropToInst.right().value()), yamlName));
}
}
public void associateResourceInstances(String yamlName, Service service, List<RequirementCapabilityRelDef> relations) {
Either<List<RequirementCapabilityRelDef>, StorageOperationStatus> relationsEither = toscaOperationFacade
- .associateResourceInstances(service, service.getUniqueId(), relations);
+ .associateResourceInstances(service, service.getUniqueId(), relations);
if (relationsEither.isRight() && relationsEither.right().value() != StorageOperationStatus.NOT_FOUND) {
StorageOperationStatus status = relationsEither.right().value();
log.debug("failed to associate instances of service {} status is {}", service.getUniqueId(), status);
public void associateResourceInstances(String yamlName, Resource resource, List<RequirementCapabilityRelDef> relations) {
Either<List<RequirementCapabilityRelDef>, StorageOperationStatus> relationsEither = toscaOperationFacade
- .associateResourceInstances(resource, resource.getUniqueId(), relations);
+ .associateResourceInstances(resource, resource.getUniqueId(), relations);
if (relationsEither.isRight() && relationsEither.right().value() != StorageOperationStatus.NOT_FOUND) {
StorageOperationStatus status = relationsEither.right().value();
log.debug("failed to associate instances of resource {} status is {}", resource.getUniqueId(), status);
if (currentCompInstance == null) {
log.debug(COMPONENT_INSTANCE_WITH_NAME_IN_RESOURCE, uploadComponentInstanceInfo.getName(), resource.getUniqueId());
BeEcompErrorManager.getInstance()
- .logInternalDataError(COMPONENT_INSTANCE_WITH_NAME + uploadComponentInstanceInfo.getName() + IN_RESOURCE, resource.getUniqueId(),
- BeEcompErrorManager.ErrorSeverity.ERROR);
+ .logInternalDataError(COMPONENT_INSTANCE_WITH_NAME + uploadComponentInstanceInfo.getName() + IN_RESOURCE, resource.getUniqueId(),
+ BeEcompErrorManager.ErrorSeverity.ERROR);
ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.NOT_TOPOLOGY_TOSCA_TEMPLATE, yamlName);
throw new ComponentException(responseFormat);
}
if (currentCompInstance == null) {
log.debug(COMPONENT_INSTANCE_WITH_NAME_IN_RESOURCE, nodesInfoValue.getName(), resource.getUniqueId());
BeEcompErrorManager.getInstance()
- .logInternalDataError(COMPONENT_INSTANCE_WITH_NAME + nodesInfoValue.getName() + IN_RESOURCE, resource.getUniqueId(),
- BeEcompErrorManager.ErrorSeverity.ERROR);
+ .logInternalDataError(COMPONENT_INSTANCE_WITH_NAME + nodesInfoValue.getName() + IN_RESOURCE, resource.getUniqueId(),
+ BeEcompErrorManager.ErrorSeverity.ERROR);
return componentsUtils.getResponseFormat(ActionStatus.NOT_TOPOLOGY_TOSCA_TEMPLATE, yamlName);
}
String resourceInstanceId = currentCompInstance.getUniqueId();
regCapRelDef.setFromNode(resourceInstanceId);
log.debug("try to find available requirement {} ", regName);
Either<RequirementDefinition, ResponseFormat> eitherReqStatus = findAvailableRequirement(regName, yamlName, nodesInfoValue,
- currentCompInstance, uploadRegInfo.getCapabilityName());
+ currentCompInstance, uploadRegInfo.getCapabilityName());
if (eitherReqStatus.isRight()) {
return eitherReqStatus.right().value();
}
if (currentCapCompInstance == null) {
log.debug("The component instance with name {} not found on resource {} ", uploadRegInfo.getNode(), resource.getUniqueId());
BeEcompErrorManager.getInstance()
- .logInternalDataError(COMPONENT_INSTANCE_WITH_NAME + uploadRegInfo.getNode() + IN_RESOURCE, resource.getUniqueId(),
- BeEcompErrorManager.ErrorSeverity.ERROR);
+ .logInternalDataError(COMPONENT_INSTANCE_WITH_NAME + uploadRegInfo.getNode() + IN_RESOURCE, resource.getUniqueId(),
+ BeEcompErrorManager.ErrorSeverity.ERROR);
return componentsUtils.getResponseFormat(ActionStatus.NOT_TOPOLOGY_TOSCA_TEMPLATE, yamlName);
}
regCapRelDef.setToNode(currentCapCompInstance.getUniqueId());
reqAndRelationshipPair.setCapabilityOwnerId(aviableCapForRel.getOwnerId());
if (aviableCapForRel == null) {
BeEcompErrorManager.getInstance().logInternalDataError(
- "aviable capability was not found. req name is " + validReq.getName() + " component instance is " + currentCapCompInstance
- .getUniqueId(), resource.getUniqueId(), BeEcompErrorManager.ErrorSeverity.ERROR);
+ "aviable capability was not found. req name is " + validReq.getName() + " component instance is " + currentCapCompInstance
+ .getUniqueId(), resource.getUniqueId(), BeEcompErrorManager.ErrorSeverity.ERROR);
return componentsUtils.getResponseFormat(ActionStatus.NOT_TOPOLOGY_TOSCA_TEMPLATE, yamlName);
}
CapabilityRequirementRelationship capReqRel = new CapabilityRequirementRelationship();
*/
package org.openecomp.sdc.be.servlets;
-import static org.apache.hc.core5.http.HttpStatus.SC_BAD_REQUEST;
import static org.openecomp.sdc.common.log.enums.EcompLoggerErrorCode.BUSINESS_PROCESS_ERROR;
import com.fasterxml.jackson.core.JsonProcessingException;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
-import org.apache.commons.collections4.MapUtils;
import org.apache.http.HttpStatus;
import org.glassfish.jersey.media.multipart.FormDataContentDisposition;
import org.glassfish.jersey.media.multipart.FormDataParam;
import org.openecomp.sdc.be.resources.data.auditing.model.DistributionData;
import org.openecomp.sdc.be.resources.data.auditing.model.ResourceCommonInfo;
import org.openecomp.sdc.be.servlets.ServiceUploadServlet.ServiceAuthorityTypeEnum;
+import org.openecomp.sdc.be.user.UserBusinessLogic;
import org.openecomp.sdc.common.api.Constants;
import org.openecomp.sdc.common.datastructure.Wrapper;
import org.openecomp.sdc.common.log.elements.LoggerSupportability;
import org.openecomp.sdc.common.zip.exception.ZipException;
import org.openecomp.sdc.exception.ResponseFormat;
import org.springframework.stereotype.Controller;
-import org.yaml.snakeyaml.Yaml;
@Loggable(prepend = true, value = Loggable.DEBUG, trim = false)
@Path("/v1/catalog")
private static final String MODIFIER_ID_IS = "modifier id is {}";
private final ElementBusinessLogic elementBusinessLogic;
private final ServiceBusinessLogic serviceBusinessLogic;
+ private final UserBusinessLogic userBusinessLogic;
@Inject
public ServiceServlet(ComponentInstanceBusinessLogic componentInstanceBL, ComponentsUtils componentsUtils,
ServletUtils servletUtils, ResourceImportManager resourceImportManager, ServiceBusinessLogic serviceBusinessLogic,
- ResourceBusinessLogic resourceBusinessLogic, ElementBusinessLogic elementBusinessLogic) {
+ ResourceBusinessLogic resourceBusinessLogic, ElementBusinessLogic elementBusinessLogic, UserBusinessLogic userBusinessLogic) {
super(componentInstanceBL, componentsUtils, servletUtils, resourceImportManager);
this.serviceBusinessLogic = serviceBusinessLogic;
this.elementBusinessLogic = elementBusinessLogic;
+ this.userBusinessLogic = userBusinessLogic;
}
@POST
@Consumes(MediaType.APPLICATION_JSON)
@Produces(MediaType.APPLICATION_JSON)
@Operation(description = "Create Service", method = "POST", summary = "Returns created service", responses = {
- @ApiResponse(content = @Content(array = @ArraySchema(schema = @Schema(implementation = Service.class)))),
- @ApiResponse(responseCode = "201", description = "Service created"), @ApiResponse(responseCode = "403", description = "Restricted operation"),
- @ApiResponse(responseCode = "400", description = "Invalid content / Missing content"),
- @ApiResponse(responseCode = "409", description = "Service already exist"),
- @ApiResponse(responseCode = "401", description = "Unauthorized Tenant")})
+ @ApiResponse(content = @Content(array = @ArraySchema(schema = @Schema(implementation = Service.class)))),
+ @ApiResponse(responseCode = "201", description = "Service created"), @ApiResponse(responseCode = "403", description = "Restricted operation"),
+ @ApiResponse(responseCode = "400", description = "Invalid content / Missing content"),
+ @ApiResponse(responseCode = "409", description = "Service already exist"),
+ @ApiResponse(responseCode = "401", description = "Unauthorized Tenant")})
@PermissionAllowed(AafPermission.PermNames.INTERNAL_ALL_VALUE)
public Response createService(@Parameter(description = "Service object to be created", required = true) String data,
@Context final HttpServletRequest request, @HeaderParam(value = Constants.USER_ID_HEADER) String userId) {
throw new ByResponseFormatComponentException(actionResponse.right().value());
}
loggerSupportability.log(LoggerSupportabilityActions.CREATE_SERVICE, service.getComponentMetadataForSupportLog(), StatusCode.COMPLETE,
- "Service {} has been created by user {} ", service.getName(), userId);
+ "Service {} has been created by user {} ", service.getName(), userId);
return buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.CREATED), actionResponse.left().value());
} else {
log.debug("Unauthorized Tenant");
throw new ByResponseFormatComponentException(actionResponse.right().value());
}
loggerSupportability.log(LoggerSupportabilityActions.CREATE_SERVICE, service.getComponentMetadataForSupportLog(), StatusCode.COMPLETE,
- "Service {} has been created by user {} ", service.getName(), userId);
+ "Service {} has been created by user {} ", service.getName(), userId);
return buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.CREATED), actionResponse.left().value());
}
}
public Either<Service, ResponseFormat> parseToService(String serviceJson, User user) {
return getComponentsUtils()
- .convertJsonToObjectUsingObjectMapper(serviceJson, user, Service.class, AuditingActionEnum.CREATE_SERVICE, ComponentTypeEnum.SERVICE);
+ .convertJsonToObjectUsingObjectMapper(serviceJson, user, Service.class, AuditingActionEnum.CREATE_SERVICE, ComponentTypeEnum.SERVICE);
}
@GET
@Consumes(MediaType.APPLICATION_JSON)
@Produces(MediaType.APPLICATION_JSON)
@Operation(description = "validate service name", method = "GET", summary = "checks if the chosen service name is available ", responses = {
- @ApiResponse(content = @Content(array = @ArraySchema(schema = @Schema(implementation = Response.class)))),
- @ApiResponse(responseCode = "200", description = "Service found"), @ApiResponse(responseCode = "403", description = "Restricted operation")})
+ @ApiResponse(content = @Content(array = @ArraySchema(schema = @Schema(implementation = Response.class)))),
+ @ApiResponse(responseCode = "200", description = "Service found"), @ApiResponse(responseCode = "403", description = "Restricted operation")})
@PermissionAllowed(AafPermission.PermNames.INTERNAL_ALL_VALUE)
public Response validateServiceName(@PathParam("serviceName") final String serviceName, @Context final HttpServletRequest request,
@HeaderParam(value = Constants.USER_ID_HEADER) String userId) {
@Consumes(MediaType.APPLICATION_JSON)
@Produces(MediaType.APPLICATION_JSON)
@Operation(description = "get component audit records", method = "GET", summary = "get audit records for a service or a resource", responses = {
- @ApiResponse(content = @Content(array = @ArraySchema(schema = @Schema(implementation = Response.class)))),
- @ApiResponse(responseCode = "200", description = "Service found"), @ApiResponse(responseCode = "403", description = "Restricted operation")})
+ @ApiResponse(content = @Content(array = @ArraySchema(schema = @Schema(implementation = Response.class)))),
+ @ApiResponse(responseCode = "200", description = "Service found"), @ApiResponse(responseCode = "403", description = "Restricted operation")})
@PermissionAllowed(AafPermission.PermNames.INTERNAL_ALL_VALUE)
public Response getComponentAuditRecords(@PathParam("componentType") final String componentType,
@PathParam("componentUniqueId") final String componentUniqueId,
validateUserExist(responseWrapper, userWrapper, userId);
if (responseWrapper.isEmpty()) {
fillUUIDAndVersion(responseWrapper, uuidWrapper, versionWrapper, userWrapper.getInnerElement(), validateComponentType(componentType),
- componentUniqueId, context);
+ componentUniqueId, context);
}
if (responseWrapper.isEmpty()) {
Either<List<Map<String, Object>>, ResponseFormat> eitherServiceAudit = serviceBusinessLogic
- .getComponentAuditRecords(versionWrapper.getInnerElement(), uuidWrapper.getInnerElement(), userId);
+ .getComponentAuditRecords(versionWrapper.getInnerElement(), uuidWrapper.getInnerElement(), userId);
if (eitherServiceAudit.isRight()) {
Response errorResponse = buildErrorResponse(eitherServiceAudit.right().value());
responseWrapper.setInnerElement(errorResponse);
@Path("/services/{serviceId}")
@Tag(name = "SDCE-2 APIs")
@Operation(description = "Delete Service", method = "DELETE", summary = "Return no content", responses = {
- @ApiResponse(content = @Content(array = @ArraySchema(schema = @Schema(implementation = Service.class)))),
- @ApiResponse(responseCode = "204", description = "Service deleted"), @ApiResponse(responseCode = "403", description = "Restricted operation"),
- @ApiResponse(responseCode = "400", description = "Invalid content / Missing content"),
- @ApiResponse(responseCode = "404", description = "Service not found")})
+ @ApiResponse(content = @Content(array = @ArraySchema(schema = @Schema(implementation = Service.class)))),
+ @ApiResponse(responseCode = "204", description = "Service deleted"), @ApiResponse(responseCode = "403", description = "Restricted operation"),
+ @ApiResponse(responseCode = "400", description = "Invalid content / Missing content"),
+ @ApiResponse(responseCode = "404", description = "Service not found")})
@PermissionAllowed(AafPermission.PermNames.INTERNAL_ALL_VALUE)
public Response deleteService(@PathParam("serviceId") final String serviceId,
@Parameter(description = "Optional parameter to determine the delete action: " +
- "DELETE, which will permanently delete theService from the system or " +
- "MARK_AS_DELETE, which will logically mark the service as deleted. Default action is to MARK_AS_DELETE")
+ "DELETE, which will permanently delete theService from the system or " +
+ "MARK_AS_DELETE, which will logically mark the service as deleted. Default action is to MARK_AS_DELETE")
@QueryParam("deleteAction") final Action deleteAction,
@Context final HttpServletRequest request) {
ServletContext context = request.getSession().getServletContext();
try {
String serviceIdLower = serviceId.toLowerCase();
loggerSupportability
- .log(LoggerSupportabilityActions.DELETE_SERVICE, StatusCode.STARTED, "Starting to delete service {} by user {} ", serviceIdLower,
- userId);
+ .log(LoggerSupportabilityActions.DELETE_SERVICE, StatusCode.STARTED, "Starting to delete service {} by user {} ", serviceIdLower,
+ userId);
ServiceBusinessLogic businessLogic = getServiceBL(context);
ResponseFormat actionResponse;
if (Action.DELETE.equals(deleteAction)) {
return buildErrorResponse(actionResponse);
}
loggerSupportability
- .log(LoggerSupportabilityActions.DELETE_SERVICE, StatusCode.COMPLETE, "Ended deleting service {} by user {}", serviceIdLower, userId);
+ .log(LoggerSupportabilityActions.DELETE_SERVICE, StatusCode.COMPLETE, "Ended deleting service {} by user {}", serviceIdLower, userId);
return buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.NO_CONTENT), null);
} catch (Exception e) {
BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Delete Service");
@Path("/services/{serviceName}/{version}")
@Tag(name = "SDCE-2 APIs")
@Operation(description = "Delete Service By Name And Version", method = "DELETE", summary = "Returns no content", responses = {
- @ApiResponse(content = @Content(array = @ArraySchema(schema = @Schema(implementation = Resource.class)))),
- @ApiResponse(responseCode = "204", description = "Service deleted"), @ApiResponse(responseCode = "403", description = "Restricted operation"),
- @ApiResponse(responseCode = "400", description = "Invalid content / Missing content"),
- @ApiResponse(responseCode = "404", description = "Service not found")})
+ @ApiResponse(content = @Content(array = @ArraySchema(schema = @Schema(implementation = Resource.class)))),
+ @ApiResponse(responseCode = "204", description = "Service deleted"), @ApiResponse(responseCode = "403", description = "Restricted operation"),
+ @ApiResponse(responseCode = "400", description = "Invalid content / Missing content"),
+ @ApiResponse(responseCode = "404", description = "Service not found")})
@PermissionAllowed(AafPermission.PermNames.INTERNAL_ALL_VALUE)
public Response deleteServiceByNameAndVersion(@PathParam("serviceName") final String serviceName, @PathParam("version") final String version,
@Context final HttpServletRequest request) {
log.debug(START_HANDLE_REQUEST_OF, url);
// get modifier id
String userId = request.getHeader(Constants.USER_ID_HEADER);
- User modifier = new User(userId);
log.debug(MODIFIER_ID_IS, userId);
- return modifier;
+ return userBusinessLogic.getUser(userId);
}
@PUT
@Consumes(MediaType.APPLICATION_JSON)
@Produces(MediaType.APPLICATION_JSON)
@Operation(description = "Update Service Metadata", method = "PUT", summary = "Returns updated service", responses = {
- @ApiResponse(content = @Content(array = @ArraySchema(schema = @Schema(implementation = Service.class)))),
- @ApiResponse(responseCode = "200", description = "Service Updated"), @ApiResponse(responseCode = "403", description = "Restricted operation"),
- @ApiResponse(responseCode = "400", description = "Invalid content / Missing content")})
+ @ApiResponse(content = @Content(array = @ArraySchema(schema = @Schema(implementation = Service.class)))),
+ @ApiResponse(responseCode = "200", description = "Service Updated"), @ApiResponse(responseCode = "403", description = "Restricted operation"),
+ @ApiResponse(responseCode = "400", description = "Invalid content / Missing content")})
@PermissionAllowed(AafPermission.PermNames.INTERNAL_ALL_VALUE)
public Response updateServiceMetadata(@PathParam("serviceId") final String serviceId,
@Parameter(description = "Service object to be Updated", required = true) String data,
@Context final HttpServletRequest request, @HeaderParam(value = Constants.USER_ID_HEADER) String userId)
- throws IOException {
+ throws IOException {
String url = request.getMethod() + " " + request.getRequestURI();
log.debug(START_HANDLE_REQUEST_OF, url);
User modifier = new User(userId);
@Consumes(MediaType.APPLICATION_JSON)
@Produces(MediaType.APPLICATION_JSON)
@Operation(description = "Update Group Instance Property Values", method = "PUT", summary = "Returns updated group instance", responses = {
- @ApiResponse(content = @Content(array = @ArraySchema(schema = @Schema(implementation = Service.class)))),
- @ApiResponse(responseCode = "200", description = "Group Instance Property Values Updated"),
- @ApiResponse(responseCode = "403", description = "Restricted operation"),
- @ApiResponse(responseCode = "400", description = "Invalid content / Missing content")})
+ @ApiResponse(content = @Content(array = @ArraySchema(schema = @Schema(implementation = Service.class)))),
+ @ApiResponse(responseCode = "200", description = "Group Instance Property Values Updated"),
+ @ApiResponse(responseCode = "403", description = "Restricted operation"),
+ @ApiResponse(responseCode = "400", description = "Invalid content / Missing content")})
@PermissionAllowed(AafPermission.PermNames.INTERNAL_ALL_VALUE)
public Response updateGroupInstancePropertyValues(@PathParam("serviceId") final String serviceId,
@PathParam("componentInstanceId") final String componentInstanceId,
if (actionResponse == null) {
log.debug("Start handle update group instance property values request. Received group instance is {}", groupInstanceId);
actionResponse = serviceBusinessLogic
- .updateGroupInstancePropertyValues(modifier, serviceId, componentInstanceId, groupInstanceId, newProperties);
+ .updateGroupInstancePropertyValues(modifier, serviceId, componentInstanceId, groupInstanceId, newProperties);
if (actionResponse.isRight()) {
actionResponse = Either.right(actionResponse.right().value());
}
@Consumes(MediaType.APPLICATION_JSON)
@Produces(MediaType.APPLICATION_JSON)
@Operation(description = "Retrieve Service", method = "GET", summary = "Returns service according to serviceId", responses = {
- @ApiResponse(content = @Content(array = @ArraySchema(schema = @Schema(implementation = Service.class)))),
- @ApiResponse(responseCode = "200", description = "Service found"), @ApiResponse(responseCode = "403", description = "Restricted operation"),
- @ApiResponse(responseCode = "404", description = "Service not found")})
+ @ApiResponse(content = @Content(array = @ArraySchema(schema = @Schema(implementation = Service.class)))),
+ @ApiResponse(responseCode = "200", description = "Service found"), @ApiResponse(responseCode = "403", description = "Restricted operation"),
+ @ApiResponse(responseCode = "404", description = "Service not found")})
@PermissionAllowed(AafPermission.PermNames.INTERNAL_ALL_VALUE)
public Response getServiceById(@PathParam("serviceId") final String serviceId, @Context final HttpServletRequest request,
@HeaderParam(value = Constants.USER_ID_HEADER) String userId) throws IOException {
@Consumes(MediaType.APPLICATION_JSON)
@Produces(MediaType.APPLICATION_JSON)
@Operation(description = "Retrieve Service", method = "GET", summary = "Returns service according to name and version", responses = {
- @ApiResponse(content = @Content(array = @ArraySchema(schema = @Schema(implementation = Service.class)))),
- @ApiResponse(responseCode = "200", description = "Service found"), @ApiResponse(responseCode = "403", description = "Restricted operation"),
- @ApiResponse(responseCode = "404", description = "Service not found")})
+ @ApiResponse(content = @Content(array = @ArraySchema(schema = @Schema(implementation = Service.class)))),
+ @ApiResponse(responseCode = "200", description = "Service found"), @ApiResponse(responseCode = "403", description = "Restricted operation"),
+ @ApiResponse(responseCode = "404", description = "Service not found")})
@PermissionAllowed(AafPermission.PermNames.INTERNAL_ALL_VALUE)
public Response getServiceByNameAndVersion(@PathParam("serviceName") final String serviceName,
@PathParam("serviceVersion") final String serviceVersion, @Context final HttpServletRequest request,
@Consumes(MediaType.APPLICATION_JSON)
@Produces(MediaType.APPLICATION_JSON)
@Operation(description = "Activate distribution", method = "POST", summary = "activate distribution", responses = {
- @ApiResponse(responseCode = "200", description = "OK"),
- @ApiResponse(responseCode = "409", description = "Service cannot be distributed due to missing deployment artifacts"),
- @ApiResponse(responseCode = "404", description = "Requested service was not found"),
- @ApiResponse(responseCode = "500", description = "Internal Server Error. Please try again later.")})
+ @ApiResponse(responseCode = "200", description = "OK"),
+ @ApiResponse(responseCode = "409", description = "Service cannot be distributed due to missing deployment artifacts"),
+ @ApiResponse(responseCode = "404", description = "Requested service was not found"),
+ @ApiResponse(responseCode = "500", description = "Internal Server Error. Please try again later.")})
@PermissionAllowed(AafPermission.PermNames.INTERNAL_ALL_VALUE)
public Response activateDistribution(@PathParam("serviceId") final String serviceId, @PathParam("env") final String env,
@Context final HttpServletRequest request, @HeaderParam(value = Constants.USER_ID_HEADER) String userId)
- throws IOException {
+ throws IOException {
String url = request.getMethod() + " " + request.getRequestURI();
log.debug(START_HANDLE_REQUEST_OF, url);
User modifier = new User(userId);
@Consumes(MediaType.APPLICATION_JSON)
@Produces(MediaType.APPLICATION_JSON)
@Operation(description = "Mark distribution as deployed", method = "POST", summary = "relevant audit record will be created", responses = {
- @ApiResponse(responseCode = "200", description = "Service was marked as deployed"),
- @ApiResponse(responseCode = "409", description = "Restricted operation"),
- @ApiResponse(responseCode = "403", description = "Service is not available"),
- @ApiResponse(responseCode = "400", description = "Invalid content / Missing content"),
- @ApiResponse(responseCode = "404", description = "Requested service was not found"),
- @ApiResponse(responseCode = "500", description = "Internal Server Error. Please try again later.")})
+ @ApiResponse(responseCode = "200", description = "Service was marked as deployed"),
+ @ApiResponse(responseCode = "409", description = "Restricted operation"),
+ @ApiResponse(responseCode = "403", description = "Service is not available"),
+ @ApiResponse(responseCode = "400", description = "Invalid content / Missing content"),
+ @ApiResponse(responseCode = "404", description = "Requested service was not found"),
+ @ApiResponse(responseCode = "500", description = "Internal Server Error. Please try again later.")})
@PermissionAllowed(AafPermission.PermNames.INTERNAL_ALL_VALUE)
public Response markDistributionAsDeployed(@PathParam("serviceId") final String serviceId, @PathParam("did") final String did,
@Context final HttpServletRequest request,
@Consumes(MediaType.APPLICATION_JSON)
@Produces(MediaType.APPLICATION_JSON)
@Operation(responses = {@ApiResponse(responseCode = "200", description = "OK"),
- @ApiResponse(responseCode = "500", description = "Internal Server Error. Please try again later.")})
+ @ApiResponse(responseCode = "500", description = "Internal Server Error. Please try again later.")})
@PermissionAllowed(AafPermission.PermNames.INTERNAL_ALL_VALUE)
public Response tempUrlToBeDeleted(@PathParam("serviceId") final String serviceId, @Context final HttpServletRequest request,
@HeaderParam(value = Constants.USER_ID_HEADER) String userId) {
try {
Service service = (serviceBusinessLogic.getService(serviceId, modifier)).left().value();
Either<Service, ResponseFormat> res = serviceBusinessLogic
- .updateDistributionStatusForActivation(service, modifier, DistributionStatusEnum.DISTRIBUTED);
+ .updateDistributionStatusForActivation(service, modifier, DistributionStatusEnum.DISTRIBUTED);
if (res.isRight()) {
buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR));
}
@Consumes(MediaType.APPLICATION_JSON)
@Produces(MediaType.APPLICATION_JSON)
@Operation(description = "Retrieve Service component relations map", method = "GET", summary = "Returns service components relations", responses = {
- @ApiResponse(content = @Content(array = @ArraySchema(schema = @Schema(implementation = ServiceRelations.class)))),
- @ApiResponse(responseCode = "200", description = "Service found"), @ApiResponse(responseCode = "403", description = "Restricted operation"),
- @ApiResponse(responseCode = "404", description = "Service not found")})
+ @ApiResponse(content = @Content(array = @ArraySchema(schema = @Schema(implementation = ServiceRelations.class)))),
+ @ApiResponse(responseCode = "200", description = "Service found"), @ApiResponse(responseCode = "403", description = "Restricted operation"),
+ @ApiResponse(responseCode = "404", description = "Service not found")})
@PermissionAllowed(AafPermission.PermNames.INTERNAL_ALL_VALUE)
public Response getServiceComponentRelationMap(@PathParam("serviceId") final String serviceId, @Context final HttpServletRequest request,
@HeaderParam(value = Constants.USER_ID_HEADER) String userId) throws IOException {
@Consumes(MediaType.APPLICATION_JSON)
@Produces(MediaType.APPLICATION_JSON)
@Operation(description = "Import Service", method = "POST", summary = "Returns imported service", responses = {
- @ApiResponse(responseCode = "201", description = "Service created"), @ApiResponse(responseCode = "403", description = "Restricted operation"),
- @ApiResponse(responseCode = "400", description = "Invalid content / Missing content"),
- @ApiResponse(responseCode = "409", description = "Service already exist")})
+ @ApiResponse(responseCode = "201", description = "Service created"), @ApiResponse(responseCode = "403", description = "Restricted operation"),
+ @ApiResponse(responseCode = "400", description = "Invalid content / Missing content"),
+ @ApiResponse(responseCode = "409", description = "Service already exist")})
public Response importNsService(@Parameter(description = "Service object to be imported", required = true) String data,
@Context final HttpServletRequest request, @HeaderParam(value = Constants.USER_ID_HEADER) String userId) {
userId = (userId != null) ? userId : request.getHeader(Constants.USER_ID_HEADER);
ServiceAuthorityTypeEnum serviceAuthorityTypeEnum = ServiceAuthorityTypeEnum.USER_TYPE_UI;
commonServiceGeneralValidations(responseWrapper, userWrapper, uploadServiceInfoWrapper, serviceAuthorityTypeEnum, userId, data);
specificServiceAuthorityValidations(responseWrapper, uploadServiceInfoWrapper, yamlStringWrapper, request,
- data, serviceAuthorityTypeEnum);
+ data, serviceAuthorityTypeEnum);
if (responseWrapper.isEmpty()) {
handleImportService(responseWrapper, userWrapper.getInnerElement(), uploadServiceInfoWrapper.getInnerElement());
}
@Tag(name = "SDCE-2 APIs")
@Produces(MediaType.APPLICATION_JSON)
@Operation(description = "Import Service", method = "POST", summary = "Returns imported service", responses = {
- @ApiResponse(responseCode = "201", description = "Service created"), @ApiResponse(responseCode = "403", description = "Restricted operation"),
- @ApiResponse(responseCode = "400", description = "Invalid content / Missing content"),
- @ApiResponse(responseCode = "409", description = "Service already exist")})
+ @ApiResponse(responseCode = "201", description = "Service created"), @ApiResponse(responseCode = "403", description = "Restricted operation"),
+ @ApiResponse(responseCode = "400", description = "Invalid content / Missing content"),
+ @ApiResponse(responseCode = "409", description = "Service already exist")})
@PermissionAllowed(AafPermission.PermNames.INTERNAL_ALL_VALUE)
public Response importReplaceService(
- @Parameter(description = "The user id", required = true) @HeaderParam(value = Constants.USER_ID_HEADER) String userId,
- @Parameter(description = "X-ECOMP-RequestID header", required = false) @HeaderParam(value = Constants.X_ECOMP_REQUEST_ID_HEADER) String requestId,
- @Parameter(description = "X-ECOMP-InstanceID header", required = true) @HeaderParam(value = Constants.X_ECOMP_INSTANCE_ID_HEADER) final String instanceIdHeader,
- @Parameter(description = "Determines the format of the body of the response", required = false) @HeaderParam(value = Constants.ACCEPT_HEADER) String accept,
- @Parameter(description = "The username and password", required = true) @HeaderParam(value = Constants.AUTHORIZATION_HEADER) String authorization,
- @Context final HttpServletRequest request, @Parameter(description = "FileInputStream") @FormDataParam("serviceZip") File file,
- @Parameter(description = "ContentDisposition") @FormDataParam("serviceZip") FormDataContentDisposition contentDispositionHeader,
- @Parameter(description = "serviceMetadata") @FormDataParam("serviceZipMetadata") String serviceInfoJsonString,
- @Parameter(description = "The requested asset uuid", required = true) @PathParam("uuid") final String uuid) {
+ @Parameter(description = "The user id", required = true) @HeaderParam(value = Constants.USER_ID_HEADER) String userId,
+ @Parameter(description = "X-ECOMP-RequestID header", required = false) @HeaderParam(value = Constants.X_ECOMP_REQUEST_ID_HEADER) String requestId,
+ @Parameter(description = "X-ECOMP-InstanceID header", required = true) @HeaderParam(value = Constants.X_ECOMP_INSTANCE_ID_HEADER) final String instanceIdHeader,
+ @Parameter(description = "Determines the format of the body of the response", required = false) @HeaderParam(value = Constants.ACCEPT_HEADER) String accept,
+ @Parameter(description = "The username and password", required = true) @HeaderParam(value = Constants.AUTHORIZATION_HEADER) String authorization,
+ @Context final HttpServletRequest request, @Parameter(description = "FileInputStream") @FormDataParam("serviceZip") File file,
+ @Parameter(description = "ContentDisposition") @FormDataParam("serviceZip") FormDataContentDisposition contentDispositionHeader,
+ @Parameter(description = "serviceMetadata") @FormDataParam("serviceZipMetadata") String serviceInfoJsonString,
+ @Parameter(description = "The requested asset uuid", required = true) @PathParam("uuid") final String uuid) {
initSpringFromContext();
String requestURI = request.getRequestURI();
String url = request.getMethod() + " " + requestURI;
AuditingActionEnum auditingActionEnum = AuditingActionEnum.Import_Replace_Service;
String assetType = "services";
Either<List<? extends Component>, ResponseFormat> assetTypeData = elementBusinessLogic
- .getCatalogComponentsByUuidAndAssetType(assetType, uuid);
+ .getCatalogComponentsByUuidAndAssetType(assetType, uuid);
if (assetTypeData.isRight() || assetTypeData.left().value().size() != 1) {
log.debug("getServiceAbstractStatus: Service Fetching Failed");
throw new ByResponseFormatComponentException(assetTypeData.right().value());
ServiceUploadServlet.ServiceAuthorityTypeEnum serviceAuthorityEnum = ServiceUploadServlet.ServiceAuthorityTypeEnum.CSAR_TYPE_BE;
// PayLoad Validations
commonServiceGeneralValidations(responseWrapper, userWrapper, uploadServiceInfoWrapper, serviceAuthorityEnum, userId,
- serviceInfoJsonString);
+ serviceInfoJsonString);
fillServicePayload(responseWrapper, uploadServiceInfoWrapper, yamlStringWrapper, modifier, serviceInfoJsonString, serviceAuthorityEnum,
- file);
+ file);
specificServiceAuthorityValidations(responseWrapper, uploadServiceInfoWrapper, yamlStringWrapper, request,
- serviceInfoJsonString, serviceAuthorityEnum);
+ serviceInfoJsonString, serviceAuthorityEnum);
log.debug("importReplaceService:get payload:{}", uploadServiceInfoWrapper.getInnerElement().getPayloadData());
ServiceMetadataDataDefinition serviceMetadataDataDefinition = (ServiceMetadataDataDefinition) oldService.getComponentMetadataDefinition()
- .getMetadataDataDefinition();
+ .getMetadataDataDefinition();
uploadServiceInfoWrapper.getInnerElement().setServiceVendorModelNumber(serviceMetadataDataDefinition.getServiceVendorModelNumber());
uploadServiceInfoWrapper.getInnerElement().setDescription(oldService.getDescription());
uploadServiceInfoWrapper.getInnerElement().setCategories(oldService.getCategories());
@Consumes(MediaType.APPLICATION_JSON)
@Produces(MediaType.APPLICATION_JSON)
@Operation(description = "Update service by tosca template import", method = "PUT", summary = "Returns updated service",
- responses = {
- @ApiResponse(content = @Content(array = @ArraySchema(schema = @Schema(implementation = Service.class)))),
- @ApiResponse(responseCode = "200", description = "Service Updated"),
- @ApiResponse(responseCode = "403", description = "Restricted operation"),
- @ApiResponse(responseCode = "400", description = "Invalid content / Missing content")})
+ responses = {
+ @ApiResponse(content = @Content(array = @ArraySchema(schema = @Schema(implementation = Service.class)))),
+ @ApiResponse(responseCode = "200", description = "Service Updated"),
+ @ApiResponse(responseCode = "403", description = "Restricted operation"),
+ @ApiResponse(responseCode = "400", description = "Invalid content / Missing content")})
@PermissionAllowed(AafPermission.PermNames.INTERNAL_ALL_VALUE)
public Response importToscaTemplate(@PathParam("serviceId") final String serviceId,
@Parameter(description = "Service object to be Updated", required = true) final String data,
@Context final HttpServletRequest request,
@HeaderParam(value = Constants.USER_ID_HEADER) final String userId) throws IOException {
initSpringFromContext();
- final String url = request.getMethod() + " " + request.getRequestURI();
- log.debug(START_HANDLE_REQUEST_OF, url);
- final User modifier = new User(userId);
- log.debug(MODIFIER_ID_IS, userId);
+ final User modifier = getUser(request);
try {
final ServiceImportBusinessLogic serviceImportBusinessLogic = serviceImportManager.getServiceImportBusinessLogic();
final Service updatedService = serviceImportBusinessLogic.updateServiceFromToscaTemplate(serviceId, modifier, data);
return buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), RepresentationUtils.toRepresentation(updatedService));
} catch (Exception e) {
BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Update Service Metadata");
- log.debug("update service metadata failed with exception", e);
+ log.error("update service metadata failed with exception", e);
+ throw e;
+ }
+ }
+
+ @PUT
+ @Path("/services/{serviceId}/toscaModel")
+ @Tag(name = "SDCE-2 APIs")
+ @Consumes(MediaType.MULTIPART_FORM_DATA)
+ @Produces(MediaType.APPLICATION_JSON)
+ @Operation(description = "Update service by tosca template model", method = "PUT", summary = "Returns updated service",
+ responses = {
+ @ApiResponse(content = @Content(array = @ArraySchema(schema = @Schema(implementation = Service.class)))),
+ @ApiResponse(responseCode = "200", description = "Service Updated"),
+ @ApiResponse(responseCode = "403", description = "Restricted operation"),
+ @ApiResponse(responseCode = "400", description = "Invalid content / Missing content")})
+ @PermissionAllowed(AafPermission.PermNames.INTERNAL_ALL_VALUE)
+ public Response importToscaModel(@PathParam("serviceId") final String serviceId,
+ @NotNull @FormDataParam("upload") final InputStream fileToUpload,
+ @Context final HttpServletRequest request,
+ @HeaderParam(value = Constants.USER_ID_HEADER) final String userId) throws IOException {
+ initSpringFromContext();
+ final User modifier = getUser(request);
+ try {
+ final ServiceImportBusinessLogic serviceImportBusinessLogic = serviceImportManager.getServiceImportBusinessLogic();
+ final Service updatedService = serviceImportBusinessLogic.updateServiceFromToscaModel(serviceId, modifier, fileToUpload);
+ return buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), RepresentationUtils.toRepresentation(updatedService));
+ } catch (Exception e) {
+ BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Update Service Metadata");
+ log.error("update service metadata failed with exception", e);
throw e;
}
}