summaryrefslogtreecommitdiffstats
path: root/catalog-be/src
diff options
context:
space:
mode:
authorvasraz <vasyl.razinkov@est.tech>2023-09-07 10:17:14 +0100
committervasraz <vasyl.razinkov@est.tech>2023-09-07 10:17:14 +0100
commitc469756a1092194adedd590d35f0f1f8feac3a36 (patch)
treefd6d13177627286b00b998ce2ae16f4ba605137d /catalog-be/src
parent5c1294eb8e2dc00cae4ef21d6111e0fa18fc2caa (diff)
Implement 'Update Service by importing Tosca Model'-story
Signed-off-by: Vasyl Razinkov <vasyl.razinkov@est.tech> Change-Id: I34414caeb53c4dcc6499d3639e4ea8f80407a6f6 Issue-ID: SDC-4579
Diffstat (limited to 'catalog-be/src')
-rw-r--r--catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/CsarValidationUtils.java16
-rw-r--r--catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/OutputsBusinessLogic.java7
-rw-r--r--catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/ServiceImportBusinessLogic.java53
-rw-r--r--catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/ServiceImportParseLogic.java262
-rw-r--r--catalog-be/src/main/java/org/openecomp/sdc/be/components/lifecycle/LifeCycleTransition.java10
-rw-r--r--catalog-be/src/main/java/org/openecomp/sdc/be/servlets/ServiceServlet.java215
6 files changed, 318 insertions, 245 deletions
diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/CsarValidationUtils.java b/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/CsarValidationUtils.java
index a45a04ea2a..1f7d9493d4 100644
--- a/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/CsarValidationUtils.java
+++ b/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/CsarValidationUtils.java
@@ -50,13 +50,13 @@ public class CsarValidationUtils {
private static final String CSAR_VERSION = "CSAR-Version";
private static final String CREATED_BY = "Created-By";
private static final String NEW_LINE_DELM = "\n";
- private static final String TOSCA_METADATA = "TOSCA-Metadata";
- private static final String TOSCA_FILE = "TOSCA.meta";
- private static final String DEL_PATTERN = "([/\\\\]+)";
- private static final String TOSCA_METADATA_PATH_PATTERN = TOSCA_METADATA +
+ public static final String TOSCA_METADATA = "TOSCA-Metadata";
+ public static final String TOSCA_FILE = "TOSCA.meta";
+ public static final String DEL_PATTERN = "([/\\\\]+)";
+ public static final String TOSCA_METADATA_PATH_PATTERN = TOSCA_METADATA +
// Artifact Group (i.e Deployment/Informational)
DEL_PATTERN + TOSCA_FILE;
- private static final String TOSCA_META_ENTRY_DEFINITIONS = "Entry-Definitions";
+ public static final String TOSCA_META_ENTRY_DEFINITIONS = "Entry-Definitions";
private static final String[] TOSCA_METADATA_FIELDS = {TOSCA_META_FILE_VERSION, CSAR_VERSION, CREATED_BY, TOSCA_META_ENTRY_DEFINITIONS};
private static final String ARTIFACTS_METADATA_FILE = "HEAT.meta";
private static final String TOSCA_CSAR_EXTENSION = ".csar";
@@ -147,18 +147,16 @@ public class CsarValidationUtils {
}
Pattern pattern = Pattern.compile(TOSCA_METADATA_PATH_PATTERN);
Optional<String> keyOp = csar.keySet().stream().filter(k -> pattern.matcher(k).matches()).findAny();
- if (!keyOp.isPresent()) {
+ if (keyOp.isEmpty()) {
log.debug(TOSCA_METADATA_TOSCA_META_FILE_IS_NOT_IN_EXPECTED_KEY_VALUE_FORM_IN_CSAR_CSAR_ID, csarUUID);
BeEcompErrorManager.getInstance()
.logInternalDataError(TOSCA_METADATA_TOSCA_META_FILE_NOT_IN_EXPECTED_KEY_VALUE_FORM_IN_CSAR_WITH_ID + csarUUID,
CSAR_INTERNALS_ARE_INVALID, ErrorSeverity.ERROR);
return Either.right(componentsUtils.getResponseFormat(ActionStatus.CSAR_INVALID_FORMAT, csarUUID));
}
- byte[] toscaMetaBytes = csar.get(keyOp.get());
Properties props = new Properties();
try {
- String propStr = new String(toscaMetaBytes);
- props.load(new StringReader(propStr.replace("\\", "\\\\")));
+ props.load(new StringReader(new String(csar.get(keyOp.get())).replace("\\", "\\\\")));
} catch (IOException e) {
log.debug(TOSCA_METADATA_TOSCA_META_FILE_IS_NOT_IN_EXPECTED_KEY_VALUE_FORM_IN_CSAR_CSAR_ID, csarUUID, e);
BeEcompErrorManager.getInstance()
diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/OutputsBusinessLogic.java b/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/OutputsBusinessLogic.java
index 58baad1a58..1f1f776245 100644
--- a/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/OutputsBusinessLogic.java
+++ b/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/OutputsBusinessLogic.java
@@ -138,9 +138,9 @@ public class OutputsBusinessLogic extends BaseBusinessLogic {
if (status.getLeft() != StorageOperationStatus.OK) {
throw new ByResponseFormatComponentException(componentsUtils.getResponseFormat(ActionStatus.OUTPUT_NAME_ALREADY_EXIST, status.getRight()));
}
- result = attributeDeclarationOrchestrator.declareAttributesToOutputs(component, componentInstOutputsMapUi).left()
- .bind(outputsToCreate -> prepareOutputsForCreation(userId, componentId, outputsToCreate)).right()
- .map(componentsUtils::getResponseFormat);
+ result = attributeDeclarationOrchestrator.declareAttributesToOutputs(component, componentInstOutputsMapUi)
+ .left().bind(outputsToCreate -> prepareOutputsForCreation(userId, componentId, outputsToCreate))
+ .right().map(componentsUtils::getResponseFormat);
return result;
} catch (final ByResponseFormatComponentException e) {
log.error("#createMultipleOutputs: Exception thrown: ", e);
@@ -222,6 +222,7 @@ public class OutputsBusinessLogic extends BaseBusinessLogic {
componentParametersView.setIgnoreComponentInstances(false);
componentParametersView.setIgnoreComponentInstancesOutputs(false);
componentParametersView.setIgnoreComponentInstancesAttributes(false);
+ componentParametersView.setIgnoreComponentInstancesProperties(false);
componentParametersView.setIgnoreUsers(false);
return componentParametersView;
}
diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/ServiceImportBusinessLogic.java b/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/ServiceImportBusinessLogic.java
index bf27d030b5..316c940ac4 100644
--- a/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/ServiceImportBusinessLogic.java
+++ b/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/ServiceImportBusinessLogic.java
@@ -20,6 +20,8 @@ import static java.util.stream.Collectors.joining;
import static java.util.stream.Collectors.toList;
import static java.util.stream.Collectors.toMap;
import static org.apache.commons.collections.CollectionUtils.isNotEmpty;
+import static org.openecomp.sdc.be.components.impl.CsarValidationUtils.TOSCA_METADATA_PATH_PATTERN;
+import static org.openecomp.sdc.be.components.impl.CsarValidationUtils.TOSCA_META_ENTRY_DEFINITIONS;
import static org.openecomp.sdc.be.components.impl.ImportUtils.findFirstToscaMapElement;
import static org.openecomp.sdc.be.components.impl.ImportUtils.findFirstToscaStringElement;
import static org.openecomp.sdc.be.components.impl.ImportUtils.getPropertyJsonStringValue;
@@ -30,6 +32,9 @@ import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import fj.data.Either;
+import java.io.IOException;
+import java.io.InputStream;
+import java.io.StringReader;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.Arrays;
@@ -44,11 +49,13 @@ import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Optional;
+import java.util.Properties;
import java.util.Set;
import java.util.TreeSet;
import java.util.concurrent.atomic.AtomicReference;
import java.util.regex.Pattern;
import java.util.stream.Collectors;
+import javax.validation.constraints.NotNull;
import lombok.Getter;
import lombok.Setter;
import org.apache.commons.collections.CollectionUtils;
@@ -168,6 +175,8 @@ import org.openecomp.sdc.common.datastructure.Wrapper;
import org.openecomp.sdc.common.kpi.api.ASDCKpiApi;
import org.openecomp.sdc.common.log.wrappers.Logger;
import org.openecomp.sdc.common.util.ValidationUtils;
+import org.openecomp.sdc.common.zip.ZipUtils;
+import org.openecomp.sdc.common.zip.exception.ZipException;
import org.openecomp.sdc.exception.ResponseFormat;
import org.springframework.beans.factory.annotation.Autowired;
import org.yaml.snakeyaml.Yaml;
@@ -283,6 +292,50 @@ public class ServiceImportBusinessLogic {
return createService(newService, AuditingActionEnum.UPDATE_SERVICE_TOSCA_TEMPLATE, modifier, payload, null);
}
+ public Service updateServiceFromToscaModel(final String serviceId, final User modifier, final @NotNull InputStream fileToUpload) {
+ final Either<Service, ResponseFormat> serviceResponseFormatEither = serviceBusinessLogic.getService(serviceId, modifier);
+ if (serviceResponseFormatEither.isRight()) {
+ throw new ByActionStatusComponentException(ActionStatus.SERVICE_NOT_FOUND, serviceId);
+ }
+ final Service serviceOriginal = serviceResponseFormatEither.left().value();
+ Map<String, byte[]> csar = null;
+ try {
+ csar = ZipUtils.readZip(fileToUpload.readAllBytes(), false);
+ } catch (final ZipException | IOException e) {
+ log.info("Failed to unzip received csar {}", serviceId, e);
+ }
+ if (csar == null) {
+ throw new ByActionStatusComponentException(ActionStatus.CSAR_NOT_FOUND);
+ }
+ final byte[] mainYamlBytes = readMainYamlFile(csar);
+ final Map<String, String> metadata = (Map<String, String>) new Yaml().loadAs(new String(mainYamlBytes), Map.class).get("metadata");
+ validateServiceMetadataBeforeCreate(serviceOriginal, metadata);
+ final Service newService = cloneServiceIdentifications(serviceOriginal);
+ updateServiceMetadata(newService, metadata);
+ return createService(newService, AuditingActionEnum.UPDATE_SERVICE_TOSCA_MODEL, modifier, csar, null);
+ }
+
+ private byte[] readMainYamlFile(final Map<String, byte[]> csar) {
+ final Pattern pattern = Pattern.compile(TOSCA_METADATA_PATH_PATTERN);
+ final Optional<String> keyOp = csar.keySet().stream().filter(k -> pattern.matcher(k).matches()).findAny();
+ if (keyOp.isEmpty()) {
+ throw new ByActionStatusComponentException(ActionStatus.ARTIFACT_NOT_FOUND_IN_CSAR, TOSCA_METADATA_PATH_PATTERN, "");
+ }
+ final Properties props = new Properties();
+ try {
+ final String propStr = new String(csar.get(keyOp.get()));
+ props.load(new StringReader(propStr.replace("\\", "\\\\")));
+ } catch (IOException e) {
+ throw new ByActionStatusComponentException(ActionStatus.ARTIFACT_NOT_FOUND_IN_CSAR, TOSCA_META_ENTRY_DEFINITIONS, "");
+ }
+ final String mainYamlFileName = props.getProperty(TOSCA_META_ENTRY_DEFINITIONS);
+ final byte[] mainYamlBytes = csar.get(mainYamlFileName);
+ if (mainYamlBytes == null) {
+ throw new ByActionStatusComponentException(ActionStatus.ARTIFACT_NOT_FOUND_IN_CSAR, mainYamlFileName, "");
+ }
+ return mainYamlBytes;
+ }
+
private Service cloneServiceIdentifications(final Service serviceOriginal) {
final Service newService = new Service(serviceOriginal.getComponentMetadataDefinition());
newService.setCategories(serviceOriginal.getCategories());
diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/ServiceImportParseLogic.java b/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/ServiceImportParseLogic.java
index 9365fac4fc..b88661740f 100644
--- a/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/ServiceImportParseLogic.java
+++ b/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/ServiceImportParseLogic.java
@@ -168,18 +168,18 @@ public class ServiceImportParseLogic {
}
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);
@@ -197,7 +197,7 @@ public class ServiceImportParseLogic {
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);
}
}
@@ -217,7 +217,7 @@ public class ServiceImportParseLogic {
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);
}
@@ -250,7 +250,7 @@ public class ServiceImportParseLogic {
}
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);
@@ -269,7 +269,7 @@ public class ServiceImportParseLogic {
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());
}
@@ -297,8 +297,8 @@ public class ServiceImportParseLogic {
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()) {
@@ -333,7 +333,7 @@ public class ServiceImportParseLogic {
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;
}
@@ -346,7 +346,7 @@ public class ServiceImportParseLogic {
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);
@@ -365,14 +365,14 @@ public class ServiceImportParseLogic {
}
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);
@@ -406,7 +406,7 @@ public class ServiceImportParseLogic {
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());
@@ -415,7 +415,7 @@ public class ServiceImportParseLogic {
} 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());
}
}
}
@@ -433,7 +433,7 @@ public class ServiceImportParseLogic {
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());
@@ -484,7 +484,7 @@ public class ServiceImportParseLogic {
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
@@ -516,11 +516,11 @@ public class ServiceImportParseLogic {
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());
@@ -541,7 +541,7 @@ public class ServiceImportParseLogic {
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());
}
@@ -551,7 +551,7 @@ public class ServiceImportParseLogic {
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());
}
@@ -566,11 +566,11 @@ public class ServiceImportParseLogic {
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);
}
@@ -618,11 +618,11 @@ public class ServiceImportParseLogic {
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);
}
@@ -699,7 +699,7 @@ public class ServiceImportParseLogic {
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));
@@ -744,10 +744,10 @@ public class ServiceImportParseLogic {
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
@@ -778,7 +778,7 @@ public class ServiceImportParseLogic {
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);
}
@@ -796,7 +796,7 @@ public class ServiceImportParseLogic {
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());
}
@@ -818,14 +818,14 @@ public class ServiceImportParseLogic {
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());
}
@@ -839,7 +839,7 @@ public class ServiceImportParseLogic {
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());
@@ -848,16 +848,16 @@ public class ServiceImportParseLogic {
}
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) {
@@ -890,7 +890,7 @@ public class ServiceImportParseLogic {
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);
}
@@ -1071,8 +1071,8 @@ public class ServiceImportParseLogic {
}
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);
@@ -1121,7 +1121,7 @@ public class ServiceImportParseLogic {
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;
}
@@ -1209,7 +1209,7 @@ public class ServiceImportParseLogic {
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();
@@ -1249,7 +1249,7 @@ public class ServiceImportParseLogic {
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));
@@ -1273,7 +1273,7 @@ public class ServiceImportParseLogic {
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);
}
@@ -1338,7 +1338,7 @@ public class ServiceImportParseLogic {
private void validateDerivedFromNotEmpty(User user, Resource resource, AuditingActionEnum actionEnum) {
log.debug("validate resource derivedFrom field");
if ((resource.getDerivedFrom() == null) || (resource.getDerivedFrom().isEmpty()) || (resource.getDerivedFrom().get(0)) == null || (resource
- .getDerivedFrom().get(0).trim().isEmpty())) {
+ .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);
@@ -1359,8 +1359,8 @@ public class ServiceImportParseLogic {
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();
}
@@ -1377,15 +1377,15 @@ public class ServiceImportParseLogic {
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;
}
@@ -1393,8 +1393,8 @@ public class ServiceImportParseLogic {
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();
}
@@ -1402,21 +1402,21 @@ public class ServiceImportParseLogic {
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);
}
}
@@ -1424,22 +1424,22 @@ public class ServiceImportParseLogic {
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);
}
@@ -1459,7 +1459,7 @@ public class ServiceImportParseLogic {
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) {
@@ -1472,8 +1472,8 @@ public class ServiceImportParseLogic {
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);
}
}
@@ -1504,7 +1504,7 @@ public class ServiceImportParseLogic {
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());
}
@@ -1526,7 +1526,7 @@ public class ServiceImportParseLogic {
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;
@@ -1541,12 +1541,12 @@ public class ServiceImportParseLogic {
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);
@@ -1610,15 +1610,15 @@ public class ServiceImportParseLogic {
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;
}
@@ -1627,7 +1627,7 @@ public class ServiceImportParseLogic {
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);
}
@@ -1653,7 +1653,7 @@ public class ServiceImportParseLogic {
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();
}
@@ -1683,7 +1683,7 @@ public class ServiceImportParseLogic {
}
if (isNotEmpty(groupsToUpdate)) {
groupBusinessLogic.updateGroups(resource, groupsToUpdate, true).left()
- .on(serviceBusinessLogic::throwComponentException);
+ .on(serviceBusinessLogic::throwComponentException);
}
}
@@ -1691,7 +1691,7 @@ public class ServiceImportParseLogic {
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());
@@ -1739,16 +1739,16 @@ public class ServiceImportParseLogic {
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) {
@@ -1758,8 +1758,8 @@ public class ServiceImportParseLogic {
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);
}
@@ -1771,11 +1771,11 @@ public class ServiceImportParseLogic {
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,
@@ -1789,7 +1789,7 @@ public class ServiceImportParseLogic {
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) {
@@ -1844,12 +1844,12 @@ public class ServiceImportParseLogic {
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);
@@ -1884,7 +1884,7 @@ public class ServiceImportParseLogic {
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();
}
@@ -1898,7 +1898,7 @@ public class ServiceImportParseLogic {
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) {
@@ -1915,8 +1915,8 @@ public class ServiceImportParseLogic {
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);
}
}
@@ -1945,7 +1945,7 @@ public class ServiceImportParseLogic {
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));
}
}
@@ -1953,7 +1953,7 @@ public class ServiceImportParseLogic {
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));
}
}
@@ -1962,7 +1962,7 @@ public class ServiceImportParseLogic {
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()) {
@@ -1992,11 +1992,11 @@ public class ServiceImportParseLogic {
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());
@@ -2008,37 +2008,37 @@ public class ServiceImportParseLogic {
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
+ )
);
}
}
@@ -2127,11 +2127,11 @@ public class ServiceImportParseLogic {
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));
}
}
}
@@ -2140,10 +2140,10 @@ public class ServiceImportParseLogic {
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));
}
}
}
@@ -2151,10 +2151,10 @@ public class ServiceImportParseLogic {
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));
}
}
@@ -2218,7 +2218,7 @@ public class ServiceImportParseLogic {
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);
@@ -2261,7 +2261,7 @@ public class ServiceImportParseLogic {
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);
@@ -2283,8 +2283,8 @@ public class ServiceImportParseLogic {
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);
}
@@ -2308,8 +2308,8 @@ public class ServiceImportParseLogic {
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();
@@ -2326,7 +2326,7 @@ public class ServiceImportParseLogic {
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();
}
@@ -2352,8 +2352,8 @@ public class ServiceImportParseLogic {
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());
@@ -2364,8 +2364,8 @@ public class ServiceImportParseLogic {
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();
diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/components/lifecycle/LifeCycleTransition.java b/catalog-be/src/main/java/org/openecomp/sdc/be/components/lifecycle/LifeCycleTransition.java
index a4cac10cea..9f1f060448 100644
--- a/catalog-be/src/main/java/org/openecomp/sdc/be/components/lifecycle/LifeCycleTransition.java
+++ b/catalog-be/src/main/java/org/openecomp/sdc/be/components/lifecycle/LifeCycleTransition.java
@@ -138,11 +138,8 @@ public abstract class LifeCycleTransition {
}
// this is only used in 2 cases
- //1. when creating vfc/cp when import vf from csar - when we
-
- // create resources from node type, we create need to change the state
-
- // to certified
+ //1. when creating vfc/cp when import vf from CSAR - when we
+ // create resources from node type, we create need to change the state to certified
//2. certification flow upno upgrade migration
if (lifecycleChangeInfo != null && lifecycleChangeInfo.getAction() != null && (
@@ -150,8 +147,7 @@ public abstract class LifeCycleTransition {
|| lifecycleChangeInfo.getAction() == LifecycleChanceActionEnum.UPGRADE_MIGRATION)) {
return Either.left(true);
}
- ResponseFormat responseFormat = componentUtils.getResponseFormat(ActionStatus.RESTRICTED_OPERATION);
- return Either.right(responseFormat);
+ return Either.right(componentUtils.getResponseFormat(ActionStatus.RESTRICTED_OPERATION));
}
protected boolean userResourceRoleValidation(Component component, ComponentTypeEnum componentType, User modifier) {
diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/servlets/ServiceServlet.java b/catalog-be/src/main/java/org/openecomp/sdc/be/servlets/ServiceServlet.java
index 746c9b1dfa..daf4bcbcd0 100644
--- a/catalog-be/src/main/java/org/openecomp/sdc/be/servlets/ServiceServlet.java
+++ b/catalog-be/src/main/java/org/openecomp/sdc/be/servlets/ServiceServlet.java
@@ -19,7 +19,6 @@
*/
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;
@@ -61,7 +60,6 @@ import javax.ws.rs.QueryParam;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
-import org.apache.commons.collections4.MapUtils;
import org.apache.http.HttpStatus;
import org.glassfish.jersey.media.multipart.FormDataContentDisposition;
import org.glassfish.jersey.media.multipart.FormDataParam;
@@ -93,6 +91,7 @@ import org.openecomp.sdc.be.resources.data.auditing.AuditingActionEnum;
import org.openecomp.sdc.be.resources.data.auditing.model.DistributionData;
import org.openecomp.sdc.be.resources.data.auditing.model.ResourceCommonInfo;
import org.openecomp.sdc.be.servlets.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;
@@ -103,7 +102,6 @@ import org.openecomp.sdc.common.util.Multitenancy;
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")
@@ -117,14 +115,16 @@ public class ServiceServlet extends AbstractValidationsServlet {
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
@@ -133,11 +133,11 @@ public class ServiceServlet extends AbstractValidationsServlet {
@Consumes(MediaType.APPLICATION_JSON)
@Produces(MediaType.APPLICATION_JSON)
@Operation(description = "Create Service", method = "POST", summary = "Returns created service", responses = {
- @ApiResponse(content = @Content(array = @ArraySchema(schema = @Schema(implementation = Service.class)))),
- @ApiResponse(responseCode = "201", description = "Service created"), @ApiResponse(responseCode = "403", description = "Restricted operation"),
- @ApiResponse(responseCode = "400", description = "Invalid content / Missing content"),
- @ApiResponse(responseCode = "409", description = "Service already exist"),
- @ApiResponse(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) {
@@ -164,7 +164,7 @@ public class ServiceServlet extends AbstractValidationsServlet {
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");
@@ -177,14 +177,14 @@ public class ServiceServlet extends AbstractValidationsServlet {
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
@@ -193,8 +193,8 @@ public class ServiceServlet extends AbstractValidationsServlet {
@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) {
@@ -221,8 +221,8 @@ public class ServiceServlet extends AbstractValidationsServlet {
@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,
@@ -241,11 +241,11 @@ public class ServiceServlet extends AbstractValidationsServlet {
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);
@@ -288,15 +288,15 @@ public class ServiceServlet extends AbstractValidationsServlet {
@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();
@@ -309,8 +309,8 @@ public class ServiceServlet extends AbstractValidationsServlet {
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)) {
@@ -324,7 +324,7 @@ public class ServiceServlet extends AbstractValidationsServlet {
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");
@@ -337,10 +337,10 @@ public class ServiceServlet extends AbstractValidationsServlet {
@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) {
@@ -364,9 +364,8 @@ public class ServiceServlet extends AbstractValidationsServlet {
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
@@ -375,14 +374,14 @@ public class ServiceServlet extends AbstractValidationsServlet {
@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);
@@ -428,10 +427,10 @@ public class ServiceServlet extends AbstractValidationsServlet {
@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,
@@ -455,7 +454,7 @@ public class ServiceServlet extends AbstractValidationsServlet {
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());
}
@@ -480,9 +479,9 @@ public class ServiceServlet extends AbstractValidationsServlet {
@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 {
@@ -515,9 +514,9 @@ public class ServiceServlet extends AbstractValidationsServlet {
@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,
@@ -545,14 +544,14 @@ public class ServiceServlet extends AbstractValidationsServlet {
@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);
@@ -580,12 +579,12 @@ public class ServiceServlet extends AbstractValidationsServlet {
@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,
@@ -616,7 +615,7 @@ public class ServiceServlet extends AbstractValidationsServlet {
@Consumes(MediaType.APPLICATION_JSON)
@Produces(MediaType.APPLICATION_JSON)
@Operation(responses = {@ApiResponse(responseCode = "200", description = "OK"),
- @ApiResponse(responseCode = "500", description = "Internal Server Error. Please try again later.")})
+ @ApiResponse(responseCode = "500", description = "Internal Server Error. Please try again later.")})
@PermissionAllowed(AafPermission.PermNames.INTERNAL_ALL_VALUE)
public Response tempUrlToBeDeleted(@PathParam("serviceId") final String serviceId, @Context final HttpServletRequest request,
@HeaderParam(value = Constants.USER_ID_HEADER) String userId) {
@@ -627,7 +626,7 @@ public class ServiceServlet extends AbstractValidationsServlet {
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));
}
@@ -645,9 +644,9 @@ public class ServiceServlet extends AbstractValidationsServlet {
@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 {
@@ -680,9 +679,9 @@ public class ServiceServlet extends AbstractValidationsServlet {
@Consumes(MediaType.APPLICATION_JSON)
@Produces(MediaType.APPLICATION_JSON)
@Operation(description = "Import Service", method = "POST", summary = "Returns imported service", responses = {
- @ApiResponse(responseCode = "201", description = "Service created"), @ApiResponse(responseCode = "403", description = "Restricted operation"),
- @ApiResponse(responseCode = "400", description = "Invalid content / Missing content"),
- @ApiResponse(responseCode = "409", description = "Service already exist")})
+ @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);
@@ -709,7 +708,7 @@ public class ServiceServlet extends AbstractValidationsServlet {
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());
}
@@ -736,20 +735,20 @@ public class ServiceServlet extends AbstractValidationsServlet {
@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;
@@ -762,7 +761,7 @@ public class ServiceServlet extends AbstractValidationsServlet {
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());
@@ -788,14 +787,14 @@ public class ServiceServlet extends AbstractValidationsServlet {
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());
@@ -820,28 +819,54 @@ public class ServiceServlet extends AbstractValidationsServlet {
@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;
}
}